+
+
+
+# PathScope
+
+**Passive URL-parameter triage for path-like parameters.**
+Point it at URLs you are allowed to review, and it tells you which query parameters *look* like they might be about files or paths — so you can decide what deserves a manual look.
+
+[](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 results are candidates for manual review — never confirmed vulnerabilities.**
+> A flag means "the wording or existing value of this parameter looks path-related".
+> It does **not** mean a parameter is exploitable, reachable, or even used by the application.
+
+---
+
+## Why this exists
+
+URL parameters such as `?file=`, `?page=`, `?template=` or `?download=` are the usual starting
+points when reviewing an application for path-handling issues. Most of the noise in that review
+comes from deciding *which* parameters are worth looking at first.
+
+PathScope does that first pass for you — **statically, offline, and without touching the target.**
+It reads URLs you already have, parses them locally, and produces a short, ranked list of
+parameters that mention paths/files in their names, or whose *existing* values already contain
+path-like patterns.
+
+It is deliberately boring: no payloads, no requests, no clever stuff.
+
+---
+
+## Safety statement
+
+PathScope is **passive by design**. It:
+
+- ✅ only analyzes URLs **you explicitly provide** (`--url`, `-i/--input`, or stdin);
+- ✅ parses everything **locally** with `urllib.parse` and regular expressions;
+- ❌ makes **no HTTP/HTTPS requests**, and **no DNS lookups**;
+- ❌ does **not crawl**, scan, fingerprint, or enumerate anything;
+- ❌ does **not generate, inject, or send test values**;
+- ❌ does **not open, read, or resolve any file or resource named in a URL parameter**;
+- ❌ does **not require root** (or `sudo`, or any elevated capability);
+- ❌ has **no third-party dependencies**, so nothing is installed from PyPI.
+
+> **Authorization:** Only analyze URLs you are authorized to review (your own applications, an
+> engagement with signed scope, a lab, a CTF you are permitted to work on, or a bug-bounty
+> program that allows it). If you are not sure, ask the asset owner first. Analyzing a URL is
+> harmless, but acting on what you find may not be — check your scope before testing anything.
+
+---
+
+## Features
+
+- **Three input modes** — a single URL, a file of URLs, or piped stdin. Sources can be combined.
+- **Robust local parsing** — repeated parameters (`?file=a&file=b`), URL-encoded names
+ (`?%66%69%6c%65=`) and values, blank values, keys without `=`, IPv6 hosts and custom ports.
+- **Transparent heuristics** — readable keyword tables and weighted rules in a single file, easy
+ to tune for your application or threat model.
+- **Values hidden by default** — output shows `file=`, and any `user:pass@` in a URL is
+ masked as `@`; use `--show-values` only when you want values on screen (or in logs).
+- **Plain-text output that works when piped** — ANSI colour is used only when stdout is a real
+ terminal. `NO_COLOR` and `--no-color` are honoured.
+- **JSON output** (`--json`) for pipelines, reports and dashboards.
+- **Graceful failure** — unreadable files, malformed URLs and malformed lines are reported, not
+ fatal; duplicates are de-duplicated; blank lines and `#` comments are skipped.
+- **Useful exit codes** and a complete `--help`.
+- **Tests included** — 97 unit and end-to-end tests, including checks that prove no network
+ modules are imported and no sockets are used.
+
+---
+
+## Requirements
+
+| Requirement | Detail |
+|---|---|
+| Python | 3.7 or newer (tested on 3.11; Kali ships 3.11+) |
+| Packages | **none** — standard library only |
+| Privileges | ordinary user; **root is not required** |
+| Network | not used |
+
+PathScope is developed and tested on Kali Linux and runs on any Linux, macOS or Windows system
+with Python 3.7+ (the test suite is executed on Python 3.11).
+
+---
+
+## Installation (Kali Linux)
+
+Kali already ships Python 3.11, so there is nothing to install. Clone or copy the files and go:
+
+```bash
+# 1. Get the files (git clone, or copy the folder over)
+git clone https://github.com/mrdineshpathro/pathscope.git
+cd pathscope
+
+# 2. Confirm Python
+python3 --version
+
+# 3. Make it executable (optional) and run it
+chmod +x path_detector.py
+./path_detector.py --help
+```
+
+Prefer a command on your `PATH`?
+
+```bash
+# Option A: a symlink (no sudo needed if ~/.local/bin is on your PATH)
+mkdir -p ~/.local/bin
+ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope
+pathscope --url 'https://example.test/view?file=report.pdf'
+
+# Option B: an alias for the current shell
+echo "alias pathscope='python3 $PWD/path_detector.py'" >> ~/.zshrc
+source ~/.zshrc # Kali's default shell is zsh; use ~/.bashrc for bash
+```
+
+> Kali's default user is `kali`. Nothing here needs `sudo`; if a command fails, fix permissions
+> in your home directory rather than escalating.
+
+---
+
+## Quick start
+
+```bash
+# Analyse one URL
+python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+
+# Analyse a file of URLs (one per line)
+python3 path_detector.py -i urls.txt
+
+# Analyse URLs piped on stdin
+cat urls.txt | python3 path_detector.py
+
+# See the existing values too (hidden by default)
+python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values
+
+# Machine-readable output for a report pipeline
+python3 path_detector.py -i urls.txt --json > findings.json
+
+# Combine several URL files
+python3 path_detector.py -i day1.txt -i day2.txt
+
+# Lower the threshold to surface weaker signals
+python3 path_detector.py -i urls.txt --min-score 20
+```
+
+> **Quote your URLs** when they contain `&`, otherwise your shell will split them into background
+> jobs. Single quotes are safest: `--url 'https://host/p?a=1&b=2'`.
+
+### Example session
+
+```console
+$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf&lang=en&page=2'
+PathScope 1.0.0 - passive URL-parameter triage
+----------------------------------------------------------------
+GitHub: https://github.com/mrdineshpathro
+Instagram: https://www.instagram.com/mr_dineshpatro
+Support: https://buymeacoffee.com/mrdineshpathro
+Candidates for manual review only: this tool never proves a vulnerability.
+No network requests are made. Only analyze URLs you are authorized to review.
+
+Candidates for manual review
+================================================================
+Analyzed 1 URL(s) and 3 distinct parameter(s); 2 candidate(s) at score >= 30.
+
+#1 file [MEDIUM score 55/100]
+ Host example.test
+ URL https://example.test/view?file=&lang=&page=
+ Parameter file
+ Value
+ Why flagged
+ - name contains path-related keyword 'file' (name score +35)
+ - value ends with a file-like extension '.pdf' (+20)
+
+#2 page [LOW score 30/100]
+ Host example.test
+ URL https://example.test/view?file=&lang=&page=
+ Parameter page
+ Value
+ Why flagged
+ - name contains path-related keyword 'page' (name score +30)
+
+Reminder: candidates for manual review, not confirmed vulnerabilities. No requests were sent and no input was injected.
+Values are hidden by default (use --show-values to display them).
+
+Done: 1 URL(s), 2 candidate(s), 0 line(s) skipped.
+```
+
+*(At the default `--min-score 30` both entries are reported; raise it, e.g. `--min-score 50`,
+if you only want stronger signals such as `file` here.)*
+
+---
+
+## Command-line reference
+
+```
+python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--json]
+ [--show-values] [--no-color] [--no-banner]
+ [--min-score N] [--strict] [--fail-on-none]
+```
+
+### Input (sources are merged and de-duplicated)
+
+| Option | Description |
+|---|---|
+| `--url URL` | Analyze one URL. Repeat the flag to add more. Values starting with `-` are safe. |
+| `-i, --input FILE` | Read one URL per line from `FILE`; repeat the flag to read several files. Blank lines and lines starting with `#` are skipped. Use `-` to read stdin explicitly. |
+| *(stdin)* | Used automatically when neither `--url` nor `--input` is given, e.g. `cat urls.txt \| python3 path_detector.py`. |
+
+### Output
+
+| Option | Description |
+|---|---|
+| `--json` | Print a single JSON document on stdout. The banner and warnings go to stderr, so `> out.json` stays clean. |
+| `--show-values` | Reveal the existing parameter values. Off by default; URLs are shown with `=` masking. |
+| `--no-color` | Disable ANSI colour even on a terminal. Colour is automatically off when piped, and `NO_COLOR` is respected. |
+| `--no-banner` | Suppress the startup banner (the banner is printed to **stderr**, not stdout). |
+
+### Heuristics and behaviour
+
+| Option | Description |
+|---|---|
+| `--min-score N` | Report parameters with a combined score of at least `N` (0–100, default **30**). |
+| `--strict` | Exit `1` if any input line was skipped (malformed URL etc.). |
+| `--fail-on-none` | Exit `3` when no candidates were flagged — handy in CI. |
+| `-h, --help` | Full help, including examples, exit codes and the project links. |
+| `--version` | Print `PathScope ` and exit. |
+
+### Exit codes
+
+| Code | Meaning |
+|---|---|
+| `0` | Analysis completed. Malformed input lines are reported as warnings but are not fatal. |
+| `1` | `--strict` was given and at least one input line was malformed/skipped. |
+| `2` | Usage error (bad flags), no usable URLs, or an unreadable input file. |
+| `3` | No candidates were flagged (only with `--fail-on-none`). |
+| `130` | Interrupted with `Ctrl-C`. |
+
+---
+
+## How scoring works
+
+PathScope combines two independent signals, then clamps the result to **0–100**:
+
+```
+score = clamp(name_score + value_score + generic_bonus, 0, 100)
+```
+
+### 1. Name score — 0–50
+
+The parameter name is split into lowercase tokens (`fileName` → `file`,`name`;
+`user-file_path` → `user`,`file`,`path`), and each token is looked up in `NAME_KEYWORDS`
+in [`path_detector.py`](path_detector.py):
+
+| Weight | Example keywords |
+|---|---|
+| 30–35 | `file`, `filename`, `filepath`, `path`, `download`, `dir`, `folder`, `template`, `include`, `page`, `basedir` |
+| 20–29 | `view`, `layout`, `theme`, `src`, `url`, `uri`, `document`, `config`, `log`, `render`, `doc`, `pg` |
+| 10–19 | `dl`, `link`, `inc`, `data`, `mount`, `root`, `action` |
+
+- **Exact token** → full weight, plus `+5` when the name has multiple tokens
+ (e.g. `download_file`).
+- **Prefix/suffix of the joined name** → discounted weight, so `filedata` still scores but
+ `profile` (ends in `file`) does not.
+- **Weak shapes only** → `+10` for a multi-word name with no keyword, `+5` for a very long name.
+- **Generic names** (`image`, `target`, `ref`, `site`, `avatar`, …) score **0 alone** and can only
+ contribute through the rule below.
+
+### 2. Value score — 0–50
+
+Only values that are **already present** in the URL are inspected — PathScope never generates
+one. Each piece of evidence is counted once, even if the value is encoded and decoded forms
+overlap.
+
+| Weight | Evidence in the existing value |
+|---|---|
+| +25 | Parent-directory sequence `../` or `..\` |
+| +20 | URL-encoded `..` (`%2e%2e`), or a known file extension (`.pdf`, `.log`, `.tar.gz`, …) |
+| +15 | Encoded slash/backslash (`%2f`, `%5c`), null byte (`%00`), or `/etc` reference |
+| +12–15 | Two or more path separators |
+| +8–10 | One separator, Windows drive path (`C:\…`), `..` / `./` segment, double encoding |
+| +5 | Value starts with `/` (absolute-looking) |
+| −10 | Value is a full URL (`https://…`), which is usually a redirect target, not a path |
+
+### 3. Generic bonus — 0–10
+
+Names like `image`, `avatar` or `target` are only interesting when the existing value is
+path-like (e.g. `?image=/static/logo.png`). In that case `+10` is added; otherwise the
+parameter is ignored entirely. This keeps ordinary tracking parameters out of the report.
+
+### Interpretation bands
+
+| Score | Band | Suggested reading |
+|---|---|---|
+| 70–100 | `HIGH` | Strong textual match — review this parameter first. |
+| 50–69 | `MEDIUM` | Likely relevant; confirm it is actually used by the app. |
+| 30–49 | `LOW` | Weak signal; review only if time allows or scope demands it. |
+
+**None of these bands imply exploitability.** They rank reading order, nothing more.
+
+### Tuning
+
+All tables and weights live at the top of `path_detector.py` (`NAME_KEYWORDS`,
+`GENERIC_NAMES`, `FILE_EXTENSIONS`, and the weights inside `analyze_name` / `analyze_value`).
+Add your application's own vocabulary (`?shop=`, `?cms_module=`, `?f=`) or drop keywords
+that are noisy for you — it is a single editable file, and the tests still apply.
+
+---
+
+## JSON output
+
+```json
+{
+ "tool": "PathScope",
+ "version": "1.0.0",
+ "disclaimer": "Candidates for manual review only. PathScope is passive: it makes no network requests, injects no values, and never confirms vulnerabilities.",
+ "min_score": 30,
+ "show_values": false,
+ "summary": {
+ "urls_analyzed": 1,
+ "parameters_analyzed": 3,
+ "candidates": 1,
+ "skipped_lines": 0
+ },
+ "findings": [
+ {
+ "index": 1,
+ "host": "example.test",
+ "parameter": "file",
+ "url": "https://example.test/view?file=&lang=",
+ "value": null,
+ "occurrences": 1,
+ "score": 55,
+ "band": "MEDIUM",
+ "reasons": [
+ "name contains path-related keyword 'file' (name score +35)",
+ "value ends with a file-like extension '.pdf' (+20)"
+ ]
+ }
+ ],
+ "links": {
+ "github": "https://github.com/mrdineshpathro",
+ "instagram": "https://www.instagram.com/mr_dineshpatro",
+ "support": "https://buymeacoffee.com/mrdineshpathro"
+ }
+}
+```
+
+With `--show-values`, `value` contains the existing value and `url` is left unmasked.
+
+---
+
+## Tests
+
+The suite uses only `unittest` (standard library) and runs fully offline:
+
+```bash
+# From the repository root
+python3 -m unittest discover -s tests -v
+
+# Or run the file directly
+python3 tests/test_path_detector.py
+```
+
+What is covered:
+
+- tokenising names (`snake_case`, `kebab-case`, `camelCase`, `PascalCase`);
+- keyword, prefix/suffix and weak-name scoring; generic-name rules;
+- value scoring: extensions, traversal, encoded and double-encoded forms, Windows paths,
+ absolute paths, full-URL penalty, and the "count each evidence once" rule;
+- URL validation (schemes, ports, IPv6, whitespace, malformed input);
+- repeated and encoded parameters, merging, sorting, masking;
+- input handling: blank lines, comments, duplicates, BOM, unreadable files;
+- CLI end-to-end: banner links, `--help`, `--version`, `--json`, `--show-values`,
+ `--strict`, `--fail-on-none`, exit codes, no ANSI codes when piped;
+- **safety:** the module imports only an allow-list of standard-library modules, defines no
+ root-related calls, and performs no socket operations while analysing URLs.
+
+---
+
+## Limitations (read these)
+
+- **It is a triage aid, not a scanner.** PathScope reads strings. It cannot tell whether a
+ parameter is used by the server, validated, ignored, or routed through a WAF.
+- **Names and values can lie.** A parameter called `file` may be a harmless enum; a parameter
+ called `x` may be the actual file handler. Treat the output as a reading order, not an answer.
+- **Only query parameters are analysed.** Path segments, JSON bodies, headers and cookies are
+ out of scope by design.
+- **Encodings beyond normal URL encoding** (e.g. UTF-16 percent-encoding, overlong UTF-8) are
+ not decoded, because decoding them would mean guessing at values.
+- **No persistence.** PathScope writes nothing to disk; redirect stdout if you need a report.
+- **Not a vulnerability verdict.** A human must verify anything before it is called a finding.
+
+---
+
+## Project layout
+
+```
+pathscope/
+├── path_detector.py # the tool (standard library only)
+├── tests/
+│ └── test_path_detector.py # unittest suite (offline)
+├── assets/
+│ └── logo.svg # original repository icon (route + magnifier)
+├── README.md
+└── LICENSE
+```
+
+---
+
+## FAQ
+
+**Does PathScope send anything to the URLs?**
+No. There is no socket code in the tool. A test asserts that no network modules are imported and
+that analysis works with socket functions patched to raise.
+
+**Why are values hidden by default?**
+URLs in bug-bounty reports, tickets and shell history routinely contain tokens, session IDs and
+personal data. Masking by default makes it hard to leak them by accident; `--show-values`
+is an explicit decision.
+
+**Can I use it in CI?**
+Yes: `python3 path_detector.py -i urls.txt --json --fail-on-none` exits `3` when nothing
+path-like is found, which you can map to a warning, and `--strict` exits `1` on malformed input.
+
+**Does it need root on Kali?**
+No. Every code path runs as your normal user; nothing binds a port, changes interface state, or
+reads privileged files.
+
+**Will it find all path-like parameters?**
+No. It finds parameters whose names or existing values match the heuristics. Parameters that
+never carry a path-like value and have neutral names will not be flagged — that is by design,
+to keep the report readable.
+
+---
+
+## Legal
+
+PathScope is provided for **authorized security review, education and defensive engineering**.
+Only analyze URLs you have permission to review, and always confirm scope in writing for
+third-party systems. The results are heuristic candidates for manual review, not a statement
+about the security of any system. See [LICENSE](LICENSE) (MIT) — the software is provided
+"as is", without warranty of any kind.
+
+---
+
+
+
+**GitHub:** https://github.com/mrdineshpathro ·
+**Instagram:** https://www.instagram.com/mr_dineshpatro ·
+**Support:** https://buymeacoffee.com/mrdineshpathro
+
+Built for Kali Linux · Python 3 · standard library only
+
+
diff --git a/assets/logo.svg b/assets/logo.svg
new file mode 100644
index 0000000..bd8256f
--- /dev/null
+++ b/assets/logo.svg
@@ -0,0 +1,78 @@
+
diff --git a/path_detector.py b/path_detector.py
new file mode 100755
index 0000000..85823b5
--- /dev/null
+++ b/path_detector.py
@@ -0,0 +1,1201 @@
+#!/usr/bin/env python3
+"""PathScope - passive URL-parameter triage for path-like parameters.
+
+PathScope reads URLs that *you* provide and highlights query parameters whose
+names or existing values look as though they might relate to file paths.
+Every result is a **candidate for manual review**, never a confirmed
+vulnerability.
+
+Safety model (by design, not by configuration):
+ * No HTTP requests, no DNS lookups, no crawling, no scanning.
+ * No test payloads are generated and nothing is sent anywhere.
+ * No file or resource named in a parameter is opened or resolved.
+ * No root privileges are used or required.
+ * Standard library only, so there is nothing to install with pip.
+
+Exit codes:
+ 0 analysis completed normally (malformed lines are warned about)
+ 1 --strict was given and at least one input line was skipped
+ 2 usage error, unreadable input file, or no usable URLs
+ 3 no candidates were flagged (only with --fail-on-none)
+ 130 interrupted with Ctrl-C
+
+Usage:
+ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+ python3 path_detector.py -i urls.txt
+ cat urls.txt | python3 path_detector.py
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+import unicodedata
+from collections import OrderedDict
+from dataclasses import dataclass, field
+from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple
+from urllib.parse import unquote, unquote_plus, urlsplit, urlunsplit
+
+__version__ = "1.0.0"
+PROGRAM = "PathScope"
+
+# ---------------------------------------------------------------------------
+# Banner. These links are printed exactly as given. They are never opened and
+# never contacted; PathScope makes no network requests of any kind.
+# ---------------------------------------------------------------------------
+GITHUB_URL = "https://github.com/mrdineshpathro"
+INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro"
+SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro"
+
+BANNER_LINKS: Tuple[Tuple[str, str], ...] = (
+ ("GitHub", GITHUB_URL),
+ ("Instagram", INSTAGRAM_URL),
+ ("Support", SUPPORT_URL),
+)
+BANNER_DISCLAIMER = (
+ "Candidates for manual review only: this tool never proves a vulnerability.",
+ "No network requests are made. Only analyze URLs you are authorized to review.",
+)
+
+EXIT_OK = 0
+EXIT_STRICT_SKIPS = 1
+EXIT_USAGE = 2
+EXIT_NO_CANDIDATES = 3
+EXIT_INTERRUPTED = 130
+
+# ---------------------------------------------------------------------------
+# Heuristics. Everything below is deliberately plain and easy to edit.
+#
+# Final score = clamp(name_score + value_score + generic_bonus, 0, 100)
+# * name_score 0-50 from NAME_KEYWORDS / weak name shapes
+# * value_score 0-50 from existing values only (never generated)
+# * generic_bonus 0-10 for generic names (image, target, ...) whose value
+# is path-like; generic names never score alone.
+# A parameter is reported when the final score >= --min-score (default 30).
+# ---------------------------------------------------------------------------
+
+NAME_KEYWORDS: Dict[str, int] = {
+ # files / downloads
+ "file": 35,
+ "filename": 35,
+ "file_name": 35,
+ "filepath": 35,
+ "file_path": 35,
+ "document": 25,
+ "doc": 20,
+ "download": 35,
+ "dl": 15,
+ "attachment": 30,
+ "upload": 25,
+ "export": 25,
+ "import": 15,
+ "archive": 20,
+ "backup": 20,
+ # paths / directories
+ "path": 35,
+ "dir": 30,
+ "directory": 30,
+ "folder": 30,
+ "root": 15,
+ "base": 15,
+ "basedir": 30,
+ "base_dir": 30,
+ "basepath": 30,
+ "base_path": 30,
+ "uri": 20,
+ "url": 20,
+ "link": 15,
+ "dest": 20,
+ "destination": 20,
+ "source": 20,
+ "src": 20,
+ "resource": 20,
+ "asset": 20,
+ "media": 20,
+ "storage": 20,
+ "mount": 15,
+ # pages / templates / includes / views
+ "page": 30,
+ "pg": 20,
+ "view": 20,
+ "display": 15,
+ "screen": 10,
+ "layout": 20,
+ "theme": 20,
+ "tpl": 30,
+ "template": 30,
+ "include": 30,
+ "inc": 15,
+ "viewfile": 30,
+ "view_file": 30,
+ "load": 20,
+ "action": 15,
+ "module": 15,
+ # code / config / logs / data files
+ "script": 25,
+ "lang": 20,
+ "language": 15,
+ "locale": 15,
+ "translation": 15,
+ "config": 20,
+ "conf": 20,
+ "settings": 15,
+ "log": 20,
+ "logfile": 30,
+ "log_file": 30,
+ "stylesheet": 30,
+ "css": 15,
+ "js": 15,
+ "style": 15,
+ "data": 10,
+ "db": 15,
+ "database": 15,
+ "report": 20,
+ "render": 20,
+}
+
+PREFIX_DISCOUNT = 7
+SUFFIX_DISCOUNT = 12
+NAME_CAP = 50
+VALUE_CAP = 50
+GENERIC_BONUS = 10
+
+# Generic names: by themselves they are not path-related, but a path-like
+# existing value makes them worth a look (e.g. image=/static/logo.png).
+GENERIC_NAMES = frozenset(
+ {
+ "image",
+ "img",
+ "photo",
+ "avatar",
+ "target",
+ "ref",
+ "referer",
+ "referrer",
+ "site",
+ "key",
+ "callback",
+ "filetarget",
+ }
+)
+
+FILE_EXTENSIONS = frozenset(
+ """
+ apk avi bak bash bat bin bmp bz2 c cgi conf config crt cs csr csv css db
+ dll doc docx dot drawio dtd env eot exe flac gif go gz h htm html ico ini
+ iso jar java jpeg jpg js json jsx key kt log md mkv mov mp3 mp4 msi odt
+ ogg otf pdf pem php phtml plist png ppt pptx ps1 py pyc rar rb rst sh so
+ sql svg swf tar tgz tif tiff toml ts tsx txt vhd wav webp woff woff2 xls
+ xlsx xml xsd yaml yml zip
+ """.split()
+)
+MULTI_EXTENSIONS = ("tar.gz", "tar.bz2", "tar.xz")
+
+WINDOWS_PATH_RE = re.compile(r"^[A-Za-z]:[/\\].+")
+
+COLOR_CODES = {
+ "bold": "1",
+ "dim": "2",
+ "red": "31",
+ "green": "32",
+ "yellow": "33",
+ "blue": "34",
+ "magenta": "35",
+ "cyan": "36",
+ "grey": "90",
+}
+
+
+# ---------------------------------------------------------------------------
+# Small utilities
+# ---------------------------------------------------------------------------
+def sanitize_text(value: str) -> str:
+ """NFC-normalise text and drop control characters (keeps output terminal-safe)."""
+ normalized = unicodedata.normalize("NFC", value)
+ return "".join(ch for ch in normalized if unicodedata.category(ch)[0] != "C")
+
+
+def truncate(text: str, limit: int = 160) -> str:
+ if len(text) <= limit:
+ return text
+ return text[: max(0, limit - 1)] + "\u2026"
+
+
+def normalize_name(name: str) -> str:
+ """Lowercase a parameter name and unify separators: 'userId' stays camel-ish."""
+ return name.strip().lower().replace("-", "_").replace(" ", "_")
+
+
+def tokenize_name(name: str) -> List[str]:
+ """Split a parameter name into lowercase tokens.
+
+ 'fileName' -> ['file', 'name']
+ 'user-file_path' -> ['user', 'file', 'path']
+ 'FILES' -> ['files']
+ """
+ parts: List[str] = []
+ current = ""
+ for char in name:
+ if char.isupper() and current and not current[-1].isupper():
+ parts.append(current)
+ current = char
+ else:
+ current += char
+ if current:
+ parts.append(current)
+
+ tokens: List[str] = []
+ for part in parts:
+ for piece in normalize_name(part).split("_"):
+ if piece:
+ tokens.append(piece)
+ return tokens
+
+
+def extension_of(text: str) -> Optional[str]:
+ """Return a known file extension at the end of the value, if any."""
+ cleaned = text.strip().rstrip(".,;:!?")
+ last = re.split(r"[/\\]", cleaned)[-1]
+ lowered = last.lower()
+ for multi in MULTI_EXTENSIONS:
+ if lowered.endswith("." + multi):
+ return multi
+ if "." not in lowered:
+ return None
+ candidate = lowered.rsplit(".", 1)[1]
+ if candidate in FILE_EXTENSIONS:
+ return candidate
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Name heuristic
+# ---------------------------------------------------------------------------
+@dataclass(frozen=True)
+class NameAnalysis:
+ """Outcome of analysing a parameter name."""
+
+ score: int = 0
+ reason: Optional[str] = None
+ keyword: Optional[str] = None
+ generic: bool = False
+ weak: bool = False
+
+
+def analyze_name(name: str) -> NameAnalysis:
+ """Score a parameter name for path-related meaning (0-50)."""
+ tokens = tokenize_name(name)
+ joined = "".join(tokens)
+
+ best_weight = 0
+ best_keyword: Optional[str] = None
+
+ # Exact token matches: "file", "path", "dir", ...
+ for token in tokens:
+ weight = NAME_KEYWORDS.get(token, 0)
+ if weight > best_weight:
+ best_weight, best_keyword = weight, token
+
+ # Compound key matches: "basepath", "viewfile", ...
+ if best_weight == 0 and joined:
+ weight = NAME_KEYWORDS.get(joined, 0)
+ if weight:
+ best_weight, best_keyword = weight, joined
+
+ # Prefix / suffix matches get a discount: "filedata" yes, "hotfile" only
+ # weakly (and not at all at the default threshold).
+ if best_weight == 0 and joined:
+ for keyword, weight in NAME_KEYWORDS.items():
+ if len(keyword) < 4:
+ continue
+ if joined.startswith(keyword) and weight > PREFIX_DISCOUNT:
+ candidate = weight - PREFIX_DISCOUNT
+ if candidate > best_weight:
+ best_weight, best_keyword = candidate, keyword
+ elif joined.endswith(keyword) and weight > SUFFIX_DISCOUNT:
+ candidate = weight - SUFFIX_DISCOUNT
+ if candidate > best_weight:
+ best_weight, best_keyword = candidate, keyword
+
+ if best_keyword is not None:
+ bonus = 5 if len(tokens) > 1 else 0
+ reason = (
+ f"name contains path-related keyword '{best_keyword}' "
+ f"(name score +{best_weight}{f', +{bonus} for multi-word name' if bonus else ''})"
+ )
+ return NameAnalysis(
+ score=min(NAME_CAP, best_weight + bonus),
+ reason=reason,
+ keyword=best_keyword,
+ )
+
+ lowered = normalize_name(name)
+ if lowered in GENERIC_NAMES:
+ return NameAnalysis(generic=True)
+
+ if "_" in lowered or "-" in name:
+ return NameAnalysis(
+ score=10,
+ reason="multi-word name with no obvious path keyword (weak signal, +10)",
+ weak=True,
+ )
+ if len(lowered) > 24:
+ return NameAnalysis(
+ score=5,
+ reason="unusually long parameter name (weak signal, +5)",
+ weak=True,
+ )
+ return NameAnalysis()
+
+
+# ---------------------------------------------------------------------------
+# Value heuristic (existing values only - PathScope never generates input)
+# ---------------------------------------------------------------------------
+@dataclass(frozen=True)
+class ValueAnalysis:
+ """Outcome of analysing an existing parameter value."""
+
+ score: int = 0
+ reasons: Tuple[str, ...] = ()
+
+
+ENCODED_PATH_MARKERS = ("%2e%2e", "%2f", "%5c", "%252e", "%252f")
+
+
+def analyze_value(raw_value: str, decoded: Optional[str] = None) -> ValueAnalysis:
+ """Score an existing value for path-like or encoded path-like content (0-50).
+
+ ``raw_value`` is exactly what appeared in the URL; ``decoded`` is the
+ single-decoded form (passed in by the caller to avoid decoding twice).
+ Each piece of evidence is counted once: when the raw value already shows
+ encoded path markers, the structural layer is skipped so the same pattern
+ is not credited twice.
+ """
+ if not raw_value and not decoded:
+ return ValueAnalysis()
+
+ if decoded is None:
+ decoded = unquote(raw_value)
+ raw_value = raw_value or ""
+ decoded = decoded or ""
+ lowered_raw = raw_value.lower()
+ encoded_path = any(marker in lowered_raw for marker in ENCODED_PATH_MARKERS)
+
+ score = 0
+ reasons: List[str] = []
+ seen = set()
+
+ def add(key: str, weight: int, reason: str) -> None:
+ nonlocal score
+ if key in seen:
+ return
+ seen.add(key)
+ score += weight
+ reasons.append(reason)
+
+ # 1. Encoding and traversal indicators, evaluated on raw and decoded forms.
+ if not encoded_path and ("../" in decoded or "..\\" in decoded):
+ add(
+ "traversal",
+ 25,
+ "value contains a parent-directory sequence ('../' or '..\\') (+25)",
+ )
+ if "%2e%2e" in lowered_raw:
+ add("pct-dotdot", 20, "value contains URL-encoded '..' (%2e%2e) (+20)")
+ if "%2f" in lowered_raw:
+ add("pct-slash", 15, "value contains URL-encoded slash (%2f) (+15)")
+ if "%5c" in lowered_raw:
+ add("pct-backslash", 15, "value contains URL-encoded backslash (%5c) (+15)")
+ if "%00" in lowered_raw:
+ add("nul-byte", 15, "value contains a null-byte encoding (%00) (+15)")
+ if "%252e" in lowered_raw or "%252f" in lowered_raw:
+ add("double-encoded", 10, "value contains double-encoded path characters (+10)")
+ if lowered_raw.startswith("/etc") or "/etc/" in lowered_raw:
+ add("system-path", 15, "value references a common system path (/etc) (+15)")
+ if "\\windows\\" in lowered_raw:
+ add("windows-dir", 10, "value references a Windows system directory (+10)")
+
+ # 2. Structural shape of the decoded value.
+ structure = decoded
+ is_full_url = "://" in structure
+ if is_full_url:
+ add("full-url", -10, "value is a full URL rather than a local path (-10)")
+
+ if not encoded_path:
+ if WINDOWS_PATH_RE.match(structure):
+ add("windows-drive", 10, "value looks like a Windows drive path (+10)")
+
+ normalized = structure.replace("\\", "/")
+ if normalized in {"..", "../"} or normalized.startswith("../") or "/../" in normalized:
+ add(
+ "dotdot",
+ 10,
+ "value is or contains a parent-directory ('..') sequence (+10)",
+ )
+ elif normalized in {".", "./"} or normalized.startswith("./"):
+ add(
+ "dot",
+ 5,
+ "value is or starts with a current-directory ('./') sequence (+5)",
+ )
+
+ if not is_full_url:
+ separators = normalized.count("/")
+ if separators == 1:
+ add("depth-1", 8, "value contains a relative path segment (+8)")
+ elif separators == 2:
+ add("depth-2", 12, "value contains two path separators (+12)")
+ elif separators >= 3:
+ add("depth-3", 15, "value contains three or more path separators (+15)")
+ if normalized.startswith("/") and len(normalized) > 1:
+ add(
+ "absolute",
+ 5,
+ "value starts with a path separator (absolute-looking path) (+5)",
+ )
+
+ ext = extension_of(structure)
+ if ext:
+ add("extension", 20, f"value ends with a file-like extension '.{ext}' (+20)")
+
+ return ValueAnalysis(score=max(0, min(VALUE_CAP, score)), reasons=tuple(reasons))
+
+
+# ---------------------------------------------------------------------------
+# URL parsing and analysis
+# ---------------------------------------------------------------------------
+@dataclass(frozen=True)
+class URLTarget:
+ """Locally parsed URL metadata (no network activity involved)."""
+
+ raw: str
+ scheme: str
+ host: str
+ port: Optional[int]
+ path: str
+
+
+class URLParseError(ValueError):
+ """Raised when a line is not a usable HTTP(S) URL."""
+
+
+def parse_target(raw: str) -> URLTarget:
+ """Validate a URL string locally. Never resolves or contacts the host."""
+ text = sanitize_text(raw).strip()
+ if not text:
+ raise URLParseError("blank input")
+ if any(char.isspace() for char in text):
+ raise URLParseError("contains whitespace")
+ if any(ord(char) < 32 or ord(char) == 127 for char in raw):
+ raise URLParseError("contains control characters")
+ try:
+ parts = urlsplit(text)
+ host = parts.hostname
+ port = parts.port
+ except ValueError as exc:
+ raise URLParseError(f"malformed URL ({exc})") from exc
+
+ scheme = (parts.scheme or "").lower()
+ if scheme not in ("http", "https"):
+ raise URLParseError(
+ f"unsupported scheme (expected http/https, got '{scheme or 'none'}')"
+ )
+ if not parts.netloc or not host:
+ raise URLParseError("missing host")
+ return URLTarget(
+ raw=text,
+ scheme=scheme,
+ host=host,
+ port=port,
+ path=parts.path or "/",
+ )
+
+
+def display_host(target: URLTarget) -> str:
+ if target.port and target.port not in (80, 443):
+ return f"{target.host}:{target.port}"
+ return target.host
+
+
+def split_query(query: str) -> List[Tuple[str, str, str]]:
+ """Split a raw query string into (decoded name, raw value, decoded value).
+
+ Kept deliberately literal (manual split on '&' and '=') so that:
+ * repeated parameters are preserved,
+ * URL-encoded names/values are visible both raw and decoded,
+ * PathScope never guesses at values it was not given.
+ """
+ pairs: List[Tuple[str, str, str]] = []
+ if not query:
+ return pairs
+ for chunk in query.split("&"):
+ if not chunk:
+ continue
+ raw_name, separator, raw_value = chunk.partition("=")
+ try:
+ name = unquote_plus(raw_name)
+ value = unquote_plus(raw_value)
+ except (UnicodeError, ValueError):
+ name, value = raw_name, raw_value
+ pairs.append((sanitize_text(name), raw_value, sanitize_text(value)))
+ return pairs
+
+
+def mask_credentials(netloc: str) -> str:
+ """Replace 'user:pass@' with '@' so secrets are not displayed."""
+ if "@" not in netloc:
+ return netloc
+ host = netloc.rsplit("@", 1)[1]
+ return f"@{host}"
+
+
+def mask_url(raw: str) -> str:
+ """Return the URL with query/fragment values and credentials hidden."""
+ parts = urlsplit(raw)
+ pairs: List[str] = []
+ for chunk in parts.query.split("&"):
+ if not chunk:
+ continue
+ if "=" in chunk:
+ name = chunk.split("=", 1)[0]
+ pairs.append(f"{name}=")
+ else:
+ pairs.append(chunk)
+ fragment = "" if parts.fragment else ""
+ return urlunsplit(
+ (
+ parts.scheme,
+ mask_credentials(parts.netloc),
+ parts.path,
+ "&".join(pairs),
+ fragment,
+ )
+ )
+
+
+@dataclass
+class ParameterFinding:
+ """One parameter that passed the heuristic threshold."""
+
+ url: str
+ host: str
+ parameter: str
+ value: Optional[str]
+ reasons: Tuple[str, ...]
+ score: int
+ occurrences: int = 1
+ index: int = 0
+
+ @property
+ def band(self) -> str:
+ return score_band(self.score)
+
+
+@dataclass
+class _ParameterGroup:
+ parameter: str
+ occurrences: int = 0
+ values: List[str] = field(default_factory=list)
+ raw_values: List[str] = field(default_factory=list)
+
+
+def analyze_url(raw: str, min_score: int = 30) -> List[ParameterFinding]:
+ """Analyse one URL and return its flagged parameters (best first).
+
+ This is purely local string analysis: nothing is requested, resolved,
+ opened or injected.
+ """
+ raw = sanitize_text(raw).strip()
+ target = parse_target(raw)
+ parts = urlsplit(raw)
+
+ groups: "OrderedDict[str, _ParameterGroup]" = OrderedDict()
+ for name, raw_value, value in split_query(parts.query):
+ if not name:
+ continue
+ canonical = "_".join(tokenize_name(name)) or name.lower()
+ group = groups.get(canonical)
+ if group is None:
+ group = groups[canonical] = _ParameterGroup(parameter=name)
+ group.occurrences += 1
+ group.values.append(value)
+ group.raw_values.append(raw_value)
+
+ findings: List[ParameterFinding] = []
+ host = display_host(target)
+ # Show URL credentials as masked, even when parameter values are shown.
+ safe_url = mask_credentials(parts.netloc)
+ if safe_url != parts.netloc:
+ safe_url = urlunsplit(
+ (parts.scheme, safe_url, parts.path, parts.query, parts.fragment)
+ )
+ else:
+ safe_url = raw
+
+ for group in groups.values():
+ name_analysis = analyze_name(group.parameter)
+ value_analyses = [
+ analyze_value(raw_value, decoded=group.values[index])
+ for index, raw_value in enumerate(group.raw_values)
+ ]
+
+ best_index = 0
+ for index, analysis in enumerate(value_analyses):
+ if analysis.score > value_analyses[best_index].score:
+ best_index = index
+ best_value_analysis = value_analyses[best_index]
+ best_value = group.values[best_index]
+
+ generic_bonus = 0
+ reasons: List[str] = []
+ if name_analysis.reason:
+ reasons.append(name_analysis.reason)
+ if name_analysis.generic:
+ if best_value_analysis.score >= 20:
+ generic_bonus = GENERIC_BONUS
+ reasons.append(
+ f"generic name '{group.parameter}' becomes relevant because its "
+ f"value is path-like (+{GENERIC_BONUS})"
+ )
+ else:
+ continue # generic names never stand alone
+ reasons.extend(best_value_analysis.reasons)
+
+ score = name_analysis.score + best_value_analysis.score + generic_bonus
+ score = max(0, min(100, score))
+ if score <= 0 or score < min_score:
+ continue
+
+ findings.append(
+ ParameterFinding(
+ url=safe_url,
+ host=host,
+ parameter=group.parameter,
+ value=best_value,
+ reasons=tuple(reasons) or (f"combined heuristic score {score}",),
+ score=score,
+ occurrences=group.occurrences,
+ )
+ )
+
+ findings.sort(key=lambda finding: (-finding.score, finding.parameter.lower()))
+ for index, finding in enumerate(findings, start=1):
+ finding.index = index
+ return findings
+
+
+def count_parameters(raw: str) -> int:
+ """Count distinct, non-empty parameter names in a URL (locally)."""
+ parts = urlsplit(raw)
+ return len({name for name, _raw, _decoded in split_query(parts.query) if name})
+
+
+# ---------------------------------------------------------------------------
+# Input handling
+# ---------------------------------------------------------------------------
+class InputError(RuntimeError):
+ """Raised for unreadable input files."""
+
+
+def read_input_file(path: str) -> List[str]:
+ try:
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as handle:
+ return handle.read().splitlines()
+ except OSError as exc:
+ raise InputError(
+ f"cannot read input file '{path}': {exc.strerror or exc}"
+ ) from exc
+
+
+def clean_input_lines(
+ lines: Iterable[str], label: str = "line"
+) -> Tuple[List[str], List[str]]:
+ """Drop blanks/comments/duplicates, validate URLs. Returns (urls, warnings)."""
+ urls: List[str] = []
+ warnings: List[str] = []
+ seen = set()
+ for line_number, line in enumerate(lines, start=1):
+ candidate = sanitize_text(line).strip()
+ if not candidate or candidate.startswith("#"):
+ continue
+ if candidate in seen:
+ continue
+ try:
+ parse_target(candidate)
+ except URLParseError as exc:
+ warnings.append(
+ f"{label} {line_number}: skipped malformed URL ({exc}): "
+ f"{truncate(candidate, 100)}"
+ )
+ continue
+ seen.add(candidate)
+ urls.append(candidate)
+ return urls, warnings
+
+
+def dedupe(items: Iterable[str]) -> List[str]:
+ result: List[str] = []
+ seen = set()
+ for item in items:
+ if item not in seen:
+ seen.add(item)
+ result.append(item)
+ return result
+
+
+def stdin_has_data() -> bool:
+ try:
+ return sys.stdin is not None and not sys.stdin.isatty()
+ except Exception: # pragma: no cover - defensive only
+ return False
+
+
+def read_stdin_lines() -> List[str]:
+ try:
+ return sys.stdin.read().splitlines()
+ except (OSError, ValueError):
+ return []
+
+
+# ---------------------------------------------------------------------------
+# Rendering
+# ---------------------------------------------------------------------------
+def stream_supports_color(stream, disabled: bool = False) -> bool:
+ if disabled or os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("TERM", "") == "dumb":
+ return False
+ try:
+ return bool(stream.isatty())
+ except Exception: # pragma: no cover - defensive only
+ return False
+
+
+class Palette:
+ """ANSI colours, used only when the target stream is an interactive terminal."""
+
+ def __init__(self, enabled: bool) -> None:
+ self.enabled = enabled
+
+ def paint(self, style: str, text: str) -> str:
+ if not self.enabled:
+ return text
+ code = COLOR_CODES[style]
+ return f"\x1b[{code}m{text}\x1b[0m"
+
+ def __getattr__(self, style: str) -> Callable[[str], str]:
+ if style not in COLOR_CODES:
+ raise AttributeError(style)
+
+ def apply(text: str) -> str:
+ return self.paint(style, text)
+
+ return apply
+
+
+def render_banner(colors: Palette) -> str:
+ title = colors.bold(colors.cyan(f"{PROGRAM} {__version__} - passive URL-parameter triage"))
+ lines = [title, colors.grey("-" * 64)]
+ for label, url in BANNER_LINKS:
+ lines.append(f"{colors.bold(label + ':')} {colors.blue(url)}")
+ for line in BANNER_DISCLAIMER:
+ lines.append(colors.yellow(line))
+ return "\n".join(lines)
+
+
+def score_band(score: int) -> str:
+ if score >= 70:
+ return "HIGH"
+ if score >= 50:
+ return "MEDIUM"
+ return "LOW"
+
+
+def render_report(
+ findings: Sequence[ParameterFinding],
+ *,
+ colors: Palette,
+ show_values: bool,
+ urls_analyzed: int,
+ parameters_analyzed: int,
+ min_score: int,
+ skipped: int,
+) -> str:
+ lines: List[str] = []
+ lines.append(colors.bold("Candidates for manual review"))
+ lines.append(colors.grey("=" * 64))
+ lines.append(
+ f"Analyzed {urls_analyzed} URL(s) and {parameters_analyzed} distinct "
+ f"parameter(s); {len(findings)} candidate(s) at score >= {min_score}."
+ )
+ if skipped:
+ lines.append(colors.yellow(f"Skipped {skipped} malformed input line(s)."))
+ lines.append("")
+
+ if not findings:
+ lines.append(
+ colors.green(
+ "No path-like parameter candidates were flagged. "
+ "This is not proof that the application is safe."
+ )
+ )
+ else:
+ band_colors = {"HIGH": colors.red, "MEDIUM": colors.yellow, "LOW": colors.cyan}
+ for finding in findings:
+ band = finding.band
+ heading = (
+ f"#{finding.index} {colors.bold(finding.parameter)} "
+ f"{band_colors[band](f'[{band} score {finding.score}/100]')}"
+ )
+ lines.append(heading)
+ lines.append(f" {colors.grey('Host')} {finding.host}")
+ shown_url = finding.url if show_values else mask_url(finding.url)
+ lines.append(f" {colors.grey('URL')} {truncate(shown_url, 160)}")
+ if show_values:
+ value_text = truncate(finding.value or "", 120) or ""
+ else:
+ value_text = colors.grey("")
+ lines.append(f" {colors.grey('Parameter')} {finding.parameter}")
+ lines.append(f" {colors.grey('Value')} {value_text}")
+ if finding.occurrences > 1:
+ lines.append(
+ f" {colors.grey('Repeated')} x{finding.occurrences} "
+ "(best-scoring existing value shown)"
+ )
+ lines.append(f" {colors.grey('Why flagged')}")
+ for reason in finding.reasons:
+ lines.append(f" - {reason}")
+ lines.append("")
+
+ lines.append(
+ colors.grey(
+ "Reminder: candidates for manual review, not confirmed vulnerabilities. "
+ "No requests were sent and no input was injected."
+ )
+ )
+ if not show_values:
+ lines.append(
+ colors.grey(
+ "Values are hidden by default (use --show-values to display them)."
+ )
+ )
+ return "\n".join(lines)
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+@dataclass
+class RunConfig:
+ urls: List[str]
+ skipped: List[str]
+ json: bool = False
+ show_values: bool = False
+ no_banner: bool = False
+ no_color: bool = False
+ min_score: int = 30
+ strict: bool = False
+ fail_on_none: bool = False
+ banner_printed: bool = False
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ prog="path_detector.py",
+ description=(
+ "PathScope: passive triage of URL query parameters whose names or "
+ "existing values look path-like. Results are candidates for manual "
+ "review, never confirmed vulnerabilities. PathScope makes no network "
+ "requests and injects no test values."
+ ),
+ epilog=(
+ "examples:\n"
+ " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n"
+ " python3 path_detector.py -i urls.txt\n"
+ " cat urls.txt | python3 path_detector.py\n"
+ " python3 path_detector.py -i urls.txt --json --show-values\n"
+ "\n"
+ "exit codes:\n"
+ " 0 completed 1 skipped lines with --strict 2 usage/input error\n"
+ " 3 no candidates with --fail-on-none 130 interrupted\n"
+ "\n"
+ "links (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 (merged and de-duplicated)")
+ source.add_argument(
+ "--url",
+ action="append",
+ default=[],
+ metavar="URL",
+ help="URL to analyze; may be repeated. Quote URLs containing '&'.",
+ )
+ source.add_argument(
+ "-i",
+ "--input",
+ action="append",
+ default=[],
+ metavar="FILE",
+ help="read URLs from FILE (one per line); may be repeated. '-' reads "
+ "stdin. Blank lines and lines starting with '#' are skipped.",
+ )
+
+ output = parser.add_argument_group("output")
+ output.add_argument(
+ "--json",
+ action="store_true",
+ help="print machine-readable JSON on stdout (banner stays on stderr)",
+ )
+ output.add_argument(
+ "--show-values",
+ action="store_true",
+ help="reveal existing parameter values; hidden/masked by default",
+ )
+ output.add_argument(
+ "--no-color",
+ action="store_true",
+ help="disable ANSI colour even on a terminal",
+ )
+ output.add_argument(
+ "--no-banner",
+ action="store_true",
+ help="do not print the startup banner and links",
+ )
+
+ heuristic = parser.add_argument_group("heuristics")
+ heuristic.add_argument(
+ "--min-score",
+ type=int,
+ default=30,
+ metavar="N",
+ help="report parameters scoring at least N (0-100, default: 30)",
+ )
+
+ behaviour = parser.add_argument_group("behaviour")
+ behaviour.add_argument(
+ "--strict",
+ action="store_true",
+ help="exit 1 if any input line was malformed or skipped",
+ )
+ behaviour.add_argument(
+ "--fail-on-none",
+ action="store_true",
+ help="exit 3 when no candidates are flagged",
+ )
+ return parser
+
+
+def collect_inputs(parser: argparse.ArgumentParser, args: argparse.Namespace
+ ) -> Tuple[List[str], List[str]]:
+ """Merge --url, -i/--input and (when no source is given) piped stdin.
+
+ Stdin is auto-detected only when neither --url nor -i/--input is present,
+ so an explicit source never blocks waiting for piped data.
+ """
+ urls: List[str] = []
+ warnings: List[str] = []
+ stdin_consumed = False
+
+ for path in args.input:
+ if path == "-":
+ if not stdin_has_data():
+ parser.error("--input '-' was given but stdin is a terminal")
+ stdin_urls, stdin_warnings = clean_input_lines(
+ read_stdin_lines(), label="stdin"
+ )
+ stdin_consumed = True
+ urls.extend(stdin_urls)
+ warnings.extend(stdin_warnings)
+ continue
+ try:
+ file_lines = read_input_file(path)
+ except InputError as exc:
+ parser.error(str(exc))
+ file_urls, file_warnings = clean_input_lines(file_lines, label=path)
+ urls.extend(file_urls)
+ warnings.extend(file_warnings)
+
+ url_values, url_warnings = clean_input_lines(args.url, label="--url")
+ urls.extend(url_values)
+ warnings.extend(url_warnings)
+
+ if not stdin_consumed and not args.url and not args.input and stdin_has_data():
+ piped_urls, piped_warnings = clean_input_lines(read_stdin_lines(), label="stdin")
+ urls.extend(piped_urls)
+ warnings.extend(piped_warnings)
+
+ return dedupe(urls), warnings
+
+
+def make_payload(config: RunConfig, findings: Sequence[ParameterFinding],
+ urls_analyzed: int, parameters_analyzed: int) -> dict:
+ return {
+ "tool": PROGRAM,
+ "version": __version__,
+ "disclaimer": (
+ "Candidates for manual review only. PathScope is passive: it makes no "
+ "network requests, injects no values, and never confirms vulnerabilities."
+ ),
+ "min_score": config.min_score,
+ "show_values": config.show_values,
+ "summary": {
+ "urls_analyzed": urls_analyzed,
+ "parameters_analyzed": parameters_analyzed,
+ "candidates": len(findings),
+ "skipped_lines": len(config.skipped),
+ },
+ "findings": [
+ {
+ "index": finding.index,
+ "host": finding.host,
+ "parameter": finding.parameter,
+ "url": finding.url if config.show_values else mask_url(finding.url),
+ "value": finding.value if config.show_values else None,
+ "occurrences": finding.occurrences,
+ "score": finding.score,
+ "band": finding.band,
+ "reasons": list(finding.reasons),
+ }
+ for finding in findings
+ ],
+ "links": {
+ "github": GITHUB_URL,
+ "instagram": INSTAGRAM_URL,
+ "support": SUPPORT_URL,
+ },
+ }
+
+
+def run(config: RunConfig, stdout=None, stderr=None) -> int:
+ stdout = stdout if stdout is not None else sys.stdout
+ stderr = stderr if stderr is not None else sys.stderr
+
+ if not config.no_banner and not config.banner_printed:
+ print(
+ render_banner(Palette(stream_supports_color(stderr, disabled=config.no_color))),
+ file=stderr,
+ )
+ print("", file=stderr)
+ config.banner_printed = True
+
+ out_colors = Palette(stream_supports_color(stdout, disabled=config.no_color))
+
+ for warning in config.skipped:
+ print(f"warning: {warning}", file=stderr)
+
+ if not config.urls:
+ print("error: no usable URLs to analyze.", file=stderr)
+ print(
+ " Use --url URL, -i/--input FILE, or pipe URLs on stdin.",
+ file=stderr,
+ )
+ print(" Try: python3 path_detector.py --help", file=stderr)
+ return EXIT_USAGE
+
+ findings: List[ParameterFinding] = []
+ urls_analyzed = 0
+ parameters_analyzed = 0
+ for url in config.urls:
+ try:
+ url_findings = analyze_url(url, min_score=config.min_score)
+ except URLParseError as exc: # defensive: validated earlier
+ print(f"warning: skipped URL ({exc})", file=stderr)
+ continue
+ urls_analyzed += 1
+ parameters_analyzed += count_parameters(url)
+ findings.extend(url_findings)
+
+ findings.sort(key=lambda finding: (-finding.score, finding.host, finding.parameter))
+ for index, finding in enumerate(findings, start=1):
+ finding.index = index
+
+ if config.json:
+ payload = make_payload(config, findings, urls_analyzed, parameters_analyzed)
+ json.dump(payload, stdout, indent=2, ensure_ascii=False)
+ stdout.write("\n")
+ else:
+ report = render_report(
+ findings,
+ colors=out_colors,
+ show_values=config.show_values,
+ urls_analyzed=urls_analyzed,
+ parameters_analyzed=parameters_analyzed,
+ min_score=config.min_score,
+ skipped=len(config.skipped),
+ )
+ print(report, file=stdout)
+ print(
+ out_colors.grey(
+ f"\nDone: {urls_analyzed} URL(s), {len(findings)} candidate(s), "
+ f"{len(config.skipped)} line(s) skipped."
+ ),
+ file=stdout,
+ )
+
+ if config.strict and config.skipped:
+ return EXIT_STRICT_SKIPS
+ if config.fail_on_none and not findings:
+ return EXIT_NO_CANDIDATES
+ return EXIT_OK
+
+
+def main(argv: Optional[Sequence[str]] = None, stdout=None, stderr=None) -> int:
+ parser = build_parser()
+ stderr = stderr if stderr is not None else sys.stderr
+ argv_list = list(sys.argv[1:] if argv is None else argv)
+
+ # The banner is part of every invocation (including --help/--version).
+ if "--no-banner" not in argv_list:
+ banner_colors = Palette(
+ stream_supports_color(stderr, disabled="--no-color" in argv_list)
+ )
+ print(render_banner(banner_colors), file=stderr)
+ print("", file=stderr)
+ banner_printed = "--no-banner" not in argv_list
+
+ args = parser.parse_args(argv_list)
+
+ if not 0 <= args.min_score <= 100:
+ parser.error("--min-score must be between 0 and 100")
+
+ config = RunConfig(urls=[], skipped=[])
+ config.json = args.json
+ config.show_values = args.show_values
+ config.no_banner = args.no_banner
+ config.no_color = args.no_color
+ config.min_score = args.min_score
+ config.strict = args.strict
+ config.fail_on_none = args.fail_on_none
+ config.banner_printed = banner_printed
+
+ try:
+ config.urls, config.skipped = collect_inputs(parser, args)
+ except KeyboardInterrupt:
+ print("\ninterrupted", file=stderr)
+ return EXIT_INTERRUPTED
+
+ try:
+ return run(config, stdout=stdout, stderr=stderr)
+ except KeyboardInterrupt:
+ print("\ninterrupted", file=stderr)
+ return EXIT_INTERRUPTED
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/test_path_detector.py b/tests/test_path_detector.py
new file mode 100755
index 0000000..5b68a90
--- /dev/null
+++ b/tests/test_path_detector.py
@@ -0,0 +1,666 @@
+#!/usr/bin/env python3
+"""Unit tests for PathScope.
+
+Run with:
+ python3 -m unittest discover -s tests -v
+or:
+ python3 tests/test_path_detector.py
+
+The tests are split into four groups:
+ 1. heuristic unit tests (names, values, extensions),
+ 2. URL parsing / analysis tests (repeats, encoding, masking),
+ 3. input handling tests (files, blank lines, duplicates),
+ 4. end-to-end CLI tests, including safety guarantees.
+
+Everything runs offline: PathScope never opens a socket, and one test proves it.
+"""
+
+from __future__ import annotations
+
+import ast
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+SCRIPT = REPO_ROOT / "path_detector.py"
+sys.path.insert(0, str(REPO_ROOT))
+
+import path_detector as pd # noqa: E402 (path setup must happen first)
+
+BANNER_LINKS = (
+ ("GitHub", "https://github.com/mrdineshpathro"),
+ ("Instagram", "https://www.instagram.com/mr_dineshpatro"),
+ ("Support", "https://buymeacoffee.com/mrdineshpathro"),
+)
+
+
+def run_cli(*args: str, stdin: str = "", timeout: int = 30) -> subprocess.CompletedProcess:
+ """Run the real CLI as a subprocess (no TTY, so no colour)."""
+ env = dict(os.environ)
+ env.pop("NO_COLOR", None)
+ env["TERM"] = "xterm-256color"
+ return subprocess.run(
+ [sys.executable, str(SCRIPT), *args],
+ input=stdin,
+ capture_output=True,
+ text=True,
+ env=env,
+ timeout=timeout,
+ cwd=str(REPO_ROOT),
+ )
+
+
+# ---------------------------------------------------------------------------
+# 1. Heuristic unit tests
+# ---------------------------------------------------------------------------
+class TestTokenizeName(unittest.TestCase):
+ def test_snake_case(self):
+ self.assertEqual(pd.tokenize_name("file_path"), ["file", "path"])
+
+ def test_kebab_case(self):
+ self.assertEqual(pd.tokenize_name("user-file-name"), ["user", "file", "name"])
+
+ def test_camel_case(self):
+ self.assertEqual(pd.tokenize_name("fileName"), ["file", "name"])
+
+ def test_pascal_case(self):
+ self.assertEqual(pd.tokenize_name("DownloadFile"), ["download", "file"])
+
+ def test_mixed_noise(self):
+ self.assertEqual(pd.tokenize_name(" TEMPLATE__id "), ["template", "id"])
+
+ def test_empty(self):
+ self.assertEqual(pd.tokenize_name(""), [])
+
+
+class TestAnalyzeName(unittest.TestCase):
+ def test_strong_keyword(self):
+ analysis = pd.analyze_name("file")
+ self.assertGreaterEqual(analysis.score, 30)
+ self.assertEqual(analysis.keyword, "file")
+
+ def test_compound_keyword(self):
+ analysis = pd.analyze_name("basepath")
+ self.assertGreaterEqual(analysis.score, 25)
+
+ def test_camel_compound(self):
+ analysis = pd.analyze_name("downloadFile")
+ self.assertGreaterEqual(analysis.score, 35)
+
+ def test_prefix_match(self):
+ analysis = pd.analyze_name("filedata")
+ self.assertIsNotNone(analysis.reason)
+ self.assertGreater(analysis.score, 0)
+
+ def test_generic_name_is_not_a_keyword(self):
+ analysis = pd.analyze_name("image")
+ self.assertTrue(analysis.generic)
+ self.assertEqual(analysis.score, 0)
+ self.assertIsNone(analysis.reason)
+
+ def test_unrelated_simple_name(self):
+ analysis = pd.analyze_name("q")
+ self.assertEqual(analysis.score, 0)
+
+ def test_weak_multipart_name(self):
+ analysis = pd.analyze_name("some_thing")
+ self.assertTrue(analysis.weak)
+ self.assertLess(analysis.score, 15)
+
+ def test_unrelated_name_does_not_mention_exploit(self):
+ analysis = pd.analyze_name("path")
+ self.assertNotIn("exploit", (analysis.reason or "").lower())
+
+
+class TestExtensionOf(unittest.TestCase):
+ def test_common_extension(self):
+ self.assertEqual(pd.extension_of("report.pdf"), "pdf")
+
+ def test_path_extension(self):
+ self.assertEqual(pd.extension_of("../../etc/shadow.txt"), "txt")
+
+ def test_multi_extension(self):
+ self.assertEqual(pd.extension_of("backup.tar.gz"), "tar.gz")
+
+ def test_no_extension(self):
+ self.assertIsNone(pd.extension_of("justwords"))
+
+ def test_unknown_extension(self):
+ self.assertIsNone(pd.extension_of("malware.xyzzy"))
+
+
+class TestAnalyzeValue(unittest.TestCase):
+ def test_file_name(self):
+ analysis = pd.analyze_value("report.pdf")
+ self.assertGreaterEqual(analysis.score, 20)
+ self.assertTrue(any("pdf" in reason for reason in analysis.reasons))
+
+ def test_plain_word(self):
+ self.assertEqual(pd.analyze_value("hello").score, 0)
+
+ def test_empty_value(self):
+ self.assertEqual(pd.analyze_value("").score, 0)
+
+ def test_traversal(self):
+ analysis = pd.analyze_value("../../etc/passwd")
+ self.assertGreaterEqual(analysis.score, 40)
+ self.assertTrue(any("parent-directory" in reason for reason in analysis.reasons))
+
+ def test_encoded_traversal_counts_once(self):
+ encoded = pd.analyze_value("%2e%2e%2f%2e%2e%2fetc%2fpasswd")
+ decoded = pd.analyze_value("../../etc/passwd")
+ self.assertGreaterEqual(encoded.score, 30)
+ self.assertLessEqual(encoded.score, decoded.score)
+
+ def test_encoded_slash(self):
+ analysis = pd.analyze_value("%2fadmin%2fpanel")
+ self.assertGreater(analysis.score, 0)
+ self.assertTrue(any("%2f" in reason for reason in analysis.reasons))
+
+ def test_double_encoded(self):
+ analysis = pd.analyze_value("%252e%252e%252f")
+ self.assertTrue(any("double-encoded" in reason for reason in analysis.reasons))
+
+ def test_absolute_path(self):
+ analysis = pd.analyze_value("/var/log/app.log")
+ self.assertGreaterEqual(analysis.score, 30)
+
+ def test_windows_path(self):
+ analysis = pd.analyze_value(r"C:\Windows\win.ini")
+ self.assertGreaterEqual(analysis.score, 30)
+
+ def test_current_directory(self):
+ analysis = pd.analyze_value("./")
+ self.assertGreaterEqual(analysis.score, 5)
+
+ def test_full_url_is_penalised(self):
+ url = pd.analyze_value("https://example.test/a/b/c.txt")
+ path = pd.analyze_value("/a/b/c.txt")
+ self.assertLess(url.score, path.score)
+
+ def test_reasons_are_strings(self):
+ analysis = pd.analyze_value("../../etc/passwd")
+ self.assertTrue(all(isinstance(reason, str) for reason in analysis.reasons))
+
+
+# ---------------------------------------------------------------------------
+# 2. URL parsing and analysis
+# ---------------------------------------------------------------------------
+class TestParseTarget(unittest.TestCase):
+ def test_valid_https(self):
+ target = pd.parse_target("https://example.test/path?file=a.txt")
+ self.assertEqual(target.scheme, "https")
+ self.assertEqual(target.host, "example.test")
+ self.assertEqual(target.path, "/path")
+
+ def test_uppercase_scheme_and_host(self):
+ target = pd.parse_target("HTTPS://Example.Test/x")
+ self.assertEqual(target.scheme, "https")
+ self.assertEqual(target.host, "example.test")
+
+ def test_custom_port_display(self):
+ target = pd.parse_target("http://example.test:8080/")
+ self.assertEqual(pd.display_host(target), "example.test:8080")
+
+ def test_ipv6_is_accepted(self):
+ target = pd.parse_target("http://[::1]:8080/?path=/tmp")
+ self.assertIn("::1", target.host)
+
+ def test_missing_scheme(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("example.test/view?file=a.txt")
+
+ def test_unsupported_scheme(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("ftp://example.test/file.txt")
+
+ def test_javascript_scheme_rejected(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("javascript:alert(1)")
+
+ def test_missing_host(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("https:///path")
+
+ def test_whitespace_rejected(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("https://example.test/a b?file=x")
+
+ def test_bad_port_rejected(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.parse_target("https://example.test:99999/")
+
+
+class TestSplitQuery(unittest.TestCase):
+ def test_pairs(self):
+ pairs = pd.split_query("a=1&b=2")
+ self.assertEqual([(name, raw, value) for name, raw, value in pairs],
+ [("a", "1", "1"), ("b", "2", "2")])
+
+ def test_blank_value_is_kept(self):
+ pairs = pd.split_query("file=")
+ self.assertEqual(len(pairs), 1)
+ self.assertEqual(pairs[0][2], "")
+
+ def test_repeated_names_are_kept(self):
+ pairs = pd.split_query("file=a&file=b")
+ self.assertEqual([pair[2] for pair in pairs], ["a", "b"])
+
+ def test_encoded_name_and_value_are_decoded_once(self):
+ pairs = pd.split_query("%66%69%6c%65=..%2Freport.pdf")
+ self.assertEqual(pairs[0][0], "file")
+ self.assertEqual(pairs[0][1], "..%2Freport.pdf")
+ self.assertEqual(pairs[0][2], "../report.pdf")
+
+ def test_empty_query(self):
+ self.assertEqual(pd.split_query(""), [])
+
+
+class TestAnalyzeURL(unittest.TestCase):
+ def test_flags_file_parameter(self):
+ findings = pd.analyze_url("https://example.test/view?file=report.pdf")
+ self.assertEqual(len(findings), 1)
+ self.assertEqual(findings[0].parameter, "file")
+ self.assertEqual(findings[0].host, "example.test")
+ self.assertGreaterEqual(findings[0].score, 30)
+
+ def test_never_uses_vulnerability_language(self):
+ findings = pd.analyze_url("https://example.test/get?doc=../../etc/passwd")
+ text = " ".join(reason for finding in findings for reason in finding.reasons)
+ for word in ("vulnerable", "exploitable", "confirmed", "LFI found"):
+ self.assertNotIn(word.lower(), text.lower())
+
+ def test_unrelated_parameter_is_not_flagged(self):
+ self.assertEqual(pd.analyze_url("https://example.test/?q=hello&utm_source=news"), [])
+
+ def test_page_is_a_keyword_but_requires_the_default_threshold(self):
+ findings = pd.analyze_url("https://example.test/?page=2")
+ self.assertEqual([finding.parameter for finding in findings], ["page"])
+ self.assertLess(pd.analyze_url("https://example.test/?page=2")[0].score, 50)
+
+ def test_encoded_parameter_name_is_decoded(self):
+ findings = pd.analyze_url("https://example.test/?%66%69%6c%65=report.pdf")
+ self.assertEqual([finding.parameter for finding in findings], ["file"])
+
+ def test_repeated_parameters_are_merged(self):
+ findings = pd.analyze_url(
+ "https://example.test/?file=one.txt&file=two.txt&file=three.pdf"
+ )
+ self.assertEqual(len(findings), 1)
+ self.assertEqual(findings[0].occurrences, 3)
+ # All occurrences score equally, so the first existing value is kept.
+ self.assertEqual(findings[0].value, "one.txt")
+
+ def test_repeated_parameters_keep_best_scoring_value(self):
+ findings = pd.analyze_url(
+ "https://example.test/?file=one.txt&file=../../etc/passwd"
+ )
+ self.assertEqual(len(findings), 1)
+ self.assertEqual(findings[0].occurrences, 2)
+ self.assertEqual(findings[0].value, "../../etc/passwd")
+
+ def test_generic_name_requires_path_like_value(self):
+ self.assertEqual(pd.analyze_url("https://example.test/?image=logo"), [])
+ flagged = pd.analyze_url("https://example.test/?image=/static/logo.png")
+ self.assertEqual([finding.parameter for finding in flagged], ["image"])
+
+ def test_generic_name_never_stands_alone(self):
+ findings = pd.analyze_url("https://example.test/?target=homepage")
+ self.assertEqual(findings, [])
+
+ def test_results_are_sorted_by_score(self):
+ findings = pd.analyze_url(
+ "https://example.test/?page=2&file=report.pdf&dir=../../etc"
+ )
+ scores = [finding.score for finding in findings]
+ self.assertEqual(scores, sorted(scores, reverse=True))
+ self.assertEqual([finding.index for finding in findings],
+ list(range(1, len(findings) + 1)))
+
+ def test_min_score_threshold(self):
+ url = "https://example.test/?file=report.pdf"
+ self.assertTrue(pd.analyze_url(url, min_score=30))
+ self.assertEqual(pd.analyze_url(url, min_score=90), [])
+
+ def test_no_query_returns_empty(self):
+ self.assertEqual(pd.analyze_url("https://example.test/path"), [])
+
+ def test_bare_key_without_value_is_tolerated(self):
+ findings = pd.analyze_url("https://example.test/?file")
+ self.assertEqual(len(findings), 1)
+ self.assertEqual(findings[0].occurrences, 1)
+
+ def test_host_without_port_in_finding(self):
+ findings = pd.analyze_url("https://example.test:443/?file=a.txt")
+ self.assertEqual(findings[0].host, "example.test")
+
+ def test_malformed_url_raises(self):
+ with self.assertRaises(pd.URLParseError):
+ pd.analyze_url("not a url")
+
+ def test_mask_url(self):
+ masked = pd.mask_url("https://example.test/a?file=secret.pdf&x=1#frag")
+ self.assertNotIn("secret.pdf", masked)
+ self.assertIn("file=", masked)
+ self.assertIn("x=", masked)
+
+ def test_findings_never_contain_credentials(self):
+ findings = pd.analyze_url("https://alice:hunter2@example.test/?file=a.txt")
+ self.assertEqual(len(findings), 1)
+ self.assertNotIn("hunter2", findings[0].url)
+ self.assertIn("@example.test", findings[0].url)
+
+ def test_mask_url_hides_credentials(self):
+ masked = pd.mask_url("https://alice:hunter2@example.test/?file=a.txt")
+ self.assertNotIn("hunter2", masked)
+ self.assertIn("@example.test", masked)
+
+ def test_count_parameters(self):
+ self.assertEqual(
+ pd.count_parameters("https://example.test/?a=1&b=2&a=3"), 2
+ )
+
+
+# ---------------------------------------------------------------------------
+# 3. Input handling
+# ---------------------------------------------------------------------------
+class TestCleanInputLines(unittest.TestCase):
+ def test_blank_lines_comments_and_duplicates(self):
+ urls, warnings = pd.clean_input_lines(
+ [
+ "",
+ " ",
+ "# a comment",
+ "https://a.test/?file=x",
+ "https://a.test/?file=x",
+ "https://b.test/?page=2",
+ ]
+ )
+ self.assertEqual(urls, ["https://a.test/?file=x", "https://b.test/?page=2"])
+ self.assertEqual(warnings, [])
+
+ def test_malformed_lines_are_reported_with_line_numbers(self):
+ urls, warnings = pd.clean_input_lines(["", "not-a-url", "https://ok.test/?a=1"])
+ self.assertEqual(urls, ["https://ok.test/?a=1"])
+ self.assertEqual(len(warnings), 1)
+ self.assertIn("line 2", warnings[0])
+
+ def test_custom_label_for_warnings(self):
+ _urls, warnings = pd.clean_input_lines(["bogus"], label="--url")
+ self.assertIn("--url 1", warnings[0])
+
+
+class TestReadInputFile(unittest.TestCase):
+ def test_reads_utf8_with_bom(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "urls.txt"
+ path.write_bytes(b"\xef\xbb\xbfhttps://a.test/?file=x\n\n")
+ lines = pd.read_input_file(str(path))
+ self.assertIn("https://a.test/?file=x", [line.strip() for line in lines])
+
+ def test_missing_file_raises_input_error(self):
+ with self.assertRaises(pd.InputError):
+ pd.read_input_file("/definitely/not/here/urls.txt")
+
+ def test_directory_raises_input_error(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(pd.InputError):
+ pd.read_input_file(tmp)
+
+
+# ---------------------------------------------------------------------------
+# 4. CLI behaviour (subprocess)
+# ---------------------------------------------------------------------------
+class TestCLI(unittest.TestCase):
+ def assert_links_present(self, text: str) -> None:
+ for label, url in BANNER_LINKS:
+ self.assertIn(f"{label}: {url}", text)
+
+ def test_banner_links_are_exact(self):
+ result = run_cli("--no-banner", "--url", "https://a.test/?file=x")
+ self.assertNotIn("GitHub:", result.stderr)
+ self.assertNotIn("instagram.com", result.stderr)
+
+ result = run_cli("--url", "https://a.test/?file=x")
+ self.assert_links_present(result.stderr)
+
+ def test_banner_without_arguments(self):
+ result = run_cli()
+ self.assert_links_present(result.stderr)
+ self.assertEqual(result.returncode, pd.EXIT_USAGE)
+
+ def test_banner_printed_once(self):
+ result = run_cli("--url", "https://a.test/?file=x")
+ self.assertEqual(result.stderr.count("PathScope " + pd.__version__), 1)
+
+ def test_help_shows_banner_and_usage(self):
+ result = run_cli("--help")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("usage:", result.stdout)
+ self.assert_links_present(result.stderr)
+ self.assertIn("examples:", result.stdout)
+ self.assertIn("https://github.com/mrdineshpathro", result.stdout)
+
+ def test_version(self):
+ result = run_cli("--version")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn(pd.__version__, result.stdout)
+
+ def test_single_url_hides_value_by_default(self):
+ result = run_cli("--url", "https://example.test/view?file=report.pdf")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("file", result.stdout)
+ self.assertIn("example.test", result.stdout)
+ self.assertNotIn("report.pdf", result.stdout)
+ self.assertIn("", result.stdout)
+
+ def test_show_values_reveals_value(self):
+ result = run_cli(
+ "--url", "https://example.test/view?file=report.pdf", "--show-values"
+ )
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("report.pdf", result.stdout)
+
+ def test_no_ansi_colour_when_piped(self):
+ result = run_cli("--url", "https://example.test/?file=report.pdf")
+ self.assertNotIn("\x1b[", result.stdout)
+ self.assertNotIn("\x1b[", result.stderr)
+
+ def test_json_output_is_valid_and_hides_values(self):
+ result = run_cli(
+ "--json", "--url", "https://example.test/?file=report.pdf&q=hello"
+ )
+ self.assertEqual(result.returncode, 0)
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["tool"], "PathScope")
+ self.assertEqual(payload["summary"]["urls_analyzed"], 1)
+ self.assertEqual(payload["summary"]["candidates"], 1)
+ finding = payload["findings"][0]
+ self.assertEqual(finding["parameter"], "file")
+ self.assertIsNone(finding["value"])
+ self.assertNotIn("report.pdf", result.stdout)
+ self.assertIn("", finding["url"])
+
+ def test_json_show_values(self):
+ result = run_cli(
+ "--json", "--show-values",
+ "--url", "https://example.test/?file=report.pdf",
+ )
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["findings"][0]["value"], "report.pdf")
+
+ def test_json_has_disclaimer_and_links(self):
+ payload = json.loads(
+ run_cli("--json", "--url", "https://a.test/?file=x").stdout
+ )
+ self.assertIn("manual review", payload["disclaimer"].lower())
+ self.assertEqual(payload["links"]["github"], pd.GITHUB_URL)
+ self.assertEqual(payload["links"]["instagram"], pd.INSTAGRAM_URL)
+ self.assertEqual(payload["links"]["support"], pd.SUPPORT_URL)
+
+ def test_input_file(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "urls.txt"
+ path.write_text(
+ "\n".join(
+ [
+ "",
+ "# comment",
+ "https://a.test/?file=one.txt",
+ "",
+ "not a url",
+ "https://b.test/?page=2",
+ ]
+ ),
+ encoding="utf-8",
+ )
+ result = run_cli("-i", str(path))
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("skipped malformed URL", result.stderr)
+ self.assertIn("Analyzed 2 URL(s)", result.stdout)
+
+ def test_multiple_input_files(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ first = Path(tmp) / "one.txt"
+ second = Path(tmp) / "two.txt"
+ first.write_text("https://a.test/?file=one.txt\n", encoding="utf-8")
+ second.write_text("https://b.test/?path=/var/log\n", encoding="utf-8")
+ result = run_cli(
+ "--no-banner", "--json", "-i", str(first), "-i", str(second)
+ )
+ self.assertEqual(result.returncode, 0)
+ self.assertEqual(json.loads(result.stdout)["summary"]["urls_analyzed"], 2)
+
+ def test_stdin_pipe(self):
+ result = run_cli(stdin="https://a.test/?file=one.txt\nhttps://b.test/?path=x\n")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("Analyzed 2 URL(s)", result.stdout)
+
+ def test_dash_input_reads_stdin(self):
+ result = run_cli("-i", "-", stdin="https://a.test/?file=one.txt\n")
+ self.assertEqual(result.returncode, 0)
+ self.assertIn("1 candidate", result.stdout)
+
+ def test_duplicate_urls_counted_once(self):
+ result = run_cli(
+ "--json",
+ stdin="https://a.test/?file=one.txt\nhttps://a.test/?file=one.txt\n",
+ )
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["summary"]["urls_analyzed"], 1)
+
+ def test_missing_input_file_exits_2(self):
+ result = run_cli("--no-banner", "-i", "/no/such/file.txt")
+ self.assertEqual(result.returncode, pd.EXIT_USAGE)
+ self.assertIn("cannot read input file", result.stderr)
+
+ def test_invalid_min_score_exits_2(self):
+ result = run_cli("--no-banner", "--min-score", "101", "--url", "https://a.test/")
+ self.assertEqual(result.returncode, pd.EXIT_USAGE)
+
+ def test_strict_mode_exits_1_on_bad_lines(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "urls.txt"
+ path.write_text("bogus\nhttps://a.test/?file=x\n", encoding="utf-8")
+ result = run_cli("--no-banner", "--strict", "-i", str(path))
+ self.assertEqual(result.returncode, pd.EXIT_STRICT_SKIPS)
+
+ def test_fail_on_none_exits_3(self):
+ result = run_cli("--no-banner", "--fail-on-none", "--url", "https://a.test/?q=hi")
+ self.assertEqual(result.returncode, pd.EXIT_NO_CANDIDATES)
+
+ def test_fail_on_none_is_zero_when_candidates_exist(self):
+ result = run_cli(
+ "--no-banner", "--fail-on-none", "--url", "https://a.test/?file=a.txt"
+ )
+ self.assertEqual(result.returncode, 0)
+
+ def test_url_with_encoded_ampersand_and_equals(self):
+ result = run_cli(
+ "--no-banner",
+ "--json",
+ "--url",
+ "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.txt",
+ )
+ self.assertEqual(result.returncode, 0)
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["summary"]["parameters_analyzed"], 2)
+
+ def test_no_usable_urls_exits_2(self):
+ result = run_cli("--no-banner", stdin="# only a comment\n\n")
+ self.assertEqual(result.returncode, pd.EXIT_USAGE)
+ self.assertIn("no usable URLs", result.stderr)
+
+
+# ---------------------------------------------------------------------------
+# 5. Safety guarantees
+# ---------------------------------------------------------------------------
+ALLOWED_IMPORTS = {
+ "__future__",
+ "argparse",
+ "collections",
+ "dataclasses",
+ "json",
+ "os",
+ "re",
+ "sys",
+ "typing",
+ "unicodedata",
+ "urllib",
+}
+FORBIDDEN_MODULES = {
+ "socket",
+ "ssl",
+ "http",
+ "urllib3",
+ "requests",
+ "httpx",
+ "aiohttp",
+ "ftplib",
+ "smtplib",
+ "telnetlib",
+ "subprocess",
+ "scapy",
+ "paramiko",
+ "dns",
+}
+
+
+class TestSafety(unittest.TestCase):
+ def test_only_standard_library_imports(self):
+ tree = ast.parse(SCRIPT.read_text(encoding="utf-8"))
+ imported: set[str] = set()
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ imported.update(alias.name.split(".")[0] for alias in node.names)
+ elif isinstance(node, ast.ImportFrom) and node.module:
+ imported.add(node.module.split(".")[0])
+ self.assertLessEqual(imported, ALLOWED_IMPORTS)
+ self.assertFalse(imported & FORBIDDEN_MODULES)
+
+ def test_no_network_calls_during_analysis(self):
+ def boom(*_args, **_kwargs):
+ raise AssertionError("PathScope attempted a network operation")
+
+ with mock.patch("socket.socket", side_effect=boom), mock.patch(
+ "socket.create_connection", side_effect=boom
+ ), mock.patch("socket.getaddrinfo", side_effect=boom):
+ findings = pd.analyze_url(
+ "https://example.test/?file=../../etc/passwd&next=https://evil.test/"
+ )
+ self.assertTrue(findings)
+
+ def test_module_has_no_root_requirement(self):
+ source = SCRIPT.read_text(encoding="utf-8")
+ for marker in ("os.geteuid", "os.seteuid", "sudo", "setuid"):
+ self.assertNotIn(marker, source)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
From 7e04fcb226b0ffc85d1b9329bdaeb9f01e9a9f41 Mon Sep 17 00:00:00 2001
From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com>
Date: Sun, 29 Nov 2026 10:32:59 +0000
Subject: [PATCH 2/8] Upgrade PathScope to v2: modular package, HAR input, 4
report formats
Restructure the monolithic v1 tool into pathscope/ modules:
textutil (bounded decoding, sanitising), heuristics (name/value rules),
sources (URL/list/stdin/HAR 1.2), detector (no I/O), report
(text/JSON/CSV/SARIF), config (strict JSON), cli, __main__
New capabilities:
- HAR 1.2 query, form (params + urlencoded) and flattened JSON parameters
- auto-detection of HAR vs URL lists, --format har/urls/auto
- --format text|json|csv|sarif, --json, --input-format, --output-format
- bounded multi-pass percent decoding (default 3, max 5), segment-only
traversal matching, malformed-escape tolerance
- values hidden by default, credentials masked, query strings/body never
printed, control characters stripped from every renderer
- repeatable --ignore-param, strict JSON config for name terms/ignores
- --fail-on-findings with documented exit codes (0/1/2/3/130)
- deterministic output across runs and input order
Tests: 138 unittest cases incl. HAR parsing, redaction, format stability,
malformed input, and safety (import allow-list, no sockets, values never
opened as files). README rewritten for Kali usage and rule tables.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
---
README.md | 701 +++++++++-------
path_detector.py | 1200 +--------------------------
pathscope/__init__.py | 43 +
pathscope/__main__.py | 10 +
pathscope/cli.py | 414 ++++++++++
pathscope/config.py | 183 +++++
pathscope/detector.py | 224 +++++
pathscope/heuristics.py | 540 +++++++++++++
pathscope/report.py | 349 ++++++++
pathscope/sources.py | 577 +++++++++++++
pathscope/textutil.py | 109 +++
tests/test_path_detector.py | 1527 ++++++++++++++++++++++++-----------
12 files changed, 3913 insertions(+), 1964 deletions(-)
create mode 100644 pathscope/__init__.py
create mode 100644 pathscope/__main__.py
create mode 100644 pathscope/cli.py
create mode 100644 pathscope/config.py
create mode 100644 pathscope/detector.py
create mode 100644 pathscope/heuristics.py
create mode 100644 pathscope/report.py
create mode 100644 pathscope/sources.py
create mode 100644 pathscope/textutil.py
diff --git a/README.md b/README.md
index 77eebb4..49c04ab 100644
--- a/README.md
+++ b/README.md
@@ -1,11 +1,11 @@
-
+
# PathScope
-**Passive URL-parameter triage for path-like parameters.**
-Point it at URLs you are allowed to review, and it tells you which query parameters *look* like they might be about files or paths — so you can decide what deserves a manual look.
+**Passive, offline triage of URL and request parameters that may be worth
+reviewing for path-traversal risk.**
[](https://www.python.org/)
[](#requirements)
@@ -20,387 +20,481 @@ Point it at URLs you are allowed to review, and it tells you which query paramet
---
-> **PathScope results are candidates for manual review — never confirmed vulnerabilities.**
-> A flag means "the wording or existing value of this parameter looks path-related".
-> It does **not** mean a parameter is exploitable, reachable, or even used by the application.
+> **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.
---
-## Why this exists
-
-URL parameters such as `?file=`, `?page=`, `?template=` or `?download=` are the usual starting
-points when reviewing an application for path-handling issues. Most of the noise in that review
-comes from deciding *which* parameters are worth looking at first.
-
-PathScope does that first pass for you — **statically, offline, and without touching the target.**
-It reads URLs you already have, parses them locally, and produces a short, ranked list of
-parameters that mention paths/files in their names, or whose *existing* values already contain
-path-like patterns.
-
-It is deliberately boring: no payloads, no requests, no clever stuff.
+## Table of contents
+
+1. [What it does](#what-it-does)
+2. [Safety model](#safety-model)
+3. [Requirements](#requirements)
+4. [Installation on Kali Linux](#installation-on-kali-linux)
+5. [Inputs](#inputs)
+6. [Quick start](#quick-start)
+7. [Reports: text, JSON, CSV, SARIF](#reports-text-json-csv-sarif)
+8. [Exit codes](#exit-codes)
+9. [Detection rules](#detection-rules)
+10. [Configuration file](#configuration-file)
+11. [Tests](#tests)
+12. [Project layout](#project-layout)
+13. [Limitations](#limitations)
+14. [FAQ](#faq)
+15. [Authorization and legal](#authorization-and-legal)
---
-## Safety statement
+## What it does
+
+Given URLs or a HAR capture **you already have**, PathScope:
-PathScope is **passive by design**. It:
+* 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.
-- ✅ only analyzes URLs **you explicitly provide** (`--url`, `-i/--input`, or stdin);
-- ✅ parses everything **locally** with `urllib.parse` and regular expressions;
-- ❌ makes **no HTTP/HTTPS requests**, and **no DNS lookups**;
-- ❌ does **not crawl**, scan, fingerprint, or enumerate anything;
-- ❌ does **not generate, inject, or send test values**;
-- ❌ does **not open, read, or resolve any file or resource named in a URL parameter**;
-- ❌ does **not require root** (or `sudo`, or any elevated capability);
-- ❌ has **no third-party dependencies**, so nothing is installed from PyPI.
+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.
-> **Authorization:** Only analyze URLs you are authorized to review (your own applications, an
-> engagement with signed scope, a lab, a CTF you are permitted to work on, or a bug-bounty
-> program that allows it). If you are not sure, ask the asset owner first. Analyzing a URL is
-> harmless, but acting on what you find may not be — check your scope before testing anything.
+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.
---
-## Features
-
-- **Three input modes** — a single URL, a file of URLs, or piped stdin. Sources can be combined.
-- **Robust local parsing** — repeated parameters (`?file=a&file=b`), URL-encoded names
- (`?%66%69%6c%65=`) and values, blank values, keys without `=`, IPv6 hosts and custom ports.
-- **Transparent heuristics** — readable keyword tables and weighted rules in a single file, easy
- to tune for your application or threat model.
-- **Values hidden by default** — output shows `file=`, and any `user:pass@` in a URL is
- masked as `@`; use `--show-values` only when you want values on screen (or in logs).
-- **Plain-text output that works when piped** — ANSI colour is used only when stdout is a real
- terminal. `NO_COLOR` and `--no-color` are honoured.
-- **JSON output** (`--json`) for pipelines, reports and dashboards.
-- **Graceful failure** — unreadable files, malformed URLs and malformed lines are reported, not
- fatal; duplicates are de-duplicated; blank lines and `#` comments are skipped.
-- **Useful exit codes** and a complete `--help`.
-- **Tests included** — 97 unit and end-to-end tests, including checks that prove no network
- modules are imported and no sockets are used.
+## 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
-| Requirement | Detail |
+| | |
|---|---|
-| Python | 3.7 or newer (tested on 3.11; Kali ships 3.11+) |
+| Python | 3.7 or newer (developed and tested on Python 3.11, which Kali ships) |
| Packages | **none** — standard library only |
| Privileges | ordinary user; **root is not required** |
-| Network | not used |
-
-PathScope is developed and tested on Kali Linux and runs on any Linux, macOS or Windows system
-with Python 3.7+ (the test suite is executed on Python 3.11).
+| Network | **never used** |
---
-## Installation (Kali Linux)
+## Installation on Kali Linux
-Kali already ships Python 3.11, so there is nothing to install. Clone or copy the files and go:
+Kali ships Python 3.11; there is nothing to install.
```bash
-# 1. Get the files (git clone, or copy the folder over)
git clone https://github.com/mrdineshpathro/pathscope.git
cd pathscope
-# 2. Confirm Python
-python3 --version
-
-# 3. Make it executable (optional) and run it
+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
```
-Prefer a command on your `PATH`?
+Optional: put it on your `PATH` without root.
```bash
-# Option A: a symlink (no sudo needed if ~/.local/bin is on your PATH)
mkdir -p ~/.local/bin
ln -sf "$PWD/path_detector.py" ~/.local/bin/pathscope
-pathscope --url 'https://example.test/view?file=report.pdf'
+pathscope --version
+```
-# Option B: an alias for the current shell
-echo "alias pathscope='python3 $PWD/path_detector.py'" >> ~/.zshrc
-source ~/.zshrc # Kali's default shell is zsh; use ~/.bashrc for bash
+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
```
-> Kali's default user is `kali`. Nothing here needs `sudo`; if a command fails, fix permissions
-> in your home directory rather than escalating.
+> 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**. |
+| stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. |
+
+### Input format
+
+* `--format auto` (default) — HAR if the file ends in `.har`/`.har.json` or the
+ JSON starts with a `log.entries` object; otherwise a URL list.
+* `--format har` — force HAR.
+* `--format urls` — force a URL list.
+* `--input-format {auto,urls,har}` — same selectors under an unambiguous name.
+
+`--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
-# Analyse one URL
+# 1. A single URL
python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
-# Analyse a file of URLs (one per line)
+# 2. A URL list (one per line)
python3 path_detector.py -i urls.txt
-# Analyse URLs piped on stdin
+# 3. Piped stdin
cat urls.txt | python3 path_detector.py
-# See the existing values too (hidden by default)
-python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values
+# 4. A local HAR capture (auto-detected)
+python3 path_detector.py -i capture.har
-# Machine-readable output for a report pipeline
-python3 path_detector.py -i urls.txt --json > findings.json
+# 5. HAR with JSON output for a report pipeline
+python3 path_detector.py -i capture.har --format json > candidates.json
-# Combine several URL files
-python3 path_detector.py -i day1.txt -i day2.txt
+# 6. Show existing values (they may contain secrets — be careful)
+python3 path_detector.py --url 'https://example.test/view?file=report.pdf' --show-values
-# Lower the threshold to surface weaker signals
-python3 path_detector.py -i urls.txt --min-score 20
+# 7. Ignore noisy parameters, in CI
+python3 path_detector.py -i urls.txt --ignore-param image --ignore-param avatar \
+ --fail-on-findings
```
-> **Quote your URLs** when they contain `&`, otherwise your shell will split them into background
-> jobs. Single quotes are safest: `--url 'https://host/p?a=1&b=2'`.
-
-### Example session
+Example terminal output (values hidden):
```console
-$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf&lang=en&page=2'
-PathScope 1.0.0 - passive URL-parameter triage
+$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+PathScope 2.0.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: this tool never proves a vulnerability.
-No network requests are made. Only analyze URLs you are authorized to review.
+Candidates for manual review only. No network requests are made; only analyze data you are authorized to review.
-Candidates for manual review
-================================================================
-Analyzed 1 URL(s) and 3 distinct parameter(s); 2 candidate(s) at score >= 30.
+PathScope candidates for manual review
+====================================================================================
+Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25.
-#1 file [MEDIUM score 55/100]
- Host example.test
- URL https://example.test/view?file=&lang=&page=
- Parameter file
- Value
- Why flagged
- - name contains path-related keyword 'file' (name score +35)
- - value ends with a file-like extension '.pdf' (+20)
-
-#2 page [LOW score 30/100]
+#1 file [MEDIUM score 43/100]
Host example.test
- URL https://example.test/view?file=&lang=&page=
- Parameter page
- Value
- Why flagged
- - name contains path-related keyword 'page' (name score +30)
+ Source url (--url)
+ Request GET https://example.test/view
+ Location query
+ Rule name-exact
+ Value (use --show-values to display)
+ Why rule(s) 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.
+```
-Reminder: candidates for manual review, not confirmed vulnerabilities. No requests were sent and no input was injected.
-Values are hidden by default (use --show-values to display them).
+---
-Done: 1 URL(s), 2 candidate(s), 0 line(s) skipped.
-```
+## Reports: text, JSON, CSV, SARIF
-*(At the default `--min-score 30` both entries are reported; raise it, e.g. `--min-score 50`,
-if you only want stronger signals such as `file` here.)*
+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`)
-## Command-line reference
+```json
+{
+ "tool": "PathScope",
+ "version": "2.0.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"]
+ },
+ "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
+ }
+ ],
+ "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`:
```
-python3 path_detector.py [-h] [--version] [--url URL] [-i FILE] [--json]
- [--show-values] [--no-color] [--no-banner]
- [--min-score N] [--strict] [--fail-on-none]
+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,
```
-### Input (sources are merged and de-duplicated)
+### SARIF 2.1.0 (`--format sarif`)
-| Option | Description |
-|---|---|
-| `--url URL` | Analyze one URL. Repeat the flag to add more. Values starting with `-` are safe. |
-| `-i, --input FILE` | Read one URL per line from `FILE`; repeat the flag to read several files. Blank lines and lines starting with `#` are skipped. Use `-` to read stdin explicitly. |
-| *(stdin)* | Used automatically when neither `--url` nor `--input` is given, e.g. `cat urls.txt \| python3 path_detector.py`. |
+Produces a valid SARIF log for GitHub code scanning or any SARIF viewer:
+one `run`, a deterministic rule catalogue, `ruleIndex` values that match the
+catalogue, `level` mapped from confidence (`warning`/`note`), and a `properties`
+bag with the score, reasons and location. Values are omitted unless
+`--show-values`.
-### Output
+### Text (`--format text`, default)
-| Option | Description |
-|---|---|
-| `--json` | Print a single JSON document on stdout. The banner and warnings go to stderr, so `> out.json` stays clean. |
-| `--show-values` | Reveal the existing parameter values. Off by default; URLs are shown with `=` masking. |
-| `--no-color` | Disable ANSI colour even on a terminal. Colour is automatically off when piped, and `NO_COLOR` is respected. |
-| `--no-banner` | Suppress the startup banner (the banner is printed to **stderr**, not stdout). |
+Human-readable blocks with the rule, evidence lines and a reminder that these
+are candidates. Colour (ANSI) is used **only** when stdout is an interactive
+terminal; pipes, files and CI logs get plain text. `--no-color` and the
+`NO_COLOR` environment variable both disable colour explicitly.
-### Heuristics and behaviour
+### Warnings
-| Option | Description |
-|---|---|
-| `--min-score N` | Report parameters with a combined score of at least `N` (0–100, default **30**). |
-| `--strict` | Exit `1` if any input line was skipped (malformed URL etc.). |
-| `--fail-on-none` | Exit `3` when no candidates were flagged — handy in CI. |
-| `-h, --help` | Full help, including examples, exit codes and the project links. |
-| `--version` | Print `PathScope ` and exit. |
+Recoverable input problems (malformed URL on line 7, unreadable HAR entry,
+truncated JSON body) are printed to **stderr** as `warning:` lines, counted in
+the summary, and never abort the run. `-q/--quiet` silences them and the
+stderr summary; JSON/CSV/SARIF on stdout stay valid.
+
+---
-### Exit codes
+## Exit codes
| Code | Meaning |
|---|---|
-| `0` | Analysis completed. Malformed input lines are reported as warnings but are not fatal. |
-| `1` | `--strict` was given and at least one input line was malformed/skipped. |
-| `2` | Usage error (bad flags), no usable URLs, or an unreadable input file. |
-| `3` | No candidates were flagged (only with `--fail-on-none`). |
+| `0` | Analysis completed. No candidates (or candidates found without `--fail-on-findings`). |
+| `1` | Analysis completed **and** candidates were found, with `--fail-on-findings`. |
+| `2` | Usage error, unreadable/malformed input file, invalid configuration, or no usable input. |
+| `3` | Internal error while producing a report (never a crash trace). |
| `130` | Interrupted with `Ctrl-C`. |
----
-
-## How scoring works
+`--fail-on-findings` is designed for CI: `0` means “nothing to look at”, `1` means
+“somebody should read this report”. It never redefines `2`.
-PathScope combines two independent signals, then clamps the result to **0–100**:
+---
-```
-score = clamp(name_score + value_score + generic_bonus, 0, 100)
-```
+## Detection rules
-### 1. Name score — 0–50
+A parameter’s score is the sum of the weights of the rules that fired, clamped
+to `0–100`. Names and values are evaluated independently and then combined.
+All rules live in `pathscope/heuristics.py` and are safe to edit.
-The parameter name is split into lowercase tokens (`fileName` → `file`,`name`;
-`user-file_path` → `user`,`file`,`path`), and each token is looked up in `NAME_KEYWORDS`
-in [`path_detector.py`](path_detector.py):
+### Name rules (`pathscope.heuristics.analyze_name`)
-| Weight | Example keywords |
-|---|---|
-| 30–35 | `file`, `filename`, `filepath`, `path`, `download`, `dir`, `folder`, `template`, `include`, `page`, `basedir` |
-| 20–29 | `view`, `layout`, `theme`, `src`, `url`, `uri`, `document`, `config`, `log`, `render`, `doc`, `pg` |
-| 10–19 | `dl`, `link`, `inc`, `data`, `mount`, `root`, `action` |
+| Rule | Weight | Fires when |
+|---|---|---|
+| `name-exact` | +35 (+5 multiword) | a token is a path term: `file`, `filepath`, `document`, `download`, `attachment`, `path`, `dir`, `folder`, `base_path`, `template`, `include`, `page`, `view`, `layout`, `config`, `log`, `script`, `resource`, `asset`, `storage`, `locale`, … |
+| `name-custom` | +30 | a token matches a term from `--config` `name_terms` |
+| `name-compound` | +35 | the whole name is a known compound without separators (`filepath`) |
+| `name-prefix` | +28 | the name starts with a path term (`filedata`) |
+| `name-suffix` | +23 | the name ends with a path term (`resolvepath`) |
+| `name-weak` | +5 | multiword name without a path term — never enough on its own |
+| `name-generic` | 0 | generic names (`image`, `img`, `target`, `ref`, `avatar`, …) only count *with* a path-like value |
-- **Exact token** → full weight, plus `+5` when the name has multiple tokens
- (e.g. `download_file`).
-- **Prefix/suffix of the joined name** → discounted weight, so `filedata` still scores but
- `profile` (ends in `file`) does not.
-- **Weak shapes only** → `+10` for a multi-word name with no keyword, `+5` for a very long name.
-- **Generic names** (`image`, `target`, `ref`, `site`, `avatar`, …) score **0 alone** and can only
- contribute through the rule below.
+`utm_source`, `gclid`, `page_size`, `urlencoded`, `landscape`, `sort` and similar
+ordinary names do not produce findings.
-### 2. Value score — 0–50
+### Value rules (`pathscope.heuristics.analyze_value`)
-Only values that are **already present** in the URL are inspected — PathScope never generates
-one. Each piece of evidence is counted once, even if the value is encoded and decoded forms
-overlap.
+Values are decoded up to `--max-decode-passes` times (default **3**, hard max **5**)
+with malformed escapes left intact. Traversal is matched as a **path segment**,
+so `report..pdf` or `v1..2` never match.
-| Weight | Evidence in the existing value |
+| Rule | Weight | Example value |
+|---|---|---|
+| `value-traversal` | +30 | `../../etc/passwd`, `..\..\win.ini`, bare `..` |
+| `value-encoded-traversal` | +15 | `%2e%2e%2f`, `..%2f`, `%252e%252e%252f` |
+| `value-encoded-slash` | +12 | `%2f`, `%5c` |
+| `value-double-encoded` | +10 | value needed ≥2 decoding passes |
+| `value-absolute` | +12 | `/var/www/html` (not `//cdn`) |
+| `value-windows-drive` | +15 | `C:\Windows\win.ini`, `D:/data` |
+| `value-unc` | +15 | `\\server\share\x` |
+| `value-multi-segment` | +6 | three or more separators |
+| `value-extension` | +8 | `.pdf`, `.php`, `.tar.gz` on a path-like value |
+| `value-path-list` | +5 | `a.css;b.css` |
+| `value-full-url` | −10 | `https://other.test/x` (usually a redirect target) |
+| `value-pairs-with-generic-name` | +10 | `image=/static/logo.png` |
+
+### Confidence bands (heuristic, not exploitability)
+
+| Score | Label |
|---|---|
-| +25 | Parent-directory sequence `../` or `..\` |
-| +20 | URL-encoded `..` (`%2e%2e`), or a known file extension (`.pdf`, `.log`, `.tar.gz`, …) |
-| +15 | Encoded slash/backslash (`%2f`, `%5c`), null byte (`%00`), or `/etc` reference |
-| +12–15 | Two or more path separators |
-| +8–10 | One separator, Windows drive path (`C:\…`), `..` / `./` segment, double encoding |
-| +5 | Value starts with `/` (absolute-looking) |
-| −10 | Value is a full URL (`https://…`), which is usually a redirect target, not a path |
+| 70–100 | `high` |
+| 40–69 | `medium` |
+| 0–39 | `low` |
-### 3. Generic bonus — 0–10
+The default threshold is **25** (`--min-score`). Recommended interpretation:
+read `high` and `medium` first, `low` only when you have time. A score is a
+reading priority, never a risk rating.
-Names like `image`, `avatar` or `target` are only interesting when the existing value is
-path-like (e.g. `?image=/static/logo.png`). In that case `+10` is added; otherwise the
-parameter is ignored entirely. This keeps ordinary tracking parameters out of the report.
+### Tuning
-### Interpretation bands
+* Add project-specific vocabulary: `--config` `name_terms` (literal strings only).
+* Silence known-noisy names: `--ignore-param NAME` (repeatable) or `--config`
+ `ignore_params`.
+* Change the vocabulary permanently by editing `PATH_NAME_TERMS`,
+ `GENERIC_NAME_TERMS`, `FILE_EXTENSIONS` or the weights in `heuristics.py`;
+ the tests exercise these tables.
-| Score | Band | Suggested reading |
-|---|---|---|
-| 70–100 | `HIGH` | Strong textual match — review this parameter first. |
-| 50–69 | `MEDIUM` | Likely relevant; confirm it is actually used by the app. |
-| 30–49 | `LOW` | Weak signal; review only if time allows or scope demands it. |
+---
-**None of these bands imply exploitability.** They rank reading order, nothing more.
+## Command-line reference
-### Tuning
+```
+python3 path_detector.py [-h] [--version] [--url URL] [-i FILE]
+ [--format {auto,urls,har,text,json,csv,sarif}]
+ [--input-format {auto,urls,har}]
+ [--output-format {text,json,csv,sarif}] [--json]
+ [--show-values] [--no-color] [--no-banner] [-q]
+ [--ignore-param NAME] [--config FILE]
+ [--min-score N] [--max-decode-passes N]
+ [--fail-on-findings]
+```
-All tables and weights live at the top of `path_detector.py` (`NAME_KEYWORDS`,
-`GENERIC_NAMES`, `FILE_EXTENSIONS`, and the weights inside `analyze_name` / `analyze_value`).
-Add your application's own vocabulary (`?shop=`, `?cms_module=`, `?f=`) or drop keywords
-that are noisy for you — it is a single editable file, and the tests still apply.
+| Option | Description |
+|---|---|
+| `--url URL` | URL to analyze; repeatable. |
+| `-i, --input FILE` | URL list or HAR file; repeatable; `-` reads stdin. |
+| `--format FMT` | Input selector (`har`, `urls`, `auto`) **or** output format (`text`, `json`, `csv`, `sarif`). |
+| `--input-format FMT` | Explicit input selector when `--format` is used for output. |
+| `--output-format FMT` | Report format (same as `--format json` etc.). |
+| `--json` | Shorthand for `--output-format json`. |
+| `--show-values` | Reveal parameter values (hidden by default). |
+| `--ignore-param NAME` | Ignore a parameter name; repeatable. |
+| `--config FILE` | JSON configuration (see below). |
+| `--min-score N` | Reporting threshold, 0–100 (default 25). |
+| `--max-decode-passes N` | Percent-decoding passes per value, 0–5 (default 3). |
+| `--fail-on-findings` | Exit `1` when candidates exist. |
+| `-q, --quiet` | Suppress warnings and the stderr summary. |
+| `--no-color` | Disable colour on terminals. |
+| `--no-banner` | Suppress the startup banner. |
+| `-h, --help` / `--version` | Help / version and exit. |
---
-## JSON output
+## Configuration file
+
+A small JSON file, validated strictly. Unknown keys, wrong types, values out of
+range, and anything that looks like a regular expression are rejected with a
+clear error and exit code `2`.
```json
{
- "tool": "PathScope",
- "version": "1.0.0",
- "disclaimer": "Candidates for manual review only. PathScope is passive: it makes no network requests, injects no values, and never confirms vulnerabilities.",
- "min_score": 30,
- "show_values": false,
- "summary": {
- "urls_analyzed": 1,
- "parameters_analyzed": 3,
- "candidates": 1,
- "skipped_lines": 0
- },
- "findings": [
- {
- "index": 1,
- "host": "example.test",
- "parameter": "file",
- "url": "https://example.test/view?file=&lang=",
- "value": null,
- "occurrences": 1,
- "score": 55,
- "band": "MEDIUM",
- "reasons": [
- "name contains path-related keyword 'file' (name score +35)",
- "value ends with a file-like extension '.pdf' (+20)"
- ]
- }
- ],
- "links": {
- "github": "https://github.com/mrdineshpathro",
- "instagram": "https://www.instagram.com/mr_dineshpatro",
- "support": "https://buymeacoffee.com/mrdineshpathro"
- }
+ "name_terms": ["download", "media_file", "cdn_blob"],
+ "ignore_params": ["image", "avatar"],
+ "min_score": 25,
+ "max_decode_passes": 3,
+ "show_values": false
}
```
-With `--show-values`, `value` contains the existing value and `url` is left unmasked.
+| Key | Type | Rules |
+|---|---|---|
+| `name_terms` | array of strings | 2–48 chars, letters/digits/`_`/`-` only, max 200 entries |
+| `ignore_params` | array of strings | same rules |
+| `min_score` | integer | 0–100 |
+| `max_decode_passes` | integer | 0–5 |
+| `show_values` | boolean | defaults values to visible; `--show-values` also works |
+
+```bash
+python3 path_detector.py --config pathscope.json -i urls.txt
+```
+
+Regular expressions are deliberately unsupported: they add a
+catastrophic-backtracking risk to a passive tool and make results harder to
+explain. Literal terms keep every finding traceable to a readable rule.
---
## Tests
-The suite uses only `unittest` (standard library) and runs fully offline:
+The suite uses only `unittest` and runs fully offline.
```bash
-# From the repository root
python3 -m unittest discover -s tests -v
-
-# Or run the file directly
+# or directly
python3 tests/test_path_detector.py
```
-What is covered:
-
-- tokenising names (`snake_case`, `kebab-case`, `camelCase`, `PascalCase`);
-- keyword, prefix/suffix and weak-name scoring; generic-name rules;
-- value scoring: extensions, traversal, encoded and double-encoded forms, Windows paths,
- absolute paths, full-URL penalty, and the "count each evidence once" rule;
-- URL validation (schemes, ports, IPv6, whitespace, malformed input);
-- repeated and encoded parameters, merging, sorting, masking;
-- input handling: blank lines, comments, duplicates, BOM, unreadable files;
-- CLI end-to-end: banner links, `--help`, `--version`, `--json`, `--show-values`,
- `--strict`, `--fail-on-none`, exit codes, no ANSI codes when piped;
-- **safety:** the module imports only an allow-list of standard-library modules, defines no
- root-related calls, and performs no socket operations while analysing URLs.
-
----
-
-## Limitations (read these)
+138 tests cover exactly the behaviours this tool promises:
-- **It is a triage aid, not a scanner.** PathScope reads strings. It cannot tell whether a
- parameter is used by the server, validated, ignored, or routed through a WAF.
-- **Names and values can lie.** A parameter called `file` may be a harmless enum; a parameter
- called `x` may be the actual file handler. Treat the output as a reading order, not an answer.
-- **Only query parameters are analysed.** Path segments, JSON bodies, headers and cookies are
- out of scope by design.
-- **Encodings beyond normal URL encoding** (e.g. UTF-16 percent-encoding, overlong UTF-8) are
- not decoded, because decoding them would mean guessing at values.
-- **No persistence.** PathScope writes nothing to disk; redirect stdout if you need a report.
-- **Not a vulnerability verdict.** A human must verify anything before it is called a finding.
+| Area | What is asserted |
+|---|---|
+| Query parsing | repeated parameters, occurrence counters, encoded names/values, `+` in names, blank values, encoded `&`/`=`, IPv6 hosts |
+| Value heuristics | literal/encoded/partially-encoded/double-encoded traversal, bounded decoding, segment-only matching (`report..pdf` does not match), Windows/UNC/absolute paths, full-URL penalty, malformed `%` sequences |
+| Name heuristics | snake_case/kebab-case/camelCase, exact/compound/prefix/suffix/custom terms, generic names, ordinary names produce nothing |
+| HAR | query, form (`postData.params` and urlencoded `text`), JSON bodies with arrays, duplicate entries, malformed entries, missing `log`, invalid JSON, BOM, version warnings |
+| Malformed input | unreadable files, directories, binary data, oversized values, control characters |
+| Redaction | values hidden by default in every format, `--show-values` reveals them, credentials masked |
+| Formats | stable JSON/CSV/SARIF, SARIF `ruleIndex` consistency, CSV columns, deterministic ordering |
+| Safety | import allow-list, no socket use (patched to raise), values never passed to `open`, no root/shell calls |
---
@@ -408,50 +502,83 @@ What is covered:
```
pathscope/
-├── path_detector.py # the tool (standard library only)
-├── tests/
-│ └── test_path_detector.py # unittest suite (offline)
-├── assets/
-│ └── logo.svg # original repository icon (route + magnifier)
+├── path_detector.py # executable entry point (thin wrapper)
+├── pathscope/
+│ ├── __init__.py # name, version, branding constants
+│ ├── textutil.py # decoding (bounded), sanitising, truncation
+│ ├── heuristics.py # name/value rules and scoring
+│ ├── sources.py # URL, list, stdin and HAR 1.2 parsing
+│ ├── detector.py # request → findings (no I/O)
+│ ├── report.py # text, JSON, CSV, SARIF renderers, banner
+│ ├── config.py # strict JSON configuration validation
+│ ├── cli.py # argument parsing, input merging, exit codes
+│ └── __main__.py # enables `python3 -m pathscope`
+├── tests/test_path_detector.py # unittest suite (offline)
+├── assets/logo.svg # original PathScope mark (route + magnifier)
├── README.md
└── LICENSE
```
+Data flow: `sources` (parse, warn) → `detector` (score, rank) → `report`
+(render). The detector has no I/O and is trivially testable.
+
+---
+
+## Limitations
+
+* **Heuristic only.** Names and values can be misleading; a parameter called
+ `file` may be an enum, and the real handler may be called `x`.
+* **Query, form and JSON bodies only.** Path segments, headers, cookies and
+ multipart file *content* are out of scope.
+* **No verification.** PathScope never checks whether the server uses, validates
+ or blocks the parameter. That requires an authorized, separate test.
+* **Encoding depth is bounded.** Three passes by default; deeper nesting is
+ reported only as `value-double-encoded`.
+* **No persistence.** Nothing is written to disk; redirect stdout if you need a
+ report file.
+* **Not a risk rating.** Scores order reading, not severity. Do not publish them
+ as vulnerability ratings.
+
---
## FAQ
-**Does PathScope send anything to the URLs?**
-No. There is no socket code in the tool. A test asserts that no network modules are imported and
-that analysis works with socket functions patched to raise.
+**Does it send anything?**
+No. The package contains no networking imports; a test asserts the import
+allow-list and another runs analysis with socket functions patched to raise.
**Why are values hidden by default?**
-URLs in bug-bounty reports, tickets and shell history routinely contain tokens, session IDs and
-personal data. Masking by default makes it hard to leak them by accident; `--show-values`
-is an explicit decision.
+URLs and HAR captures routinely contain session tokens and personal data.
+Masking by default makes accidental disclosure in tickets or CI logs much harder.
+`--show-values` is a deliberate choice, and even then query strings of the URL
+itself are never printed — only the specific parameter you asked to see.
+
+**How do I use it in CI?**
+`python3 path_detector.py -i capture.har --format sarif --fail-on-findings > pathscope.sarif`
+then upload the SARIF file. Exit `0` = nothing flagged, `1` = candidates found.
-**Can I use it in CI?**
-Yes: `python3 path_detector.py -i urls.txt --json --fail-on-none` exits `3` when nothing
-path-like is found, which you can map to a warning, and `--strict` exits `1` on malformed input.
+**Can HAR replay send requests?**
+No. PathScope only reads `log.entries[].request.url`, `queryString` and
+`postData`. No `curl`, no `requests`, no sockets.
-**Does it need root on Kali?**
-No. Every code path runs as your normal user; nothing binds a port, changes interface state, or
-reads privileged files.
+**Which Python versions work?**
+3.7+. The code avoids 3.8+ syntax; CI was run on 3.11 (Kali default).
-**Will it find all path-like parameters?**
-No. It finds parameters whose names or existing values match the heuristics. Parameters that
-never carry a path-like value and have neutral names will not be flagged — that is by design,
-to keep the report readable.
+**Why not regex configuration?**
+ReDoS risk and explainability. Literal terms are validated and predictable.
---
-## Legal
+## Authorization and legal
+
+PathScope is a **defensive triage aid** for authorized security review,
+education and engineering. Only analyze URLs, files and HAR captures you are
+authorized to review. If a system is not yours, confirm scope in writing before
+you analyze data from it — and remember that a finding here is a reason to look,
+not a license to test.
-PathScope is provided for **authorized security review, education and defensive engineering**.
-Only analyze URLs you have permission to review, and always confirm scope in writing for
-third-party systems. The results are heuristic candidates for manual review, not a statement
-about the security of any system. See [LICENSE](LICENSE) (MIT) — the software is provided
-"as is", without warranty of any kind.
+Provided under the MIT License (see [LICENSE](LICENSE)), without warranty of any
+kind.
---
diff --git a/path_detector.py b/path_detector.py
index 85823b5..fa4fbf1 100755
--- a/path_detector.py
+++ b/path_detector.py
@@ -1,1201 +1,27 @@
#!/usr/bin/env python3
-"""PathScope - passive URL-parameter triage for path-like parameters.
+"""PathScope - convenient executable entry point.
-PathScope reads URLs that *you* provide and highlights query parameters whose
-names or existing values look as though they might relate to file paths.
-Every result is a **candidate for manual review**, never a confirmed
-vulnerability.
+Examples:
+ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
+ python3 path_detector.py -i urls.txt
+ python3 path_detector.py -i capture.har --format json
+ cat urls.txt | python3 path_detector.py --format sarif
-Safety model (by design, not by configuration):
- * No HTTP requests, no DNS lookups, no crawling, no scanning.
- * No test payloads are generated and nothing is sent anywhere.
- * No file or resource named in a parameter is opened or resolved.
- * No root privileges are used or required.
- * Standard library only, so there is nothing to install with pip.
-
-Exit codes:
- 0 analysis completed normally (malformed lines are warned about)
- 1 --strict was given and at least one input line was skipped
- 2 usage error, unreadable input file, or no usable URLs
- 3 no candidates were flagged (only with --fail-on-none)
- 130 interrupted with Ctrl-C
-
-Usage:
- python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
- python3 path_detector.py -i urls.txt
- cat urls.txt | python3 path_detector.py
+This wrapper only adds the project directory to ``sys.path`` so the tool runs
+from a fresh checkout without installation. All logic lives in ``pathscope/``.
"""
from __future__ import annotations
-import argparse
-import json
import os
-import re
import sys
-import unicodedata
-from collections import OrderedDict
-from dataclasses import dataclass, field
-from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple
-from urllib.parse import unquote, unquote_plus, urlsplit, urlunsplit
-
-__version__ = "1.0.0"
-PROGRAM = "PathScope"
-
-# ---------------------------------------------------------------------------
-# Banner. These links are printed exactly as given. They are never opened and
-# never contacted; PathScope makes no network requests of any kind.
-# ---------------------------------------------------------------------------
-GITHUB_URL = "https://github.com/mrdineshpathro"
-INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro"
-SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro"
-
-BANNER_LINKS: Tuple[Tuple[str, str], ...] = (
- ("GitHub", GITHUB_URL),
- ("Instagram", INSTAGRAM_URL),
- ("Support", SUPPORT_URL),
-)
-BANNER_DISCLAIMER = (
- "Candidates for manual review only: this tool never proves a vulnerability.",
- "No network requests are made. Only analyze URLs you are authorized to review.",
-)
-
-EXIT_OK = 0
-EXIT_STRICT_SKIPS = 1
-EXIT_USAGE = 2
-EXIT_NO_CANDIDATES = 3
-EXIT_INTERRUPTED = 130
-
-# ---------------------------------------------------------------------------
-# Heuristics. Everything below is deliberately plain and easy to edit.
-#
-# Final score = clamp(name_score + value_score + generic_bonus, 0, 100)
-# * name_score 0-50 from NAME_KEYWORDS / weak name shapes
-# * value_score 0-50 from existing values only (never generated)
-# * generic_bonus 0-10 for generic names (image, target, ...) whose value
-# is path-like; generic names never score alone.
-# A parameter is reported when the final score >= --min-score (default 30).
-# ---------------------------------------------------------------------------
-
-NAME_KEYWORDS: Dict[str, int] = {
- # files / downloads
- "file": 35,
- "filename": 35,
- "file_name": 35,
- "filepath": 35,
- "file_path": 35,
- "document": 25,
- "doc": 20,
- "download": 35,
- "dl": 15,
- "attachment": 30,
- "upload": 25,
- "export": 25,
- "import": 15,
- "archive": 20,
- "backup": 20,
- # paths / directories
- "path": 35,
- "dir": 30,
- "directory": 30,
- "folder": 30,
- "root": 15,
- "base": 15,
- "basedir": 30,
- "base_dir": 30,
- "basepath": 30,
- "base_path": 30,
- "uri": 20,
- "url": 20,
- "link": 15,
- "dest": 20,
- "destination": 20,
- "source": 20,
- "src": 20,
- "resource": 20,
- "asset": 20,
- "media": 20,
- "storage": 20,
- "mount": 15,
- # pages / templates / includes / views
- "page": 30,
- "pg": 20,
- "view": 20,
- "display": 15,
- "screen": 10,
- "layout": 20,
- "theme": 20,
- "tpl": 30,
- "template": 30,
- "include": 30,
- "inc": 15,
- "viewfile": 30,
- "view_file": 30,
- "load": 20,
- "action": 15,
- "module": 15,
- # code / config / logs / data files
- "script": 25,
- "lang": 20,
- "language": 15,
- "locale": 15,
- "translation": 15,
- "config": 20,
- "conf": 20,
- "settings": 15,
- "log": 20,
- "logfile": 30,
- "log_file": 30,
- "stylesheet": 30,
- "css": 15,
- "js": 15,
- "style": 15,
- "data": 10,
- "db": 15,
- "database": 15,
- "report": 20,
- "render": 20,
-}
-
-PREFIX_DISCOUNT = 7
-SUFFIX_DISCOUNT = 12
-NAME_CAP = 50
-VALUE_CAP = 50
-GENERIC_BONUS = 10
-
-# Generic names: by themselves they are not path-related, but a path-like
-# existing value makes them worth a look (e.g. image=/static/logo.png).
-GENERIC_NAMES = frozenset(
- {
- "image",
- "img",
- "photo",
- "avatar",
- "target",
- "ref",
- "referer",
- "referrer",
- "site",
- "key",
- "callback",
- "filetarget",
- }
-)
-
-FILE_EXTENSIONS = frozenset(
- """
- apk avi bak bash bat bin bmp bz2 c cgi conf config crt cs csr csv css db
- dll doc docx dot drawio dtd env eot exe flac gif go gz h htm html ico ini
- iso jar java jpeg jpg js json jsx key kt log md mkv mov mp3 mp4 msi odt
- ogg otf pdf pem php phtml plist png ppt pptx ps1 py pyc rar rb rst sh so
- sql svg swf tar tgz tif tiff toml ts tsx txt vhd wav webp woff woff2 xls
- xlsx xml xsd yaml yml zip
- """.split()
-)
-MULTI_EXTENSIONS = ("tar.gz", "tar.bz2", "tar.xz")
-
-WINDOWS_PATH_RE = re.compile(r"^[A-Za-z]:[/\\].+")
-
-COLOR_CODES = {
- "bold": "1",
- "dim": "2",
- "red": "31",
- "green": "32",
- "yellow": "33",
- "blue": "34",
- "magenta": "35",
- "cyan": "36",
- "grey": "90",
-}
-
-
-# ---------------------------------------------------------------------------
-# Small utilities
-# ---------------------------------------------------------------------------
-def sanitize_text(value: str) -> str:
- """NFC-normalise text and drop control characters (keeps output terminal-safe)."""
- normalized = unicodedata.normalize("NFC", value)
- return "".join(ch for ch in normalized if unicodedata.category(ch)[0] != "C")
-
-
-def truncate(text: str, limit: int = 160) -> str:
- if len(text) <= limit:
- return text
- return text[: max(0, limit - 1)] + "\u2026"
-
-
-def normalize_name(name: str) -> str:
- """Lowercase a parameter name and unify separators: 'userId' stays camel-ish."""
- return name.strip().lower().replace("-", "_").replace(" ", "_")
-
-
-def tokenize_name(name: str) -> List[str]:
- """Split a parameter name into lowercase tokens.
-
- 'fileName' -> ['file', 'name']
- 'user-file_path' -> ['user', 'file', 'path']
- 'FILES' -> ['files']
- """
- parts: List[str] = []
- current = ""
- for char in name:
- if char.isupper() and current and not current[-1].isupper():
- parts.append(current)
- current = char
- else:
- current += char
- if current:
- parts.append(current)
-
- tokens: List[str] = []
- for part in parts:
- for piece in normalize_name(part).split("_"):
- if piece:
- tokens.append(piece)
- return tokens
-
-
-def extension_of(text: str) -> Optional[str]:
- """Return a known file extension at the end of the value, if any."""
- cleaned = text.strip().rstrip(".,;:!?")
- last = re.split(r"[/\\]", cleaned)[-1]
- lowered = last.lower()
- for multi in MULTI_EXTENSIONS:
- if lowered.endswith("." + multi):
- return multi
- if "." not in lowered:
- return None
- candidate = lowered.rsplit(".", 1)[1]
- if candidate in FILE_EXTENSIONS:
- return candidate
- return None
-
-
-# ---------------------------------------------------------------------------
-# Name heuristic
-# ---------------------------------------------------------------------------
-@dataclass(frozen=True)
-class NameAnalysis:
- """Outcome of analysing a parameter name."""
-
- score: int = 0
- reason: Optional[str] = None
- keyword: Optional[str] = None
- generic: bool = False
- weak: bool = False
-
-
-def analyze_name(name: str) -> NameAnalysis:
- """Score a parameter name for path-related meaning (0-50)."""
- tokens = tokenize_name(name)
- joined = "".join(tokens)
-
- best_weight = 0
- best_keyword: Optional[str] = None
-
- # Exact token matches: "file", "path", "dir", ...
- for token in tokens:
- weight = NAME_KEYWORDS.get(token, 0)
- if weight > best_weight:
- best_weight, best_keyword = weight, token
-
- # Compound key matches: "basepath", "viewfile", ...
- if best_weight == 0 and joined:
- weight = NAME_KEYWORDS.get(joined, 0)
- if weight:
- best_weight, best_keyword = weight, joined
-
- # Prefix / suffix matches get a discount: "filedata" yes, "hotfile" only
- # weakly (and not at all at the default threshold).
- if best_weight == 0 and joined:
- for keyword, weight in NAME_KEYWORDS.items():
- if len(keyword) < 4:
- continue
- if joined.startswith(keyword) and weight > PREFIX_DISCOUNT:
- candidate = weight - PREFIX_DISCOUNT
- if candidate > best_weight:
- best_weight, best_keyword = candidate, keyword
- elif joined.endswith(keyword) and weight > SUFFIX_DISCOUNT:
- candidate = weight - SUFFIX_DISCOUNT
- if candidate > best_weight:
- best_weight, best_keyword = candidate, keyword
-
- if best_keyword is not None:
- bonus = 5 if len(tokens) > 1 else 0
- reason = (
- f"name contains path-related keyword '{best_keyword}' "
- f"(name score +{best_weight}{f', +{bonus} for multi-word name' if bonus else ''})"
- )
- return NameAnalysis(
- score=min(NAME_CAP, best_weight + bonus),
- reason=reason,
- keyword=best_keyword,
- )
-
- lowered = normalize_name(name)
- if lowered in GENERIC_NAMES:
- return NameAnalysis(generic=True)
-
- if "_" in lowered or "-" in name:
- return NameAnalysis(
- score=10,
- reason="multi-word name with no obvious path keyword (weak signal, +10)",
- weak=True,
- )
- if len(lowered) > 24:
- return NameAnalysis(
- score=5,
- reason="unusually long parameter name (weak signal, +5)",
- weak=True,
- )
- return NameAnalysis()
-
-
-# ---------------------------------------------------------------------------
-# Value heuristic (existing values only - PathScope never generates input)
-# ---------------------------------------------------------------------------
-@dataclass(frozen=True)
-class ValueAnalysis:
- """Outcome of analysing an existing parameter value."""
-
- score: int = 0
- reasons: Tuple[str, ...] = ()
-
-
-ENCODED_PATH_MARKERS = ("%2e%2e", "%2f", "%5c", "%252e", "%252f")
-
-
-def analyze_value(raw_value: str, decoded: Optional[str] = None) -> ValueAnalysis:
- """Score an existing value for path-like or encoded path-like content (0-50).
-
- ``raw_value`` is exactly what appeared in the URL; ``decoded`` is the
- single-decoded form (passed in by the caller to avoid decoding twice).
- Each piece of evidence is counted once: when the raw value already shows
- encoded path markers, the structural layer is skipped so the same pattern
- is not credited twice.
- """
- if not raw_value and not decoded:
- return ValueAnalysis()
-
- if decoded is None:
- decoded = unquote(raw_value)
- raw_value = raw_value or ""
- decoded = decoded or ""
- lowered_raw = raw_value.lower()
- encoded_path = any(marker in lowered_raw for marker in ENCODED_PATH_MARKERS)
-
- score = 0
- reasons: List[str] = []
- seen = set()
-
- def add(key: str, weight: int, reason: str) -> None:
- nonlocal score
- if key in seen:
- return
- seen.add(key)
- score += weight
- reasons.append(reason)
-
- # 1. Encoding and traversal indicators, evaluated on raw and decoded forms.
- if not encoded_path and ("../" in decoded or "..\\" in decoded):
- add(
- "traversal",
- 25,
- "value contains a parent-directory sequence ('../' or '..\\') (+25)",
- )
- if "%2e%2e" in lowered_raw:
- add("pct-dotdot", 20, "value contains URL-encoded '..' (%2e%2e) (+20)")
- if "%2f" in lowered_raw:
- add("pct-slash", 15, "value contains URL-encoded slash (%2f) (+15)")
- if "%5c" in lowered_raw:
- add("pct-backslash", 15, "value contains URL-encoded backslash (%5c) (+15)")
- if "%00" in lowered_raw:
- add("nul-byte", 15, "value contains a null-byte encoding (%00) (+15)")
- if "%252e" in lowered_raw or "%252f" in lowered_raw:
- add("double-encoded", 10, "value contains double-encoded path characters (+10)")
- if lowered_raw.startswith("/etc") or "/etc/" in lowered_raw:
- add("system-path", 15, "value references a common system path (/etc) (+15)")
- if "\\windows\\" in lowered_raw:
- add("windows-dir", 10, "value references a Windows system directory (+10)")
-
- # 2. Structural shape of the decoded value.
- structure = decoded
- is_full_url = "://" in structure
- if is_full_url:
- add("full-url", -10, "value is a full URL rather than a local path (-10)")
-
- if not encoded_path:
- if WINDOWS_PATH_RE.match(structure):
- add("windows-drive", 10, "value looks like a Windows drive path (+10)")
-
- normalized = structure.replace("\\", "/")
- if normalized in {"..", "../"} or normalized.startswith("../") or "/../" in normalized:
- add(
- "dotdot",
- 10,
- "value is or contains a parent-directory ('..') sequence (+10)",
- )
- elif normalized in {".", "./"} or normalized.startswith("./"):
- add(
- "dot",
- 5,
- "value is or starts with a current-directory ('./') sequence (+5)",
- )
-
- if not is_full_url:
- separators = normalized.count("/")
- if separators == 1:
- add("depth-1", 8, "value contains a relative path segment (+8)")
- elif separators == 2:
- add("depth-2", 12, "value contains two path separators (+12)")
- elif separators >= 3:
- add("depth-3", 15, "value contains three or more path separators (+15)")
- if normalized.startswith("/") and len(normalized) > 1:
- add(
- "absolute",
- 5,
- "value starts with a path separator (absolute-looking path) (+5)",
- )
-
- ext = extension_of(structure)
- if ext:
- add("extension", 20, f"value ends with a file-like extension '.{ext}' (+20)")
-
- return ValueAnalysis(score=max(0, min(VALUE_CAP, score)), reasons=tuple(reasons))
-
-
-# ---------------------------------------------------------------------------
-# URL parsing and analysis
-# ---------------------------------------------------------------------------
-@dataclass(frozen=True)
-class URLTarget:
- """Locally parsed URL metadata (no network activity involved)."""
-
- raw: str
- scheme: str
- host: str
- port: Optional[int]
- path: str
-
-
-class URLParseError(ValueError):
- """Raised when a line is not a usable HTTP(S) URL."""
-
-
-def parse_target(raw: str) -> URLTarget:
- """Validate a URL string locally. Never resolves or contacts the host."""
- text = sanitize_text(raw).strip()
- if not text:
- raise URLParseError("blank input")
- if any(char.isspace() for char in text):
- raise URLParseError("contains whitespace")
- if any(ord(char) < 32 or ord(char) == 127 for char in raw):
- raise URLParseError("contains control characters")
- try:
- parts = urlsplit(text)
- host = parts.hostname
- port = parts.port
- except ValueError as exc:
- raise URLParseError(f"malformed URL ({exc})") from exc
-
- scheme = (parts.scheme or "").lower()
- if scheme not in ("http", "https"):
- raise URLParseError(
- f"unsupported scheme (expected http/https, got '{scheme or 'none'}')"
- )
- if not parts.netloc or not host:
- raise URLParseError("missing host")
- return URLTarget(
- raw=text,
- scheme=scheme,
- host=host,
- port=port,
- path=parts.path or "/",
- )
-
-
-def display_host(target: URLTarget) -> str:
- if target.port and target.port not in (80, 443):
- return f"{target.host}:{target.port}"
- return target.host
-
-
-def split_query(query: str) -> List[Tuple[str, str, str]]:
- """Split a raw query string into (decoded name, raw value, decoded value).
-
- Kept deliberately literal (manual split on '&' and '=') so that:
- * repeated parameters are preserved,
- * URL-encoded names/values are visible both raw and decoded,
- * PathScope never guesses at values it was not given.
- """
- pairs: List[Tuple[str, str, str]] = []
- if not query:
- return pairs
- for chunk in query.split("&"):
- if not chunk:
- continue
- raw_name, separator, raw_value = chunk.partition("=")
- try:
- name = unquote_plus(raw_name)
- value = unquote_plus(raw_value)
- except (UnicodeError, ValueError):
- name, value = raw_name, raw_value
- pairs.append((sanitize_text(name), raw_value, sanitize_text(value)))
- return pairs
-
-
-def mask_credentials(netloc: str) -> str:
- """Replace 'user:pass@' with '@' so secrets are not displayed."""
- if "@" not in netloc:
- return netloc
- host = netloc.rsplit("@", 1)[1]
- return f"@{host}"
-
-
-def mask_url(raw: str) -> str:
- """Return the URL with query/fragment values and credentials hidden."""
- parts = urlsplit(raw)
- pairs: List[str] = []
- for chunk in parts.query.split("&"):
- if not chunk:
- continue
- if "=" in chunk:
- name = chunk.split("=", 1)[0]
- pairs.append(f"{name}=")
- else:
- pairs.append(chunk)
- fragment = "" if parts.fragment else ""
- return urlunsplit(
- (
- parts.scheme,
- mask_credentials(parts.netloc),
- parts.path,
- "&".join(pairs),
- fragment,
- )
- )
-
-
-@dataclass
-class ParameterFinding:
- """One parameter that passed the heuristic threshold."""
-
- url: str
- host: str
- parameter: str
- value: Optional[str]
- reasons: Tuple[str, ...]
- score: int
- occurrences: int = 1
- index: int = 0
-
- @property
- def band(self) -> str:
- return score_band(self.score)
-
-
-@dataclass
-class _ParameterGroup:
- parameter: str
- occurrences: int = 0
- values: List[str] = field(default_factory=list)
- raw_values: List[str] = field(default_factory=list)
-
-
-def analyze_url(raw: str, min_score: int = 30) -> List[ParameterFinding]:
- """Analyse one URL and return its flagged parameters (best first).
-
- This is purely local string analysis: nothing is requested, resolved,
- opened or injected.
- """
- raw = sanitize_text(raw).strip()
- target = parse_target(raw)
- parts = urlsplit(raw)
-
- groups: "OrderedDict[str, _ParameterGroup]" = OrderedDict()
- for name, raw_value, value in split_query(parts.query):
- if not name:
- continue
- canonical = "_".join(tokenize_name(name)) or name.lower()
- group = groups.get(canonical)
- if group is None:
- group = groups[canonical] = _ParameterGroup(parameter=name)
- group.occurrences += 1
- group.values.append(value)
- group.raw_values.append(raw_value)
-
- findings: List[ParameterFinding] = []
- host = display_host(target)
- # Show URL credentials as masked, even when parameter values are shown.
- safe_url = mask_credentials(parts.netloc)
- if safe_url != parts.netloc:
- safe_url = urlunsplit(
- (parts.scheme, safe_url, parts.path, parts.query, parts.fragment)
- )
- else:
- safe_url = raw
-
- for group in groups.values():
- name_analysis = analyze_name(group.parameter)
- value_analyses = [
- analyze_value(raw_value, decoded=group.values[index])
- for index, raw_value in enumerate(group.raw_values)
- ]
-
- best_index = 0
- for index, analysis in enumerate(value_analyses):
- if analysis.score > value_analyses[best_index].score:
- best_index = index
- best_value_analysis = value_analyses[best_index]
- best_value = group.values[best_index]
-
- generic_bonus = 0
- reasons: List[str] = []
- if name_analysis.reason:
- reasons.append(name_analysis.reason)
- if name_analysis.generic:
- if best_value_analysis.score >= 20:
- generic_bonus = GENERIC_BONUS
- reasons.append(
- f"generic name '{group.parameter}' becomes relevant because its "
- f"value is path-like (+{GENERIC_BONUS})"
- )
- else:
- continue # generic names never stand alone
- reasons.extend(best_value_analysis.reasons)
-
- score = name_analysis.score + best_value_analysis.score + generic_bonus
- score = max(0, min(100, score))
- if score <= 0 or score < min_score:
- continue
-
- findings.append(
- ParameterFinding(
- url=safe_url,
- host=host,
- parameter=group.parameter,
- value=best_value,
- reasons=tuple(reasons) or (f"combined heuristic score {score}",),
- score=score,
- occurrences=group.occurrences,
- )
- )
-
- findings.sort(key=lambda finding: (-finding.score, finding.parameter.lower()))
- for index, finding in enumerate(findings, start=1):
- finding.index = index
- return findings
-
-
-def count_parameters(raw: str) -> int:
- """Count distinct, non-empty parameter names in a URL (locally)."""
- parts = urlsplit(raw)
- return len({name for name, _raw, _decoded in split_query(parts.query) if name})
-
-
-# ---------------------------------------------------------------------------
-# Input handling
-# ---------------------------------------------------------------------------
-class InputError(RuntimeError):
- """Raised for unreadable input files."""
-
-
-def read_input_file(path: str) -> List[str]:
- try:
- with open(path, "r", encoding="utf-8-sig", errors="replace") as handle:
- return handle.read().splitlines()
- except OSError as exc:
- raise InputError(
- f"cannot read input file '{path}': {exc.strerror or exc}"
- ) from exc
-
-
-def clean_input_lines(
- lines: Iterable[str], label: str = "line"
-) -> Tuple[List[str], List[str]]:
- """Drop blanks/comments/duplicates, validate URLs. Returns (urls, warnings)."""
- urls: List[str] = []
- warnings: List[str] = []
- seen = set()
- for line_number, line in enumerate(lines, start=1):
- candidate = sanitize_text(line).strip()
- if not candidate or candidate.startswith("#"):
- continue
- if candidate in seen:
- continue
- try:
- parse_target(candidate)
- except URLParseError as exc:
- warnings.append(
- f"{label} {line_number}: skipped malformed URL ({exc}): "
- f"{truncate(candidate, 100)}"
- )
- continue
- seen.add(candidate)
- urls.append(candidate)
- return urls, warnings
-
-
-def dedupe(items: Iterable[str]) -> List[str]:
- result: List[str] = []
- seen = set()
- for item in items:
- if item not in seen:
- seen.add(item)
- result.append(item)
- return result
-
-
-def stdin_has_data() -> bool:
- try:
- return sys.stdin is not None and not sys.stdin.isatty()
- except Exception: # pragma: no cover - defensive only
- return False
-
-
-def read_stdin_lines() -> List[str]:
- try:
- return sys.stdin.read().splitlines()
- except (OSError, ValueError):
- return []
-
-
-# ---------------------------------------------------------------------------
-# Rendering
-# ---------------------------------------------------------------------------
-def stream_supports_color(stream, disabled: bool = False) -> bool:
- if disabled or os.environ.get("NO_COLOR"):
- return False
- if os.environ.get("TERM", "") == "dumb":
- return False
- try:
- return bool(stream.isatty())
- except Exception: # pragma: no cover - defensive only
- return False
-
-
-class Palette:
- """ANSI colours, used only when the target stream is an interactive terminal."""
-
- def __init__(self, enabled: bool) -> None:
- self.enabled = enabled
-
- def paint(self, style: str, text: str) -> str:
- if not self.enabled:
- return text
- code = COLOR_CODES[style]
- return f"\x1b[{code}m{text}\x1b[0m"
-
- def __getattr__(self, style: str) -> Callable[[str], str]:
- if style not in COLOR_CODES:
- raise AttributeError(style)
-
- def apply(text: str) -> str:
- return self.paint(style, text)
-
- return apply
-
-
-def render_banner(colors: Palette) -> str:
- title = colors.bold(colors.cyan(f"{PROGRAM} {__version__} - passive URL-parameter triage"))
- lines = [title, colors.grey("-" * 64)]
- for label, url in BANNER_LINKS:
- lines.append(f"{colors.bold(label + ':')} {colors.blue(url)}")
- for line in BANNER_DISCLAIMER:
- lines.append(colors.yellow(line))
- return "\n".join(lines)
-
-
-def score_band(score: int) -> str:
- if score >= 70:
- return "HIGH"
- if score >= 50:
- return "MEDIUM"
- return "LOW"
-
-
-def render_report(
- findings: Sequence[ParameterFinding],
- *,
- colors: Palette,
- show_values: bool,
- urls_analyzed: int,
- parameters_analyzed: int,
- min_score: int,
- skipped: int,
-) -> str:
- lines: List[str] = []
- lines.append(colors.bold("Candidates for manual review"))
- lines.append(colors.grey("=" * 64))
- lines.append(
- f"Analyzed {urls_analyzed} URL(s) and {parameters_analyzed} distinct "
- f"parameter(s); {len(findings)} candidate(s) at score >= {min_score}."
- )
- if skipped:
- lines.append(colors.yellow(f"Skipped {skipped} malformed input line(s)."))
- lines.append("")
-
- if not findings:
- lines.append(
- colors.green(
- "No path-like parameter candidates were flagged. "
- "This is not proof that the application is safe."
- )
- )
- else:
- band_colors = {"HIGH": colors.red, "MEDIUM": colors.yellow, "LOW": colors.cyan}
- for finding in findings:
- band = finding.band
- heading = (
- f"#{finding.index} {colors.bold(finding.parameter)} "
- f"{band_colors[band](f'[{band} score {finding.score}/100]')}"
- )
- lines.append(heading)
- lines.append(f" {colors.grey('Host')} {finding.host}")
- shown_url = finding.url if show_values else mask_url(finding.url)
- lines.append(f" {colors.grey('URL')} {truncate(shown_url, 160)}")
- if show_values:
- value_text = truncate(finding.value or "", 120) or ""
- else:
- value_text = colors.grey("")
- lines.append(f" {colors.grey('Parameter')} {finding.parameter}")
- lines.append(f" {colors.grey('Value')} {value_text}")
- if finding.occurrences > 1:
- lines.append(
- f" {colors.grey('Repeated')} x{finding.occurrences} "
- "(best-scoring existing value shown)"
- )
- lines.append(f" {colors.grey('Why flagged')}")
- for reason in finding.reasons:
- lines.append(f" - {reason}")
- lines.append("")
-
- lines.append(
- colors.grey(
- "Reminder: candidates for manual review, not confirmed vulnerabilities. "
- "No requests were sent and no input was injected."
- )
- )
- if not show_values:
- lines.append(
- colors.grey(
- "Values are hidden by default (use --show-values to display them)."
- )
- )
- return "\n".join(lines)
-
-
-# ---------------------------------------------------------------------------
-# CLI
-# ---------------------------------------------------------------------------
-@dataclass
-class RunConfig:
- urls: List[str]
- skipped: List[str]
- json: bool = False
- show_values: bool = False
- no_banner: bool = False
- no_color: bool = False
- min_score: int = 30
- strict: bool = False
- fail_on_none: bool = False
- banner_printed: bool = False
-
-
-def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(
- prog="path_detector.py",
- description=(
- "PathScope: passive triage of URL query parameters whose names or "
- "existing values look path-like. Results are candidates for manual "
- "review, never confirmed vulnerabilities. PathScope makes no network "
- "requests and injects no test values."
- ),
- epilog=(
- "examples:\n"
- " python3 path_detector.py --url 'https://example.test/view?file=report.pdf'\n"
- " python3 path_detector.py -i urls.txt\n"
- " cat urls.txt | python3 path_detector.py\n"
- " python3 path_detector.py -i urls.txt --json --show-values\n"
- "\n"
- "exit codes:\n"
- " 0 completed 1 skipped lines with --strict 2 usage/input error\n"
- " 3 no candidates with --fail-on-none 130 interrupted\n"
- "\n"
- "links (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 (merged and de-duplicated)")
- source.add_argument(
- "--url",
- action="append",
- default=[],
- metavar="URL",
- help="URL to analyze; may be repeated. Quote URLs containing '&'.",
- )
- source.add_argument(
- "-i",
- "--input",
- action="append",
- default=[],
- metavar="FILE",
- help="read URLs from FILE (one per line); may be repeated. '-' reads "
- "stdin. Blank lines and lines starting with '#' are skipped.",
- )
-
- output = parser.add_argument_group("output")
- output.add_argument(
- "--json",
- action="store_true",
- help="print machine-readable JSON on stdout (banner stays on stderr)",
- )
- output.add_argument(
- "--show-values",
- action="store_true",
- help="reveal existing parameter values; hidden/masked by default",
- )
- output.add_argument(
- "--no-color",
- action="store_true",
- help="disable ANSI colour even on a terminal",
- )
- output.add_argument(
- "--no-banner",
- action="store_true",
- help="do not print the startup banner and links",
- )
-
- heuristic = parser.add_argument_group("heuristics")
- heuristic.add_argument(
- "--min-score",
- type=int,
- default=30,
- metavar="N",
- help="report parameters scoring at least N (0-100, default: 30)",
- )
-
- behaviour = parser.add_argument_group("behaviour")
- behaviour.add_argument(
- "--strict",
- action="store_true",
- help="exit 1 if any input line was malformed or skipped",
- )
- behaviour.add_argument(
- "--fail-on-none",
- action="store_true",
- help="exit 3 when no candidates are flagged",
- )
- return parser
-
-
-def collect_inputs(parser: argparse.ArgumentParser, args: argparse.Namespace
- ) -> Tuple[List[str], List[str]]:
- """Merge --url, -i/--input and (when no source is given) piped stdin.
-
- Stdin is auto-detected only when neither --url nor -i/--input is present,
- so an explicit source never blocks waiting for piped data.
- """
- urls: List[str] = []
- warnings: List[str] = []
- stdin_consumed = False
-
- for path in args.input:
- if path == "-":
- if not stdin_has_data():
- parser.error("--input '-' was given but stdin is a terminal")
- stdin_urls, stdin_warnings = clean_input_lines(
- read_stdin_lines(), label="stdin"
- )
- stdin_consumed = True
- urls.extend(stdin_urls)
- warnings.extend(stdin_warnings)
- continue
- try:
- file_lines = read_input_file(path)
- except InputError as exc:
- parser.error(str(exc))
- file_urls, file_warnings = clean_input_lines(file_lines, label=path)
- urls.extend(file_urls)
- warnings.extend(file_warnings)
-
- url_values, url_warnings = clean_input_lines(args.url, label="--url")
- urls.extend(url_values)
- warnings.extend(url_warnings)
-
- if not stdin_consumed and not args.url and not args.input and stdin_has_data():
- piped_urls, piped_warnings = clean_input_lines(read_stdin_lines(), label="stdin")
- urls.extend(piped_urls)
- warnings.extend(piped_warnings)
-
- return dedupe(urls), warnings
-
-
-def make_payload(config: RunConfig, findings: Sequence[ParameterFinding],
- urls_analyzed: int, parameters_analyzed: int) -> dict:
- return {
- "tool": PROGRAM,
- "version": __version__,
- "disclaimer": (
- "Candidates for manual review only. PathScope is passive: it makes no "
- "network requests, injects no values, and never confirms vulnerabilities."
- ),
- "min_score": config.min_score,
- "show_values": config.show_values,
- "summary": {
- "urls_analyzed": urls_analyzed,
- "parameters_analyzed": parameters_analyzed,
- "candidates": len(findings),
- "skipped_lines": len(config.skipped),
- },
- "findings": [
- {
- "index": finding.index,
- "host": finding.host,
- "parameter": finding.parameter,
- "url": finding.url if config.show_values else mask_url(finding.url),
- "value": finding.value if config.show_values else None,
- "occurrences": finding.occurrences,
- "score": finding.score,
- "band": finding.band,
- "reasons": list(finding.reasons),
- }
- for finding in findings
- ],
- "links": {
- "github": GITHUB_URL,
- "instagram": INSTAGRAM_URL,
- "support": SUPPORT_URL,
- },
- }
-
-
-def run(config: RunConfig, stdout=None, stderr=None) -> int:
- stdout = stdout if stdout is not None else sys.stdout
- stderr = stderr if stderr is not None else sys.stderr
-
- if not config.no_banner and not config.banner_printed:
- print(
- render_banner(Palette(stream_supports_color(stderr, disabled=config.no_color))),
- file=stderr,
- )
- print("", file=stderr)
- config.banner_printed = True
-
- out_colors = Palette(stream_supports_color(stdout, disabled=config.no_color))
-
- for warning in config.skipped:
- print(f"warning: {warning}", file=stderr)
-
- if not config.urls:
- print("error: no usable URLs to analyze.", file=stderr)
- print(
- " Use --url URL, -i/--input FILE, or pipe URLs on stdin.",
- file=stderr,
- )
- print(" Try: python3 path_detector.py --help", file=stderr)
- return EXIT_USAGE
-
- findings: List[ParameterFinding] = []
- urls_analyzed = 0
- parameters_analyzed = 0
- for url in config.urls:
- try:
- url_findings = analyze_url(url, min_score=config.min_score)
- except URLParseError as exc: # defensive: validated earlier
- print(f"warning: skipped URL ({exc})", file=stderr)
- continue
- urls_analyzed += 1
- parameters_analyzed += count_parameters(url)
- findings.extend(url_findings)
-
- findings.sort(key=lambda finding: (-finding.score, finding.host, finding.parameter))
- for index, finding in enumerate(findings, start=1):
- finding.index = index
-
- if config.json:
- payload = make_payload(config, findings, urls_analyzed, parameters_analyzed)
- json.dump(payload, stdout, indent=2, ensure_ascii=False)
- stdout.write("\n")
- else:
- report = render_report(
- findings,
- colors=out_colors,
- show_values=config.show_values,
- urls_analyzed=urls_analyzed,
- parameters_analyzed=parameters_analyzed,
- min_score=config.min_score,
- skipped=len(config.skipped),
- )
- print(report, file=stdout)
- print(
- out_colors.grey(
- f"\nDone: {urls_analyzed} URL(s), {len(findings)} candidate(s), "
- f"{len(config.skipped)} line(s) skipped."
- ),
- file=stdout,
- )
-
- if config.strict and config.skipped:
- return EXIT_STRICT_SKIPS
- if config.fail_on_none and not findings:
- return EXIT_NO_CANDIDATES
- return EXIT_OK
-
-
-def main(argv: Optional[Sequence[str]] = None, stdout=None, stderr=None) -> int:
- parser = build_parser()
- stderr = stderr if stderr is not None else sys.stderr
- argv_list = list(sys.argv[1:] if argv is None else argv)
-
- # The banner is part of every invocation (including --help/--version).
- if "--no-banner" not in argv_list:
- banner_colors = Palette(
- stream_supports_color(stderr, disabled="--no-color" in argv_list)
- )
- print(render_banner(banner_colors), file=stderr)
- print("", file=stderr)
- banner_printed = "--no-banner" not in argv_list
-
- args = parser.parse_args(argv_list)
-
- if not 0 <= args.min_score <= 100:
- parser.error("--min-score must be between 0 and 100")
-
- config = RunConfig(urls=[], skipped=[])
- config.json = args.json
- config.show_values = args.show_values
- config.no_banner = args.no_banner
- config.no_color = args.no_color
- config.min_score = args.min_score
- config.strict = args.strict
- config.fail_on_none = args.fail_on_none
- config.banner_printed = banner_printed
-
- try:
- config.urls, config.skipped = collect_inputs(parser, args)
- except KeyboardInterrupt:
- print("\ninterrupted", file=stderr)
- return EXIT_INTERRUPTED
- try:
- return run(config, stdout=stdout, stderr=stderr)
- except KeyboardInterrupt:
- print("\ninterrupted", file=stderr)
- return EXIT_INTERRUPTED
+if __package__ in (None, ""):
+ _HERE = os.path.dirname(os.path.abspath(__file__))
+ if _HERE not in sys.path:
+ sys.path.insert(0, _HERE)
+from pathscope.cli import main # noqa: E402 (path setup must come first)
if __name__ == "__main__":
sys.exit(main())
diff --git a/pathscope/__init__.py b/pathscope/__init__.py
new file mode 100644
index 0000000..5b0b228
--- /dev/null
+++ b/pathscope/__init__.py
@@ -0,0 +1,43 @@
+"""PathScope - passive, offline triage of path-like request parameters.
+
+Findings produced by this package are **heuristic candidates for manual
+review**, not proof of any vulnerability.
+
+The package is deliberately conservative:
+
+* it only reads input the user supplies (URLs, stdin, local HAR files);
+* it never imports networking or process modules (see ``tests/test_path_detector.py``);
+* parameter values are treated as inert strings and are never resolved,
+ opened, or used as filesystem paths.
+"""
+
+from __future__ import annotations
+
+PROGRAM = "PathScope"
+__version__ = "2.0.0"
+
+# Displayed on every start. These are never opened and never requested.
+GITHUB_URL = "https://github.com/mrdineshpathro"
+INSTAGRAM_URL = "https://www.instagram.com/mr_dineshpatro"
+SUPPORT_URL = "https://buymeacoffee.com/mrdineshpathro"
+
+BANNER_LINKS = (
+ ("GitHub", GITHUB_URL),
+ ("Instagram", INSTAGRAM_URL),
+ ("Support", SUPPORT_URL),
+)
+
+
+
+def banner_lines() -> tuple:
+ """The exact branding lines printed at startup (no colour applied)."""
+ return tuple(f"{label}: {url}" for label, url in BANNER_LINKS)
+
+__all__ = [
+ "PROGRAM",
+ "__version__",
+ "GITHUB_URL",
+ "INSTAGRAM_URL",
+ "SUPPORT_URL",
+ "BANNER_LINKS",
+]
diff --git a/pathscope/__main__.py b/pathscope/__main__.py
new file mode 100644
index 0000000..9859fbf
--- /dev/null
+++ b/pathscope/__main__.py
@@ -0,0 +1,10 @@
+"""Allow ``python3 -m pathscope`` as well as ``python3 path_detector.py``."""
+
+from __future__ import annotations
+
+import sys
+
+from .cli import main
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/pathscope/cli.py b/pathscope/cli.py
new file mode 100644
index 0000000..d066b04
--- /dev/null
+++ b/pathscope/cli.py
@@ -0,0 +1,414 @@
+"""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 sys
+from typing import Optional, Sequence
+
+from . import (
+ GITHUB_URL,
+ INSTAGRAM_URL,
+ PROGRAM,
+ SUPPORT_URL,
+ __version__,
+)
+from .config import Config, ConfigError, describe_schema, load_config, merge_ignore
+from .detector import DEFAULT_MIN_SCORE, AnalysisOptions, analyze_requests, summarize
+from .report import (
+ FORMAT_JSON,
+ FORMAT_TEXT,
+ FORMATS,
+ Palette,
+ render,
+ render_banner,
+ supports_color,
+)
+from .sources import (
+ INPUT_FORMAT_AUTO,
+ INPUT_FORMATS,
+ InputError,
+ LoadResult,
+ load_file,
+ load_stdin,
+ make_url_requests,
+)
+from .textutil import MAX_DECODE_PASSES
+
+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\n"
+ " 2 usage/input error 3 internal error 130 interrupted\n"
+ "\n"
+ "configuration 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}",
+ 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)",
+ )
+
+ output = parser.add_argument_group("output")
+ output.add_argument(
+ "--output-format",
+ choices=FORMATS,
+ default=None,
+ metavar="{text,json,csv,sarif}",
+ 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)",
+ )
+
+ tuning = parser.add_argument_group("detection and configuration")
+ 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",
+ )
+ 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 _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 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
+ config = Config()
+ if args.config:
+ try:
+ config = load_config(args.config)
+ except ConfigError as exc:
+ print(f"error: {exc}", file=stderr)
+ return EXIT_USAGE
+
+ min_score = args.min_score if args.min_score is not None else config.min_score
+ if not 0 <= min_score <= 100:
+ parser.error("--min-score must be between 0 and 100")
+
+ max_passes = (
+ args.max_decode_passes
+ if args.max_decode_passes is not None
+ else config.max_decode_passes
+ )
+ if not 0 <= max_passes <= 5:
+ parser.error("--max-decode-passes must be between 0 and 5")
+
+ show_values = bool(args.show_values or config.show_values)
+
+ 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()
+
+ 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
+
+ if not quiet:
+ for warning in loaded.warnings:
+ print(f"warning: {warning}", file=stderr)
+
+ 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,
+ )
+ print(" Try: python3 path_detector.py --help", file=stderr)
+ return EXIT_USAGE
+
+ options = AnalysisOptions(
+ min_score=min_score,
+ max_decode_passes=max_passes,
+ extra_terms=tuple(config.merged_terms()),
+ ignore_params=tuple(merge_ignore(args.ignore_param, config)),
+ show_values=show_values,
+ )
+
+ try:
+ report = analyze_requests(loaded.requests, options)
+ report.warnings = list(loaded.warnings)
+ report.skipped = loaded.skipped
+ colors = Palette(supports_color(stdout) and not args.no_color)
+ rendered = render(report, 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()
+
+ if not quiet:
+ print(f"pathscope: {summarize(report)}", file=stderr)
+ if report.candidate_count and args.output_format == FORMAT_TEXT:
+ print(
+ "pathscope: candidates are for manual review, not confirmed vulnerabilities",
+ file=stderr,
+ )
+
+ if args.fail_on_findings and report.candidate_count:
+ return EXIT_FINDINGS
+ return EXIT_OK
+
+
+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",
+]
diff --git a/pathscope/config.py b/pathscope/config.py
new file mode 100644
index 0000000..62ec751
--- /dev/null
+++ b/pathscope/config.py
@@ -0,0 +1,183 @@
+"""Optional JSON configuration for PathScope.
+
+Schema (all keys optional, unknown keys rejected)::
+
+ {
+ "name_terms": ["download", "media_file"],
+ "ignore_params": ["image", "avatar"],
+ "min_score": 25,
+ "max_decode_passes": 3,
+ "show_values": false
+ }
+
+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.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, 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
+
+
+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
+ show_values: bool = False
+ source: str = ""
+
+ 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 = {
+ "name_terms",
+ "ignore_params",
+ "min_score",
+ "max_decode_passes",
+ "show_values",
+}
+
+
+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()
+ 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 "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
+
+ return config
+
+
+def load_config(path: str) -> Config:
+ """Read and validate ``path``. Raises :class:`ConfigError` on any problem."""
+ 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
+
+ config = validate_payload(payload)
+ config.source = path
+ return config
+
+
+def describe_schema() -> Tuple[str, ...]:
+ """Human-readable schema lines for ``--help`` and the README."""
+ return (
+ ' "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',
+ ' "show_values": false boolean',
+ )
+
+
+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,
+ "show_values": False,
+ }
+
+
+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..b46c68a
--- /dev/null
+++ b/pathscope/detector.py
@@ -0,0 +1,224 @@
+"""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
+
+from dataclasses import dataclass, field
+from typing import Dict, Iterable, List, Optional, Sequence, Tuple
+from urllib.parse import urlsplit, urlunsplit
+
+from .heuristics import Analysis, analyze_parameter, canonical_name
+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}
+
+
+@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
+
+
+@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
+
+ 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,
+ }
+
+
+@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
+
+ @property
+ def candidate_count(self) -> int:
+ return len(self.findings)
+
+ @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}),
+ )
+ ignored = {canonical_name(item) for item in options.ignore_params if item}
+
+ findings: List[Finding] = []
+ for request in _dedupe_requests(requests):
+ 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,
+ )
+ 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
+ findings.append(
+ Finding(
+ 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),
+ )
+ )
+ for index, finding in enumerate(findings, start=1):
+ finding.index = index
+ report.findings = findings
+ return report
+
+
+def summarize(report: Report) -> str:
+ """One-line summary used by renderers and the CLI stderr trailer."""
+ counts = report.confidence_counts
+ return (
+ 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"
+ )
diff --git a/pathscope/heuristics.py b/pathscope/heuristics.py
new file mode 100644
index 0000000..eabdb00
--- /dev/null
+++ b/pathscope/heuristics.py
@@ -0,0 +1,540 @@
+"""Transparent, easy-to-edit heuristics for PathScope.
+
+Two independent signals are combined:
+
+``name``
+ What the parameter is called (``file``, ``base_path``, ``template`` ...).
+
+``value``
+ What the parameter *already* contains, treated purely as a string:
+ traversal segments, encoded slashes, absolute paths, Windows paths,
+ file extensions, and so on.
+
+Neither signal is a vulnerability test. They rank reading order. All tables
+live at module level so a user can adjust them without touching logic.
+
+Scoring: every :class:`Evidence` carries a weight; the score is their sum,
+clamped to ``0..100``. ``docs/README`` documents each rule and its weight.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from typing import Dict, FrozenSet, Iterable, List, Tuple
+
+from .textutil import MAX_DECODE_PASSES, decode_forms, sanitize_text
+
+NAME_CAP = 45
+VALUE_CAP = 55
+MAX_SCORE = 100
+
+#: Weight for an exact, strong name term.
+STRONG_NAME_WEIGHT = 35
+#: Extra weight when a strong term is part of a multiword name (``download_file``).
+MULTIWORD_BONUS = 5
+#: Discount for ``name-prefix`` and ``name-suffix`` matches.
+PREFIX_DISCOUNT = 7
+SUFFIX_DISCOUNT = 12
+#: Bonus when a generic name (``image``, ``target`` ...) has a path-like value.
+GENERIC_BONUS = 10
+
+# ---------------------------------------------------------------------------
+# Parameter-name vocabulary
+# ---------------------------------------------------------------------------
+#: Exact tokens that strongly suggest a path-like consumer.
+PATH_NAME_TERMS: FrozenSet[str] = frozenset(
+ """
+ file filename filepath files document doc download upload attachment
+ archive export path dir directory folder root base basedir basepath uri
+ url link dest destination src resource asset media storage page
+ view layout theme tpl template include inc load action module plugin
+ script config conf settings log logfile
+ style css js data db database report render read open pathname fname
+ folderpath filepathname
+ """.split()
+)
+
+#: Names that are only meaningful when the existing value is path-like.
+GENERIC_NAME_TERMS: FrozenSet[str] = frozenset(
+ """
+ image img photo avatar target ref referer referrer site key callback
+ filetarget
+ """.split()
+)
+
+# ---------------------------------------------------------------------------
+# Value indicators
+# ---------------------------------------------------------------------------
+#: Traversal must be a path *segment*: two dots bounded by separators or the
+#: ends of the string. ``report..pdf`` or ``v1..2`` never match.
+SEGMENT_TRAVERSAL_RE = re.compile(r"(?:^|[/\\])\.\.(?:[/\\]|$)")
+#: A Windows drive path, e.g. ``C:\Windows`` or ``D:/data``.
+WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[/\\]")
+#: A UNC path, e.g. ``\\server\share``.
+UNC_PATH_RE = re.compile(r"^\\\\[A-Za-z0-9._$-]+[\\/]")
+#: A POSIX absolute path (but not a protocol-relative URL like ``//cdn``).
+ABSOLUTE_PATH_RE = re.compile(r"^/(?!/)[A-Za-z0-9._~%-]")
+#: Anything that parses as a full URL, e.g. ``https://`` or ``file://``.
+FULL_URL_RE = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://")
+
+#: Percent-encoded octet sequences worth naming in a reason.
+ENCODED_MARKERS: Tuple[Tuple[str, str], ...] = (
+ ("%2e%2e", "encoded-dotdot"),
+ ("%2f", "encoded-slash"),
+ ("%5c", "encoded-backslash"),
+ ("%00", "encoded-nul"),
+ ("%252e", "nested-encoded-dotdot"),
+)
+
+#: Well-known file extensions. Extension-only evidence is weak (+8).
+FILE_EXTENSIONS: FrozenSet[str] = frozenset(
+ """
+ apk avi bak bash bat bin bmp bz2 c cgi conf config crt cs csr csv css db
+ dll doc docx dot drawio dtd env eot exe flac gif go gz h htm html ico ini
+ iso jar java jpeg jpg js json jsx key kt log md mkv mov mp3 mp4 msi odt
+ ogg otf pdf pem php phtml plist png ppt pptx ps1 py pyc rar rb rst sh so
+ sql svg swf tar tgz tif tiff toml ts tsx txt vhd wav webp woff woff2 xls
+ xlsx xml xsd yaml yml zip
+ """.split()
+)
+MULTI_EXTENSIONS: Tuple[str, ...] = ("tar.gz", "tar.bz2", "tar.xz", "tar.zst")
+
+
+@dataclass(frozen=True)
+class Evidence:
+ """One explainable reason a parameter was considered path-like."""
+
+ rule: str
+ reason: str
+ weight: int
+ layer: str # "name" or "value"
+
+ def as_dict(self) -> Dict[str, object]:
+ return {
+ "rule": self.rule,
+ "layer": self.layer,
+ "weight": self.weight,
+ "reason": self.reason,
+ }
+
+
+@dataclass
+class Analysis:
+ """Aggregated evidence for one parameter identity."""
+
+ name: str
+ evidence: List[Evidence] = field(default_factory=list)
+ decoded_value: str = ""
+ decode_passes: int = 0
+
+ @property
+ def score(self) -> int:
+ return max(0, min(MAX_SCORE, sum(item.weight for item in self.evidence)))
+
+ @property
+ def rules(self) -> List[str]:
+ return [item.rule for item in self.evidence]
+
+ @property
+ def primary_rule(self) -> str:
+ return self.rules[0] if self.rules else "none"
+
+ @property
+ def reasons(self) -> List[str]:
+ return [item.reason for item in self.evidence]
+
+ @property
+ def confidence(self) -> str:
+ """Heuristic band. Never an exploitability judgement."""
+ if self.score >= 70:
+ return "high"
+ if self.score >= 40:
+ return "medium"
+ return "low"
+
+
+# ---------------------------------------------------------------------------
+# Tokenisation
+# ---------------------------------------------------------------------------
+_CAMEL_SPLIT_RE = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
+_NON_ALNUM_RE = re.compile(r"[^A-Za-z0-9]+")
+_DIGIT_SPLIT_RE = re.compile(r"(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])")
+
+
+def tokenize_name(name: str) -> List[str]:
+ """Split a parameter name into lowercase tokens.
+
+ ``fileName`` -> ``['file', 'name']``
+ ``base_path`` -> ``['base', 'path']``
+ ``X-File-Path`` -> ``['x', 'file', 'path']``
+ """
+ if not name:
+ return []
+ text = sanitize_text(name).strip()
+ tokens: List[str] = []
+ for chunk in _NON_ALNUM_RE.split(_CAMEL_SPLIT_RE.sub(" ", text)):
+ for piece in _DIGIT_SPLIT_RE.split(chunk):
+ if piece:
+ tokens.append(piece.lower())
+ return tokens
+
+
+def canonical_name(name: str) -> str:
+ """Stable, comparable form of a parameter name."""
+ return "_".join(tokenize_name(name)) or sanitize_text(name).lower()
+
+
+def extension_of(text: str) -> str:
+ """Return the file extension at the end of ``text`` (``""`` if none)."""
+ cleaned = text.strip().strip("\"'").rstrip(".,;:!?)]}")
+ last = re.split(r"[/\\]", cleaned)[-1].lower()
+ for multi in MULTI_EXTENSIONS:
+ if last.endswith("." + multi):
+ return multi
+ if "." not in last:
+ return ""
+ candidate = last.rsplit(".", 1)[1]
+ return candidate if candidate in FILE_EXTENSIONS else ""
+
+
+# ---------------------------------------------------------------------------
+# Name analysis
+# ---------------------------------------------------------------------------
+def analyze_name(name: str, extra_terms: Iterable[str] = ()) -> List[Evidence]:
+ """Return name-based evidence.
+
+ Rules:
+ ``name-custom`` exact user-configured term, +30
+ ``name-exact`` exact built-in path term, +35 (+5 multiword)
+ ``name-compound`` the whole name is a known compound, +35
+ ``name-prefix`` name starts with a path term, +28
+ ``name-suffix`` name ends with a path term, +23
+ ``name-generic`` generic name (image/target/...), +0 (context only)
+ ``name-weak`` multiword name without a term, +5 (never alone)
+ """
+ tokens = tokenize_name(name)
+ if not tokens:
+ return []
+ joined = "".join(tokens)
+ lowered = sanitize_text(name).lower()
+
+ custom = {term.strip().lower().replace("-", "_") for term in extra_terms if term.strip()}
+ path_terms = PATH_NAME_TERMS | (custom - GENERIC_NAME_TERMS)
+
+ # Configured terms may be single tokens ("blob") or compounds ("cdn_blob").
+ custom_candidates = [token for token in tokens if token in custom]
+ custom_candidates += [name for name in (joined, lowered, canonical_name(name)) if name in custom]
+ builtin_hit = any(token in PATH_NAME_TERMS for token in tokens)
+ if custom_candidates and not builtin_hit:
+ term = custom_candidates[0]
+ return [
+ Evidence(
+ "name-custom",
+ f"parameter name contains configured term '{term}' (+30)",
+ 30,
+ "name",
+ )
+ ]
+
+ hits = [token for token in tokens if token in path_terms]
+ if hits:
+ best = max(hits, key=len)
+ bonus = MULTIWORD_BONUS if len(tokens) > 1 else 0
+ suffix = f", +{bonus} multiword" if bonus else ""
+ return [
+ Evidence(
+ "name-exact",
+ f"parameter name contains path-related term '{best}' "
+ f"(+{STRONG_NAME_WEIGHT}{suffix})",
+ STRONG_NAME_WEIGHT + bonus,
+ "name",
+ )
+ ]
+
+ if "_" not in joined and joined in path_terms and len(joined) > 4:
+ return [
+ Evidence(
+ "name-compound",
+ f"parameter name '{lowered}' is a known path compound (+{STRONG_NAME_WEIGHT})",
+ STRONG_NAME_WEIGHT,
+ "name",
+ )
+ ]
+
+ # Prefix/suffix matching keeps only whole-word boundaries so that
+ # "urlencoded" is not read as "url" and "landscape" is not read as "page".
+ prefix_match = ""
+ suffix_match = ""
+ for term in sorted(path_terms, key=len, reverse=True):
+ if len(term) < 4:
+ continue
+ if joined.startswith(term) and len(joined) > len(term):
+ prefix_match = term
+ break
+ if joined.endswith(term) and len(joined) > len(term):
+ suffix_match = term
+ break
+ if prefix_match:
+ weight = STRONG_NAME_WEIGHT - PREFIX_DISCOUNT
+ return [
+ Evidence(
+ "name-prefix",
+ f"parameter name starts with path-related term '{prefix_match}' (+{weight})",
+ weight,
+ "name",
+ )
+ ]
+ if suffix_match:
+ weight = STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT
+ return [
+ Evidence(
+ "name-suffix",
+ f"parameter name ends with path-related term '{suffix_match}' (+{weight})",
+ weight,
+ "name",
+ )
+ ]
+
+ if any(token in GENERIC_NAME_TERMS for token in tokens):
+ return [
+ Evidence(
+ "name-generic",
+ "parameter name is generic (image/target/ref/...): considered only "
+ "when its value is path-like (+0)",
+ 0,
+ "name",
+ )
+ ]
+
+ if len(tokens) > 1:
+ return [
+ Evidence(
+ "name-weak",
+ "multiword parameter name without a path term (weak, +5)",
+ 5,
+ "name",
+ )
+ ]
+ return []
+
+
+# ---------------------------------------------------------------------------
+# Value analysis
+# ---------------------------------------------------------------------------
+def _is_segment_traversal(text: str) -> bool:
+ return bool(SEGMENT_TRAVERSAL_RE.search(text))
+
+
+def analyze_value(
+ value: str, max_decode_passes: int = MAX_DECODE_PASSES
+) -> List[Evidence]:
+ """Return value-based evidence. The value is treated purely as a string.
+
+ Rules:
+ ``value-traversal`` ``..`` used as a path segment, +30
+ ``value-encoded-traversal`` ``..`` only visible after decoding, +15
+ ``value-encoded-slash`` ``%2f``/``%5c`` present, +12
+ ``value-double-encoded`` two or more decoding passes needed, +10
+ ``value-windows-drive`` ``C:\\`` or ``D:/`` prefix, +15
+ ``value-unc`` ``\\\\server\\share`` prefix, +15
+ ``value-absolute`` starts with ``/`` (but not ``//``), +12
+ ``value-multi-segment`` 2+ path separators, +6
+ ``value-extension`` known file extension at the end, +8
+ ``value-full-url`` an ``scheme://`` URL, -10
+ ``value-encoded`` informational only (0)
+ """
+ raw = sanitize_text(value or "")
+ if not raw:
+ return []
+
+ lowered_raw = raw.lower()
+ forms = decode_forms(raw, max_decode_passes)
+ deepest = forms[-1][1]
+ max_pass = forms[-1][0]
+ evidence: List[Evidence] = []
+
+ if any(marker in lowered_raw for marker, _name in ENCODED_MARKERS):
+ evidence.append(
+ Evidence(
+ "value-encoded",
+ "value contains percent-encoded octets (informational, +0)",
+ 0,
+ "value",
+ )
+ )
+ if "%2f" in lowered_raw or "%5c" in lowered_raw:
+ evidence.append(
+ Evidence(
+ "value-encoded-slash",
+ "value contains an encoded slash or backslash (%2f / %5c) (+12)",
+ 12,
+ "value",
+ )
+ )
+ if max_pass >= 2:
+ evidence.append(
+ Evidence(
+ "value-double-encoded",
+ f"value required {max_pass} decoding passes (nested encoding) (+10)",
+ 10,
+ "value",
+ )
+ )
+
+ if _is_segment_traversal(raw):
+ evidence.append(
+ Evidence(
+ "value-traversal",
+ "value contains a '..' path segment ('../', '..\\' or bare '..') (+30)",
+ 30,
+ "value",
+ )
+ )
+ shape = raw
+ elif _is_segment_traversal(deepest):
+ evidence.append(
+ Evidence(
+ "value-encoded-traversal",
+ "value contains a '..' segment only after percent-decoding (+15)",
+ 15,
+ "value",
+ )
+ )
+ shape = deepest
+ else:
+ shape = deepest
+
+ if WINDOWS_DRIVE_RE.match(shape):
+ evidence.append(
+ Evidence(
+ "value-windows-drive",
+ "value looks like a Windows drive path ('C:\\...') (+15)",
+ 15,
+ "value",
+ )
+ )
+ elif UNC_PATH_RE.match(shape):
+ evidence.append(
+ Evidence(
+ "value-unc",
+ "value looks like a Windows UNC path ('\\\\server\\share') (+15)",
+ 15,
+ "value",
+ )
+ )
+ elif ABSOLUTE_PATH_RE.match(shape):
+ evidence.append(
+ Evidence(
+ "value-absolute",
+ "value starts with a path separator (absolute-looking) (+12)",
+ 12,
+ "value",
+ )
+ )
+
+ if FULL_URL_RE.match(shape):
+ evidence.append(
+ Evidence(
+ "value-full-url",
+ "value is a full URL rather than a local path (-10)",
+ -10,
+ "value",
+ )
+ )
+ else:
+ # A trailing separator right after ".." ("../etc/passwd") is part of the
+ # traversal evidence, so it is not counted a second time here.
+ separators = shape.count("/") + shape.count("\\")
+ if _is_segment_traversal(shape):
+ separators = max(0, separators - 1)
+ if separators >= 2:
+ evidence.append(
+ Evidence(
+ "value-multi-segment",
+ f"value contains {separators} path separators (+6)",
+ 6,
+ "value",
+ )
+ )
+ extension = extension_of(shape)
+ if extension:
+ evidence.append(
+ Evidence(
+ "value-extension",
+ f"value ends with a file-like extension '.{extension}' (+8)",
+ 8,
+ "value",
+ )
+ )
+ if separators and any(sep in shape for sep in (";", ",")):
+ evidence.append(
+ Evidence(
+ "value-path-list",
+ "value looks like a semicolon/comma separated list of paths (+5)",
+ 5,
+ "value",
+ )
+ )
+
+ # Percent-encoding alone is not a path signal; drop the placeholder so the
+ # evidence list only contains scoring rules.
+ return [item for item in evidence if item.weight != 0]
+
+
+# ---------------------------------------------------------------------------
+# Combine
+# ---------------------------------------------------------------------------
+def analyze_parameter(
+ name: str,
+ value: str,
+ *,
+ max_decode_passes: int = MAX_DECODE_PASSES,
+ extra_terms: Iterable[str] = (),
+ ignore: Iterable[str] = (),
+ min_score: int = 25,
+) -> Analysis:
+ """Combine name and value evidence for one parameter.
+
+ Returns an :class:`Analysis` whose ``evidence`` is empty when the
+ parameter is not a candidate. Generic names only score through their
+ value; strong names can score on their own.
+ """
+ if canonical_name(name) in {canonical_name(item) for item in ignore}:
+ return Analysis(name=name)
+
+ name_evidence = analyze_name(name, extra_terms)
+ value_evidence = analyze_value(value, max_decode_passes)
+
+ generic = any(item.rule == "name-generic" for item in name_evidence)
+ has_path_value = any(item.weight > 0 for item in value_evidence)
+
+ if generic:
+ name_evidence = [] # generic names never contribute on their own
+ if not has_path_value:
+ return Analysis(name=name)
+
+ evidence: List[Evidence] = list(name_evidence) + list(value_evidence)
+ if generic and has_path_value:
+ evidence.append(
+ Evidence(
+ "value-pairs-with-generic-name",
+ f"generic parameter name is paired with a path-like value (+{GENERIC_BONUS})",
+ GENERIC_BONUS,
+ "value",
+ )
+ )
+
+ analysis = Analysis(name=name, evidence=evidence)
+ if analysis.score < max(1, min_score):
+ return Analysis(name=name)
+
+ decoded_value = value or ""
+ passes = 0
+ if value:
+ forms = decode_forms(sanitize_text(value), max_decode_passes)
+ decoded_value = forms[-1][1]
+ passes = forms[-1][0]
+ analysis.decoded_value = decoded_value
+ analysis.decode_passes = passes
+ return analysis
diff --git a/pathscope/report.py b/pathscope/report.py
new file mode 100644
index 0000000..c8006d5
--- /dev/null
+++ b/pathscope/report.py
@@ -0,0 +1,349 @@
+"""Renderers: readable terminal output, JSON, CSV and SARIF 2.1.0.
+
+All renderers are deterministic: no timestamps, no hostnames of the analysing
+machine, no random ordering. Every string that originates from input passes
+through :func:`pathscope.textutil.sanitize_text`, so control characters cannot
+reach a terminal or a report.
+"""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+from typing import Dict, List
+
+from . import PROGRAM, __version__
+from .detector import Report
+from .textutil import encode_display, sanitize_text, truncate
+
+FORMAT_TEXT = "text"
+FORMAT_JSON = "json"
+FORMAT_CSV = "csv"
+FORMAT_SARIF = "sarif"
+FORMATS = (FORMAT_TEXT, FORMAT_JSON, FORMAT_CSV, FORMAT_SARIF)
+
+CSV_COLUMNS = (
+ "index",
+ "host",
+ "source_type",
+ "source",
+ "method",
+ "location",
+ "parameter",
+ "rule",
+ "rules",
+ "confidence",
+ "score",
+ "reasons",
+ "resource",
+ "value",
+)
+
+DISCLAIMER = (
+ "Candidates for manual review only. PathScope is passive and offline: it "
+ "sends no requests, performs no DNS lookups, injects no test values, and "
+ "never confirms or proves a vulnerability."
+)
+
+TERMINAL_WIDTH = 84
+
+
+# ---------------------------------------------------------------------------
+# Colour helper
+# ---------------------------------------------------------------------------
+class Palette:
+ """ANSI colours that are enabled only for interactive terminals."""
+
+ CODES = {
+ "bold": "1",
+ "dim": "2",
+ "red": "31",
+ "green": "32",
+ "yellow": "33",
+ "blue": "34",
+ "magenta": "35",
+ "cyan": "36",
+ "grey": "90",
+ }
+
+ def __init__(self, enabled: bool) -> None:
+ self.enabled = enabled
+
+ def paint(self, style: str, text: str) -> str:
+ if not self.enabled:
+ return text
+ return f"\x1b[{self.CODES[style]}m{text}\x1b[0m"
+
+
+def supports_color(stream) -> bool:
+ """True only when ``stream`` is a genuine interactive TTY (and TERM is sane)."""
+ try:
+ if not stream.isatty():
+ return False
+ except Exception: # pragma: no cover - exotic stream objects
+ return False
+ import os
+
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("TERM", "") == "dumb":
+ return False
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Text
+# ---------------------------------------------------------------------------
+def render_text(report: Report, colors: Palette) -> str:
+ lines: List[str] = []
+ heading = "PathScope candidates for manual review"
+ lines.append(colors.paint("bold", heading))
+ lines.append(colors.paint("grey", "=" * TERMINAL_WIDTH))
+ lines.append(
+ f"Analyzed {report.requests_analyzed} request(s) and "
+ f"{report.parameters_analyzed} parameter(s); "
+ f"{report.candidate_count} candidate(s) at score >= {report.min_score}."
+ )
+ if report.skipped:
+ lines.append(colors.paint("yellow", f"Skipped {report.skipped} input line(s) / entries."))
+ lines.append("")
+
+ if not report.findings:
+ lines.append(
+ colors.paint(
+ "green",
+ "No path-like parameter candidates were flagged. "
+ "This is not proof that the application is safe.",
+ )
+ )
+ for finding in report.findings:
+ band_color = {"high": colors.paint("red", "HIGH"),
+ "medium": colors.paint("yellow", "MEDIUM"),
+ "low": colors.paint("cyan", "LOW")}[finding.confidence]
+ lines.append(
+ f"#{finding.index} {colors.paint('bold', finding.parameter)} "
+ f"[{band_color} score {finding.score}/100]"
+ )
+ lines.append(f" {'Host':<10} {finding.host}")
+ lines.append(f" {'Source':<10} {finding.source_type}"
+ f" ({truncate(encode_display(finding.source_label), 60)})")
+ lines.append(f" {'Request':<10} {finding.method} {truncate(encode_display(finding.resource), 110)}")
+ lines.append(f" {'Location':<10} {finding.location}")
+ lines.append(f" {'Rule':<10} {finding.rule}")
+ if finding.occurrences > 1:
+ lines.append(f" {'Repeats':<10} {finding.occurrences} occurrence(s)")
+ if report.show_values:
+ shown = truncate(encode_display(finding.value or ""), 120)
+ lines.append(f" {'Value':<10} {shown if shown else ''}")
+ else:
+ lines.append(
+ f" {'Value':<10} {colors.paint('grey', '')} "
+ f"(use --show-values to display)"
+ )
+ lines.append(f" {'Why':<10}rule(s) and evidence:")
+ for reason in finding.reasons:
+ lines.append(f" - {truncate(encode_display(reason), 140)}")
+ lines.append("")
+
+ lines.append(colors.paint("grey", "Reminder: these are candidates for manual review, not "
+ "confirmed vulnerabilities. No requests were sent."))
+ return "\n".join(lines)
+
+
+# ---------------------------------------------------------------------------
+# JSON
+# ---------------------------------------------------------------------------
+def build_json_payload(report: Report) -> Dict[str, object]:
+ return {
+ "tool": PROGRAM,
+ "version": __version__,
+ "disclaimer": DISCLAIMER,
+ "passive": True,
+ "network_requests_made": 0,
+ "min_score": report.min_score,
+ "show_values": report.show_values,
+ "summary": {
+ "requests_analyzed": report.requests_analyzed,
+ "parameters_analyzed": report.parameters_analyzed,
+ "candidates": report.candidate_count,
+ "confidence": report.confidence_counts,
+ "skipped": report.skipped,
+ "sources": list(report.sources),
+ },
+ "warnings": list(report.warnings),
+ "findings": [finding.as_dict() for finding in report.findings],
+ "links": {
+ "github": "https://github.com/mrdineshpathro",
+ "instagram": "https://www.instagram.com/mr_dineshpatro",
+ "support": "https://buymeacoffee.com/mrdineshpathro",
+ },
+ }
+
+
+def render_json(report: Report) -> str:
+ return json.dumps(build_json_payload(report), indent=2, ensure_ascii=False) + "\n"
+
+
+# ---------------------------------------------------------------------------
+# CSV
+# ---------------------------------------------------------------------------
+def render_csv(report: Report) -> str:
+ buffer = io.StringIO()
+ writer = csv.writer(buffer, lineterminator="\n", quoting=csv.QUOTE_MINIMAL)
+ writer.writerow(CSV_COLUMNS)
+ for finding in report.findings:
+ writer.writerow(
+ [
+ finding.index,
+ finding.host,
+ finding.source_type,
+ finding.source_label,
+ finding.method,
+ finding.location,
+ finding.parameter,
+ finding.rule,
+ ";".join(finding.rules),
+ finding.confidence,
+ finding.score,
+ "; ".join(finding.reasons),
+ finding.resource,
+ finding.value if report.show_values else "",
+ ]
+ )
+ return buffer.getvalue()
+
+
+# ---------------------------------------------------------------------------
+# SARIF 2.1.0
+# ---------------------------------------------------------------------------
+SARIF_LEVELS = {"high": "warning", "medium": "note", "low": "note"}
+
+
+def rule_catalogue(report: Report) -> List[str]:
+ """All rule ids used by the findings, in deterministic sorted order."""
+ return sorted({rule for finding in report.findings for rule in finding.rules})
+
+
+def sarif_rules(report: Report) -> List[Dict[str, object]]:
+ """Deterministic rule catalogue built from the findings only."""
+ return [
+ {
+ "id": rule,
+ "name": rule,
+ "shortDescription": {
+ "text": f"PathScope heuristic: {rule}",
+ },
+ "help": {
+ "text": (
+ "Heuristic indicator of a path-like request parameter. "
+ "This is a candidate for manual review, not a vulnerability."
+ )
+ },
+ }
+ for rule in rule_catalogue(report)
+ ]
+
+
+def render_sarif(report: Report) -> str:
+ results: List[Dict[str, object]] = []
+ catalogue = rule_catalogue(report)
+ for finding in report.findings:
+ results.append(
+ {
+ "ruleId": finding.rule,
+ "ruleIndex": catalogue.index(finding.rule),
+ "level": SARIF_LEVELS.get(finding.confidence, "note"),
+ "message": {
+ "text": (
+ f"Parameter '{sanitize_text(finding.parameter)}' in the "
+ f"{finding.location} of {finding.method} {finding.resource} "
+ f"looks path-like (heuristic score {finding.score}/100). "
+ "Candidate for manual review only."
+ )
+ },
+ "locations": [
+ {
+ "physicalLocation": {
+ "artifactLocation": {"uri": sanitize_text(finding.resource)},
+ },
+ "logicalLocations": [
+ {"fullyQualifiedName": sanitize_text(finding.parameter)}
+ ],
+ }
+ ],
+ "properties": {
+ "host": finding.host,
+ "sourceType": finding.source_type,
+ "location": finding.location,
+ "method": finding.method,
+ "parameter": finding.parameter,
+ "score": finding.score,
+ "confidence": finding.confidence,
+ "occurrences": finding.occurrences,
+ "rules": list(finding.rules),
+ "reasons": list(finding.reasons),
+ "valueIncluded": report.show_values,
+ },
+ }
+ )
+
+ payload = {
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
+ "version": "2.1.0",
+ "runs": [
+ {
+ "tool": {
+ "driver": {
+ "name": PROGRAM,
+ "version": __version__,
+ "informationUri": "https://github.com/mrdineshpathro",
+ "semanticVersion": __version__,
+ "rules": sarif_rules(report),
+ "properties": {
+ "passive": True,
+ "disclaimer": DISCLAIMER,
+ },
+ }
+ },
+ "properties": {
+ "requestsAnalyzed": report.requests_analyzed,
+ "parametersAnalyzed": report.parameters_analyzed,
+ "candidates": report.candidate_count,
+ "minScore": report.min_score,
+ },
+ "results": results,
+ }
+ ],
+ }
+ return json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
+
+
+def render(report: Report, output_format: str, colors: Palette) -> str:
+ if output_format == FORMAT_JSON:
+ return render_json(report)
+ if output_format == FORMAT_CSV:
+ return render_csv(report)
+ if output_format == FORMAT_SARIF:
+ return render_sarif(report)
+ return render_text(report, colors)
+
+
+# ---------------------------------------------------------------------------
+# Banner
+# ---------------------------------------------------------------------------
+def render_banner(palette: Palette) -> str:
+ from . import BANNER_LINKS
+
+ lines = [palette.paint("bold", f"{PROGRAM} {__version__} - passive path-parameter triage")]
+ lines.append(palette.paint("grey", "-" * 64))
+ for label, url in BANNER_LINKS:
+ lines.append(f"{palette.paint('bold', label + ':')} {palette.paint('blue', url)}")
+ lines.append(
+ palette.paint(
+ "yellow",
+ "Candidates for manual review only. No network requests are made; "
+ "only analyze data you are authorized to review.",
+ )
+ )
+ return "\n".join(lines)
diff --git a/pathscope/sources.py b/pathscope/sources.py
new file mode 100644
index 0000000..304181b
--- /dev/null
+++ b/pathscope/sources.py
@@ -0,0 +1,577 @@
+"""Input parsing for PathScope: URLs, URL lists, stdin and local HAR 1.2 files.
+
+All parsing is local. No URL is fetched, no connection is opened, and HAR
+entries are never replayed. Parameter values are carried as plain strings.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
+from urllib.parse import unquote_plus, urlsplit, urlunsplit
+
+from .textutil import sanitize_text
+
+# Source kinds shown in reports.
+SOURCE_URL = "url"
+SOURCE_FILE = "file"
+SOURCE_STDIN = "stdin"
+SOURCE_HAR = "har"
+
+# Parameter locations.
+LOCATION_QUERY = "query"
+LOCATION_FORM = "form"
+LOCATION_JSON = "json"
+
+#: Safety limits so a hostile or accidental huge HAR cannot exhaust memory.
+MAX_HAR_ENTRIES = 20000
+MAX_JSON_DEPTH = 24
+MAX_JSON_PARAMETERS = 5000
+MAX_VALUE_CHARS = 20000
+
+QUERY_SEPARATORS = "&"
+
+
+class URLParseError(ValueError):
+ """Raised when a line cannot be interpreted as an http(s) URL."""
+
+
+class InputError(RuntimeError):
+ """Raised when an input file cannot be read or is not what it claims."""
+
+
+@dataclass(frozen=True)
+class URLInfo:
+ """Locally parsed URL metadata."""
+
+ raw: str
+ scheme: str
+ host: str
+ port: Optional[int]
+ path: str
+ query: str
+
+ @property
+ def display_host(self) -> str:
+ host = self.host
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ if self.port and self.port not in (80, 443):
+ return f"{host}:{self.port}"
+ return host
+
+ @property
+ def display_resource(self) -> str:
+ """Scheme+host+path only: the query string is never shown by default."""
+ host = self.host
+ if ":" in host and not host.startswith("["):
+ host = f"[{host}]"
+ netloc = host if not self.port else f"{host}:{self.port}"
+ return urlunsplit((self.scheme, netloc, self.path or "/", "", ""))
+
+
+@dataclass(frozen=True)
+class Parameter:
+ """One name/value pair exactly as it appears in the input."""
+
+ name: str
+ value: str
+ location: str = LOCATION_QUERY
+ occurrence: int = 1
+
+ def key(self) -> Tuple[str, str]:
+ return (self.location, canonical(self.name))
+
+
+@dataclass
+class Request:
+ """A single analysed request and the source it came from."""
+
+ url: URLInfo
+ source_type: str
+ source_label: str
+ parameters: List[Parameter] = field(default_factory=list)
+ method: str = "GET"
+ index: int = 0
+
+ @property
+ def dedupe_key(self) -> Tuple[Any, ...]:
+ return (
+ self.source_type,
+ self.source_label,
+ self.method,
+ self.url.raw,
+ tuple((p.location, p.name, p.value) for p in self.parameters),
+ )
+
+
+@dataclass
+class LoadResult:
+ """Requests plus recoverable diagnostics produced while loading."""
+
+ requests: List[Request] = field(default_factory=list)
+ warnings: List[str] = field(default_factory=list)
+ skipped: int = 0
+
+ def extend(self, other: "LoadResult") -> None:
+ self.requests.extend(other.requests)
+ self.warnings.extend(other.warnings)
+ self.skipped += other.skipped
+
+
+def canonical(name: str) -> str:
+ """Comparable form of a parameter name, without importing heuristics."""
+ text = sanitize_text(name or "").strip().lower()
+ return "_".join(part for part in text.replace("-", "_").split("_") if part)
+
+
+# ---------------------------------------------------------------------------
+# URLs
+# ---------------------------------------------------------------------------
+def parse_url(raw: str) -> URLInfo:
+ """Validate and split one URL locally. Never resolves or contacts the host."""
+ text = sanitize_text(raw or "").strip()
+ if not text:
+ raise URLParseError("blank input")
+ if any(ch.isspace() for ch in text):
+ raise URLParseError("contains whitespace")
+ if any(ord(ch) < 32 or ord(ch) == 127 for ch in raw or ""):
+ raise URLParseError("contains control characters")
+ try:
+ parts = urlsplit(text)
+ host = parts.hostname
+ port = parts.port
+ except ValueError as exc:
+ raise URLParseError(f"malformed URL ({exc})") from exc
+ scheme = (parts.scheme or "").lower()
+ if scheme not in ("http", "https"):
+ raise URLParseError(f"unsupported scheme (expected http/https, got '{scheme or 'none'}')")
+ if not parts.netloc or not host:
+ raise URLParseError("missing host")
+ return URLInfo(
+ raw=text,
+ scheme=scheme,
+ host=host,
+ port=port,
+ path=parts.path or "/",
+ query=parts.query,
+ )
+
+
+def split_query(query: str) -> List[Tuple[str, str]]:
+ """Split a raw query string into ``(name, value)`` pairs.
+
+ Kept literal (split on ``&`` then the first ``=``) so repeated parameters
+ and percent-encoded names/values survive intact. ``+`` is decoded as space
+ in the name only, matching form conventions.
+ """
+ pairs: List[Tuple[str, str]] = []
+ if not query:
+ return pairs
+ for chunk in query.split(QUERY_SEPARATORS):
+ if not chunk:
+ continue
+ raw_name, _sep, raw_value = chunk.partition("=")
+ try:
+ name = unquote_plus(raw_name)
+ except (UnicodeError, ValueError): # pragma: no cover - defensive
+ name = raw_name
+ pairs.append((sanitize_text(name), raw_value))
+ return pairs
+
+
+def query_parameters(query: str) -> List[Parameter]:
+ """Return query parameters with occurrence counters for repeated names."""
+ counts: Dict[str, int] = {}
+ parameters: List[Parameter] = []
+ for name, value in split_query(query):
+ if not name:
+ continue
+ key = canonical(name)
+ counts[key] = counts.get(key, 0) + 1
+ parameters.append(
+ Parameter(
+ name=sanitize_text(name),
+ value=sanitize_text(value)[:MAX_VALUE_CHARS],
+ location=LOCATION_QUERY,
+ occurrence=counts[key],
+ )
+ )
+ return parameters
+
+
+def request_from_url(
+ raw: str, source_type: str, source_label: str, index: int = 0
+) -> Request:
+ """Build a :class:`Request` from a URL string."""
+ info = parse_url(raw)
+ return Request(
+ url=info,
+ source_type=source_type,
+ source_label=source_label,
+ parameters=query_parameters(info.query),
+ index=index,
+ )
+
+
+# ---------------------------------------------------------------------------
+# URL lists and stdin
+# ---------------------------------------------------------------------------
+def read_text(path: str) -> str:
+ """Read a UTF-8 (BOM-tolerant) text file, raising :class:`InputError`."""
+ try:
+ with open(path, "r", encoding="utf-8-sig", errors="replace") as handle:
+ return handle.read()
+ except OSError as exc:
+ raise InputError(f"cannot read input file '{path}': {exc.strerror or exc}") from exc
+
+
+def load_url_lines(
+ lines: Iterable[str], source_type: str, label: str
+) -> LoadResult:
+ """Load one-URL-per-line input, skipping blanks, comments and duplicates."""
+ result = LoadResult()
+ seen: set = set()
+ for line_number, line in enumerate(lines, start=1):
+ candidate = sanitize_text(line).strip()
+ if not candidate or candidate.startswith("#"):
+ continue
+ if candidate in seen:
+ continue
+ try:
+ request = request_from_url(candidate, source_type, label, len(result.requests))
+ except URLParseError as exc:
+ result.warnings.append(
+ f"{label} line {line_number}: skipped malformed URL ({exc})"
+ )
+ result.skipped += 1
+ continue
+ seen.add(candidate)
+ result.requests.append(request)
+ return result
+
+
+def load_url_file(path: str) -> LoadResult:
+ return load_url_lines(read_text(path).splitlines(), SOURCE_FILE, path)
+
+
+def load_stdin_urls(text: str) -> LoadResult:
+ return load_url_lines(text.splitlines(), SOURCE_STDIN, "stdin")
+
+
+# ---------------------------------------------------------------------------
+# HAR 1.2
+# ---------------------------------------------------------------------------
+class HarError(InputError):
+ """Raised when a document is not a usable HAR file."""
+
+
+def looks_like_har(text: str, path_hint: str = "") -> bool:
+ """Cheap local heuristic: ``.har`` extension or a top-level ``log`` object."""
+ lowered = (path_hint or "").lower()
+ if lowered.endswith(".har") or lowered.endswith(".har.json"):
+ return True
+ stripped = text.lstrip("\ufeff \t\r\n")
+ if not stripped.startswith("{"):
+ return False
+ head = stripped[:4096].lower()
+ return '"log"' in head and '"entries"' in head
+
+
+def _as_text(value: Any) -> str:
+ if value is None:
+ return ""
+ if isinstance(value, str):
+ return sanitize_text(value)[:MAX_VALUE_CHARS]
+ return sanitize_text(json.dumps(value, ensure_ascii=False, sort_keys=True))[
+ :MAX_VALUE_CHARS
+ ]
+
+
+def _json_parameters(
+ payload: Any, warnings: List[str], entry_label: str
+) -> List[Parameter]:
+ """Flatten a JSON body into ``(path, scalar)`` parameters.
+
+ Nested objects use dots (``user.file``) and arrays use brackets
+ (``files[0].path``). Only scalar leaves become parameters; numbers and
+ booleans are stringified. The payload is never written anywhere.
+ """
+ parameters: List[Parameter] = []
+ stack: List[Tuple[str, Any, int]] = [("", payload, 0)]
+ truncated = False
+
+ while stack:
+ prefix, node, depth = stack.pop(0)
+ if len(parameters) >= MAX_JSON_PARAMETERS:
+ truncated = True
+ break
+ if depth > MAX_JSON_DEPTH:
+ truncated = True
+ continue
+ if isinstance(node, dict):
+ for key, value in reversed(list(node.items())):
+ name = str(key)
+ new_prefix = f"{prefix}.{name}" if prefix else name
+ stack.insert(0, (new_prefix, value, depth + 1))
+ elif isinstance(node, list):
+ for index, value in enumerate(node):
+ new_prefix = f"{prefix}[{index}]"
+ stack.insert(0, (new_prefix, value, depth + 1))
+ else:
+ if prefix:
+ parameters.append(
+ Parameter(
+ name=prefix,
+ value=_as_text(node),
+ location=LOCATION_JSON,
+ )
+ )
+
+ if truncated:
+ warnings.append(
+ f"{entry_label}: JSON body exceeded limits "
+ f"({MAX_JSON_PARAMETERS} parameters / depth {MAX_JSON_DEPTH}); "
+ "analysis truncated"
+ )
+ return parameters
+
+
+def _form_parameters(
+ body: Dict[str, Any], entry_label: str, warnings: List[str]
+) -> List[Parameter]:
+ """Extract form parameters from a HAR ``postData`` object."""
+ parameters: List[Parameter] = []
+ mime = str(body.get("mimeType") or "").lower()
+ text = body.get("text")
+ raw_params = body.get("params")
+
+ if isinstance(raw_params, list):
+ for item in raw_params:
+ if not isinstance(item, dict):
+ continue
+ name = _as_text(item.get("name"))
+ if not name:
+ continue
+ if item.get("value") is not None:
+ value = _as_text(item.get("value"))
+ elif item.get("fileName"):
+ # Multipart uploads record the client-side file name here.
+ value = _as_text(item.get("fileName"))
+ else:
+ value = ""
+ parameters.append(Parameter(name=name, value=value, location=LOCATION_FORM))
+ if parameters:
+ return parameters
+
+ if isinstance(text, str) and text:
+ if "json" in mime:
+ try:
+ payload = json.loads(text)
+ except ValueError as exc:
+ warnings.append(f"{entry_label}: malformed JSON body skipped ({exc})")
+ return []
+ return _json_parameters(payload, warnings, entry_label)
+ if "x-www-form-urlencoded" in mime or mime == "":
+ pairs = split_query(text)
+ if pairs and "=" in text:
+ return [
+ Parameter(
+ name=name,
+ value=sanitize_text(value)[:MAX_VALUE_CHARS],
+ location=LOCATION_FORM,
+ )
+ for name, value in pairs
+ if name
+ ]
+ return parameters
+
+
+def _har_entry_parameters(
+ request: Dict[str, Any], entry_label: str, warnings: List[str]
+) -> Tuple[URLInfo, List[Parameter]]:
+ raw_url = request.get("url")
+ if not isinstance(raw_url, str) or not raw_url:
+ raise URLParseError("missing request.url")
+ info = parse_url(raw_url)
+
+ parameters: List[Parameter] = []
+
+ # Query: prefer the recorded queryString, else derive from the URL.
+ query_list = request.get("queryString")
+ if isinstance(query_list, list) and query_list:
+ counts: Dict[str, int] = {}
+ for item in query_list:
+ if not isinstance(item, dict):
+ continue
+ name = _as_text(item.get("name"))
+ if not name:
+ continue
+ key = canonical(name)
+ counts[key] = counts.get(key, 0) + 1
+ parameters.append(
+ Parameter(
+ name=name,
+ value=_as_text(item.get("value")),
+ location=LOCATION_QUERY,
+ occurrence=counts[key],
+ )
+ )
+ else:
+ parameters.extend(query_parameters(info.query))
+
+ # Bodies: only present when the HAR recorded them.
+ post_data = request.get("postData")
+ if isinstance(post_data, dict):
+ parameters.extend(_form_parameters(post_data, entry_label, warnings))
+
+ return info, parameters
+
+
+def load_har(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse a HAR 1.2 document. Raises :class:`HarError` if unusable."""
+ source_label = source_label or label
+ try:
+ document = json.loads(text.lstrip("\ufeff"))
+ except ValueError as exc:
+ raise HarError(f"{label}: not valid JSON ({exc})") from exc
+
+ if not isinstance(document, dict):
+ raise HarError(f"{label}: HAR root must be a JSON object")
+ log = document.get("log")
+ if not isinstance(log, dict):
+ raise HarError(f"{label}: missing HAR 'log' object")
+ version = log.get("version")
+ if not isinstance(version, str) or not version.startswith("1."):
+ warnings_version = version if isinstance(version, str) else "missing"
+ # Not fatal: many exporters omit or vary the version field.
+ version_warning = (
+ f"{label}: HAR version '{warnings_version}' is not 1.x; "
+ "entries will still be parsed defensively"
+ )
+ else:
+ version_warning = ""
+
+ entries = log.get("entries")
+ if not isinstance(entries, list):
+ raise HarError(f"{label}: HAR 'log.entries' must be an array")
+
+ result = LoadResult()
+ if version_warning:
+ result.warnings.append(version_warning)
+ if len(entries) > MAX_HAR_ENTRIES:
+ result.warnings.append(
+ f"{label}: {len(entries)} entries exceed the limit of {MAX_HAR_ENTRIES}; "
+ "only the first entries are analyzed"
+ )
+ entries = entries[:MAX_HAR_ENTRIES]
+
+ seen: set = set()
+ for entry_index, entry in enumerate(entries):
+ entry_label = f"{label} entry {entry_index}"
+ if not isinstance(entry, dict):
+ result.warnings.append(f"{entry_label}: skipped non-object entry")
+ result.skipped += 1
+ continue
+ request = entry.get("request")
+ if not isinstance(request, dict):
+ result.warnings.append(f"{entry_label}: skipped entry without a request")
+ result.skipped += 1
+ continue
+ try:
+ info, parameters = _har_entry_parameters(request, entry_label, result.warnings)
+ except URLParseError as exc:
+ result.warnings.append(f"{entry_label}: skipped malformed request URL ({exc})")
+ result.skipped += 1
+ continue
+ except (TypeError, ValueError) as exc: # pragma: no cover - defensive
+ result.warnings.append(f"{entry_label}: skipped unreadable entry ({exc})")
+ result.skipped += 1
+ continue
+
+ method = _as_text(request.get("method") or "GET").upper()
+ request_key = (method, info.raw, tuple((p.location, p.name, p.value) for p in parameters))
+ if request_key in seen:
+ continue
+ seen.add(request_key)
+
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_HAR,
+ source_label=source_label,
+ parameters=parameters,
+ method=method,
+ index=len(result.requests),
+ )
+ )
+ return result
+
+
+def load_har_file(path: str) -> LoadResult:
+ return load_har(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+def load_stdin_har(text: str) -> LoadResult:
+ return load_har(text, "stdin")
+
+
+# ---------------------------------------------------------------------------
+# Format detection and dispatch
+# ---------------------------------------------------------------------------
+INPUT_FORMAT_AUTO = "auto"
+INPUT_FORMAT_URLS = "urls"
+INPUT_FORMAT_HAR = "har"
+INPUT_FORMATS = (INPUT_FORMAT_AUTO, INPUT_FORMAT_URLS, INPUT_FORMAT_HAR)
+
+
+def detect_input_format(text: str, path: str = "") -> str:
+ """Return ``har`` or ``urls`` for a text blob and optional filename."""
+ return INPUT_FORMAT_HAR if looks_like_har(text, path) else INPUT_FORMAT_URLS
+
+
+def load_file(path: str, input_format: str = INPUT_FORMAT_AUTO) -> LoadResult:
+ """Load a file as URLs or HAR, honouring an explicit format when given."""
+ if input_format == INPUT_FORMAT_HAR:
+ return load_har_file(path)
+ if input_format == INPUT_FORMAT_URLS:
+ return load_url_file(path)
+ text = read_text(path)
+ if detect_input_format(text, path) == INPUT_FORMAT_HAR:
+ return load_har(text, os.path.basename(path) or path, source_label=path)
+ return load_url_lines(text.splitlines(), SOURCE_FILE, path)
+
+
+def load_stdin(text: str, input_format: str = INPUT_FORMAT_AUTO) -> LoadResult:
+ if input_format == INPUT_FORMAT_HAR:
+ return load_stdin_har(text)
+ if input_format == INPUT_FORMAT_URLS:
+ return load_stdin_urls(text)
+ if detect_input_format(text) == INPUT_FORMAT_HAR:
+ return load_stdin_har(text)
+ return load_stdin_urls(text)
+
+
+def make_url_requests(urls: Sequence[str]) -> LoadResult:
+ """Load ``--url`` values, reporting each malformed one non-fatally."""
+ result = LoadResult()
+ seen: set = set()
+ for index, raw in enumerate(urls, start=1):
+ candidate = sanitize_text(raw).strip()
+ if not candidate:
+ result.warnings.append(f"--url #{index}: skipped blank URL")
+ result.skipped += 1
+ continue
+ if candidate in seen:
+ continue
+ try:
+ request = request_from_url(candidate, SOURCE_URL, "--url")
+ except URLParseError as exc:
+ result.warnings.append(f"--url #{index}: skipped malformed URL ({exc})")
+ result.skipped += 1
+ continue
+ seen.add(candidate)
+ result.requests.append(request)
+ return result
diff --git a/pathscope/textutil.py b/pathscope/textutil.py
new file mode 100644
index 0000000..5231a3a
--- /dev/null
+++ b/pathscope/textutil.py
@@ -0,0 +1,109 @@
+"""String helpers shared by PathScope.
+
+Everything in this module is pure string processing. Nothing here touches the
+filesystem, the network, or the process environment beyond explicit arguments.
+"""
+
+from __future__ import annotations
+
+import unicodedata
+from typing import Iterable, List, Tuple
+from urllib.parse import unquote, unquote_plus
+
+#: Maximum number of percent-decoding passes applied to one value. Early exit
+#: keeps decoding cheap when the value contains nothing encoded.
+MAX_DECODE_PASSES = 3
+
+#: A value is decoded only when it contains a percent escape. This keeps large
+#: bodies and ordinary words out of the decoder entirely.
+_PERCENT = "%"
+
+
+def sanitize_text(value: str) -> str:
+ """Normalise to NFC and remove Unicode control characters.
+
+ This is applied to every string that reaches a renderer, so a crafted
+ parameter value cannot inject ANSI escapes or other terminal control codes
+ into the output.
+ """
+ normalized = unicodedata.normalize("NFC", value)
+ return "".join(ch for ch in normalized if unicodedata.category(ch)[0] != "C")
+
+
+def truncate(text: str, limit: int = 160) -> str:
+ """Shorten ``text`` to ``limit`` characters with a trailing ellipsis."""
+ if len(text) <= limit:
+ return text
+ if limit <= 1:
+ return "\u2026"[:limit]
+ return text[: limit - 1] + "\u2026"
+
+
+def decode_value(value: str, max_passes: int = MAX_DECODE_PASSES, plus: bool = False) -> Tuple[str, int]:
+ """Percent-decode ``value`` in memory, at most ``max_passes`` times.
+
+ Returns ``(decoded_text, passes_applied)``. Decoding never raises: malformed
+ escapes are left as-is and invalid UTF-8 is replaced, because the goal is to
+ *read* a value, never to interpret or use it.
+ """
+ decoder = unquote_plus if plus else unquote
+ current = value
+ passes = 0
+ while passes < max_passes and _PERCENT in current:
+ try:
+ decoded = decoder(current, errors="replace")
+ except (UnicodeError, ValueError): # pragma: no cover - defensive only
+ break
+ if decoded == current:
+ break
+ current = decoded
+ passes += 1
+ return current, passes
+
+
+def decode_forms(value: str, max_passes: int = MAX_DECODE_PASSES) -> List[Tuple[int, str]]:
+ """Return every decoding stage of ``value`` as ``(passes, text)``.
+
+ Stage 0 is the untouched value. Later stages are produced by
+ repeated percent-decoding, and duplicate stages are collapsed so a value
+ is never scored twice for the same evidence.
+ """
+ forms: List[Tuple[int, str]] = [(0, value)]
+ current = value
+ for stage in range(1, max_passes + 1):
+ if _PERCENT not in current:
+ break
+ try:
+ decoded = unquote(current, errors="replace")
+ except (UnicodeError, ValueError): # pragma: no cover - defensive only
+ break
+ if decoded == current:
+ break
+ current = decoded
+ forms.append((stage, decoded))
+ return forms
+
+
+def dedupe(items: Iterable[str]) -> List[str]:
+ """Order-preserving de-duplication."""
+ seen = set()
+ result: List[str] = []
+ for item in items:
+ if item in seen:
+ continue
+ seen.add(item)
+ result.append(item)
+ return result
+
+
+def encode_display(text: str) -> str:
+ """Flatten ``text`` onto one display line.
+
+ Control characters are replaced with a single space (not deleted) so that
+ ``"a\nb"`` does not silently become ``"ab"`` in reports.
+ """
+ flattened = "".join(
+ " " if (ch.isspace() or unicodedata.category(ch)[0] == "C") else ch
+ for ch in text
+ )
+ return " ".join(flattened.split())
diff --git a/tests/test_path_detector.py b/tests/test_path_detector.py
index 5b68a90..cc5f887 100755
--- a/tests/test_path_detector.py
+++ b/tests/test_path_detector.py
@@ -1,23 +1,29 @@
#!/usr/bin/env python3
-"""Unit tests for PathScope.
+"""Tests for PathScope (stdlib ``unittest`` only, fully offline).
+
+Run from the project root:
-Run with:
python3 -m unittest discover -s tests -v
-or:
python3 tests/test_path_detector.py
-The tests are split into four groups:
- 1. heuristic unit tests (names, values, extensions),
- 2. URL parsing / analysis tests (repeats, encoding, masking),
- 3. input handling tests (files, blank lines, duplicates),
- 4. end-to-end CLI tests, including safety guarantees.
+Coverage maps to the project requirements:
-Everything runs offline: PathScope never opens a socket, and one test proves it.
+* repeated query parameters and URL decoding -> TestQueryParsing
+* literal / encoded / multi-encoded traversal -> TestValueHeuristics
+* parameter-name heuristics and non-findings -> TestNameHeuristics
+* HAR query, form and JSON parameters -> TestHarInput
+* malformed input and graceful errors -> TestMalformedInput, TestCli
+* value redaction and --show-values -> TestRedaction, TestCli
+* stable JSON, CSV and SARIF output -> TestReportFormats
+* no network access in the implementation -> TestSafety
"""
from __future__ import annotations
import ast
+import builtins
+import csv
+import io
import json
import os
import subprocess
@@ -31,17 +37,66 @@
SCRIPT = REPO_ROOT / "path_detector.py"
sys.path.insert(0, str(REPO_ROOT))
-import path_detector as pd # noqa: E402 (path setup must happen first)
+from pathscope import BANNER_LINKS, __version__ # noqa: E402
+from pathscope import cli, config, detector, heuristics, report, sources, textutil # noqa: E402
+
+HAR_SAMPLE = {
+ "log": {
+ "version": "1.2",
+ "creator": {"name": "unit-test", "version": "1"},
+ "entries": [
+ {
+ "request": {
+ "method": "GET",
+ "url": "https://app.test/files?path=../../etc/passwd&lang=en",
+ "queryString": [
+ {"name": "path", "value": "../../etc/passwd"},
+ {"name": "lang", "value": "en"},
+ ],
+ },
+ "response": {"status": 200},
+ },
+ {
+ "request": {
+ "method": "POST",
+ "url": "https://app.test/upload",
+ "postData": {
+ "mimeType": "application/x-www-form-urlencoded",
+ "text": "attachment=%2Ftmp%2Freport.pdf¬e=hello",
+ },
+ }
+ },
+ {
+ "request": {
+ "method": "POST",
+ "url": "https://app.test/api",
+ "postData": {
+ "mimeType": "application/json",
+ "text": json.dumps(
+ {
+ "file": {"path": "C:\\Windows\\win.ini"},
+ "ids": [1, 2],
+ "name": "x",
+ }
+ ),
+ },
+ }
+ },
+ ],
+ }
+}
+
-BANNER_LINKS = (
- ("GitHub", "https://github.com/mrdineshpathro"),
- ("Instagram", "https://www.instagram.com/mr_dineshpatro"),
- ("Support", "https://buymeacoffee.com/mrdineshpathro"),
-)
+def banner_line(label: str) -> str:
+ """The exact branded line for a label, e.g. ``GitHub: https://...``."""
+ for known, url in BANNER_LINKS:
+ if known == label:
+ return f"{label}: {url}"
+ raise KeyError(label)
-def run_cli(*args: str, stdin: str = "", timeout: int = 30) -> subprocess.CompletedProcess:
- """Run the real CLI as a subprocess (no TTY, so no colour)."""
+def run_cli(*args: str, stdin: str = "", timeout: int = 45) -> subprocess.CompletedProcess:
+ """Run the real CLI in a subprocess (stdout/stderr are pipes, so no colour)."""
env = dict(os.environ)
env.pop("NO_COLOR", None)
env["TERM"] = "xterm-256color"
@@ -56,568 +111,1000 @@ def run_cli(*args: str, stdin: str = "", timeout: int = 30) -> subprocess.Comple
)
+def run_inprocess(*args: str, stdin: str = ""):
+ """Run the CLI in-process with captured streams."""
+ out, err = io.StringIO(), io.StringIO()
+ code = cli.run(list(args), stdout=out, stderr=err, stdin_text=stdin)
+ return code, out.getvalue(), err.getvalue()
+
+
+def write_temp(name: str, content: str, binary: bool = False) -> str:
+ handle = tempfile.NamedTemporaryFile(
+ "wb" if binary else "w",
+ suffix=name,
+ delete=False,
+ encoding=None if binary else "utf-8",
+ )
+ with handle as stream:
+ stream.write(content)
+ return handle.name
+
+
# ---------------------------------------------------------------------------
-# 1. Heuristic unit tests
+# textutil
# ---------------------------------------------------------------------------
-class TestTokenizeName(unittest.TestCase):
- def test_snake_case(self):
- self.assertEqual(pd.tokenize_name("file_path"), ["file", "path"])
+class TestTextUtil(unittest.TestCase):
+ def test_sanitize_removes_control_characters(self):
+ dirty = "file\x1b[31m.pdf\x00\x07"
+ clean = textutil.sanitize_text(dirty)
+ self.assertNotIn("\x1b", clean)
+ self.assertNotIn("\x00", clean)
+ self.assertNotIn("\x07", clean)
+ self.assertEqual(clean, "file[31m.pdf")
- def test_kebab_case(self):
- self.assertEqual(pd.tokenize_name("user-file-name"), ["user", "file", "name"])
+ def test_truncate(self):
+ self.assertEqual(textutil.truncate("abcdef", 4), "abc\u2026")
+ self.assertEqual(textutil.truncate("abc", 10), "abc")
- def test_camel_case(self):
- self.assertEqual(pd.tokenize_name("fileName"), ["file", "name"])
+ def test_decode_single(self):
+ decoded, passes = textutil.decode_value("%2e%2e%2fetc")
+ self.assertEqual(decoded, "../etc")
+ self.assertEqual(passes, 1)
- def test_pascal_case(self):
- self.assertEqual(pd.tokenize_name("DownloadFile"), ["download", "file"])
+ def test_decode_multi(self):
+ decoded, passes = textutil.decode_value("%252e%252e%252fetc")
+ self.assertEqual(decoded, "../etc")
+ self.assertEqual(passes, 2)
- def test_mixed_noise(self):
- self.assertEqual(pd.tokenize_name(" TEMPLATE__id "), ["template", "id"])
+ def test_decode_is_bounded(self):
+ decoded, passes = textutil.decode_value("%25252e%25252e", max_passes=1)
+ self.assertEqual(passes, 1)
+ self.assertEqual(decoded, "%252e%252e")
- def test_empty(self):
- self.assertEqual(pd.tokenize_name(""), [])
+ def test_decode_malformed_does_not_raise(self):
+ for value in ("%zz", "%", "%E0%A4%A", "%FF%FE"):
+ decoded, _passes = textutil.decode_value(value)
+ self.assertIsInstance(decoded, str)
+ def test_decode_noop_without_percent(self):
+ self.assertEqual(textutil.decode_value("../../etc"), ("../../etc", 0))
-class TestAnalyzeName(unittest.TestCase):
- def test_strong_keyword(self):
- analysis = pd.analyze_name("file")
- self.assertGreaterEqual(analysis.score, 30)
- self.assertEqual(analysis.keyword, "file")
+ def test_decode_forms_dedupes(self):
+ forms = textutil.decode_forms("plain")
+ self.assertEqual(forms, [(0, "plain")])
- def test_compound_keyword(self):
- analysis = pd.analyze_name("basepath")
- self.assertGreaterEqual(analysis.score, 25)
+ def test_dedupe_preserves_order(self):
+ self.assertEqual(textutil.dedupe(["b", "a", "b", "c", "a"]), ["b", "a", "c"])
- def test_camel_compound(self):
- analysis = pd.analyze_name("downloadFile")
- self.assertGreaterEqual(analysis.score, 35)
+ def test_encode_display_flattens_whitespace(self):
+ self.assertEqual(textutil.encode_display("a\nb\tc"), "a b c")
- def test_prefix_match(self):
- analysis = pd.analyze_name("filedata")
- self.assertIsNotNone(analysis.reason)
- self.assertGreater(analysis.score, 0)
- def test_generic_name_is_not_a_keyword(self):
- analysis = pd.analyze_name("image")
- self.assertTrue(analysis.generic)
- self.assertEqual(analysis.score, 0)
- self.assertIsNone(analysis.reason)
+# ---------------------------------------------------------------------------
+# Heuristics: parameter names
+# ---------------------------------------------------------------------------
+class TestNameHeuristics(unittest.TestCase):
+ def test_tokenize_variants(self):
+ self.assertEqual(heuristics.tokenize_name("fileName"), ["file", "name"])
+ self.assertEqual(heuristics.tokenize_name("base_path"), ["base", "path"])
+ self.assertEqual(heuristics.tokenize_name("X-File-Path"), ["x", "file", "path"])
+ self.assertEqual(heuristics.tokenize_name("FILES"), ["files"])
+ self.assertEqual(heuristics.tokenize_name("file_path2"), ["file", "path", "2"])
+ self.assertEqual(heuristics.tokenize_name(""), [])
+
+ def test_exact_name_terms(self):
+ for name in ("file", "path", "dir", "folder", "template", "include",
+ "download", "page", "resource", "attachment", "filepath"):
+ rules = [e.rule for e in heuristics.analyze_name(name)]
+ self.assertIn("name-exact", rules, name)
+
+ def test_multiword_name_bonus(self):
+ single = sum(e.weight for e in heuristics.analyze_name("file"))
+ multi = sum(e.weight for e in heuristics.analyze_name("download_file"))
+ self.assertGreater(multi, single)
+
+ def test_camel_case_and_kebab_case(self):
+ for name in ("fileName", "file-name", "file_name"):
+ self.assertGreater(sum(e.weight for e in heuristics.analyze_name(name)), 0)
+
+ def test_prefix_match_is_discounted(self):
+ exact = sum(e.weight for e in heuristics.analyze_name("file"))
+ prefix = sum(e.weight for e in heuristics.analyze_name("filedata"))
+ self.assertGreater(prefix, 0)
+ self.assertLess(prefix, exact)
+
+ def test_ordinary_names_are_not_flagged(self):
+ for name in ("q", "search", "utm_source", "utm_campaign", "gclid",
+ "fbclid", "urlencoded", "landscape", "session", "sort",
+ "orderby", "callback", "x" * 40):
+ evidence = heuristics.analyze_name(name)
+ total = sum(item.weight for item in evidence)
+ self.assertLess(total, 25, name)
+
+ def test_generic_names_score_zero_alone(self):
+ for name in ("image", "img", "target", "ref", "avatar"):
+ evidence = heuristics.analyze_name(name)
+ self.assertEqual(sum(item.weight for item in evidence), 0, name)
+ self.assertIn("name-generic", [item.rule for item in evidence], name)
+
+ def test_custom_terms(self):
+ evidence = heuristics.analyze_name("cdn_blob", extra_terms=["cdn_blob"])
+ self.assertEqual([e.rule for e in evidence], ["name-custom"])
+ # A built-in term always wins over a configured duplicate.
+ evidence = heuristics.analyze_name("media_file", extra_terms=["media_file", "download"])
+ self.assertEqual([e.rule for e in evidence], ["name-exact"])
+
+ def test_custom_term_does_not_override_builtin(self):
+ rules = [e.rule for e in heuristics.analyze_name("file", extra_terms=["file"])]
+ self.assertEqual(rules, ["name-exact"])
+
+ def test_canonical_name(self):
+ self.assertEqual(heuristics.canonical_name("File_Name"), "file_name")
+ self.assertEqual(heuristics.canonical_name("file-name"), "file_name")
- def test_unrelated_simple_name(self):
- analysis = pd.analyze_name("q")
- self.assertEqual(analysis.score, 0)
- def test_weak_multipart_name(self):
- analysis = pd.analyze_name("some_thing")
- self.assertTrue(analysis.weak)
- self.assertLess(analysis.score, 15)
+# ---------------------------------------------------------------------------
+# Heuristics: values
+# ---------------------------------------------------------------------------
+class TestValueHeuristics(unittest.TestCase):
+ def score(self, value: str, **kwargs) -> int:
+ return sum(item.weight for item in heuristics.analyze_value(value, **kwargs))
+
+ def rules(self, value: str, **kwargs):
+ return [item.rule for item in heuristics.analyze_value(value, **kwargs)]
+
+ def test_literal_traversal(self):
+ self.assertIn("value-traversal", self.rules("../../etc/passwd"))
+ self.assertIn("value-traversal", self.rules(r"..\..\windows\win.ini"))
+ self.assertIn("value-traversal", self.rules(".."))
+ self.assertIn("value-traversal", self.rules("foo/../bar"))
+
+ def test_traversal_must_be_a_segment(self):
+ for value in ("report..pdf", "v1..2", "version 1..2", "a..b", "..hidden"):
+ self.assertNotIn("value-traversal", self.rules(value), value)
+
+ def test_encoded_traversal(self):
+ rules = self.rules("%2e%2e%2f%2e%2e%2fetc%2fpasswd")
+ self.assertIn("value-encoded-traversal", rules)
+ self.assertIn("value-encoded-slash", rules)
+ self.assertNotIn("value-traversal", rules)
+
+ def test_partially_encoded_traversal(self):
+ rules = self.rules("..%2f..%2fetc%2fpasswd")
+ self.assertIn("value-encoded-traversal", rules)
+
+ def test_double_encoded_traversal(self):
+ rules = self.rules("%252e%252e%252f%252e%252e%252fetc%252fpasswd")
+ self.assertIn("value-encoded-traversal", rules)
+ self.assertIn("value-double-encoded", rules)
+
+ def test_decoding_is_bounded(self):
+ # Four nested encodings must not be decoded with the default 3 passes.
+ rules = self.rules("%25252e%25252e%25252f", max_decode_passes=2)
+ self.assertNotIn("value-encoded-traversal", rules)
+
+ def test_traversal_not_counted_twice(self):
+ plain = self.score("../../etc/passwd")
+ encoded = self.score("%2e%2e%2f%2e%2e%2fetc%2fpasswd")
+ self.assertGreater(plain, 0)
+ self.assertGreaterEqual(plain, encoded)
+
+ def test_absolute_paths(self):
+ self.assertIn("value-absolute", self.rules("/var/www/html"))
+ self.assertIn("value-windows-drive", self.rules("C:\\Windows\\win.ini"))
+ self.assertIn("value-windows-drive", self.rules("D:/data/x"))
+ self.assertIn("value-unc", self.rules(r"\\server\share\x"))
+
+ def test_protocol_relative_is_not_absolute(self):
+ self.assertNotIn("value-absolute", self.rules("//cdn.test/x.js"))
- def test_unrelated_name_does_not_mention_exploit(self):
- analysis = pd.analyze_name("path")
- self.assertNotIn("exploit", (analysis.reason or "").lower())
+ def test_full_url_is_penalised(self):
+ self.assertIn("value-full-url", self.rules("https://other.test/a/b"))
+ self.assertLess(self.score("https://other.test/a/b"), 0)
+
+ def test_extension_on_path_like_value(self):
+ self.assertIn("value-extension", self.rules("/static/app.js"))
+ self.assertIn("value-extension", self.rules("report.tar.gz"))
+
+ def test_plain_values_score_zero(self):
+ for value in ("", "hello", "en", "12345", "true", "50%", "%zz", "name"):
+ self.assertEqual(self.score(value), 0, value)
+
+ def test_malformed_encoding_is_safe(self):
+ for value in ("%", "%E0%A4%A", "%zz%2e", "%FF/%FE"):
+ self.assertIsInstance(self.rules(value), list)
+
+ def test_analyze_parameter_combines_layers(self):
+ analysis = heuristics.analyze_parameter("file", "../../etc/passwd")
+ self.assertIn("name-exact", analysis.rules)
+ self.assertIn("value-traversal", analysis.rules)
+ self.assertGreaterEqual(analysis.score, 60)
+ self.assertIn(analysis.confidence, {"medium", "high"})
+
+ def test_generic_name_needs_path_value(self):
+ self.assertFalse(heuristics.analyze_parameter("image", "logo").evidence)
+ analysis = heuristics.analyze_parameter("image", "/static/logo.png")
+ self.assertTrue(analysis.evidence)
+ self.assertIn("value-pairs-with-generic-name", analysis.rules)
+
+ def test_ordinary_parameter_is_not_a_finding(self):
+ for name, value in (("lang", "en"), ("test", "2"), ("q", "hello"),
+ ("utm_source", "newsletter"), ("id", "42")):
+ analysis = heuristics.analyze_parameter(name, value)
+ self.assertEqual(analysis.evidence, [], (name, value))
+
+ def test_ignore_list(self):
+ analysis = heuristics.analyze_parameter("file", "../../etc/passwd", ignore=["file"])
+ self.assertEqual(analysis.evidence, [])
+
+ def test_min_score_filter(self):
+ self.assertFalse(heuristics.analyze_parameter("page", "2", min_score=60).evidence)
+ self.assertTrue(heuristics.analyze_parameter("page", "2", min_score=25).evidence)
+
+ def test_reasons_are_explainable_and_neutral(self):
+ analysis = heuristics.analyze_parameter("file", "%2e%2e%2fetc%2fpasswd")
+ blob = " ".join(analysis.reasons).lower()
+ for banned in ("exploitable", "vulnerable", "confirmed", "attack"):
+ self.assertNotIn(banned, blob)
+ self.assertTrue(analysis.reasons)
-class TestExtensionOf(unittest.TestCase):
- def test_common_extension(self):
- self.assertEqual(pd.extension_of("report.pdf"), "pdf")
+# ---------------------------------------------------------------------------
+# Sources: URLs and query parsing
+# ---------------------------------------------------------------------------
+class TestQueryParsing(unittest.TestCase):
+ def test_parse_url(self):
+ info = sources.parse_url("https://Example.Test:8443/a/b?x=1")
+ self.assertEqual(info.scheme, "https")
+ self.assertEqual(info.host, "example.test")
+ self.assertEqual(info.port, 8443)
+ self.assertEqual(info.path, "/a/b")
+ self.assertEqual(info.query, "x=1")
+ self.assertEqual(info.display_host, "example.test:8443")
+
+ def test_display_resource_excludes_query(self):
+ info = sources.parse_url("https://example.test/a?secret=abc#frag")
+ self.assertNotIn("secret", info.display_resource)
+ self.assertNotIn("abc", info.display_resource)
+
+ def test_repeated_parameters(self):
+ params = sources.query_parameters("file=a.txt&file=b.txt&file=c.txt")
+ self.assertEqual([p.value for p in params], ["a.txt", "b.txt", "c.txt"])
+ self.assertEqual([p.occurrence for p in params], [1, 2, 3])
+
+ def test_encoded_names_and_values(self):
+ params = sources.query_parameters("%66%69%6c%65=..%2Freports%2Fq1.pdf")
+ self.assertEqual(params[0].name, "file")
+ self.assertEqual(params[0].value, "..%2Freports%2Fq1.pdf")
+
+ def test_plus_is_space_in_names(self):
+ params = sources.query_parameters("file+name=x")
+ self.assertEqual(params[0].name, "file name")
+
+ def test_blank_values_and_bare_keys(self):
+ params = sources.query_parameters("file=&path")
+ self.assertEqual([(p.name, p.value) for p in params], [("file", ""), ("path", "")])
+
+ def test_semicolon_is_not_a_separator(self):
+ params = sources.query_parameters("a=1;b=2&c=3")
+ self.assertEqual([p.name for p in params], ["a", "c"])
+
+ def test_ampersand_inside_encoded_value(self):
+ params = sources.query_parameters("next=%2Fhome%3Ftab%3Dfiles&file=a.txt")
+ self.assertEqual([p.name for p in params], ["next", "file"])
- def test_path_extension(self):
- self.assertEqual(pd.extension_of("../../etc/shadow.txt"), "txt")
+ def test_empty_query(self):
+ self.assertEqual(sources.query_parameters(""), [])
- def test_multi_extension(self):
- self.assertEqual(pd.extension_of("backup.tar.gz"), "tar.gz")
+ def test_blank_query_chunks_are_skipped(self):
+ self.assertEqual([p.name for p in sources.query_parameters("&&a=1&&")], ["a"])
- def test_no_extension(self):
- self.assertIsNone(pd.extension_of("justwords"))
+ def test_invalid_scheme(self):
+ for url in ("ftp://a.test/x", "javascript:alert(1)", "file:///etc/passwd",
+ "example.test/a?x=1", "https:///a"):
+ with self.assertRaises(sources.URLParseError, msg=url):
+ sources.parse_url(url)
- def test_unknown_extension(self):
- self.assertIsNone(pd.extension_of("malware.xyzzy"))
+ def test_whitespace_url_is_rejected(self):
+ with self.assertRaises(sources.URLParseError):
+ sources.parse_url("https://a.test/a b?file=x")
+ def test_bad_port(self):
+ with self.assertRaises(sources.URLParseError):
+ sources.parse_url("https://a.test:99999/")
-class TestAnalyzeValue(unittest.TestCase):
- def test_file_name(self):
- analysis = pd.analyze_value("report.pdf")
- self.assertGreaterEqual(analysis.score, 20)
- self.assertTrue(any("pdf" in reason for reason in analysis.reasons))
+ def test_ipv6_display(self):
+ info = sources.parse_url("http://[::1]:8080/?file=x")
+ self.assertEqual(info.display_host, "[::1]:8080")
- def test_plain_word(self):
- self.assertEqual(pd.analyze_value("hello").score, 0)
- def test_empty_value(self):
- self.assertEqual(pd.analyze_value("").score, 0)
+class TestUrlListInput(unittest.TestCase):
+ def test_blank_lines_comments_and_duplicates(self):
+ result = sources.load_url_lines(
+ ["", " ", "# note", "https://a.test/?file=x", "https://a.test/?file=x",
+ "https://b.test/?page=2"],
+ sources.SOURCE_FILE, "urls.txt",
+ )
+ self.assertEqual(len(result.requests), 2)
+ self.assertEqual(result.warnings, [])
+ self.assertEqual(result.skipped, 0)
+
+ def test_malformed_lines_are_warnings(self):
+ result = sources.load_url_lines(
+ ["not-a-url", "https://ok.test/?file=x", "ftp://bad.test/"],
+ sources.SOURCE_FILE, "urls.txt",
+ )
+ self.assertEqual(len(result.requests), 1)
+ self.assertEqual(result.skipped, 2)
+ self.assertEqual(len(result.warnings), 2)
+ self.assertIn("urls.txt line 1", result.warnings[0])
+
+ def test_source_metadata(self):
+ result = sources.load_url_lines(["https://a.test/?file=x"], sources.SOURCE_STDIN, "stdin")
+ request = result.requests[0]
+ self.assertEqual(request.source_type, "stdin")
+ self.assertEqual(request.source_label, "stdin")
+
+ def test_url_flags(self):
+ result = sources.make_url_requests(
+ ["https://a.test/?file=x", "https://a.test/?file=x", "bad", ""]
+ )
+ self.assertEqual(len(result.requests), 1)
+ self.assertEqual(result.skipped, 2)
- def test_traversal(self):
- analysis = pd.analyze_value("../../etc/passwd")
- self.assertGreaterEqual(analysis.score, 40)
- self.assertTrue(any("parent-directory" in reason for reason in analysis.reasons))
- def test_encoded_traversal_counts_once(self):
- encoded = pd.analyze_value("%2e%2e%2f%2e%2e%2fetc%2fpasswd")
- decoded = pd.analyze_value("../../etc/passwd")
- self.assertGreaterEqual(encoded.score, 30)
- self.assertLessEqual(encoded.score, decoded.score)
+# ---------------------------------------------------------------------------
+# HAR input
+# ---------------------------------------------------------------------------
+class TestHarInput(unittest.TestCase):
+ def load(self, payload) -> sources.LoadResult:
+ text = payload if isinstance(payload, str) else json.dumps(payload)
+ return sources.load_har(text, "sample.har")
+
+ def test_query_parameters(self):
+ result = self.load(HAR_SAMPLE)
+ query = [p for r in result.requests for p in r.parameters if p.location == "query"]
+ self.assertEqual({p.name for p in query}, {"path", "lang"})
+ self.assertEqual(result.requests[0].source_type, "har")
+ self.assertEqual(result.requests[0].method, "GET")
+
+ def test_form_parameters(self):
+ result = self.load(HAR_SAMPLE)
+ form = [p for r in result.requests for p in r.parameters if p.location == "form"]
+ self.assertEqual({p.name for p in form}, {"attachment", "note"})
+
+ def test_form_params_array(self):
+ payload = {
+ "log": {
+ "version": "1.2",
+ "entries": [
+ {
+ "request": {
+ "url": "https://a.test/u",
+ "method": "POST",
+ "postData": {
+ "mimeType": "multipart/form-data",
+ "params": [
+ {"name": "file", "fileName": "/tmp/x.txt", "contentType": "text/plain"},
+ {"name": "note", "value": "hi"},
+ ],
+ },
+ }
+ }
+ ],
+ }
+ }
+ result = self.load(payload)
+ form = {p.name: p.value for p in result.requests[0].parameters}
+ self.assertEqual(form["file"], "/tmp/x.txt")
+ self.assertEqual(form["note"], "hi")
+
+ def test_json_parameters_flattened(self):
+ result = self.load(HAR_SAMPLE)
+ json_params = {p.name: p.value for p in result.requests[2].parameters
+ if p.location == "json"}
+ self.assertIn("file.path", json_params)
+ self.assertEqual(json_params["file.path"], "C:\\Windows\\win.ini")
+ self.assertIn("ids[0]", json_params)
+ self.assertEqual(json_params["ids[0]"], "1")
+ self.assertIn("name", json_params)
+
+ def test_malformed_entries_are_skipped_with_warnings(self):
+ payload = {
+ "log": {
+ "version": "1.2",
+ "entries": [
+ "not-an-object",
+ {"no_request": True},
+ {"request": {"url": "ftp://bad.test/x"}},
+ {"request": {"url": "not-a-url"}},
+ {"request": {"url": "https://ok.test/?file=x"}},
+ ],
+ }
+ }
+ result = self.load(payload)
+ self.assertEqual(len(result.requests), 1)
+ self.assertEqual(result.skipped, 4)
+ self.assertGreaterEqual(len(result.warnings), 4)
+
+ def test_missing_log_is_an_error(self):
+ with self.assertRaises(sources.HarError):
+ self.load({"foo": []})
+
+ def test_entries_must_be_a_list(self):
+ with self.assertRaises(sources.HarError):
+ self.load({"log": {"version": "1.2", "entries": {}}})
+
+ def test_invalid_json_is_an_error(self):
+ with self.assertRaises(sources.HarError):
+ sources.load_har("{not json", "bad.har")
+
+ def test_duplicate_har_requests_are_collapsed(self):
+ entry = {
+ "request": {
+ "method": "GET",
+ "url": "https://a.test/?file=x",
+ "queryString": [{"name": "file", "value": "x"}],
+ }
+ }
+ result = self.load({"log": {"version": "1.2", "entries": [entry, dict(entry)]}})
+ self.assertEqual(len(result.requests), 1)
+
+ def test_query_falls_back_to_url_when_query_string_missing(self):
+ payload = {"log": {"version": "1.2", "entries": [
+ {"request": {"url": "https://a.test/?file=abc&x=1"}}
+ ]}}
+ result = self.load(payload)
+ self.assertEqual([p.name for p in result.requests[0].parameters], ["file", "x"])
+
+ def test_har_version_variation_only_warns(self):
+ payload = {"log": {"version": "9.9", "entries": [
+ {"request": {"url": "https://a.test/?file=x"}}
+ ]}}
+ result = self.load(payload)
+ self.assertEqual(len(result.requests), 1)
+ self.assertTrue(any("version" in w for w in result.warnings))
+
+ def test_format_detection(self):
+ self.assertEqual(
+ sources.detect_input_format(json.dumps(HAR_SAMPLE), ""), sources.INPUT_FORMAT_HAR
+ )
+ self.assertEqual(sources.detect_input_format("https://a.test/?x=1", "urls.txt"),
+ sources.INPUT_FORMAT_URLS)
+ self.assertEqual(sources.detect_input_format("not json", "capture.har"),
+ sources.INPUT_FORMAT_HAR)
+
+ def test_bom_prefixed_har_is_accepted(self):
+ result = sources.load_har("\ufeff" + json.dumps(HAR_SAMPLE), "bom.har")
+ self.assertEqual(len(result.requests), 3)
+
+ def test_json_depth_limit_does_not_crash(self):
+ deep = {"a": {"b": {"c": {"d": {"e": "x"}}}}}
+ payload = {"log": {"version": "1.2", "entries": [
+ {"request": {"url": "https://a.test/x", "postData": {
+ "mimeType": "application/json",
+ "text": json.dumps(deep),
+ }}}
+ ]}}
+ result = self.load(payload)
+ self.assertEqual(len(result.requests), 1)
+ self.assertTrue(any("json" in p.name or "a.b" in p.name
+ for p in result.requests[0].parameters))
- def test_encoded_slash(self):
- analysis = pd.analyze_value("%2fadmin%2fpanel")
- self.assertGreater(analysis.score, 0)
- self.assertTrue(any("%2f" in reason for reason in analysis.reasons))
- def test_double_encoded(self):
- analysis = pd.analyze_value("%252e%252e%252f")
- self.assertTrue(any("double-encoded" in reason for reason in analysis.reasons))
+# ---------------------------------------------------------------------------
+# Detector
+# ---------------------------------------------------------------------------
+class TestDetector(unittest.TestCase):
+ def analyze(self, urls, **options):
+ requests = []
+ for index, url in enumerate(urls):
+ requests.append(sources.request_from_url(url, sources.SOURCE_URL, "--url", index))
+ opts = detector.AnalysisOptions(**options)
+ return detector.analyze_requests(requests, opts)
+
+ def test_finding_fields(self):
+ result = self.analyze(["https://example.test/view?file=report.pdf"])
+ self.assertEqual(len(result.findings), 1)
+ finding = result.findings[0]
+ self.assertEqual(finding.host, "example.test")
+ self.assertEqual(finding.parameter, "file")
+ self.assertEqual(finding.rule, "name-exact")
+ self.assertEqual(finding.location, "query")
+ self.assertEqual(finding.confidence, "medium")
+ self.assertEqual(finding.resource, "https://example.test/view")
+ self.assertEqual(finding.source_type, "url")
+
+ def test_repeated_parameters_are_grouped(self):
+ result = self.analyze([
+ "https://a.test/x?file=one.txt&file=../../etc/passwd&file=three.txt"
+ ])
+ self.assertEqual(len(result.findings), 1)
+ finding = result.findings[0]
+ self.assertEqual(finding.occurrences, 3)
+ self.assertIn("value-traversal", finding.rules)
+
+ def test_show_values_only_when_requested(self):
+ hidden = self.analyze(["https://a.test/?file=secret.pdf"]).findings[0]
+ self.assertIsNone(hidden.value)
+ shown = self.analyze(["https://a.test/?file=secret.pdf"], show_values=True).findings[0]
+ self.assertEqual(shown.value, "secret.pdf")
+
+ def test_ignore_params(self):
+ result = self.analyze(
+ ["https://a.test/?file=/x&path=/y"], ignore_params=("file",)
+ )
+ self.assertEqual([f.parameter for f in result.findings], ["path"])
+
+ def test_min_score(self):
+ low = self.analyze(["https://a.test/?file=report.pdf"], min_score=90)
+ self.assertEqual(low.findings, [])
+
+ def test_ordering_is_deterministic(self):
+ urls = [
+ "https://b.test/?page=2&file=/a/b.txt&dir=../x",
+ "https://a.test/?template=home&file=/z",
+ ]
+ first = self.analyze(urls)
+ second = self.analyze(list(reversed(urls)))
+ self.assertEqual(
+ [(f.parameter, f.score, f.host) for f in first.findings],
+ [(f.parameter, f.score, f.host) for f in second.findings],
+ )
+ self.assertEqual([f.index for f in first.findings], list(range(1, len(first.findings) + 1)))
- def test_absolute_path(self):
- analysis = pd.analyze_value("/var/log/app.log")
- self.assertGreaterEqual(analysis.score, 30)
+ def test_no_duplicate_requests(self):
+ url = "https://a.test/?file=x.pdf"
+ result = self.analyze([url, url])
+ self.assertEqual(result.requests_analyzed, 1)
- def test_windows_path(self):
- analysis = pd.analyze_value(r"C:\Windows\win.ini")
- self.assertGreaterEqual(analysis.score, 30)
+ def test_counts(self):
+ result = self.analyze(["https://a.test/?file=x.pdf&q=hi&lang=en"])
+ self.assertEqual(result.requests_analyzed, 1)
+ self.assertEqual(result.parameters_analyzed, 3)
+ self.assertEqual(result.candidate_count, 1)
- def test_current_directory(self):
- analysis = pd.analyze_value("./")
- self.assertGreaterEqual(analysis.score, 5)
+ def test_sources_are_listed(self):
+ result = self.analyze(["https://a.test/?file=x.pdf"])
+ self.assertEqual(result.sources, ["--url"])
- def test_full_url_is_penalised(self):
- url = pd.analyze_value("https://example.test/a/b/c.txt")
- path = pd.analyze_value("/a/b/c.txt")
- self.assertLess(url.score, path.score)
+ def test_no_query_string_leaks_into_resource(self):
+ result = self.analyze(["https://a.test/a?file=/x?secret=1"])
+ for finding in result.findings:
+ self.assertNotIn("secret", finding.resource)
- def test_reasons_are_strings(self):
- analysis = pd.analyze_value("../../etc/passwd")
- self.assertTrue(all(isinstance(reason, str) for reason in analysis.reasons))
+ def test_empty_input(self):
+ result = detector.analyze_requests([], detector.AnalysisOptions())
+ self.assertEqual(result.candidate_count, 0)
+ self.assertEqual(result.requests_analyzed, 0)
# ---------------------------------------------------------------------------
-# 2. URL parsing and analysis
+# Report formats
# ---------------------------------------------------------------------------
-class TestParseTarget(unittest.TestCase):
- def test_valid_https(self):
- target = pd.parse_target("https://example.test/path?file=a.txt")
- self.assertEqual(target.scheme, "https")
- self.assertEqual(target.host, "example.test")
- self.assertEqual(target.path, "/path")
-
- def test_uppercase_scheme_and_host(self):
- target = pd.parse_target("HTTPS://Example.Test/x")
- self.assertEqual(target.scheme, "https")
- self.assertEqual(target.host, "example.test")
-
- def test_custom_port_display(self):
- target = pd.parse_target("http://example.test:8080/")
- self.assertEqual(pd.display_host(target), "example.test:8080")
-
- def test_ipv6_is_accepted(self):
- target = pd.parse_target("http://[::1]:8080/?path=/tmp")
- self.assertIn("::1", target.host)
-
- def test_missing_scheme(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("example.test/view?file=a.txt")
-
- def test_unsupported_scheme(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("ftp://example.test/file.txt")
-
- def test_javascript_scheme_rejected(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("javascript:alert(1)")
-
- def test_missing_host(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("https:///path")
-
- def test_whitespace_rejected(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("https://example.test/a b?file=x")
-
- def test_bad_port_rejected(self):
- with self.assertRaises(pd.URLParseError):
- pd.parse_target("https://example.test:99999/")
-
-
-class TestSplitQuery(unittest.TestCase):
- def test_pairs(self):
- pairs = pd.split_query("a=1&b=2")
- self.assertEqual([(name, raw, value) for name, raw, value in pairs],
- [("a", "1", "1"), ("b", "2", "2")])
-
- def test_blank_value_is_kept(self):
- pairs = pd.split_query("file=")
- self.assertEqual(len(pairs), 1)
- self.assertEqual(pairs[0][2], "")
-
- def test_repeated_names_are_kept(self):
- pairs = pd.split_query("file=a&file=b")
- self.assertEqual([pair[2] for pair in pairs], ["a", "b"])
-
- def test_encoded_name_and_value_are_decoded_once(self):
- pairs = pd.split_query("%66%69%6c%65=..%2Freport.pdf")
- self.assertEqual(pairs[0][0], "file")
- self.assertEqual(pairs[0][1], "..%2Freport.pdf")
- self.assertEqual(pairs[0][2], "../report.pdf")
-
- def test_empty_query(self):
- self.assertEqual(pd.split_query(""), [])
-
-
-class TestAnalyzeURL(unittest.TestCase):
- def test_flags_file_parameter(self):
- findings = pd.analyze_url("https://example.test/view?file=report.pdf")
- self.assertEqual(len(findings), 1)
- self.assertEqual(findings[0].parameter, "file")
- self.assertEqual(findings[0].host, "example.test")
- self.assertGreaterEqual(findings[0].score, 30)
-
- def test_never_uses_vulnerability_language(self):
- findings = pd.analyze_url("https://example.test/get?doc=../../etc/passwd")
- text = " ".join(reason for finding in findings for reason in finding.reasons)
- for word in ("vulnerable", "exploitable", "confirmed", "LFI found"):
- self.assertNotIn(word.lower(), text.lower())
-
- def test_unrelated_parameter_is_not_flagged(self):
- self.assertEqual(pd.analyze_url("https://example.test/?q=hello&utm_source=news"), [])
-
- def test_page_is_a_keyword_but_requires_the_default_threshold(self):
- findings = pd.analyze_url("https://example.test/?page=2")
- self.assertEqual([finding.parameter for finding in findings], ["page"])
- self.assertLess(pd.analyze_url("https://example.test/?page=2")[0].score, 50)
-
- def test_encoded_parameter_name_is_decoded(self):
- findings = pd.analyze_url("https://example.test/?%66%69%6c%65=report.pdf")
- self.assertEqual([finding.parameter for finding in findings], ["file"])
-
- def test_repeated_parameters_are_merged(self):
- findings = pd.analyze_url(
- "https://example.test/?file=one.txt&file=two.txt&file=three.pdf"
+class TestReportFormats(unittest.TestCase):
+ def build_report(self, show_values: bool = False):
+ requests = [
+ sources.request_from_url(
+ "https://example.test/view?file=report.pdf&lang=en", sources.SOURCE_URL, "--url"
+ ),
+ sources.request_from_url(
+ "https://other.test/dl?path=../../etc/passwd", sources.SOURCE_FILE, "urls.txt"
+ ),
+ ]
+ return detector.analyze_requests(
+ requests, detector.AnalysisOptions(show_values=show_values)
)
- self.assertEqual(len(findings), 1)
- self.assertEqual(findings[0].occurrences, 3)
- # All occurrences score equally, so the first existing value is kept.
- self.assertEqual(findings[0].value, "one.txt")
-
- def test_repeated_parameters_keep_best_scoring_value(self):
- findings = pd.analyze_url(
- "https://example.test/?file=one.txt&file=../../etc/passwd"
+
+ def test_json_is_stable_and_complete(self):
+ first = report.render_json(self.build_report())
+ second = report.render_json(self.build_report())
+ self.assertEqual(first, second)
+ payload = json.loads(first)
+ self.assertEqual(payload["tool"], "PathScope")
+ self.assertEqual(payload["version"], __version__)
+ self.assertTrue(payload["passive"])
+ self.assertEqual(payload["network_requests_made"], 0)
+ self.assertIn("manual review", payload["disclaimer"])
+ self.assertEqual(payload["summary"]["candidates"], len(payload["findings"]))
+ for finding in payload["findings"]:
+ for key in ("host", "source_type", "parameter", "rule", "confidence",
+ "score", "reasons", "location"):
+ self.assertIn(key, finding)
+ self.assertNotIn("report.pdf", first)
+
+ def test_json_show_values(self):
+ payload = json.loads(report.render_json(self.build_report(show_values=True)))
+ values = {f["parameter"]: f["value"] for f in payload["findings"]}
+ self.assertEqual(values["file"], "report.pdf")
+
+ def test_csv_columns_and_escaping(self):
+ text = report.render_csv(self.build_report())
+ rows = list(csv.DictReader(io.StringIO(text)))
+ self.assertEqual(list(rows[0].keys()), list(report.CSV_COLUMNS))
+ self.assertEqual(len(rows), 2)
+ self.assertEqual(rows[0]["value"], "")
+ for row in rows:
+ self.assertIn(row["rule"], row["rules"].split(";"))
+
+ def test_csv_show_values(self):
+ text = report.render_csv(self.build_report(show_values=True))
+ rows = list(csv.DictReader(io.StringIO(text)))
+ self.assertIn("report.pdf", [row["value"] for row in rows])
+
+ def test_sarif_minimum_requirements(self):
+ payload = json.loads(report.render_sarif(self.build_report()))
+ self.assertEqual(payload["version"], "2.1.0")
+ self.assertIn("$schema", payload)
+ run = payload["runs"][0]
+ driver = run["tool"]["driver"]
+ self.assertEqual(driver["name"], "PathScope")
+ rule_ids = [rule["id"] for rule in driver["rules"]]
+ self.assertTrue(rule_ids)
+ for result in run["results"]:
+ self.assertIn(result["ruleId"], rule_ids)
+ self.assertEqual(rule_ids[result["ruleIndex"]], result["ruleId"])
+ self.assertIn(result["level"], ("warning", "note"))
+ self.assertIn("manual review", result["message"]["text"].lower())
+
+ def test_sarif_is_deterministic(self):
+ self.assertEqual(
+ report.render_sarif(self.build_report()),
+ report.render_sarif(self.build_report()),
)
- self.assertEqual(len(findings), 1)
- self.assertEqual(findings[0].occurrences, 2)
- self.assertEqual(findings[0].value, "../../etc/passwd")
-
- def test_generic_name_requires_path_like_value(self):
- self.assertEqual(pd.analyze_url("https://example.test/?image=logo"), [])
- flagged = pd.analyze_url("https://example.test/?image=/static/logo.png")
- self.assertEqual([finding.parameter for finding in flagged], ["image"])
-
- def test_generic_name_never_stands_alone(self):
- findings = pd.analyze_url("https://example.test/?target=homepage")
- self.assertEqual(findings, [])
-
- def test_results_are_sorted_by_score(self):
- findings = pd.analyze_url(
- "https://example.test/?page=2&file=report.pdf&dir=../../etc"
+
+ def test_text_output_hides_and_shows_values(self):
+ hidden = report.render_text(self.build_report(), report.Palette(False))
+ self.assertIn("", hidden)
+ self.assertNotIn("report.pdf", hidden)
+ shown = report.render_text(self.build_report(show_values=True), report.Palette(False))
+ self.assertIn("report.pdf", shown)
+
+ def test_text_has_no_ansi_when_palette_disabled(self):
+ text = report.render_text(self.build_report(), report.Palette(False))
+ self.assertNotIn("\x1b[", text)
+
+ def test_palette_enabled_adds_ansi(self):
+ text = report.render_text(self.build_report(), report.Palette(True))
+ self.assertIn("\x1b[", text)
+
+ def test_control_characters_are_escaped(self):
+ requests = [
+ sources.request_from_url(
+ "https://a.test/?file=../../etc/passwd%1b[31mred%0aInjected",
+ sources.SOURCE_URL,
+ "--url",
+ )
+ ]
+ result = detector.analyze_requests(
+ requests, detector.AnalysisOptions(show_values=True)
)
- scores = [finding.score for finding in findings]
- self.assertEqual(scores, sorted(scores, reverse=True))
- self.assertEqual([finding.index for finding in findings],
- list(range(1, len(findings) + 1)))
-
- def test_min_score_threshold(self):
- url = "https://example.test/?file=report.pdf"
- self.assertTrue(pd.analyze_url(url, min_score=30))
- self.assertEqual(pd.analyze_url(url, min_score=90), [])
-
- def test_no_query_returns_empty(self):
- self.assertEqual(pd.analyze_url("https://example.test/path"), [])
-
- def test_bare_key_without_value_is_tolerated(self):
- findings = pd.analyze_url("https://example.test/?file")
- self.assertEqual(len(findings), 1)
- self.assertEqual(findings[0].occurrences, 1)
-
- def test_host_without_port_in_finding(self):
- findings = pd.analyze_url("https://example.test:443/?file=a.txt")
- self.assertEqual(findings[0].host, "example.test")
-
- def test_malformed_url_raises(self):
- with self.assertRaises(pd.URLParseError):
- pd.analyze_url("not a url")
-
- def test_mask_url(self):
- masked = pd.mask_url("https://example.test/a?file=secret.pdf&x=1#frag")
- self.assertNotIn("secret.pdf", masked)
- self.assertIn("file=", masked)
- self.assertIn("x=", masked)
-
- def test_findings_never_contain_credentials(self):
- findings = pd.analyze_url("https://alice:hunter2@example.test/?file=a.txt")
- self.assertEqual(len(findings), 1)
- self.assertNotIn("hunter2", findings[0].url)
- self.assertIn("@example.test", findings[0].url)
-
- def test_mask_url_hides_credentials(self):
- masked = pd.mask_url("https://alice:hunter2@example.test/?file=a.txt")
- self.assertNotIn("hunter2", masked)
- self.assertIn("@example.test", masked)
-
- def test_count_parameters(self):
- self.assertEqual(
- pd.count_parameters("https://example.test/?a=1&b=2&a=3"), 2
+ plain = report.render_text(result, report.Palette(False))
+ for rendered in (
+ plain,
+ report.render_json(result),
+ report.render_csv(result),
+ report.render_sarif(result),
+ ):
+ # No escape sequence from the *input* may survive into any format.
+ self.assertNotIn("\x1b[31mred", rendered)
+ # With colour disabled there must be no ANSI at all.
+ self.assertNotIn("\x1b", plain)
+ self.assertFalse(
+ any(line.strip() == "Injected" for line in
+ report.render_text(result, report.Palette(False)).splitlines())
)
+ def test_banner_contains_exact_links(self):
+ banner = report.render_banner(report.Palette(False))
+ for label, url in BANNER_LINKS:
+ self.assertIn(banner_line(label), banner)
+
# ---------------------------------------------------------------------------
-# 3. Input handling
+# Configuration
# ---------------------------------------------------------------------------
-class TestCleanInputLines(unittest.TestCase):
- def test_blank_lines_comments_and_duplicates(self):
- urls, warnings = pd.clean_input_lines(
- [
- "",
- " ",
- "# a comment",
- "https://a.test/?file=x",
- "https://a.test/?file=x",
- "https://b.test/?page=2",
- ]
+class TestConfig(unittest.TestCase):
+ def test_valid_config(self):
+ cfg = config.validate_payload(
+ {"name_terms": ["download"], "ignore_params": ["image"], "min_score": 10}
)
- self.assertEqual(urls, ["https://a.test/?file=x", "https://b.test/?page=2"])
- self.assertEqual(warnings, [])
-
- def test_malformed_lines_are_reported_with_line_numbers(self):
- urls, warnings = pd.clean_input_lines(["", "not-a-url", "https://ok.test/?a=1"])
- self.assertEqual(urls, ["https://ok.test/?a=1"])
- self.assertEqual(len(warnings), 1)
- self.assertIn("line 2", warnings[0])
-
- def test_custom_label_for_warnings(self):
- _urls, warnings = pd.clean_input_lines(["bogus"], label="--url")
- self.assertIn("--url 1", warnings[0])
-
+ self.assertEqual(cfg.name_terms, ["download"])
+ self.assertEqual(cfg.ignore_params, ["image"])
+ self.assertEqual(cfg.min_score, 10)
+
+ def test_unknown_keys_rejected(self):
+ with self.assertRaises(config.ConfigError):
+ config.validate_payload({"regexes": [".*"]})
+
+ def test_regex_like_terms_rejected(self):
+ for term in ("(a+)+$", ".*", "a|b", "[a-z]"):
+ with self.assertRaises(config.ConfigError, msg=term):
+ config.validate_payload({"name_terms": [term]})
+
+ def test_wrong_types_rejected(self):
+ cases = (
+ {"name_terms": "download"},
+ {"name_terms": [1]},
+ {"ignore_params": ["a", 2]},
+ {"min_score": "high"},
+ {"min_score": True},
+ {"min_score": 101},
+ {"max_decode_passes": 9},
+ {"show_values": "yes"},
+ [],
+ )
+ for payload in cases:
+ with self.assertRaises(config.ConfigError, msg=str(payload)):
+ config.validate_payload(payload)
+
+ def test_term_length_limits(self):
+ with self.assertRaises(config.ConfigError):
+ config.validate_payload({"name_terms": ["x"]})
+ with self.assertRaises(config.ConfigError):
+ config.validate_payload({"name_terms": ["x" * 200]})
+
+ def test_missing_file_and_invalid_json(self):
+ with self.assertRaises(config.ConfigError):
+ config.load_config("/definitely/not/here.json")
+ path = write_temp(".json", "{not json")
+ try:
+ with self.assertRaises(config.ConfigError):
+ config.load_config(path)
+ finally:
+ os.unlink(path)
+
+ def test_load_valid_file(self):
+ path = write_temp(".json", json.dumps(config.dump_example()))
+ try:
+ cfg = config.load_config(path)
+ finally:
+ os.unlink(path)
+ self.assertIn("download", cfg.name_terms)
+ self.assertEqual(cfg.source, path)
+
+ def test_merge_ignore_deduplicates(self):
+ cfg = config.Config(ignore_params=["image"])
+ self.assertEqual(config.merge_ignore(["image", "config"], cfg), ["image", "config"])
-class TestReadInputFile(unittest.TestCase):
- def test_reads_utf8_with_bom(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "urls.txt"
- path.write_bytes(b"\xef\xbb\xbfhttps://a.test/?file=x\n\n")
- lines = pd.read_input_file(str(path))
- self.assertIn("https://a.test/?file=x", [line.strip() for line in lines])
- def test_missing_file_raises_input_error(self):
- with self.assertRaises(pd.InputError):
- pd.read_input_file("/definitely/not/here/urls.txt")
+# ---------------------------------------------------------------------------
+# Malformed input
+# ---------------------------------------------------------------------------
+class TestMalformedInput(unittest.TestCase):
+ def test_unreadable_file_raises(self):
+ with self.assertRaises(sources.InputError):
+ sources.load_file("/no/such/file.txt")
- def test_directory_raises_input_error(self):
+ def test_directory_raises(self):
with tempfile.TemporaryDirectory() as tmp:
- with self.assertRaises(pd.InputError):
- pd.read_input_file(tmp)
+ with self.assertRaises(sources.InputError):
+ sources.load_file(tmp, sources.INPUT_FORMAT_URLS)
+
+ def test_binary_garbage_does_not_crash(self):
+ path = write_temp(".har", b"\x00\x01\x02\xff", binary=True)
+ try:
+ with self.assertRaises(sources.HarError):
+ sources.load_har(sources.read_text(path), "binary.har")
+ finally:
+ os.unlink(path)
+
+ def test_huge_value_is_truncated(self):
+ value = "a" * (sources.MAX_VALUE_CHARS + 5000)
+ params = sources.query_parameters(f"file={value}")
+ self.assertEqual(len(params[0].value), sources.MAX_VALUE_CHARS)
+
+ def test_control_characters_are_stripped_from_input(self):
+ result = sources.load_url_lines(
+ ["https://a.test/?file=x\x1b[31m"], sources.SOURCE_FILE, "u.txt"
+ )
+ self.assertEqual(len(result.requests), 1)
+ self.assertNotIn("\x1b", result.requests[0].url.raw)
# ---------------------------------------------------------------------------
-# 4. CLI behaviour (subprocess)
+# CLI
# ---------------------------------------------------------------------------
-class TestCLI(unittest.TestCase):
- def assert_links_present(self, text: str) -> None:
+class TestCli(unittest.TestCase):
+ def test_banner_on_every_start(self):
+ code, out, err = run_inprocess("--url", "https://a.test/?file=x.pdf")
+ self.assertEqual(code, cli.EXIT_OK)
for label, url in BANNER_LINKS:
- self.assertIn(f"{label}: {url}", text)
-
- def test_banner_links_are_exact(self):
- result = run_cli("--no-banner", "--url", "https://a.test/?file=x")
- self.assertNotIn("GitHub:", result.stderr)
- self.assertNotIn("instagram.com", result.stderr)
-
- result = run_cli("--url", "https://a.test/?file=x")
- self.assert_links_present(result.stderr)
+ self.assertIn(f"{label}: {url}", err)
+ self.assertEqual(err.count("PathScope " + __version__), 1)
- def test_banner_without_arguments(self):
- result = run_cli()
- self.assert_links_present(result.stderr)
- self.assertEqual(result.returncode, pd.EXIT_USAGE)
+ def test_banner_suppressed(self):
+ code, out, err = run_inprocess("--no-banner", "--url", "https://a.test/?q=1")
+ self.assertNotIn("instagram.com", err)
- def test_banner_printed_once(self):
- result = run_cli("--url", "https://a.test/?file=x")
- self.assertEqual(result.stderr.count("PathScope " + pd.__version__), 1)
-
- def test_help_shows_banner_and_usage(self):
+ def test_help(self):
result = run_cli("--help")
self.assertEqual(result.returncode, 0)
self.assertIn("usage:", result.stdout)
- self.assert_links_present(result.stderr)
- self.assertIn("examples:", result.stdout)
- self.assertIn("https://github.com/mrdineshpathro", result.stdout)
+ self.assertIn("exit codes:", result.stdout)
+ self.assertIn("https://buymeacoffee.com/mrdineshpathro", result.stdout)
+ for label, url in BANNER_LINKS:
+ self.assertIn(banner_line(label), result.stderr)
def test_version(self):
result = run_cli("--version")
self.assertEqual(result.returncode, 0)
- self.assertIn(pd.__version__, result.stdout)
+ self.assertIn(__version__, result.stdout)
- def test_single_url_hides_value_by_default(self):
- result = run_cli("--url", "https://example.test/view?file=report.pdf")
+ def test_single_url(self):
+ result = run_cli("--no-banner", "--url", "https://example.test/view?file=report.pdf")
self.assertEqual(result.returncode, 0)
self.assertIn("file", result.stdout)
- self.assertIn("example.test", result.stdout)
+ self.assertIn("name-exact", result.stdout)
+ self.assertIn("candidates for manual review", result.stdout.lower())
self.assertNotIn("report.pdf", result.stdout)
- self.assertIn("", result.stdout)
- def test_show_values_reveals_value(self):
+ def test_show_values(self):
result = run_cli(
- "--url", "https://example.test/view?file=report.pdf", "--show-values"
+ "--no-banner", "--show-values", "--url", "https://a.test/?file=report.pdf"
)
- self.assertEqual(result.returncode, 0)
self.assertIn("report.pdf", result.stdout)
- def test_no_ansi_colour_when_piped(self):
- result = run_cli("--url", "https://example.test/?file=report.pdf")
+ def test_no_ansi_when_piped(self):
+ result = run_cli("--no-banner", "--url", "https://a.test/?file=report.pdf")
self.assertNotIn("\x1b[", result.stdout)
self.assertNotIn("\x1b[", result.stderr)
- def test_json_output_is_valid_and_hides_values(self):
- result = run_cli(
- "--json", "--url", "https://example.test/?file=report.pdf&q=hello"
- )
- self.assertEqual(result.returncode, 0)
+ def test_json_shorthand(self):
+ result = run_cli("--no-banner", "-q", "--json", "--url", "https://a.test/?file=a.pdf")
payload = json.loads(result.stdout)
self.assertEqual(payload["tool"], "PathScope")
- self.assertEqual(payload["summary"]["urls_analyzed"], 1)
- self.assertEqual(payload["summary"]["candidates"], 1)
- finding = payload["findings"][0]
- self.assertEqual(finding["parameter"], "file")
- self.assertIsNone(finding["value"])
- self.assertNotIn("report.pdf", result.stdout)
- self.assertIn("", finding["url"])
+ self.assertIsNone(payload["findings"][0]["value"])
- def test_json_show_values(self):
- result = run_cli(
- "--json", "--show-values",
- "--url", "https://example.test/?file=report.pdf",
- )
- payload = json.loads(result.stdout)
- self.assertEqual(payload["findings"][0]["value"], "report.pdf")
-
- def test_json_has_disclaimer_and_links(self):
- payload = json.loads(
- run_cli("--json", "--url", "https://a.test/?file=x").stdout
- )
- self.assertIn("manual review", payload["disclaimer"].lower())
- self.assertEqual(payload["links"]["github"], pd.GITHUB_URL)
- self.assertEqual(payload["links"]["instagram"], pd.INSTAGRAM_URL)
- self.assertEqual(payload["links"]["support"], pd.SUPPORT_URL)
+ def test_format_flag_selects_output(self):
+ for fmt in ("json", "csv", "sarif"):
+ result = run_cli("--no-banner", "-q", "--format", fmt,
+ "--url", "https://a.test/?file=a.pdf")
+ self.assertEqual(result.returncode, 0, fmt)
+ if fmt != "csv":
+ json.loads(result.stdout)
def test_input_file(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "urls.txt"
- path.write_text(
- "\n".join(
- [
- "",
- "# comment",
- "https://a.test/?file=one.txt",
- "",
- "not a url",
- "https://b.test/?page=2",
- ]
- ),
- encoding="utf-8",
- )
- result = run_cli("-i", str(path))
+ path = write_temp(
+ ".txt",
+ "\n".join(["", "# comment", "https://a.test/?file=one.pdf", "bad-url",
+ "https://b.test/?path=../../etc"]),
+ )
+ try:
+ result = run_cli("--no-banner", "-i", path)
+ finally:
+ os.unlink(path)
self.assertEqual(result.returncode, 0)
+ self.assertIn("Analyzed 2 request(s)", result.stdout)
self.assertIn("skipped malformed URL", result.stderr)
- self.assertIn("Analyzed 2 URL(s)", result.stdout)
- def test_multiple_input_files(self):
- with tempfile.TemporaryDirectory() as tmp:
- first = Path(tmp) / "one.txt"
- second = Path(tmp) / "two.txt"
- first.write_text("https://a.test/?file=one.txt\n", encoding="utf-8")
- second.write_text("https://b.test/?path=/var/log\n", encoding="utf-8")
- result = run_cli(
- "--no-banner", "--json", "-i", str(first), "-i", str(second)
- )
+ def test_har_file_auto_detected(self):
+ path = write_temp(".har", json.dumps(HAR_SAMPLE))
+ try:
+ result = run_cli("--no-banner", "-q", "--json", "-i", path)
+ finally:
+ os.unlink(path)
+ payload = json.loads(result.stdout)
+ # lang=en is now intentionally out of the vocabulary (ordinary i18n value).
+ self.assertEqual(len(payload["findings"]), 3)
+ locations = {f["location"] for f in payload["findings"]}
+ self.assertIn("form", locations)
+ self.assertIn("json", locations)
+ self.assertIn("query", locations)
+
+ def test_har_forced_format(self):
+ path = write_temp(".json", json.dumps(HAR_SAMPLE))
+ try:
+ result = run_cli("--no-banner", "-q", "--format", "har", "-i", path)
+ finally:
+ os.unlink(path)
self.assertEqual(result.returncode, 0)
- self.assertEqual(json.loads(result.stdout)["summary"]["urls_analyzed"], 2)
+ self.assertIn("Source", result.stdout)
- def test_stdin_pipe(self):
- result = run_cli(stdin="https://a.test/?file=one.txt\nhttps://b.test/?path=x\n")
- self.assertEqual(result.returncode, 0)
- self.assertIn("Analyzed 2 URL(s)", result.stdout)
+ def test_stdin_urls(self):
+ result = run_cli("--no-banner", "--json", stdin="https://a.test/?file=a.pdf\n")
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["findings"][0]["source_type"], "stdin")
+
+ def test_stdin_har(self):
+ result = run_cli("--no-banner", "-q", "--json", stdin=json.dumps(HAR_SAMPLE))
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["findings"][0]["source_type"], "har")
def test_dash_input_reads_stdin(self):
- result = run_cli("-i", "-", stdin="https://a.test/?file=one.txt\n")
+ result = run_cli("--no-banner", "-q", "-i", "-", stdin="https://a.test/?file=x.pdf\n")
self.assertEqual(result.returncode, 0)
- self.assertIn("1 candidate", result.stdout)
+ self.assertIn("file", result.stdout)
- def test_duplicate_urls_counted_once(self):
- result = run_cli(
- "--json",
- stdin="https://a.test/?file=one.txt\nhttps://a.test/?file=one.txt\n",
- )
- payload = json.loads(result.stdout)
- self.assertEqual(payload["summary"]["urls_analyzed"], 1)
+ def test_duplicate_requests_are_analyzed_once(self):
+ stdin = "https://a.test/?file=x.pdf\nhttps://a.test/?file=x.pdf\n"
+ result = run_cli("--no-banner", "-q", "--json", stdin=stdin)
+ self.assertEqual(json.loads(result.stdout)["summary"]["requests_analyzed"], 1)
- def test_missing_input_file_exits_2(self):
+ def test_no_input_is_a_usage_error(self):
+ result = run_cli("--no-banner", stdin="")
+ self.assertEqual(result.returncode, cli.EXIT_USAGE)
+ self.assertIn("no usable input", result.stderr)
+
+ def test_missing_file_is_a_usage_error(self):
result = run_cli("--no-banner", "-i", "/no/such/file.txt")
- self.assertEqual(result.returncode, pd.EXIT_USAGE)
+ self.assertEqual(result.returncode, cli.EXIT_USAGE)
self.assertIn("cannot read input file", result.stderr)
- def test_invalid_min_score_exits_2(self):
- result = run_cli("--no-banner", "--min-score", "101", "--url", "https://a.test/")
- self.assertEqual(result.returncode, pd.EXIT_USAGE)
-
- def test_strict_mode_exits_1_on_bad_lines(self):
- with tempfile.TemporaryDirectory() as tmp:
- path = Path(tmp) / "urls.txt"
- path.write_text("bogus\nhttps://a.test/?file=x\n", encoding="utf-8")
- result = run_cli("--no-banner", "--strict", "-i", str(path))
- self.assertEqual(result.returncode, pd.EXIT_STRICT_SKIPS)
-
- def test_fail_on_none_exits_3(self):
- result = run_cli("--no-banner", "--fail-on-none", "--url", "https://a.test/?q=hi")
- self.assertEqual(result.returncode, pd.EXIT_NO_CANDIDATES)
+ def test_invalid_har_is_a_usage_error(self):
+ path = write_temp(".har", "not json")
+ try:
+ result = run_cli("--no-banner", "-i", path, "--format", "har")
+ finally:
+ os.unlink(path)
+ self.assertEqual(result.returncode, cli.EXIT_USAGE)
+ self.assertIn("not valid JSON", result.stderr)
+
+ def test_invalid_config_is_a_usage_error(self):
+ path = write_temp(".json", '{"name_terms": ["(a+)+$"]}')
+ try:
+ result = run_cli("--no-banner", "--config", path, "--url", "https://a.test/?file=x")
+ finally:
+ os.unlink(path)
+ self.assertEqual(result.returncode, cli.EXIT_USAGE)
+ self.assertIn("regular expressions", result.stderr)
+
+ def test_config_terms_are_used(self):
+ path = write_temp(".json", json.dumps({"name_terms": ["cdn_blob"]}))
+ try:
+ result = run_cli("--no-banner", "-q", "--json", "--config", path,
+ "--url", "https://a.test/?cdn_blob=/x")
+ finally:
+ os.unlink(path)
+ payload = json.loads(result.stdout)
+ self.assertEqual(payload["findings"][0]["rule"], "name-custom")
- def test_fail_on_none_is_zero_when_candidates_exist(self):
+ def test_ignore_param_flag(self):
result = run_cli(
- "--no-banner", "--fail-on-none", "--url", "https://a.test/?file=a.txt"
+ "--no-banner", "-q", "--json",
+ "--ignore-param", "file", "--ignore-param", "down",
+ "--url", "https://a.test/?file=/x&down=1&path=/y",
)
+ payload = json.loads(result.stdout)
+ self.assertEqual([f["parameter"] for f in payload["findings"]], ["path"])
+
+ def test_fail_on_findings(self):
+ result = run_cli("--no-banner", "-q", "--fail-on-findings",
+ "--url", "https://a.test/?file=x.pdf")
+ self.assertEqual(result.returncode, cli.EXIT_FINDINGS)
+ result = run_cli("--no-banner", "-q", "--fail-on-findings",
+ "--url", "https://a.test/?q=hello")
+ self.assertEqual(result.returncode, cli.EXIT_OK)
+
+ def test_min_score_bounds(self):
+ result = run_cli("--no-banner", "--min-score", "200", "--url", "https://a.test/?file=x")
+ self.assertEqual(result.returncode, cli.EXIT_USAGE)
+ result = run_cli("--no-banner", "-q", "--min-score", "0",
+ "--url", "https://a.test/?q=hello")
self.assertEqual(result.returncode, 0)
- def test_url_with_encoded_ampersand_and_equals(self):
+ def test_quiet_suppresses_stderr_summary(self):
+ result = run_cli("--no-banner", "-q", "--url", "https://a.test/?file=x.pdf")
+ self.assertEqual(result.stderr.strip(), "")
+
+ def test_url_with_encoded_ampersand(self):
result = run_cli(
- "--no-banner",
- "--json",
- "--url",
- "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.txt",
+ "--no-banner", "-q", "--json",
+ "--url", "https://a.test/?next=%2Fhome%3Ftab%3Dfiles&file=a.pdf",
)
- self.assertEqual(result.returncode, 0)
payload = json.loads(result.stdout)
self.assertEqual(payload["summary"]["parameters_analyzed"], 2)
- def test_no_usable_urls_exits_2(self):
- result = run_cli("--no-banner", stdin="# only a comment\n\n")
- self.assertEqual(result.returncode, pd.EXIT_USAGE)
- self.assertIn("no usable URLs", result.stderr)
-
# ---------------------------------------------------------------------------
-# 5. Safety guarantees
+# Safety
# ---------------------------------------------------------------------------
-ALLOWED_IMPORTS = {
- "__future__",
- "argparse",
- "collections",
- "dataclasses",
- "json",
- "os",
- "re",
- "sys",
- "typing",
- "unicodedata",
- "urllib",
-}
FORBIDDEN_MODULES = {
"socket",
"ssl",
"http",
+ "https",
+ "urllib.request",
"urllib3",
"requests",
"httpx",
@@ -626,40 +1113,100 @@ def test_no_usable_urls_exits_2(self):
"smtplib",
"telnetlib",
"subprocess",
- "scapy",
+ "multiprocessing",
"paramiko",
"dns",
+ "scapy",
+ "selenium",
}
+ALLOWED_THIRD_PARTY = set()
+
+
+def project_modules():
+ for path in sorted((REPO_ROOT / "pathscope").glob("*.py")):
+ yield path
+
class TestSafety(unittest.TestCase):
- def test_only_standard_library_imports(self):
- tree = ast.parse(SCRIPT.read_text(encoding="utf-8"))
- imported: set[str] = set()
- for node in ast.walk(tree):
- if isinstance(node, ast.Import):
- imported.update(alias.name.split(".")[0] for alias in node.names)
- elif isinstance(node, ast.ImportFrom) and node.module:
- imported.add(node.module.split(".")[0])
- self.assertLessEqual(imported, ALLOWED_IMPORTS)
- self.assertFalse(imported & FORBIDDEN_MODULES)
-
- def test_no_network_calls_during_analysis(self):
+ def test_imports_are_standard_library_only(self):
+ allowed_stdlib = {
+ "__future__", "argparse", "csv", "dataclasses", "io", "json", "os",
+ "re", "sys", "typing", "unicodedata", "urllib.parse", "collections",
+ "pathlib", "textwrap",
+ }
+ for path in project_modules():
+ tree = ast.parse(path.read_text(encoding="utf-8"))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ for alias in node.names:
+ root = alias.name.split(".")[0]
+ self.assertIn(root, {m.split(".")[0] for m in allowed_stdlib},
+ f"{path.name}: {alias.name}")
+ self.assertNotIn(alias.name, FORBIDDEN_MODULES)
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
+ root = node.module.split(".")[0]
+ self.assertIn(root, {m.split(".")[0] for m in allowed_stdlib},
+ f"{path.name}: {node.module}")
+ self.assertNotIn(node.module, FORBIDDEN_MODULES)
+
+ def test_no_network_modules_in_sys_modules_during_analysis(self):
+ before = set(sys.modules)
+ requests = [
+ sources.request_from_url(
+ "https://a.test/?file=../../etc/passwd&next=https://evil.test/x",
+ sources.SOURCE_URL,
+ "--url",
+ )
+ ]
+ detector.analyze_requests(requests, detector.AnalysisOptions(show_values=True))
+ report.render_json(detector.analyze_requests(requests, detector.AnalysisOptions()))
+ new = set(sys.modules) - before
+ self.assertFalse({m for m in new if m.split(".")[0] in {"socket", "http", "ssl"}})
+
+ def test_sockets_are_never_used(self):
def boom(*_args, **_kwargs):
raise AssertionError("PathScope attempted a network operation")
- with mock.patch("socket.socket", side_effect=boom), mock.patch(
- "socket.create_connection", side_effect=boom
- ), mock.patch("socket.getaddrinfo", side_effect=boom):
- findings = pd.analyze_url(
- "https://example.test/?file=../../etc/passwd&next=https://evil.test/"
+ with mock.patch("socket.socket", side_effect=boom), \
+ mock.patch("socket.create_connection", side_effect=boom), \
+ mock.patch("socket.getaddrinfo", side_effect=boom):
+ code, out, err = run_inprocess(
+ "--no-banner", "-q", "--show-values",
+ "--url", "https://a.test/?file=../../etc/passwd&url=https://evil.test/",
)
- self.assertTrue(findings)
-
- def test_module_has_no_root_requirement(self):
- source = SCRIPT.read_text(encoding="utf-8")
- for marker in ("os.geteuid", "os.seteuid", "sudo", "setuid"):
- self.assertNotIn(marker, source)
+ self.assertEqual(code, 0)
+ self.assertIn("'..' path segment", out)
+
+ def test_parameter_values_are_never_opened_as_files(self):
+ """A value like /etc/passwd must not reach ``open``/``os.open``."""
+ sentinel = "/etc/passwd"
+
+ def guarded_open(file, *args, **kwargs): # noqa: A002
+ if isinstance(file, (str, bytes)) and sentinel in str(file):
+ raise AssertionError(f"PathScope tried to open {file!r}")
+ return real_open(file, *args, **kwargs)
+
+ real_open = builtins.open
+ real_os_open = os.open
+ with mock.patch("builtins.open", side_effect=guarded_open), \
+ mock.patch("os.open", side_effect=guarded_open):
+ analysis = heuristics.analyze_parameter("file", sentinel)
+ self.assertTrue(analysis.evidence)
+ self.assertIs(os.open, real_os_open)
+
+ def test_source_has_no_root_or_shell_calls(self):
+ for path in project_modules():
+ text = path.read_text(encoding="utf-8")
+ for marker in ("os.geteuid", "os.seteuid", "setuid", "os.system(",
+ "shell=True", "sudo "):
+ self.assertNotIn(marker, text, f"{path.name}: {marker}")
+
+ def test_no_urllib_request_usage(self):
+ for path in project_modules():
+ text = path.read_text(encoding="utf-8")
+ self.assertNotIn("urllib.request", text, path.name)
+ self.assertNotIn("urlopen", text, path.name)
if __name__ == "__main__":
From dfb88c48fa9f5e3c9a12b85619e2fe07b2eab0a3 Mon Sep 17 00:00:00 2001
From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com>
Date: Sun, 29 Nov 2026 11:08:42 +0000
Subject: [PATCH 3/8] Add PathScope 2.1 feature set: presets, diff, formats,
reports, UX
Features
- presets: minimal (>=50, weak names off), balanced (>=25), noisy (>=10),
with strict/high/default/loud/broad aliases; --init-config writes a
validated starter JSON and refuses to overwrite
- config inheritance: validated 'extends' (preset name or relative .json),
list merge, scalar override, cycle + depth (4) protection
- Baselines/diff: stable 16-hex fingerprints (host+location+param+rule+path),
--baseline and --suppress, --show-known, resolved list, --mark-reviewed
ledger; --fail-on-findings gates on new candidates in diff mode
- inputs: Burp proxy XML (base64/plain, form/JSON/multipart), OpenAPI/Swagger
parameter inventory, raw HTTP requests (### separated), recon exports
(httpx/ffuf/katana/nuclei lines and JSONL) with auto-detection refined so
plain URL lists keep their format
- outputs: Markdown and HTML reports (--save-report, --output-format), fully
escaped, plus fingerprints/status in JSON, CSV and SARIF partialFingerprints
- UX: --explain/--explain-value scoring trace, --top, --group-by,
--summary-only compact view
Tests: 209 total (71 new) covering presets, extends cycles, fingerprint
stability, baseline flows and exit codes, suppression ledgers, explain output,
Burp/OpenAPI/raw/recon parsing, Markdown/HTML escaping, and new report metadata.
README updated with presets, diff workflow, extra inputs and CLI reference.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
---
README.md | 154 ++++++-
pathscope/__init__.py | 2 +-
pathscope/cli.py | 394 ++++++++++++++--
pathscope/config.py | 128 +++++-
pathscope/detector.py | 125 ++++-
pathscope/extra_formats.py | 693 ++++++++++++++++++++++++++++
pathscope/heuristics.py | 9 +-
pathscope/presets.py | 126 +++++
pathscope/report.py | 132 +++++-
pathscope/sources.py | 78 +++-
pathscope/writers.py | 274 +++++++++++
tests/test_features.py | 895 ++++++++++++++++++++++++++++++++++++
tests/test_path_detector.py | 3 +-
13 files changed, 2927 insertions(+), 86 deletions(-)
create mode 100644 pathscope/extra_formats.py
create mode 100644 pathscope/presets.py
create mode 100644 pathscope/writers.py
create mode 100644 tests/test_features.py
diff --git a/README.md b/README.md
index 49c04ab..397cb38 100644
--- a/README.md
+++ b/README.md
@@ -35,15 +35,17 @@ reviewing for path-traversal risk.**
4. [Installation on Kali Linux](#installation-on-kali-linux)
5. [Inputs](#inputs)
6. [Quick start](#quick-start)
-7. [Reports: text, JSON, CSV, SARIF](#reports-text-json-csv-sarif)
-8. [Exit codes](#exit-codes)
-9. [Detection rules](#detection-rules)
-10. [Configuration file](#configuration-file)
-11. [Tests](#tests)
-12. [Project layout](#project-layout)
-13. [Limitations](#limitations)
-14. [FAQ](#faq)
-15. [Authorization and legal](#authorization-and-legal)
+7. [Presets](#presets)
+8. [Baselines, diff and suppression](#baselines-diff-and-suppression)
+9. [Reports: text, JSON, CSV, SARIF, Markdown, HTML](#reports)
+10. [Exit codes](#exit-codes)
+11. [Detection rules](#detection-rules)
+12. [Configuration file](#configuration-file)
+13. [Tests](#tests)
+14. [Project layout](#project-layout)
+15. [Limitations](#limitations)
+16. [FAQ](#faq)
+17. [Authorization and legal](#authorization-and-legal)
---
@@ -151,15 +153,21 @@ PathScope accepts three sources, which are merged and de-duplicated:
| 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. |
| stdin | `cat urls.txt \| pathscope`, `pathscope -i -` | Auto-detected when no other source is given. |
### Input format
-* `--format auto` (default) — HAR if the file ends in `.har`/`.har.json` or the
- JSON starts with a `log.entries` object; otherwise a URL list.
-* `--format har` — force HAR.
-* `--format urls` — force a URL list.
-* `--input-format {auto,urls,har}` — same selectors under an unambiguous name.
+* `--format auto` (default) — detects, in order: HAR (`.har`/`.har.json` or a
+ `log.entries` object), Burp XML, OpenAPI JSON, raw HTTP request, recon
+ output, then a plain URL list.
+* `--format har|burp|openapi|raw|recon|urls` — force an input format.
+* `--input-format {auto,urls,har,burp,openapi,raw,httpx,ffuf,nuclei,recon}` —
+ 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).
@@ -208,7 +216,7 @@ Example terminal output (values hidden):
```console
$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
-PathScope 2.0.0 - passive path-parameter triage
+PathScope 2.1.0 - passive path-parameter triage
----------------------------------------------------------------
GitHub: https://github.com/mrdineshpathro
Instagram: https://www.instagram.com/mr_dineshpatro
@@ -225,8 +233,8 @@ Analyzed 1 request(s) and 1 parameter(s); 1 candidate(s) at score >= 25.
Request GET https://example.test/view
Location query
Rule name-exact
- Value (use --show-values to display)
- Why rule(s) and evidence:
+ 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)
@@ -235,7 +243,58 @@ Reminder: these are candidates for manual review, not confirmed vulnerabilities.
---
-## Reports: text, JSON, CSV, SARIF
+## 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`,
@@ -247,7 +306,7 @@ Every format contains the same fields: `host`, `source_type`, `source`,
```json
{
"tool": "PathScope",
- "version": "2.0.0",
+ "version": "2.1.0",
"disclaimer": "Candidates for manual review only. ...",
"passive": true,
"network_requests_made": 0,
@@ -259,7 +318,11 @@ Every format contains the same fields: `host`, `source_type`, `source`,
"candidates": 1,
"confidence": {"high": 0, "medium": 1, "low": 0},
"skipped": 0,
- "sources": ["urls.txt"]
+ "sources": ["urls.txt"],
+ "mode": "scan",
+ "new": 1,
+ "known": 0,
+ "resolved": 0
},
"warnings": [],
"findings": [
@@ -281,7 +344,10 @@ Every format contains the same fields: `host`, `source_type`, `source`,
"value ends with a file-like extension '.pdf' (+8)"
],
"resource": "https://example.test/view",
- "value": null
+ "value": null,
+ "fingerprint": "ec274fecea647284",
+ "status": "new",
+ "note": ""
}
],
"links": {
@@ -301,6 +367,18 @@ index,host,source_type,source,method,location,parameter,rule,rules,confidence,sc
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 `.pdf",
+ sources.SOURCE_URL,
+ "--url",
+ )
+ ]
+ data = detector.analyze_requests(
+ requests, detector.AnalysisOptions(show_values=True)
+ )
+ html_text = writers.render_html(data)
+ # No raw markup from the input may survive into the document.
+ self.assertNotIn("", html_text)
+ self.assertIn("<script>", html_text)
+ self.assertIn("</script>", html_text)
+ self.assertIn("", html_text)
+ self.assertIn("manual review", html_text)
+
+ def test_save_report_flag(self):
+ directory = tempfile.mkdtemp()
+ for name, marker in (("report.md", "# PathScope report"),
+ ("report.html", "")):
+ path = os.path.join(directory, name)
+ code, out, err = run_inprocess(
+ "--no-banner", "-q", "--save-report", path,
+ "--url", "https://a.test/?file=/x/y.pdf",
+ )
+ self.assertEqual(code, cli.EXIT_OK)
+ self.assertTrue(os.path.exists(path))
+ self.assertIn(marker, Path(path).read_text())
+ cleanup(path)
+
+ def test_save_report_rejects_unknown_extension(self):
+ code, _out, err = run_inprocess(
+ "--no-banner", "-q", "--save-report", "/tmp/report.pdf",
+ "--url", "https://a.test/?file=x.pdf",
+ )
+ self.assertEqual(code, cli.EXIT_USAGE)
+ self.assertIn("unsupported report extension", err)
+
+ def test_output_format_markdown_and_html(self):
+ for fmt, marker in (("markdown", "# PathScope report"),
+ ("html", "")):
+ code, out, _err = run_inprocess(
+ "--no-banner", "-q", "--output-format", fmt,
+ "--url", "https://a.test/?file=x.pdf",
+ )
+ self.assertEqual(code, cli.EXIT_OK)
+ self.assertIn(marker, out)
+
+
+# ---------------------------------------------------------------------------
+# Burp XML
+# ---------------------------------------------------------------------------
+class TestBurpInput(unittest.TestCase):
+ def test_base64_and_plain_requests(self):
+ result = extra_formats.load_burp(burp_xml(), "sample.xml")
+ self.assertEqual(len(result.requests), 2)
+ self.assertEqual(result.skipped, 1)
+ query = [p for r in result.requests for p in r.parameters
+ if p.location == sources.LOCATION_QUERY]
+ form = [p for r in result.requests for p in r.parameters
+ if p.location == sources.LOCATION_FORM]
+ self.assertEqual([p.name for p in query], ["path"])
+ self.assertEqual([p.name for p in form], ["attachment"])
+ self.assertIn("secret.txt", form[0].value)
+
+ def test_burp_request_shape(self):
+ result = extra_formats.load_burp(burp_xml(), "sample.xml")
+ first = result.requests[0]
+ self.assertEqual(first.source_type, "burp")
+ self.assertEqual(first.method, "GET")
+ self.assertEqual(first.url.host, "app.test")
+ self.assertEqual(first.url.path, "/dl")
+
+ def test_burp_missing_items(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_burp("no items", "x.xml")
+
+ def test_burp_invalid_xml(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_burp("", "broken.xml")
+
+ def test_burp_detection(self):
+ self.assertEqual(
+ extra_formats.detect_extra_format(burp_xml(), "capture.xml"),
+ extra_formats.INPUT_FORMAT_BURP,
+ )
+
+ def test_cli_burp_file(self):
+ path = write_temp(".xml", burp_xml())
+ try:
+ code, out, _err = run_inprocess("--no-banner", "-q", "--json", "-i", path)
+ finally:
+ cleanup(path)
+ self.assertEqual(code, cli.EXIT_OK)
+ payload = json.loads(out)
+ self.assertEqual({f["source_type"] for f in payload["findings"]}, {"burp"})
+ self.assertEqual(payload["summary"]["candidates"], 2)
+
+
+# ---------------------------------------------------------------------------
+# OpenAPI
+# ---------------------------------------------------------------------------
+class TestOpenApiInput(unittest.TestCase):
+ def test_parameters_are_inventoried(self):
+ result = extra_formats.load_openapi(json.dumps(OPENAPI), "api.json")
+ names = {(r.method, p.location, p.name) for r in result.requests for p in r.parameters}
+ self.assertIn(("GET", "query", "fileId"), names)
+ self.assertIn(("GET", "query", "download"), names)
+ self.assertNotIn(("GET", "query", "X-Trace"), names) # headers ignored
+ self.assertIn(("POST", "json", "template"), names)
+ self.assertIn(("POST", "json", "options.layout"), names)
+
+ def test_requests_are_synthetic_and_value_free(self):
+ result = extra_formats.load_openapi(json.dumps(OPENAPI), "api.json")
+ for request in result.requests:
+ self.assertEqual(request.source_type, "openapi")
+ for parameter in request.parameters:
+ self.assertEqual(parameter.value, "")
+
+ def test_not_openapi(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_openapi(json.dumps({"paths": {}}), "x.json")
+
+ def test_swagger2_host(self):
+ payload = {
+ "swagger": "2.0",
+ "host": "legacy.test",
+ "basePath": "/api",
+ "schemes": ["https"],
+ "paths": {"/x": {"get": {"parameters": [{"name": "file", "in": "query"}]}}},
+ }
+ result = extra_formats.load_openapi(json.dumps(payload), "swagger.json")
+ self.assertEqual(result.requests[0].url.host, "legacy.test")
+ self.assertEqual(result.requests[0].url.scheme, "https")
+
+ def test_yaml_hint_is_explicit(self):
+ path = write_temp(".yaml", "openapi: 3.0.0\npaths: {}\n")
+ try:
+ with self.assertRaises(extra_formats.HarError) as ctx:
+ extra_formats.load_extra_file(path, "openapi-yaml")
+ finally:
+ cleanup(path)
+ self.assertIn("YAML", str(ctx.exception))
+
+ def test_cli_openapi_file(self):
+ path = write_temp(".json", json.dumps(OPENAPI))
+ try:
+ code, out, _err = run_inprocess("--no-banner", "-q", "--json", "-i", path)
+ finally:
+ cleanup(path)
+ self.assertEqual(code, cli.EXIT_OK)
+ payload = json.loads(out)
+ self.assertEqual(payload["summary"]["candidates"], 4)
+ self.assertEqual({f["location"] for f in payload["findings"]}, {"query", "json"})
+
+
+# ---------------------------------------------------------------------------
+# Raw HTTP
+# ---------------------------------------------------------------------------
+class TestRawHttpInput(unittest.TestCase):
+ def test_single_request(self):
+ text = (
+ "GET /view?file=../../etc/passwd HTTP/1.1\n"
+ "Host: app.test\n"
+ "Accept: */*\n\n"
+ )
+ result = extra_formats.load_raw_http(text, "request.txt")
+ self.assertEqual(len(result.requests), 1)
+ self.assertEqual(result.requests[0].url.host, "app.test")
+ self.assertEqual([p.name for p in result.requests[0].parameters], ["file"])
+
+ def test_form_body(self):
+ text = (
+ "POST /import HTTP/1.1\n"
+ "Host: app.test\n"
+ "Content-Type: application/x-www-form-urlencoded\n\n"
+ "source=%2Fvar%2Fwww%2Fdump.sql&format=csv\n"
+ )
+ result = extra_formats.load_raw_http(text, "request.txt")
+ form = {p.name: p.value for p in result.requests[0].parameters}
+ self.assertEqual(form["source"], "/var/www/dump.sql")
+
+ def test_multiple_requests(self):
+ text = (
+ "GET /a?file=x HTTP/1.1\nHost: a.test\n\n"
+ "###\n"
+ "GET /b?path=y HTTP/1.1\nHost: b.test\n\n"
+ )
+ result = extra_formats.load_raw_http(text, "requests.txt")
+ self.assertEqual([r.url.host for r in result.requests], ["a.test", "b.test"])
+
+ def test_missing_host(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_raw_http("GET /a?file=x HTTP/1.1\n\n", "x.txt")
+
+ def test_malformed_request_line(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_raw_http("nonsense\nHost: a.test\n\n", "x.txt")
+
+ def test_detection(self):
+ text = "POST /x HTTP/1.1\nHost: a.test\n\n"
+ self.assertEqual(
+ extra_formats.detect_extra_format(text, "req.txt"),
+ extra_formats.INPUT_FORMAT_RAW,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Recon exports
+# ---------------------------------------------------------------------------
+class TestReconInput(unittest.TestCase):
+ def test_httpx_lines(self):
+ text = (
+ '"https://app.test/dl?file=x.pdf" [200] [1234 bytes]\n'
+ "https://app.test/api?path=/var/www [404] [12 bytes]\n"
+ )
+ result = extra_formats.load_recon_text(text, "httpx.txt")
+ self.assertEqual(len(result.requests), 2)
+ self.assertEqual({p.name for r in result.requests for p in r.parameters},
+ {"file", "path"})
+
+ def test_ffuf_lines(self):
+ # ffuf directory hits are not URLs; only URL-bearing lines are used.
+ text = (
+ "admin [Status: 200, Size: 123]\n"
+ "https://app.test/dl?file=x.pdf [Status: 200, Size: 999]\n"
+ )
+ result = extra_formats.load_recon_text(text, "ffuf.txt")
+ self.assertEqual(len(result.requests), 1)
+ self.assertEqual(result.requests[0].url.host, "app.test")
+
+ def test_nuclei_jsonl(self):
+ line = json.dumps({"template": "t", "matched-at": "https://app.test/?file=x"})
+ result = extra_formats.load_recon_text(line, "nuclei.jsonl")
+ self.assertEqual(result.requests[0].url.host, "app.test")
+
+ def test_no_urls_is_an_error(self):
+ with self.assertRaises(extra_formats.HarError):
+ extra_formats.load_recon_text("nothing here\n", "x.txt")
+
+ def test_plain_url_list_is_not_recon(self):
+ text = "https://a.test/?file=1\nhttps://b.test/?path=2\n"
+ self.assertEqual(sources.detect_input_format(text), sources.INPUT_FORMAT_URLS)
+
+ def test_recon_detection(self):
+ text = "https://a.test/x [200] [1234 bytes]\n"
+ self.assertEqual(
+ sources.detect_input_format(text), sources.FORMAT_RECON
+ if hasattr(sources, "FORMAT_RECON") else "recon",
+ )
+
+
+# ---------------------------------------------------------------------------
+# Terminal UX: --top, --group-by, --summary-only
+# ---------------------------------------------------------------------------
+SAMPLE_URLS = [
+ "https://a.test/?file=/x/a.pdf",
+ "https://b.test/?path=/var/www",
+ "https://c.test/?download=/tmp/x.zip",
+]
+
+
+class TestTerminalUx(unittest.TestCase):
+ def test_top_limits_output(self):
+ stdin = "\n".join(SAMPLE_URLS)
+ full = run_inprocess("--no-banner", "-q", "--url", SAMPLE_URLS[0],
+ "--url", SAMPLE_URLS[1], "--url", SAMPLE_URLS[2])[1]
+ limited = run_inprocess("--no-banner", "-q", "--top", "1",
+ "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1],
+ "--url", SAMPLE_URLS[2])[1]
+ self.assertGreater(full.count("#"), limited.count("#"))
+ self.assertIn("#1", limited)
+ self.assertNotIn("#2", limited)
+
+ def test_top_zero_shows_all(self):
+ out = run_inprocess("--no-banner", "-q", "--top", "0",
+ "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1])[1]
+ self.assertIn("#2", out)
+
+ def test_group_by_host(self):
+ out = run_inprocess("--no-banner", "-q", "--group-by", "host",
+ "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[1])[1]
+ self.assertIn("== a.test ==", out)
+ self.assertIn("== b.test ==", out)
+
+ def test_group_by_confidence(self):
+ out = run_inprocess("--no-banner", "-q", "--group-by", "confidence",
+ "--url", SAMPLE_URLS[0], "--url", SAMPLE_URLS[2])[1]
+ self.assertIn("confidence", out)
+
+ def test_summary_only(self):
+ code, out, _err = run_inprocess("--no-banner", "-q", "--summary-only",
+ "--url", SAMPLE_URLS[0])
+ self.assertEqual(code, cli.EXIT_OK)
+ self.assertIn("PathScope summary", out)
+ self.assertIn("Candidates per host", out)
+ self.assertIn("Candidates per rule", out)
+ self.assertNotIn("Why", out)
+
+
+# ---------------------------------------------------------------------------
+# Report metadata for the new features
+# ---------------------------------------------------------------------------
+class TestReportMetadata(unittest.TestCase):
+ def test_json_summary_includes_mode_and_diff_counts(self):
+ requests = [sources.request_from_url("https://a.test/?file=x.pdf",
+ sources.SOURCE_URL, "--url")]
+ payload = json.loads(
+ report.render_json(detector.analyze_requests(requests, detector.AnalysisOptions()))
+ )
+ self.assertEqual(payload["summary"]["mode"], "scan")
+ self.assertEqual(payload["summary"]["new"], 1)
+ self.assertEqual(payload["summary"]["known"], 0)
+ self.assertEqual(payload["findings"][0]["status"], "new")
+ self.assertTrue(payload["findings"][0]["fingerprint"])
+
+ def test_csv_has_fingerprint_and_status(self):
+ requests = [sources.request_from_url("https://a.test/?file=x.pdf",
+ sources.SOURCE_URL, "--url")]
+ text = report.render_csv(detector.analyze_requests(requests,
+ detector.AnalysisOptions()))
+ header = text.splitlines()[0].split(",")
+ self.assertIn("fingerprint", header)
+ self.assertIn("status", header)
+ self.assertIn("note", header)
+
+ def test_sarif_has_partial_fingerprints_and_baseline_state(self):
+ requests = [sources.request_from_url("https://a.test/?file=x.pdf",
+ sources.SOURCE_URL, "--url")]
+ payload = json.loads(
+ report.render_sarif(detector.analyze_requests(requests,
+ detector.AnalysisOptions()))
+ )
+ result = payload["runs"][0]["results"][0]
+ self.assertIn("partialFingerprints", result)
+ self.assertIn("pathscope/v1", result["partialFingerprints"])
+ self.assertEqual(result["baselineState"], "new")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/tests/test_path_detector.py b/tests/test_path_detector.py
index cc5f887..2bb34b0 100755
--- a/tests/test_path_detector.py
+++ b/tests/test_path_detector.py
@@ -1133,7 +1133,8 @@ def test_imports_are_standard_library_only(self):
allowed_stdlib = {
"__future__", "argparse", "csv", "dataclasses", "io", "json", "os",
"re", "sys", "typing", "unicodedata", "urllib.parse", "collections",
- "pathlib", "textwrap",
+ "pathlib", "textwrap", "xml", "xml.etree", "xml.etree.ElementTree",
+ "base64", "copy", "hashlib", "html",
}
for path in project_modules():
tree = ast.parse(path.read_text(encoding="utf-8"))
From b714eaa4ebf4dededede4ebc2281de631ef732ca Mon Sep 17 00:00:00 2001
From: mrdineshpathro <153123519+mrdineshpathro@users.noreply.github.com>
Date: Sun, 29 Nov 2026 11:32:16 +0000
Subject: [PATCH 4/8] Add PathScope 2.2: watch mode, interactive reports, rule
registry, CI toolkit
Eight feature groups, each with tests and README sections.
1. Live watch mode (--watch FILE --interval N)
Re-reads a growing HAR/URL file and prints only candidates not reported
before. Polls skip unchanged files (size+mtime), a shrunk/rotated capture
starts a fresh baseline, transient read errors retry quietly, Ctrl-C stops
with a summary. A missing file is a usage error instead of an endless loop.
2. Interactive HTML report (--save-report FILE.html --interactive)
Self-contained page: sortable columns, text and confidence filters,
reviewed-only mode, localStorage review marks, copy-fingerprint buttons and
print CSS. No external assets, no network primitives in the inline script;
every dynamic string is escaped exactly like the static writer.
3. Rule registry and tuning (--list-rules, --rules, --disable-rule)
New pathscope/rules.py holds all 29 rules with layer, default weight and
description. Weights can be overridden or rules removed at runtime; unknown
ids, out-of-range weights and positive demotions are rejected. --explain now
reports the effective book, folded/i18n settings and overridden weights.
4. CI toolkit (--policy, --init-policy, junit, --github-annotations, --self-test)
New pathscope/policy.py evaluates max_high/medium/low/total, min_score,
fail_on_known, ignore_rules and ignore_hosts against new findings, with
explainable violations and exit code 1. New pathscope/ci.py renders JUnit
XML, GitHub workflow annotations (escaped per the Actions spec) and the
ten-check --self-test. Adds .github/workflows/pathscope.yml,
.pre-commit-hooks.yaml, an example config and .pathscope/policy.json.
5. Scale helpers (--dedupe-by, --max-entries, --stats, --progress)
Findings collapse by path (default), parameter or not at all; input entries
can be capped with a reported truncation warning; --stats records phase
timings on stderr and in JSON; --progress writes rate-limited updates to
stderr only, leaving stdout machine-readable.
6. More tool exports (postman, zap, mitmproxy, graphql, cookies)
New pathscope/tool_formats.py parses Postman v2.x collections (nested
folders, query/urlencoded/formdata/raw bodies), ZAP JSON history and alert
exports, mitmproxy flow exports and GraphQL introspection results. Cookie
jars contribute names only; values are discarded before analysis.
7. Fuzzy and multilingual names (--name-lang, --no-fold)
New pathscope/naming.py folds diacritics, compatibility forms, exotic
separators and invisible characters, expands bounded leet spellings
(f1le -> file) and ships German, Spanish, French, Portuguese, Italian and
Dutch term packs. Folded matches use weaker rules (name-folded +20,
name-leet +12, name-i18n-fold +21) and English tables always win.
8. Value-shape demotion (--no-demote, --disable-rule)
New pathscope/valueshape.py recognises UUIDs, hex digests, JWTs, base64
blobs, e-mail addresses, IP literals and bool/number/enum values and emits
explicit negative rules, visible in --explain and every report, so a shape
demotion never hides a candidate silently.
Config gains name_lang, fold_names and demote_shapes (validated, merged
through extends, carried through the CLI merge). Version 2.2.0.
Tests: 335 total (127 new) covering watch polling and rotation, interactive
markup and script guarantees, rule validation and overrides, policy gates,
JUnit/annotation escaping, self-test, every tool format, folding/i18n edge
cases, demotion thresholds, dedupe/limits/stats/progress, README anchors and
the shipped CI files. README adds eight sections and a full CLI table.
Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
---
.github/workflows/pathscope.yml | 83 ++
.pathscope/policy.json | 10 +
.pre-commit-config.example.yaml | 7 +
.pre-commit-hooks.yaml | 28 +
README.md | 336 ++++++-
pathscope/__init__.py | 2 +-
pathscope/ci.py | 300 +++++++
pathscope/cli.py | 389 +++++++-
pathscope/config.py | 71 +-
pathscope/detector.py | 99 +-
pathscope/heuristics.py | 443 ++++++---
pathscope/naming.py | 296 ++++++
pathscope/policy.py | 252 ++++++
pathscope/presets.py | 9 +
pathscope/progress.py | 108 +++
pathscope/report.py | 20 +-
pathscope/rules.py | 445 +++++++++
pathscope/sources.py | 23 +
pathscope/tool_formats.py | 785 ++++++++++++++++
pathscope/valueshape.py | 195 ++++
pathscope/watch.py | 220 +++++
pathscope/writers.py | 291 +++++-
tests/test_features_v22.py | 1498 +++++++++++++++++++++++++++++++
tests/test_path_detector.py | 18 +-
24 files changed, 5742 insertions(+), 186 deletions(-)
create mode 100644 .github/workflows/pathscope.yml
create mode 100644 .pathscope/policy.json
create mode 100644 .pre-commit-config.example.yaml
create mode 100644 .pre-commit-hooks.yaml
create mode 100644 pathscope/ci.py
create mode 100644 pathscope/naming.py
create mode 100644 pathscope/policy.py
create mode 100644 pathscope/progress.py
create mode 100644 pathscope/rules.py
create mode 100644 pathscope/tool_formats.py
create mode 100644 pathscope/valueshape.py
create mode 100644 pathscope/watch.py
create mode 100644 tests/test_features_v22.py
diff --git a/.github/workflows/pathscope.yml b/.github/workflows/pathscope.yml
new file mode 100644
index 0000000..52fe36f
--- /dev/null
+++ b/.github/workflows/pathscope.yml
@@ -0,0 +1,83 @@
+# 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
+
+ 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/.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/README.md b/README.md
index 397cb38..da022a6 100644
--- a/README.md
+++ b/README.md
@@ -37,15 +37,22 @@ reviewing for path-traversal risk.**
6. [Quick start](#quick-start)
7. [Presets](#presets)
8. [Baselines, diff and suppression](#baselines-diff-and-suppression)
-9. [Reports: text, JSON, CSV, SARIF, Markdown, HTML](#reports)
-10. [Exit codes](#exit-codes)
-11. [Detection rules](#detection-rules)
-12. [Configuration file](#configuration-file)
-13. [Tests](#tests)
-14. [Project layout](#project-layout)
-15. [Limitations](#limitations)
-16. [FAQ](#faq)
-17. [Authorization and legal](#authorization-and-legal)
+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. [Exit codes](#exit-codes)
+16. [Detection rules](#detection-rules)
+17. [Configuration file](#configuration-file)
+18. [Tests](#tests)
+19. [Project layout](#project-layout)
+20. [Limitations](#limitations)
+21. [FAQ](#faq)
+22. [Authorization and legal](#authorization-and-legal)
---
@@ -157,17 +164,23 @@ PathScope accepts three sources, which are merged and de-duplicated:
| 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), Burp XML, OpenAPI JSON, raw HTTP request, recon
- output, then a plain URL list.
-* `--format har|burp|openapi|raw|recon|urls` — force an input format.
-* `--input-format {auto,urls,har,burp,openapi,raw,httpx,ffuf,nuclei,recon}` —
- the same selectors under an unambiguous name. Use `--input-format` together
- with `--format json` when you want to force the input **and** choose output.
+ `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).
@@ -216,7 +229,7 @@ Example terminal output (values hidden):
```console
$ python3 path_detector.py --url 'https://example.test/view?file=report.pdf'
-PathScope 2.1.0 - passive path-parameter triage
+PathScope 2.2.0 - passive path-parameter triage
----------------------------------------------------------------
GitHub: https://github.com/mrdineshpathro
Instagram: https://www.instagram.com/mr_dineshpatro
@@ -403,12 +416,227 @@ stderr summary; JSON/CSV/SARIF on stdout stay valid.
---
+## Live watch mode
+
+A proxy keeps appending to a capture while you work. `--watch` re-reads the
+file on a timer and prints **only candidates it has not reported before**, one
+line each, so a long session stays readable.
+
+```bash
+python3 path_detector.py --watch capture.har --interval 2
+python3 path_detector.py --watch urls.txt --preset noisy --interval 5
+```
+
+```
+Watching capture.har every 2s for new candidates. Press Ctrl-C to stop. No requests are sent.
+[new] app.test query file HIGH 71/100 name-exact
+[new] cdn.test form attachment MEDIUM 53/100 name-exact
+Stopped after 42 poll(s) in 84.0s; 2 candidate(s) seen in total.
+```
+
+* Polling only parses the file when its size/mtime changed.
+* Identity is the usual fingerprint, so the same parameter never repeats.
+* A capture that shrinks (rotated/replaced) starts a fresh baseline.
+* A missing file is a usage error (exit `2`); a transient read failure while a
+ proxy is writing is retried quietly.
+* Ctrl-C stops cleanly and prints a summary. Nothing is ever requested.
+
+---
+
+## Rule registry and tuning
+
+Every rule and its default weight is listed in `pathscope/rules.py` and is
+visible from the command line. Rules can be reweighted, disabled and explained
+without editing code.
+
+```bash
+# What rules exist, with effective weights?
+python3 path_detector.py --list-rules
+
+# Reweight and disable rules for this run (JSON)
+cat > rules.json <<'JSON'
+{
+ "weights": { "name-exact": 40, "value-weak": 0 },
+ "disable": ["name-weak"]
+}
+JSON
+python3 path_detector.py -i capture.har --rules rules.json
+
+# One-off: remove a rule just for this run
+python3 path_detector.py -i capture.har --disable-rule name-suffix
+
+# Why did (or didn't) this parameter fire?
+python3 path_detector.py --explain base_path --explain-value ../../etc/passwd
+```
+
+`--explain` prints the effective threshold, the rule book in use, every rule
+that fired with its layer, weight and reason, the total, and whether the result
+would be reported. Overridden weights are shown as `44 (default +35)`.
+
+`--disable-rule` accepts a full id (`value-traversal`) or an unambiguous short
+form (`traversal`, `uuid`). Unknown ids are rejected with exit `2`. Demotion
+rules (`value-demote-*`) may not be given a positive weight.
+
+---
+
+## Multilingual and folded names
+
+**Folding** is always on: diacritics, compatibility forms (fullwidth), exotic
+separators and invisible characters are normalised before tokenisation, so
+`fıle`, `file` and `F_I_L_E` are all `file`. Names that only match after
+folding get the weaker `name-folded` rule (+20), never the full `name-exact`
+weight.
+
+Leet spellings are de-obfuscated for tokens of 3+ characters (`f1le` → `file`,
+`p4th` → `path`) and score `name-leet` (+12).
+
+**Term packs** add path vocabulary from other languages:
+
+| Tag | Language | Examples |
+|---|---|---|
+| `de` | German | `datei`, `pfad`, `ordner`, `herunterladen` |
+| `es` | Spanish | `archivo`, `ruta`, `carpeta`, `descargar` |
+| `fr` | French | `fichier`, `chemin`, `dossier`, `telecharger` |
+| `pt` | Portuguese | `arquivo`, `caminho`, `pasta`, `baixar` |
+| `it` | Italian | `percorso`, `cartella`, `allegato`, `scaricare` |
+| `nl` | Dutch | `bestand`, `pad`, `map`, `bijlage` |
+
+```bash
+python3 path_detector.py -i capture.har --name-lang de,es
+python3 path_detector.py -i capture.har --name-lang auto # every pack
+```
+
+`--name-lang off` (default) keeps English only. In a configuration file use
+`"name_lang": ["de", "es"]`, `["auto"]` or `[]`. English tables always win: a
+word that is generic in English (`image`, `document`) is never re-labelled as a
+foreign finding, and a folded-only match scores `name-i18n-fold` (+21) rather
+than the full `name-i18n` (+25).
+
+`--no-fold` disables folding entirely (useful when auditing the sanitizer).
+
+---
+
+## Value-shape demotion
+
+A parameter named `file` whose value is a UUID, a hash, a JWT, a base64 blob, an
+e-mail address, an IP literal or a plain boolean/number is probably not a
+filesystem path. PathScope adds **negative** evidence for those shapes:
+
+| Rule | Weight | Shape |
+|---|---|---|
+| `value-demote-uuid` | −20 | `550e8400-e29b-41d4-a716-446655440000` |
+| `value-demote-hash` | −18 | MD5/SHA digests, `sha256:…` |
+| `value-demote-jwt` | −20 | `eyJ….eyJ….…` |
+| `value-demote-base64` | −12 | long base64 blobs |
+| `value-demote-email` | −8 | `user@example.test` |
+| `value-demote-ip` | −10 | `192.168.1.1`, `2001:db8::1` |
+| `value-demote-scalar` | −10 | `true`, `42`, `3.14`, short enums |
+
+Demotions appear in `--explain` and in every report (`rules`, `reasons`), so a
+candidate that drops below the threshold is visible rather than silently
+filtered. Tune them with `--rules`, remove them with
+`--disable-rule value-demote-uuid`, or turn the whole layer off with
+`--no-demote` / `"demote_shapes": false`.
+
+---
+
+## CI integration
+
+Four small pieces make PathScope fit a pipeline without a wrapper script.
+
+**Policy gate.** `--policy FILE` (or inline JSON) expresses what may not happen:
+
+```json
+{
+ "description": "no new high-confidence candidates",
+ "max_high": 0,
+ "max_medium": 10,
+ "max_total": 20,
+ "min_score": 0,
+ "fail_on_known": false,
+ "ignore_rules": ["name-weak"],
+ "ignore_hosts": ["static.example.test"]
+}
+```
+
+```bash
+python3 path_detector.py -i capture.har --baseline baseline.json \
+ --policy pathscope-policy.json
+python3 path_detector.py --init-policy pathscope-policy.json # starter file
+```
+
+Only *new* findings count unless `fail_on_known` is true. Exit code `1` means
+the policy failed; the reasons are printed to stderr
+(`policy failed: max_high=0 exceeded (1 found)`).
+
+**JUnit XML.** `--output-format junit` writes one `testcase` per confidence band
+plus one per finding, so GitLab/Jenkins/Azure show each candidate:
+
+```bash
+python3 path_detector.py -i capture.har --output-format junit > pathscope.xml
+```
+
+**GitHub annotations.** `--github-annotations` prints workflow commands on
+stdout; high-confidence candidates become `::warning`, others `::notice`:
+
+```bash
+python3 path_detector.py -i capture.har --github-annotations
+```
+
+**Self-test.** `--self-test` runs ten checks about the installation (banner,
+parsing, scoring, privacy defaults, escaping, bounded decoding) and exits `1` if
+any fail. It reads no user files and uses no network.
+
+Ready-made files live in the repository: `.github/workflows/pathscope.yml`
+(runs the tests, scans an artifact if present, and honours a baseline) and
+`.pre-commit-hooks.yaml` (blocking new high-confidence candidates in changed
+captures). Both are plain YAML with no third-party actions beyond
+`actions/checkout`.
+
+---
+
+## Scale and performance
+
+| Option | Effect |
+|---|---|
+| `--dedupe-by path` | **default** — one finding per host + location + parameter; `occurrences` counts resources |
+| `--dedupe-by param` | one finding per parameter name, across hosts |
+| `--dedupe-by none` | every (resource, parameter) pair stays separate |
+| `--max-entries N` | analyse at most N input entries; the rest are reported as truncated |
+| `--stats` | parse/analyse timings and counts on stderr and in JSON |
+
+Analysis is single-pass and in-memory; a 20 000-entry HAR is bounded by
+`MAX_HAR_ENTRIES` and the JSON body limits. Use `--preset minimal` and
+`--dedupe-by path` on very large captures to keep output short, and `--top N`
+when you only want the best few. `--progress` writes phase updates to stderr and
+leaves stdout machine-readable.
+
+---
+
+## Interactive HTML report
+
+`--save-report FILE.html --interactive` writes a single self-contained page with
+sortable columns, a text filter, a confidence filter, "reviewed only" mode and
+one-click fingerprint copying. Review checkboxes are stored in the browser's
+`localStorage`; nothing is uploaded and there are no external assets, so the
+file works offline and from `file://`.
+
+```bash
+python3 path_detector.py -i capture.har --save-report triage.html --interactive
+```
+
+`--interactive` requires an `.html`/`.htm` `--save-report`; use it on a report
+you plan to hand to a human reviewer, and keep the static/Markdown writers for
+tickets and archives.
+
+---
+
## Exit codes
| Code | Meaning |
|---|---|
| `0` | Analysis completed. No candidates (or candidates found without `--fail-on-findings`). |
-| `1` | `--fail-on-findings` and at least one candidate was reported (in diff mode: at least one **new** candidate). |
+| `1` | `--fail-on-findings` and at least one candidate was reported (in diff mode: at least one **new** candidate), **or** a `--policy` was violated. |
| `2` | Usage error, unreadable/malformed input file, invalid configuration, or no usable input. |
| `3` | Internal error while producing a report (never a crash trace). |
| `130` | Interrupted with `Ctrl-C`. |
@@ -434,6 +662,10 @@ All rules live in `pathscope/heuristics.py` and are safe to edit.
| `name-prefix` | +28 | the name starts with a path term (`filedata`) |
| `name-suffix` | +23 | the name ends with a path term (`resolvepath`) |
| `name-weak` | +5 | multiword name without a path term — never enough on its own |
+| `name-folded` | +20 | the term appears only after diacritic/compatibility folding |
+| `name-leet` | +12 | the term appears only after leet expansion (`f1le` → `file`) |
+| `name-i18n` | +25 | the term comes from an enabled language pack |
+| `name-i18n-fold` | +21 | a pack term that only matches after folding |
| `name-generic` | 0 | generic names (`image`, `img`, `target`, `ref`, `avatar`, …) only count *with* a path-like value |
`utm_source`, `gclid`, `page_size`, `urlencoded`, `landscape`, `sort` and similar
@@ -459,6 +691,7 @@ so `report..pdf` or `v1..2` never match.
| `value-path-list` | +5 | `a.css;b.css` |
| `value-full-url` | −10 | `https://other.test/x` (usually a redirect target) |
| `value-pairs-with-generic-name` | +10 | `image=/static/logo.png` |
+| `value-demote-*` | −8 … −20 | UUID, hash, JWT, base64, e-mail, IP, scalar (see [Value-shape demotion](#value-shape-demotion)) |
### Confidence bands (heuristic, not exploitability)
@@ -477,9 +710,14 @@ reading priority, never a risk rating.
* Add project-specific vocabulary: `--config` `name_terms` (literal strings only).
* Silence known-noisy names: `--ignore-param NAME` (repeatable) or `--config`
`ignore_params`.
-* Change the vocabulary permanently by editing `PATH_NAME_TERMS`,
- `GENERIC_NAME_TERMS`, `FILE_EXTENSIONS` or the weights in `heuristics.py`;
+* Change weights at runtime with `--rules FILE` / `--disable-rule RULE`, or
+ permanently in `pathscope/rules.py`; `--list-rules` always reflects the
+ effective values.
+* Change the vocabulary by editing `PATH_NAME_TERMS`, `GENERIC_NAME_TERMS`,
+ `FILE_EXTENSIONS` (English) or `pathscope/naming.py` (other languages);
the tests exercise these tables.
+* Widen the name layer with `--name-lang de,es,…` and narrow the value layer
+ with `--no-demote`.
---
@@ -487,11 +725,20 @@ reading priority, never a risk rating.
```
python3 path_detector.py [-h] [--version] [--url URL] [-i FILE]
- [--format {auto,urls,har,text,json,csv,sarif}]
- [--input-format {auto,urls,har}]
- [--output-format {text,json,csv,sarif}] [--json]
- [--show-values] [--no-color] [--no-banner] [-q]
- [--ignore-param NAME] [--config FILE]
+ [--format FORMAT] [--input-format FORMAT]
+ [--output-format {text,json,csv,sarif,markdown,html,junit}]
+ [--json] [--show-values] [--no-color] [--no-banner] [-q]
+ [--save-report FILE] [--interactive] [--progress] [--stats]
+ [--github-annotations] [--top N] [--group-by FIELD]
+ [--summary-only] [--preset NAME] [--baseline FILE]
+ [--suppress FILE] [--mark-reviewed FILE] [--show-known]
+ [--explain PARAM] [--explain-value VALUE]
+ [--init-config FILE] [--init-policy FILE]
+ [--rules FILE] [--list-rules] [--disable-rule RULE]
+ [--name-lang LIST] [--no-fold] [--no-demote]
+ [--dedupe-by {path,param,none}] [--max-entries N]
+ [--policy FILE|JSON] [--watch FILE] [--interval SECONDS]
+ [--self-test] [--ignore-param NAME] [--config FILE]
[--min-score N] [--max-decode-passes N]
[--fail-on-findings]
```
@@ -522,6 +769,24 @@ python3 path_detector.py [-h] [--version] [--url URL] [-i FILE]
| `--top N` | Show only the N best text candidates. |
| `--group-by FIELD` | Group text output by `host`, `rule`, `confidence`, `location`. |
| `--summary-only` | Compact counts-per-host/rule view. |
+| `--interactive` | Add sorting/filtering/review boxes to an HTML `--save-report`. |
+| `--progress` | Phase progress on stderr (stdout stays machine-readable). |
+| `--stats` | Timings and counts on stderr, and in the JSON payload. |
+| `--github-annotations` | Emit GitHub Actions annotations on stdout. |
+| `--output-format junit` | JUnit XML for CI test reports. |
+| `--list-rules` | Print every rule, effective weight and description. |
+| `--rules FILE` | JSON weight overrides (`{"weights": {...}, "disable": [...]}`). |
+| `--disable-rule RULE` | Remove a rule from scoring; repeatable. |
+| `--name-lang LIST` | Term packs: `de,es,fr,pt,it,nl`, `auto`, `off`. |
+| `--no-fold` | Disable diacritic/compatibility folding. |
+| `--no-demote` | Disable value-shape demotion. |
+| `--dedupe-by MODE` | `path` (default), `param` or `none`. |
+| `--max-entries N` | Analyse at most N input entries (0 = unlimited). |
+| `--policy FILE\|JSON` | CI gate; exit 1 when violated. |
+| `--init-policy FILE` | Write a starter policy and exit. |
+| `--watch FILE` | Re-analyse a growing capture; print new candidates only. |
+| `--interval SECONDS` | Polling interval for `--watch` (default 2). |
+| `--self-test` | Run the built-in environment checks (exit 1 on failure). |
| `-q, --quiet` | Suppress warnings and the stderr summary. |
| `--no-color` | Disable colour on terminals. |
| `--no-banner` | Suppress the startup banner. |
@@ -555,6 +820,9 @@ clear error and exit code `2`.
| `max_decode_passes` | integer | 0–5 |
| `weak_names` | boolean | enables the weak `name-weak` rule (default `true`) |
| `show_values` | boolean | defaults values to visible; `--show-values` also works |
+| `name_lang` | array | enabled term packs (`["de","es"]`, `["auto"]` or `[]`) |
+| `fold_names` | boolean | diacritic/compatibility folding (default `true`) |
+| `demote_shapes` | boolean | UUID/hash/scalar demotion (default `true`) |
| `extends` | string | base preset (`minimal`/`balanced`/`noisy`) or another `.json` file, relative to this file |
```bash
@@ -579,7 +847,7 @@ python3 -m unittest discover -s tests -v
python3 tests/test_path_detector.py
```
-209 tests cover exactly the behaviours this tool promises:
+322 tests cover exactly the behaviours this tool promises:
| Area | What is asserted |
|---|---|
@@ -596,6 +864,14 @@ python3 tests/test_path_detector.py
| Extra inputs | Burp XML (base64 + plain + multipart), OpenAPI query/body inventory, raw HTTP with `###`, recon lines and JSONL |
| Reports | Markdown/HTML content and escaping, `--save-report`, SARIF fingerprints |
| UX | `--top`, `--group-by`, `--summary-only`, `--explain` |
+| Watch mode | stable polls, new-only output, rotation, Ctrl-C, missing file |
+| Rules | registry validation, overrides, disabling, `--list-rules`, `--explain` |
+| i18n & folding | fullwidth/diacritic/leet names, packs, English-first precedence |
+| Demotion | every shape, thresholds, `--no-demote`, disabled rules |
+| CI | policy evaluation, JUnit XML, GitHub annotation escaping, self-test |
+| Tool exports | Postman, ZAP, mitmproxy, GraphQL, cookie jars (names only) |
+| Scale | dedupe modes, `--max-entries`, `--stats`, rate-limited progress |
+| Interactive | controls, escaping, self-containment, HTML-only enforcement |
---
@@ -614,7 +890,15 @@ pathscope/
│ ├── config.py # strict JSON configuration + extends
│ ├── presets.py # minimal / balanced / noisy postures
│ ├── extra_formats.py # Burp XML, OpenAPI, raw HTTP, recon exports
-│ ├── writers.py # Markdown / HTML report files
+│ ├── rules.py # rule registry, weights, overrides
+│ ├── naming.py # folding, leet variants, language packs
+│ ├── valueshape.py # UUID/hash/JWT/base64/email/IP/scalar demotion
+│ ├── tool_formats.py # Postman, ZAP, mitmproxy, GraphQL, cookies
+│ ├── policy.py # CI policy evaluation
+│ ├── ci.py # JUnit, GitHub annotations, --self-test
+│ ├── watch.py # live re-analysis (--watch)
+│ ├── progress.py # stderr progress (--progress)
+│ ├── writers.py # Markdown / HTML / interactive HTML reports
│ ├── cli.py # argument parsing, input merging, exit codes
│ └── __main__.py # enables `python3 -m pathscope`
├── tests/test_path_detector.py # unittest suite (offline)
diff --git a/pathscope/__init__.py b/pathscope/__init__.py
index 711ad8f..6b99187 100644
--- a/pathscope/__init__.py
+++ b/pathscope/__init__.py
@@ -14,7 +14,7 @@
from __future__ import annotations
PROGRAM = "PathScope"
-__version__ = "2.1.0"
+__version__ = "2.2.0"
# Displayed on every start. These are never opened and never requested.
GITHUB_URL = "https://github.com/mrdineshpathro"
diff --git a/pathscope/ci.py b/pathscope/ci.py
new file mode 100644
index 0000000..772e8f8
--- /dev/null
+++ b/pathscope/ci.py
@@ -0,0 +1,300 @@
+"""CI helpers: JUnit XML, GitHub annotations and a ``--self-test`` runner.
+
+All three are pure functions over a :class:`pathscope.detector.Report`, so they
+are testable without touching the network, the filesystem or a CI provider.
+
+JUnit XML
+ One ```` per confidence band plus one per finding, so a CI UI
+ lists every candidate. Failures carry the fingerprint, which keeps a
+ baseline stable across runs.
+
+GitHub annotations
+ ``::warning`` / ``::notice`` workflow commands on stdout, which the
+ Actions runner turns into inline PR annotations. Every dynamic field is
+ escaped per GitHub's documented rules, and values are never included.
+
+Self-test
+ A built-in suite of assertions about this installation: banner strings,
+ parsing, scoring and privacy defaults. It never reads user files.
+"""
+
+from __future__ import annotations
+
+from typing import Dict, List, Sequence
+from xml.sax.saxutils import escape as xml_escape, quoteattr
+
+from . import PROGRAM, __version__, banner_lines
+from .detector import Report
+from .report import DISCLAIMER
+
+# ---------------------------------------------------------------------------
+# JUnit XML
+# ---------------------------------------------------------------------------
+JUNIT_BANDS = ("high", "medium", "low")
+
+
+def _attr(value: object) -> str:
+ return quoteattr(str(value))
+
+
+def render_junit(report: Report, suite_name: str = "PathScope") -> str:
+ """Return a JUnit XML document describing this run."""
+ counts = report.confidence_counts
+ failures = 0
+ cases: List[str] = []
+
+ for band in JUNIT_BANDS:
+ band_count = counts.get(band, 0)
+ if band_count:
+ failures += 1
+ inner = (
+ f""
+ + xml_escape(
+ f"{band_count} {band}-confidence candidate(s) for manual review.\n"
+ + DISCLAIMER
+ )
+ + ""
+ )
+ cases.append(
+ f' {inner}'
+ )
+ else:
+ cases.append(
+ f' '
+ )
+
+ for finding in report.findings:
+ name = f"{finding.host} {finding.location}:{finding.parameter}"
+ message = (
+ f"score {finding.score}/100, rule {finding.rule}, "
+ f"fingerprint {finding.fingerprint}"
+ )
+ inner = (
+ f""
+ + xml_escape("\n".join(finding.reasons) or DISCLAIMER)
+ + ""
+ )
+ cases.append(
+ f' {inner}"
+ )
+
+ metadata = (
+ f"requests={report.requests_analyzed} parameters={report.parameters_analyzed} "
+ f"candidates={report.candidate_count} mode={report.mode} "
+ f"new={report.new_count} known={report.known_count} "
+ f"resolved={len(report.resolved)}"
+ )
+ lines = [
+ '',
+ f'',
+ f' ',
+ f" "
+ f''
+ f''
+ f"",
+ f" ",
+ ]
+ lines.extend(cases)
+ lines.append(" ")
+ lines.append("")
+ return "\n".join(lines) + "\n"
+
+
+# ---------------------------------------------------------------------------
+# GitHub Actions annotations
+# ---------------------------------------------------------------------------
+#: GitHub workflow-command escaping (documented in the Actions toolkit).
+_GH_ESCAPE = {"%": "%25", "\r": "%0D", "\n": "%0A"}
+_GH_PROPERTY_ESCAPE = {":": "%3A", ",": "%2C"}
+
+
+def _gh_escape(value: str) -> str:
+ for char, replacement in _GH_ESCAPE.items():
+ value = value.replace(char, replacement)
+ return value
+
+
+def _gh_property(value: str) -> str:
+ value = _gh_escape(value)
+ for char, replacement in _GH_PROPERTY_ESCAPE.items():
+ value = value.replace(char, replacement)
+ return value
+
+
+def render_github_annotations(report: Report) -> str:
+ """Return workflow commands (one per finding) for GitHub Actions.
+
+ High-confidence candidates become warnings, medium/low become notices.
+ Known findings are annotated as notices only when they are visible in the
+ report (``--show-known``); resolved entries produce nothing.
+ """
+ lines: List[str] = [
+ f"::notice title=PathScope::Analyzed {report.requests_analyzed} request(s); "
+ f"{report.candidate_count} candidate(s) for manual review."
+ ]
+ for finding in report.findings:
+ level = "warning" if finding.confidence == "high" else "notice"
+ reason = finding.reasons[0] if finding.reasons else "heuristic match"
+ title = f"PathScope {finding.confidence}: {finding.parameter}"
+ message = (
+ f"{finding.host} {finding.location} parameter '{finding.parameter}' "
+ f"scored {finding.score}/100 ({finding.rule}); {reason}. "
+ f"fingerprint {finding.fingerprint}. Candidate for manual review only."
+ )
+ lines.append(
+ f"::{level} file={_gh_property(finding.resource)},"
+ f"title={_gh_property(title)}::{_gh_escape(message)}"
+ )
+ if report.mode == "diff":
+ lines.append(
+ f"::notice title=PathScope diff::{report.new_count} new, "
+ f"{report.known_count} known, {len(report.resolved)} resolved "
+ f"(baseline {_gh_escape(report.baseline_source or 'unspecified')})."
+ )
+ return "\n".join(lines) + "\n"
+
+
+# ---------------------------------------------------------------------------
+# Self-test
+# ---------------------------------------------------------------------------
+def _selftest_checks() -> List[tuple]:
+ """Assertions about this installation. Returns ``[(name, callable)]``."""
+ from . import config, heuristics, sources, textutil, writers
+
+ def banner_exact() -> None:
+ lines = banner_lines()
+ assert len(lines) == 3, "expected three banner lines"
+ assert any(line.startswith("GitHub: https://") for line in lines), "GitHub link"
+ assert all(": " in line for line in lines), "label: url format"
+
+ def url_parse() -> None:
+ info = sources.parse_url("https://Example.TEST:8443/a/b?x=1")
+ assert info.host == "example.test", info.host
+ assert info.port == 8443, info.port
+ assert info.path == "/a/b", info.path
+
+ def query_split() -> None:
+ pairs = sources.split_query("a=1&a=2&b=%2e%2e")
+ assert [name for name, _value in pairs] == ["a", "a", "b"], pairs
+
+ def traversal_scores() -> None:
+ analysis = heuristics.analyze_parameter("file", "../../etc/passwd")
+ assert "value-traversal" in analysis.rules, analysis.rules
+ assert analysis.score >= 60, analysis.score
+
+ def ordinary_ignored() -> None:
+ assert not heuristics.analyze_parameter("lang", "en").evidence, "lang/en"
+ assert not heuristics.analyze_parameter("q", "hello").evidence, "q/hello"
+
+ def values_hidden() -> None:
+ request = sources.request_from_url(
+ "https://a.test/?file=secret.txt", sources.SOURCE_URL, "--self-test"
+ )
+ from . import detector
+
+ report = detector.analyze_requests([request], detector.AnalysisOptions())
+ finding = report.findings[0]
+ assert finding.value is None, "values must be hidden by default"
+
+ def config_roundtrip() -> None:
+ payload = config.dump_example()
+ parsed = config.validate_payload(payload)
+ assert parsed.min_score == payload["min_score"], "min_score roundtrip"
+
+ def report_renderers() -> None:
+ from . import detector, report as report_module
+
+ request = sources.request_from_url(
+ "https://a.test/?file=../../etc/passwd", sources.SOURCE_URL, "--self-test"
+ )
+ report = detector.analyze_requests([request], detector.AnalysisOptions())
+ from .writers import render_html, render_markdown
+
+ palette = report_module.Palette(False)
+ renderers = {
+ "markdown": lambda: render_markdown(report),
+ "html": lambda: render_html(report),
+ "json": lambda: report_module.render_json(report),
+ "csv": lambda: report_module.render_csv(report),
+ "sarif": lambda: report_module.render_sarif(report),
+ "junit": lambda: render_junit(report),
+ "text": lambda: report_module.render_text(report, palette),
+ }
+ for name, render in renderers.items():
+ text = render()
+ assert text and "a.test" in text, name
+
+ def html_escapes() -> None:
+ from . import detector
+
+ request = sources.request_from_url(
+ "https://a.test/?file=", 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
+
+ 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),
+ ]
+
+
+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)
+
+
+__all__ = [
+ "JUNIT_BANDS",
+ "render_github_annotations",
+ "render_junit",
+ "render_selftest",
+ "run_selftest",
+]
diff --git a/pathscope/cli.py b/pathscope/cli.py
index 5b67453..46b694d 100644
--- a/pathscope/cli.py
+++ b/pathscope/cli.py
@@ -33,7 +33,10 @@
describe_presets,
resolve_preset,
)
+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,
@@ -44,9 +47,12 @@
)
from .heuristics import analyze_parameter
from .report import (
+ FORMAT_CSV,
+ FORMAT_HTML,
FORMAT_JSON,
+ FORMAT_JUNIT,
FORMAT_MARKDOWN,
- FORMAT_HTML,
+ FORMAT_SARIF,
FORMAT_TEXT,
FORMATS,
Palette,
@@ -56,6 +62,15 @@
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 .sources import (
INPUT_FORMAT_AUTO,
INPUT_FORMATS,
@@ -66,7 +81,12 @@
make_url_requests,
)
from .textutil import MAX_DECODE_PASSES
-from .writers import SUPPORTED_EXTENSIONS, write_report
+from .writers import (
+ SUPPORTED_EXTENSIONS,
+ render_html_interactive,
+ write_report,
+ writer_supports_interactive,
+)
EXIT_OK = 0
EXIT_FINDINGS = 1
@@ -102,8 +122,9 @@ def build_parser() -> argparse.ArgumentParser:
" --output-format to set both in one run.\n"
"\n"
"exit codes:\n"
- " 0 no candidates 1 candidates with --fail-on-findings\n"
- " 2 usage/input error 3 internal error 130 interrupted\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())
@@ -147,15 +168,16 @@ def build_parser() -> argparse.ArgumentParser:
dest="format",
choices=FORMAT_CHOICES,
default=None,
- metavar="{auto,urls,har,text,json,csv,sarif}",
+ 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)",
+ 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")
@@ -163,7 +185,7 @@ def build_parser() -> argparse.ArgumentParser:
"--output-format",
choices=FORMATS,
default=None,
- metavar="{text,json,csv,sarif}",
+ metavar="{text,json,csv,sarif,markdown,html,junit}",
help="report format written to stdout (default: text)",
)
output.add_argument(
@@ -197,6 +219,27 @@ def build_parser() -> argparse.ArgumentParser:
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,
@@ -293,6 +336,86 @@ def build_parser() -> argparse.ArgumentParser:
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)",
+ )
return parser
@@ -423,9 +546,23 @@ 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
@@ -444,10 +581,17 @@ def _merge_config(base: Config, overlay: Config) -> Config:
)
-def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int:
+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 "",
@@ -456,6 +600,10 @@ def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int:
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(
@@ -463,6 +611,21 @@ def _explain(argv: argparse.Namespace, config: Config, stdout, stderr) -> int:
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.",
@@ -536,6 +699,84 @@ def collect_inputs(
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 _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,
*,
@@ -554,9 +795,17 @@ def run(
args = parser.parse_args(argv_list)
resolve_formats(args)
quiet = args.quiet
+ 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
config, error = _apply_preset_and_config(args)
if error:
@@ -567,12 +816,45 @@ def run(
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
+
+ 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)
+ 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:
@@ -586,15 +868,35 @@ def run(
if baseline is None:
baseline = suppression
else:
- merged = Baseline(
- source=f"{args.baseline} + {args.suppress}",
- )
+ 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
- show_values = bool(args.show_values or config.show_values)
+ options = _build_options(args, config, book)
+
+ # -- 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
needs_stdin = "-" in args.input
if stdin_text is None and needs_stdin:
@@ -602,6 +904,7 @@ def run(
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:
@@ -610,6 +913,7 @@ def run(
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:
@@ -625,19 +929,20 @@ def run(
print(" Try: python3 path_detector.py --help", file=stderr)
return EXIT_USAGE
- options = 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=show_values,
- weak_names=config.weak_names,
- )
-
try:
+ progress.start("analyzing", len(loaded.requests))
report_data = analyze_requests(loaded.requests, options)
- report_data.warnings = list(loaded.warnings)
+ 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:
@@ -645,7 +950,9 @@ def run(
for index, finding in enumerate(report_data.findings, start=1):
finding.index = index
colors = Palette(supports_color(stdout) and not args.no_color)
- if args.summary_only:
+ if args.github_annotations:
+ rendered = ci_module.render_github_annotations(report_data)
+ 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)
@@ -662,13 +969,17 @@ def run(
if args.save_report:
try:
- kind = write_report(args.save_report, report_data)
+ 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 to {args.save_report}", file=stderr
+ f"pathscope: wrote {kind} report{extra} to {args.save_report}",
+ file=stderr,
)
if args.mark_reviewed:
@@ -682,14 +993,38 @@ def run(
if code != EXIT_OK:
return code
+ 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,
)
+ # -- gates: --policy first (more specific), then --fail-on-findings --
+ if policy is not None:
+ 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 report_data.new_count:
return EXIT_FINDINGS
return EXIT_OK
diff --git a/pathscope/config.py b/pathscope/config.py
index db04497..dc855cd 100644
--- a/pathscope/config.py
+++ b/pathscope/config.py
@@ -9,7 +9,10 @@
"min_score": 25,
"max_decode_passes": 3,
"weak_names": true,
- "show_values": false
+ "show_values": false,
+ "name_lang": ["de", "es"],
+ "fold_names": true,
+ "demote_shapes": true
}
Only literal terms are accepted. Regular expressions are deliberately not
@@ -54,6 +57,12 @@ class Config:
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).
@@ -77,8 +86,15 @@ def merged_ignore(self) -> List[str]:
"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):
@@ -155,6 +171,40 @@ def validate_payload(payload: Any) -> Config:
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
@@ -203,6 +253,19 @@ def merge_configs(base: Config, overlay: Config) -> Config:
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)),
@@ -275,6 +338,9 @@ def describe_schema() -> Tuple[str, ...]:
' "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',
)
@@ -287,6 +353,9 @@ def dump_example() -> Dict[str, object]:
"max_decode_passes": 3,
"weak_names": True,
"show_values": False,
+ "name_lang": ["de", "es"],
+ "fold_names": True,
+ "demote_shapes": True,
}
diff --git a/pathscope/detector.py b/pathscope/detector.py
index 1cc3cb9..14b6024 100644
--- a/pathscope/detector.py
+++ b/pathscope/detector.py
@@ -8,11 +8,13 @@
from __future__ import annotations
import hashlib
-from dataclasses import dataclass, field
+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
@@ -22,6 +24,15 @@
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."""
@@ -32,6 +43,21 @@ class AnalysisOptions:
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
@@ -99,6 +125,14 @@ class Report:
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, ...] = ()
@property
def candidate_count(self) -> int:
@@ -170,11 +204,24 @@ def analyze_requests(
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] = []
- for request in _dedupe_requests(requests):
+ 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):
@@ -193,6 +240,10 @@ def analyze_requests(
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
@@ -240,12 +291,56 @@ def analyze_requests(
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
# ---------------------------------------------------------------------------
diff --git a/pathscope/heuristics.py b/pathscope/heuristics.py
index 86f0f98..e30b298 100644
--- a/pathscope/heuristics.py
+++ b/pathscope/heuristics.py
@@ -14,7 +14,15 @@
live at module level so a user can adjust them without touching logic.
Scoring: every :class:`Evidence` carries a weight; the score is their sum,
-clamped to ``0..100``. ``docs/README`` documents each rule and its weight.
+clamped to ``0..100``. Default weights live in :mod:`pathscope.rules` so they
+can be listed (``--list-rules``), overridden (``--rules``) and disabled
+(``--disable-rule``). ``--explain`` prints the effective trace for one name.
+
+Names are matched after folding diacritics and compatibility characters, and
+optionally against multilingual term packs plus leet spellings (``f1le``).
+Values are additionally checked for shapes that *do not* look like paths
+(UUIDs, hashes, JWTs, base64, e-mail, IPs, booleans/numbers) and demoted with
+an explicit, visible negative rule.
"""
from __future__ import annotations
@@ -23,21 +31,27 @@
from dataclasses import dataclass, field
from typing import Dict, FrozenSet, Iterable, List, Tuple
+from . import naming, valueshape
+from .rules import (
+ DEFAULT_BOOK,
+ GENERIC_BONUS,
+ MULTIWORD_BONUS,
+ PREFIX_DISCOUNT,
+ RULE_INDEX,
+ STRONG_NAME_WEIGHT,
+ SUFFIX_DISCOUNT,
+ RuleBook,
+)
from .textutil import MAX_DECODE_PASSES, decode_forms, sanitize_text
NAME_CAP = 45
VALUE_CAP = 55
MAX_SCORE = 100
-#: Weight for an exact, strong name term.
-STRONG_NAME_WEIGHT = 35
-#: Extra weight when a strong term is part of a multiword name (``download_file``).
-MULTIWORD_BONUS = 5
-#: Discount for ``name-prefix`` and ``name-suffix`` matches.
-PREFIX_DISCOUNT = 7
-SUFFIX_DISCOUNT = 12
-#: Bonus when a generic name (``image``, ``target`` ...) has a path-like value.
-GENERIC_BONUS = 10
+#: Section headings used by ``--list-rules``/``--explain``.
+SECTION_NAME = "name"
+SECTION_VALUE = "value"
+SECTION_DEMOTION = "demotion"
# ---------------------------------------------------------------------------
# Parameter-name vocabulary
@@ -162,16 +176,18 @@ def confidence(self) -> str:
_DIGIT_SPLIT_RE = re.compile(r"(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])")
-def tokenize_name(name: str) -> List[str]:
- """Split a parameter name into lowercase tokens.
+def tokenize_name(name: str, fold: bool = True) -> List[str]:
+ """Split a parameter name into lowercase ASCII tokens.
``fileName`` -> ``['file', 'name']``
``base_path`` -> ``['base', 'path']``
``X-File-Path`` -> ``['x', 'file', 'path']``
+ ``fıle`` -> ``['file']`` (diacritics are folded first)
"""
if not name:
return []
- text = sanitize_text(name).strip()
+ cleaned = sanitize_text(name).strip()
+ text = naming.fold_name(cleaned) if fold else cleaned
tokens: List[str] = []
for chunk in _NON_ALNUM_RE.split(_CAMEL_SPLIT_RE.sub(" ", text)):
for piece in _DIGIT_SPLIT_RE.split(chunk):
@@ -201,68 +217,206 @@ def extension_of(text: str) -> str:
# ---------------------------------------------------------------------------
# Name analysis
# ---------------------------------------------------------------------------
+def _weight(book: RuleBook, rule: str) -> int:
+ """Effective weight for ``rule`` in ``book`` (0 when disabled)."""
+ return book.weight(rule)
+
+
+def _books(book: RuleBook, rule: str, reason: str, layer: str) -> List[Evidence]:
+ """Build Evidence only when the rule is enabled and has a non-zero weight."""
+ weight = _weight(book, rule)
+ if book.is_disabled(rule) or weight == 0:
+ return []
+ if reason.endswith(")"):
+ # Replace the default "(+N)" tail with the effective weight so that an
+ # overridden rule is described accurately in every report.
+ reason = reason[: reason.rfind(" (")] + f" ({weight:+d})"
+ return [Evidence(rule, reason, weight, layer)]
+
+
+def _weak_name_evidence(book: RuleBook) -> List[Evidence]:
+ return _books(
+ book,
+ "name-weak",
+ "multiword parameter name without a path term (weak, +5)",
+ "name",
+ )
+
+
+def _generic_name_evidence() -> List[Evidence]:
+ """Zero-weight context marker; kept even at weight 0 so pairing works."""
+ weight = DEFAULT_BOOK.weight("name-generic")
+ return [
+ Evidence(
+ "name-generic",
+ "parameter name is generic (image/target/ref/...): considered only "
+ "when its value is path-like (+0)",
+ weight,
+ "name",
+ )
+ ]
+
+
def analyze_name(
- name: str, extra_terms: Iterable[str] = (), weak_names: bool = True
+ name: str,
+ extra_terms: Iterable[str] = (),
+ weak_names: bool = True,
+ *,
+ book: RuleBook = DEFAULT_BOOK,
+ languages: Tuple[str, ...] = (),
+ fold: bool = True,
) -> List[Evidence]:
"""Return name-based evidence.
- Rules:
- ``name-custom`` exact user-configured term, +30
- ``name-exact`` exact built-in path term, +35 (+5 multiword)
- ``name-compound`` the whole name is a known compound, +35
- ``name-prefix`` name starts with a path term, +28
- ``name-suffix`` name ends with a path term, +23
- ``name-generic`` generic name (image/target/...), +0 (context only)
- ``name-weak`` multiword name without a term, +5 (never alone)
+ Rules (weights from ``book``):
+ ``name-custom`` exact user-configured term
+ ``name-exact`` exact built-in path term (+multiword bonus)
+ ``name-compound`` the whole name is a known compound
+ ``name-prefix`` name starts with a path term
+ ``name-suffix`` name ends with a path term
+ ``name-folded`` term appears only after diacritic/compatibility folding
+ ``name-leet`` term appears only after leet expansion (``f1le``)
+ ``name-i18n`` term from a non-English term pack
+ ``name-i18n-fold`` as above, only after folding
+ ``name-generic`` generic name (image/target/...), 0 (context only)
+ ``name-weak`` multiword name without a path term (never alone)
"""
- tokens = tokenize_name(name)
+ if not name:
+ return []
+ tokens = tokenize_name(name, fold=fold)
if not tokens:
return []
joined = "".join(tokens)
- lowered = sanitize_text(name).lower()
custom = {term.strip().lower().replace("-", "_") for term in extra_terms if term.strip()}
path_terms = PATH_NAME_TERMS | (custom - GENERIC_NAME_TERMS)
# Configured terms may be single tokens ("blob") or compounds ("cdn_blob").
+ canonical_names = {joined, sanitize_text(name).lower(), canonical_name(name)}
custom_candidates = [token for token in tokens if token in custom]
- custom_candidates += [name for name in (joined, lowered, canonical_name(name)) if name in custom]
+ custom_candidates += [candidate for candidate in canonical_names if candidate in custom]
builtin_hit = any(token in PATH_NAME_TERMS for token in tokens)
if custom_candidates and not builtin_hit:
term = custom_candidates[0]
- return [
- Evidence(
- "name-custom",
- f"parameter name contains configured term '{term}' (+30)",
- 30,
- "name",
- )
- ]
+ return _books(
+ book,
+ "name-custom",
+ f"parameter name contains configured term '{term}' (+30)",
+ "name",
+ )
hits = [token for token in tokens if token in path_terms]
if hits:
best = max(hits, key=len)
bonus = MULTIWORD_BONUS if len(tokens) > 1 else 0
suffix = f", +{bonus} multiword" if bonus else ""
+ weight = _weight(book, "name-exact") + bonus
+ if book.is_disabled("name-exact"):
+ return []
return [
Evidence(
"name-exact",
- f"parameter name contains path-related term '{best}' "
- f"(+{STRONG_NAME_WEIGHT}{suffix})",
- STRONG_NAME_WEIGHT + bonus,
+ f"parameter name contains path-related term '{best}' ({weight:+d}{suffix})",
+ weight,
"name",
)
]
- if "_" not in joined and joined in path_terms and len(joined) > 4:
- return [
- Evidence(
- "name-compound",
- f"parameter name '{lowered}' is a known path compound (+{STRONG_NAME_WEIGHT})",
- STRONG_NAME_WEIGHT,
+ # A term can also hide in a folded or de-leeted spelling.
+ if fold:
+ folded_joined = "".join(tokenize_name(naming.fold_name(name)))
+ if folded_joined != joined:
+ folded_hits = [
+ term for term in path_terms if len(term) >= 4 and term in folded_joined
+ ]
+ if folded_hits:
+ evidence = _books(
+ book,
+ "name-folded",
+ "parameter name matches a path term only after diacritic/"
+ f"compatibility folding ('{max(folded_hits, key=len)}') (+20)",
+ "name",
+ )
+ if evidence:
+ return evidence
+
+ leet_hits: List[str] = []
+ leet_candidates = _NON_ALNUM_RE.split(
+ naming.fold_name(sanitize_text(name)).lower()
+ )
+ for token in [item for item in leet_candidates if len(item) >= 3]:
+ for variant in naming.leet_variants(token):
+ found = [term for term in path_terms if len(term) >= 4 and term in variant]
+ if found:
+ leet_hits.append(max(found, key=len))
+ break
+ if leet_hits:
+ break
+ if leet_hits:
+ evidence = _books(
+ book,
+ "name-leet",
+ f"parameter name matches path term '{leet_hits[0]}' only after leet "
+ "expansion (+12)",
"name",
)
- ]
+ if evidence:
+ return evidence
+
+ # Non-English term packs (German, Spanish, ...). A token that already
+ # exists in an English table (generic words like "image"/"document") is
+ # never re-labelled as foreign.
+ language_hits: List[Tuple[str, str, bool]] = []
+ if languages:
+ packs = naming.language_terms(languages)
+ english_tokens = PATH_NAME_TERMS | GENERIC_NAME_TERMS
+ # ``sanitize_text`` already applies NFKC, which removes the accents
+ # that NFKD folding would normally strip. So a folded-only match is one
+ # that still needed folding *after* sanitisation (e.g. dotless "ı").
+ # Join with the same rule tokenisation uses (ASCII punctuation only),
+ # so accented letters survive into ``plain_joined`` and a match there
+ # really means "no folding was needed".
+ sanitized = sanitize_text(name)
+ folded_joined = "".join(tokenize_name(naming.fold_name(sanitized)))
+ plain_joined = "".join(tokenize_name(sanitized, fold=False))
+ for tag, terms in packs.items():
+ for term in terms:
+ if len(term) < 4 or term in english_tokens:
+ continue
+ # Order matters: a spelling that needed folding is a weaker
+ # signal even though the folded tokens would also match.
+ if term in folded_joined and term not in plain_joined:
+ language_hits.append((tag, term, True))
+ elif term in tokens or term in plain_joined:
+ language_hits.append((tag, term, False))
+ if language_hits:
+ tag, term, folded = max(language_hits, key=lambda item: (len(item[1]), item[1]))
+ label = naming.LANGUAGE_LABELS.get(tag, tag)
+ if folded:
+ evidence = _books(
+ book,
+ "name-i18n-fold",
+ f"parameter name matches {label} path term '{term}' only after "
+ "folding (+21)",
+ "name",
+ )
+ else:
+ evidence = _books(
+ book,
+ "name-i18n",
+ f"parameter name contains {label} path-related term '{term}' (+25)",
+ "name",
+ )
+ if evidence:
+ return evidence
+
+ if "_" not in joined and joined in path_terms and len(joined) > 4:
+ return _books(
+ book,
+ "name-compound",
+ f"parameter name '{joined}' is a known path compound (+35)",
+ "name",
+ )
# Prefix/suffix matching keeps only whole-word boundaries so that
# "urlencoded" is not read as "url" and "landscape" is not read as "page".
@@ -278,46 +432,37 @@ def analyze_name(
suffix_match = term
break
if prefix_match:
- weight = STRONG_NAME_WEIGHT - PREFIX_DISCOUNT
- return [
- Evidence(
- "name-prefix",
- f"parameter name starts with path-related term '{prefix_match}' (+{weight})",
- weight,
- "name",
- )
- ]
+ weight = _weight(book, "name-prefix")
+ if not book.is_disabled("name-prefix") and weight:
+ return [
+ Evidence(
+ "name-prefix",
+ f"parameter name starts with path-related term '{prefix_match}' "
+ f"({weight:+d})",
+ weight,
+ "name",
+ )
+ ]
if suffix_match:
- weight = STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT
- return [
- Evidence(
- "name-suffix",
- f"parameter name ends with path-related term '{suffix_match}' (+{weight})",
- weight,
- "name",
- )
- ]
+ weight = _weight(book, "name-suffix")
+ if not book.is_disabled("name-suffix") and weight:
+ return [
+ Evidence(
+ "name-suffix",
+ f"parameter name ends with path-related term '{suffix_match}' "
+ f"({weight:+d})",
+ weight,
+ "name",
+ )
+ ]
if any(token in GENERIC_NAME_TERMS for token in tokens):
- return [
- Evidence(
- "name-generic",
- "parameter name is generic (image/target/ref/...): considered only "
- "when its value is path-like (+0)",
- 0,
- "name",
- )
- ]
+ if book.is_disabled("name-generic"):
+ return []
+ return _generic_name_evidence()
if len(tokens) > 1 and weak_names:
- return [
- Evidence(
- "name-weak",
- "multiword parameter name without a path term (weak, +5)",
- 5,
- "name",
- )
- ]
+ return _weak_name_evidence(book)
return []
@@ -328,8 +473,26 @@ def _is_segment_traversal(text: str) -> bool:
return bool(SEGMENT_TRAVERSAL_RE.search(text))
+def _value_evidence(
+ book: RuleBook, rule: str, reason: str, default_weight: int
+) -> List[Evidence]:
+ """Value-layer evidence with the effective weight (and disabled check)."""
+ if book.is_disabled(rule):
+ return []
+ weight = book.weight(rule)
+ if weight == 0:
+ return []
+ if reason.endswith(")"):
+ reason = reason[: reason.rfind(" (")] + f" ({weight:+d})"
+ return [Evidence(rule, reason, weight, "value")]
+
+
def analyze_value(
- value: str, max_decode_passes: int = MAX_DECODE_PASSES
+ value: str,
+ max_decode_passes: int = MAX_DECODE_PASSES,
+ *,
+ book: RuleBook = DEFAULT_BOOK,
+ demote: bool = True,
) -> List[Evidence]:
"""Return value-based evidence. The value is treated purely as a string.
@@ -343,8 +506,9 @@ def analyze_value(
``value-absolute`` starts with ``/`` (but not ``//``), +12
``value-multi-segment`` 2+ path separators, +6
``value-extension`` known file extension at the end, +8
+ ``value-path-list`` semicolon/comma separated paths, +5
``value-full-url`` an ``scheme://`` URL, -10
- ``value-encoded`` informational only (0)
+ ``value-demote-*`` UUID/hash/JWT/base64/e-mail/IP/scalar, negative
"""
raw = sanitize_text(value or "")
if not raw:
@@ -366,41 +530,41 @@ def analyze_value(
)
)
if "%2f" in lowered_raw or "%5c" in lowered_raw:
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-encoded-slash",
"value contains an encoded slash or backslash (%2f / %5c) (+12)",
12,
- "value",
)
)
if max_pass >= 2:
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-double-encoded",
f"value required {max_pass} decoding passes (nested encoding) (+10)",
10,
- "value",
)
)
if _is_segment_traversal(raw):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-traversal",
"value contains a '..' path segment ('../', '..\\' or bare '..') (+30)",
30,
- "value",
)
)
shape = raw
elif _is_segment_traversal(deepest):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-encoded-traversal",
"value contains a '..' segment only after percent-decoding (+15)",
15,
- "value",
)
)
shape = deepest
@@ -408,40 +572,40 @@ def analyze_value(
shape = deepest
if WINDOWS_DRIVE_RE.match(shape):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-windows-drive",
"value looks like a Windows drive path ('C:\\...') (+15)",
15,
- "value",
)
)
elif UNC_PATH_RE.match(shape):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-unc",
"value looks like a Windows UNC path ('\\\\server\\share') (+15)",
15,
- "value",
)
)
elif ABSOLUTE_PATH_RE.match(shape):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-absolute",
"value starts with a path separator (absolute-looking) (+12)",
12,
- "value",
)
)
if FULL_URL_RE.match(shape):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-full-url",
"value is a full URL rather than a local path (-10)",
-10,
- "value",
)
)
else:
@@ -451,39 +615,58 @@ def analyze_value(
if _is_segment_traversal(shape):
separators = max(0, separators - 1)
if separators >= 2:
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-multi-segment",
f"value contains {separators} path separators (+6)",
6,
- "value",
)
)
extension = extension_of(shape)
if extension:
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-extension",
f"value ends with a file-like extension '.{extension}' (+8)",
8,
- "value",
)
)
if separators and any(sep in shape for sep in (";", ",")):
- evidence.append(
- Evidence(
+ evidence.extend(
+ _value_evidence(
+ book,
"value-path-list",
"value looks like a semicolon/comma separated list of paths (+5)",
5,
- "value",
)
)
+ if demote:
+ evidence.extend(demotion_evidence(raw, book))
+
# Percent-encoding alone is not a path signal; drop the placeholder so the
# evidence list only contains scoring rules.
return [item for item in evidence if item.weight != 0]
+def demotion_evidence(value: str, book: RuleBook = DEFAULT_BOOK) -> List[Evidence]:
+ """Negative evidence for value shapes that do not look like paths."""
+ evidence: List[Evidence] = []
+ for rule, reason in valueshape.demotions(sanitize_text(value)):
+ if book.is_disabled(rule):
+ continue
+ weight = book.weight(rule)
+ if weight == 0:
+ continue
+ if weight > 0: # a positive override would invert the rule's meaning
+ weight = -weight
+ reason = reason[: reason.rfind(" (")] + f" ({weight:+d})" if reason.endswith(")") else reason
+ evidence.append(Evidence(rule, reason, weight, "value"))
+ return evidence
+
+
# ---------------------------------------------------------------------------
# Combine
# ---------------------------------------------------------------------------
@@ -496,6 +679,10 @@ def analyze_parameter(
ignore: Iterable[str] = (),
min_score: int = 25,
weak_names: bool = True,
+ book: RuleBook = DEFAULT_BOOK,
+ languages: Tuple[str, ...] = (),
+ fold: bool = True,
+ demote: bool = True,
) -> Analysis:
"""Combine name and value evidence for one parameter.
@@ -506,8 +693,15 @@ def analyze_parameter(
if canonical_name(name) in {canonical_name(item) for item in ignore}:
return Analysis(name=name)
- name_evidence = analyze_name(name, extra_terms, weak_names=weak_names)
- value_evidence = analyze_value(value, max_decode_passes)
+ name_evidence = analyze_name(
+ name,
+ extra_terms,
+ weak_names=weak_names,
+ book=book,
+ languages=languages,
+ fold=fold,
+ )
+ value_evidence = analyze_value(value, max_decode_passes, book=book, demote=demote)
generic = any(item.rule == "name-generic" for item in name_evidence)
has_path_value = any(item.weight > 0 for item in value_evidence)
@@ -518,15 +712,18 @@ def analyze_parameter(
return Analysis(name=name)
evidence: List[Evidence] = list(name_evidence) + list(value_evidence)
- if generic and has_path_value:
- evidence.append(
- Evidence(
- "value-pairs-with-generic-name",
- f"generic parameter name is paired with a path-like value (+{GENERIC_BONUS})",
- GENERIC_BONUS,
- "value",
+ if generic and has_path_value and not book.is_disabled("value-pairs-with-generic-name"):
+ pairing_weight = book.weight("value-pairs-with-generic-name")
+ if pairing_weight:
+ evidence.append(
+ Evidence(
+ "value-pairs-with-generic-name",
+ "generic parameter name is paired with a path-like value "
+ f"({pairing_weight:+d})",
+ pairing_weight,
+ "value",
+ )
)
- )
analysis = Analysis(name=name, evidence=evidence)
if analysis.score < max(1, min_score):
diff --git a/pathscope/naming.py b/pathscope/naming.py
new file mode 100644
index 0000000..be5ed5c
--- /dev/null
+++ b/pathscope/naming.py
@@ -0,0 +1,296 @@
+"""Name folding and multilingual path terminology.
+
+Two independent additions to the name layer:
+
+**Folding** (:func:`fold_name`, :func:`leet_variants`)
+ ``fıle`` (dotless i), ``file`` (fullwidth), ``f1le`` and ``f_i_l_e`` all
+ denote ``file``. Folding is applied *before* tokenisation so the existing
+ term tables keep working unchanged. Folded matches are reported with their
+ own weaker rules, so a leet spelling never looks as strong as a plain one.
+
+**Term packs** (:data:`LANGUAGE_PACKS`)
+ Path-related vocabulary for German, Spanish, French, Portuguese, Italian
+ and Dutch. ``--name-lang de,es`` enables a list, ``auto`` uses all packs,
+ ``off`` (default) uses English only.
+
+Everything here is a literal lookup table. No regular expressions are built
+from user input, and nothing is network-aware.
+"""
+
+from __future__ import annotations
+
+import unicodedata
+from typing import Dict, FrozenSet, List, Sequence, Tuple
+
+#: Languages with a built-in term pack, in display order.
+LANGUAGE_NAMES: Tuple[str, ...] = ("de", "es", "fr", "pt", "it", "nl")
+
+LANGUAGE_LABELS: Dict[str, str] = {
+ "de": "German",
+ "es": "Spanish",
+ "fr": "French",
+ "pt": "Portuguese",
+ "it": "Italian",
+ "nl": "Dutch",
+}
+
+#: ``--name-lang`` selectors.
+NAME_LANG_OFF = "off"
+NAME_LANG_AUTO = "auto"
+NAME_LANG_ALL = "all"
+
+#: Path-related terms per language. Deliberately small, high-signal lists:
+#: words that commonly name a file/path consumer in that language.
+LANGUAGE_PACKS: Dict[str, FrozenSet[str]] = {
+ "de": frozenset(
+ """
+ datei dateipfad pfad ordner verzeichnis herunterladen hochladen
+ anhang bild dokument speichern laden oeffnen oeffne quelle ziel
+ vorlage seite verwenden
+ """.split()
+ ),
+ "es": frozenset(
+ """
+ archivo ruta carpeta directorio descargar subir adjunto documento
+ imagen guardar cargar abrir origen destino plantilla pagina recurso
+ indice
+ """.split()
+ ),
+ "fr": frozenset(
+ """
+ fichier chemin dossier repertoire telecharger televerser piece jointe
+ document image enregistrer charger ouvrir source cible modele page
+ ressource
+ """.split()
+ ),
+ "pt": frozenset(
+ """
+ arquivo caminho pasta diretorio baixar carregar enviar anexo documento
+ imagem salvar abrir origem destino modelo pagina recurso
+ """.split()
+ ),
+ "it": frozenset(
+ """
+ percorso cartella scaricare caricare allegato documento immagine
+ salvare aprire origine destinazione modello pagina risorsa
+ """.split()
+ ),
+ "nl": frozenset(
+ """
+ bestand pad map downloaden uploaden bijlage afbeelding opslaan laden
+ openen bron doel sjabloon pagina bronbestand
+ """.split()
+ ),
+}
+
+#: Aliases accepted on the command line for each pack.
+LANGUAGE_ALIASES: Dict[str, str] = {
+ "german": "de",
+ "deutsch": "de",
+ "spanish": "es",
+ "espanol": "es",
+ "español": "es",
+ "french": "fr",
+ "francais": "fr",
+ "français": "fr",
+ "portuguese": "pt",
+ "portugues": "pt",
+ "português": "pt",
+ "italian": "it",
+ "italiano": "it",
+ "dutch": "nl",
+ "nederlands": "nl",
+ "english": "en",
+ "en": "en",
+}
+
+#: Leet substitutions used for the *weak* folded rule. Each mapping is applied
+#: one at a time to the whole token; only tokens of 3+ characters are folded so
+#: that short identifiers (``id1``) are not mangled into false positives.
+LEET_MAP: Dict[str, Tuple[str, ...]] = {
+ "1": ("l", "i"),
+ "0": ("o",),
+ "3": ("e",),
+ "4": ("a",),
+ "5": ("s",),
+ "7": ("t",),
+ "@": ("a",),
+ "$": ("s",),
+}
+
+#: Bound so a pathological token cannot explode into thousands of variants.
+MAX_LEET_VARIANTS = 48
+
+#: Characters that are folded to an ASCII equivalent before tokenisation.
+_DIACRITIC_FOLD = {
+ "ı": "i",
+ "ß": "ss",
+ "ø": "o",
+ "đ": "d",
+ "ð": "d",
+ "ł": "l",
+ "æ": "ae",
+ "œ": "oe",
+ "þ": "th",
+ "ħ": "h",
+ "ŧ": "t",
+ "ĸ": "k",
+}
+
+#: Characters that are treated as separators when they appear in a name.
+_SEPARATOR_FOLD = {
+ "\u2010": "-", # hyphen
+ "\u2011": "-",
+ "\u2012": "-",
+ "\u2013": "-",
+ "\u2014": "-",
+ "\u2212": "-",
+ "\uff0d": "-",
+ "\u2044": "/",
+}
+
+#: Zero-width and bidi control characters that are stripped outright.
+_INVISIBLE = frozenset(
+ "\u200b\u200c\u200d\u2060\ufeff\u00ad"
+ "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069"
+)
+
+
+def fold_name(name: str) -> str:
+ """Return an ASCII-folded copy of ``name`` suitable for tokenisation.
+
+ Handles compatibility forms (fullwidth letters), accent stripping,
+ Turkish dotless i, common ligatures, exotic separators and invisible
+ characters. The result is a plain string; it is never executed or opened.
+ """
+ if not name:
+ return ""
+ # NFKC folds fullwidth/halfwidth forms and compatibility characters.
+ text = unicodedata.normalize("NFKC", name)
+ out: List[str] = []
+ for char in text:
+ if char in _INVISIBLE:
+ continue
+ if char in _SEPARATOR_FOLD:
+ out.append(_SEPARATOR_FOLD[char])
+ continue
+ lowered = char.lower()
+ if lowered in _DIACRITIC_FOLD:
+ out.append(_DIACRITIC_FOLD[lowered])
+ continue
+ decomposed = unicodedata.normalize("NFKD", char)
+ out.append("".join(ch for ch in decomposed if not unicodedata.combining(ch)))
+ # Remove stray combining marks left by decomposition of unusual sequences.
+ result = unicodedata.normalize("NFKD", "".join(out))
+ return "".join(ch for ch in result if not unicodedata.combining(ch))
+
+
+def leet_variants(token: str) -> List[str]:
+ """Return de-leeted spellings of ``token`` (``f1le`` -> ``file``).
+
+ Deterministic and bounded: each digit is expanded once, in order, and the
+ result is truncated to :data:`MAX_LEET_VARIANTS`.
+ """
+ if len(token) < 3:
+ return []
+ variants: List[str] = []
+ frontier = [token]
+ for index, char in enumerate(token):
+ replacements = LEET_MAP.get(char)
+ if not replacements:
+ continue
+ next_frontier: List[str] = []
+ for base in frontier:
+ for replacement in replacements:
+ candidate = base[:index] + replacement + base[index + 1 :]
+ next_frontier.append(candidate)
+ if len(next_frontier) >= MAX_LEET_VARIANTS:
+ break
+ if len(next_frontier) >= MAX_LEET_VARIANTS:
+ break
+ frontier = next_frontier
+ for candidate in frontier:
+ if candidate != token and candidate not in variants:
+ variants.append(candidate)
+ return variants
+
+
+def language_terms(languages: Sequence[str]) -> Dict[str, FrozenSet[str]]:
+ """Return ``{tag: terms}`` for the requested language tags.
+
+ Unknown tags are ignored; ``auto``/``all`` expand to every pack.
+ """
+ wanted: List[str] = []
+ for entry in languages:
+ for piece in str(entry).replace(";", ",").split(","):
+ key = piece.strip().lower()
+ if not key:
+ continue
+ key = LANGUAGE_ALIASES.get(key, key)
+ if key in (NAME_LANG_AUTO, NAME_LANG_ALL):
+ wanted.extend(LANGUAGE_NAMES)
+ elif key in LANGUAGE_PACKS:
+ wanted.append(key)
+ ordered = [tag for tag in LANGUAGE_NAMES if tag in set(wanted)]
+ return {tag: LANGUAGE_PACKS[tag] for tag in ordered}
+
+
+def parse_languages(value: str) -> Tuple[str, ...]:
+ """Parse a ``--name-lang`` value into normalized tags.
+
+ ``"off"`` and empty strings return ``()``; ``auto``/``all`` return every
+ pack. Unknown tags raise :class:`ValueError` so a typo is visible.
+ """
+ if not value or not value.strip():
+ return ()
+ tokens = [
+ token.strip().lower()
+ for token in str(value).replace(";", ",").split(",")
+ if token.strip()
+ ]
+ result: List[str] = []
+ for token in tokens:
+ canonical = LANGUAGE_ALIASES.get(token, token)
+ if canonical in (NAME_LANG_OFF, "none", "english-only"):
+ continue
+ if canonical in (NAME_LANG_AUTO, NAME_LANG_ALL):
+ for tag in LANGUAGE_NAMES:
+ if tag not in result:
+ result.append(tag)
+ continue
+ if canonical not in LANGUAGE_PACKS:
+ raise ValueError(
+ f"unknown language '{token}' (choose from "
+ f"{', '.join(LANGUAGE_NAMES)} or auto/off)"
+ )
+ if canonical not in result:
+ result.append(canonical)
+ return tuple(result)
+
+
+def describe_languages() -> Tuple[str, ...]:
+ """Lines describing the term packs, used in ``--help`` and the README."""
+ lines: List[str] = []
+ for tag in LANGUAGE_NAMES:
+ sample = ", ".join(sorted(LANGUAGE_PACKS[tag])[:6])
+ lines.append(f" {tag:<3} {LANGUAGE_LABELS[tag]:<11} {sample} ...")
+ lines.append(f" {NAME_LANG_AUTO:<11} every pack above")
+ return tuple(lines)
+
+
+__all__ = [
+ "LANGUAGE_NAMES",
+ "LANGUAGE_LABELS",
+ "LANGUAGE_PACKS",
+ "LANGUAGE_ALIASES",
+ "LEET_MAP",
+ "NAME_LANG_AUTO",
+ "NAME_LANG_ALL",
+ "NAME_LANG_OFF",
+ "MAX_LEET_VARIANTS",
+ "describe_languages",
+ "fold_name",
+ "language_terms",
+ "leet_variants",
+ "parse_languages",
+]
diff --git a/pathscope/policy.py b/pathscope/policy.py
new file mode 100644
index 0000000..0193dc7
--- /dev/null
+++ b/pathscope/policy.py
@@ -0,0 +1,252 @@
+"""CI policy evaluation for PathScope.
+
+A policy answers one question: *should this run fail the build?* It is
+deliberately separate from ``--fail-on-findings`` (which is "any new candidate").
+
+Policy file (JSON, all keys optional)::
+
+ {
+ "max_high": 0,
+ "max_medium": 5,
+ "max_low": 100,
+ "max_total": 25,
+ "min_score": 40,
+ "fail_on_known": false,
+ "ignore_rules": ["name-weak"],
+ "ignore_hosts": ["static.example.test"]
+ }
+
+Evaluation counts only *new* findings unless ``fail_on_known`` is true, so a
+saved baseline keeps a pipeline quiet. Every decision is explainable: the
+result carries the rule that fired and the numbers behind it.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Dict, List, Optional, Sequence
+
+from .detector import Finding, Report
+
+#: Keys accepted in a policy file.
+POLICY_KEYS = (
+ "max_high",
+ "max_medium",
+ "max_low",
+ "max_total",
+ "min_score",
+ "fail_on_known",
+ "ignore_rules",
+ "ignore_hosts",
+ "description",
+)
+
+DEFAULT_POLICY = "default"
+
+
+class PolicyError(ValueError):
+ """Raised when a policy file is invalid."""
+
+
+@dataclass
+class Policy:
+ """A validated CI gate."""
+
+ max_high: Optional[int] = None
+ max_medium: Optional[int] = None
+ max_low: Optional[int] = None
+ max_total: Optional[int] = None
+ min_score: int = 0
+ fail_on_known: bool = False
+ ignore_rules: Sequence[str] = ()
+ ignore_hosts: Sequence[str] = ()
+ description: str = ""
+ source: str = ""
+
+ # -- construction -----------------------------------------------------
+ @classmethod
+ def from_payload(cls, payload: object, source: str = "") -> "Policy":
+ if payload is None:
+ payload = {}
+ if not isinstance(payload, dict):
+ raise PolicyError("policy must be a JSON object")
+ unknown = sorted(set(payload) - set(POLICY_KEYS))
+ if unknown:
+ raise PolicyError(
+ "unknown policy key(s): " + ", ".join(unknown)
+ + f" (allowed: {', '.join(POLICY_KEYS)})"
+ )
+ policy = cls(source=source)
+ for key in ("max_high", "max_medium", "max_low", "max_total"):
+ if key in payload:
+ value = payload[key]
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+ raise PolicyError(f"'{key}' must be a non-negative integer")
+ setattr(policy, key, value)
+ if "min_score" in payload:
+ value = payload["min_score"]
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:
+ raise PolicyError("'min_score' must be an integer between 0 and 100")
+ policy.min_score = value
+ if "fail_on_known" in payload:
+ if not isinstance(payload["fail_on_known"], bool):
+ raise PolicyError("'fail_on_known' must be true or false")
+ policy.fail_on_known = payload["fail_on_known"]
+ for key in ("ignore_rules", "ignore_hosts"):
+ if key in payload:
+ value = payload[key]
+ if not isinstance(value, list) or not all(isinstance(x, str) for x in value):
+ raise PolicyError(f"'{key}' must be an array of strings")
+ if len(value) > 200:
+ raise PolicyError(f"'{key}' may contain at most 200 entries")
+ setattr(policy, key, [item.strip() for item in value if item.strip()])
+ if "description" in payload:
+ if not isinstance(payload["description"], str):
+ raise PolicyError("'description' must be a string")
+ policy.description = payload["description"][:200]
+ return policy
+
+ # -- queries ----------------------------------------------------------
+ def is_empty(self) -> bool:
+ return (
+ self.max_high is None
+ and self.max_medium is None
+ and self.max_low is None
+ and self.max_total is None
+ and self.min_score == 0
+ )
+
+ def describe(self) -> str:
+ parts: List[str] = []
+ for key in ("max_high", "max_medium", "max_low", "max_total"):
+ value = getattr(self, key)
+ if value is not None:
+ parts.append(f"{key}={value}")
+ if self.min_score:
+ parts.append(f"min_score={self.min_score}")
+ if self.fail_on_known:
+ parts.append("fail_on_known=true")
+ if self.ignore_rules:
+ parts.append("ignore_rules=" + ",".join(self.ignore_rules))
+ if self.ignore_hosts:
+ parts.append("ignore_hosts=" + ",".join(self.ignore_hosts))
+ return "; ".join(parts) or "no limits"
+
+
+@dataclass
+class PolicyResult:
+ """Outcome of applying a policy to one report."""
+
+ passed: bool
+ violations: List[str] = field(default_factory=list)
+ counts: Dict[str, int] = field(default_factory=dict)
+ policy: Optional[Policy] = None
+ ignored: int = 0
+
+ @property
+ def exit_code(self) -> int:
+ return 0 if self.passed else 1
+
+ def describe(self) -> str:
+ if self.passed:
+ return "policy passed"
+ return "policy failed: " + "; ".join(self.violations)
+
+
+def _eligible(finding: Finding, policy: Policy) -> bool:
+ if policy.ignore_rules and finding.rule in policy.ignore_rules:
+ return False
+ if policy.ignore_hosts and finding.host in policy.ignore_hosts:
+ return False
+ if policy.min_score and finding.score < policy.min_score:
+ return False
+ if finding.status == "known" and not policy.fail_on_known:
+ return False
+ return True
+
+
+def evaluate(report: Report, policy: Policy) -> PolicyResult:
+ """Apply ``policy`` to ``report`` (uses new findings unless told otherwise)."""
+ counts = {"high": 0, "medium": 0, "low": 0, "total": 0}
+ ignored = 0
+ for finding in report.findings:
+ if not _eligible(finding, policy):
+ if finding.status != "known" and policy.min_score and finding.score < policy.min_score:
+ ignored += 1
+ continue
+ counts[finding.confidence] = counts.get(finding.confidence, 0) + 1
+ counts["total"] += 1
+
+ violations: List[str] = []
+ checks = (
+ ("max_high", counts["high"]),
+ ("max_medium", counts["medium"]),
+ ("max_low", counts["low"]),
+ ("max_total", counts["total"]),
+ )
+ for key, actual in checks:
+ limit = getattr(policy, key)
+ if limit is not None and actual > limit:
+ violations.append(f"{key}={limit} exceeded ({actual} found)")
+ return PolicyResult(
+ passed=not violations,
+ violations=violations,
+ counts=counts,
+ policy=policy,
+ ignored=ignored,
+ )
+
+
+def load_policy(path: str) -> Policy:
+ """Read a policy file. Raises :class:`PolicyError`."""
+ try:
+ with open(path, "r", encoding="utf-8-sig") as handle:
+ raw = handle.read()
+ except OSError as exc:
+ raise PolicyError(f"cannot read policy '{path}': {exc.strerror or exc}") from exc
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise PolicyError(
+ f"policy '{path}' is not valid JSON: line {exc.lineno}: {exc.msg}"
+ ) from exc
+ return Policy.from_payload(payload, source=path)
+
+
+def starter_policy() -> str:
+ """Default policy written by ``--init-policy``."""
+ return (
+ "{\n"
+ ' "description": "PathScope CI gate: no new high-confidence candidates",\n'
+ ' "max_high": 0,\n'
+ ' "max_medium": 10,\n'
+ ' "max_total": 20,\n'
+ ' "min_score": 0,\n'
+ ' "fail_on_known": false,\n'
+ ' "ignore_rules": [],\n'
+ ' "ignore_hosts": []\n'
+ "}\n"
+ )
+
+
+def parse_inline_policy(text: str) -> Policy:
+ """Parse a ``--policy`` value that is JSON rather than a file path."""
+ try:
+ payload = json.loads(text)
+ except json.JSONDecodeError as exc:
+ raise PolicyError(f"inline policy is not valid JSON: {exc.msg}") from exc
+ return Policy.from_payload(payload)
+
+
+__all__ = [
+ "DEFAULT_POLICY",
+ "POLICY_KEYS",
+ "Policy",
+ "PolicyError",
+ "PolicyResult",
+ "evaluate",
+ "load_policy",
+ "parse_inline_policy",
+ "starter_policy",
+]
diff --git a/pathscope/presets.py b/pathscope/presets.py
index 5a4e905..4df4013 100644
--- a/pathscope/presets.py
+++ b/pathscope/presets.py
@@ -84,6 +84,9 @@ def apply(self, config: Config) -> Config:
' "min_score": 50,\n'
' "max_decode_passes": 3,\n'
' "weak_names": false,\n'
+ ' "name_lang": [],\n'
+ ' "fold_names": true,\n'
+ ' "demote_shapes": true,\n'
' "show_values": false\n'
'}\n'
),
@@ -94,6 +97,9 @@ def apply(self, config: Config) -> Config:
' "min_score": 25,\n'
' "max_decode_passes": 3,\n'
' "weak_names": true,\n'
+ ' "name_lang": [],\n'
+ ' "fold_names": true,\n'
+ ' "demote_shapes": true,\n'
' "show_values": false\n'
'}\n'
),
@@ -104,6 +110,9 @@ def apply(self, config: Config) -> Config:
' "min_score": 10,\n'
' "max_decode_passes": 3,\n'
' "weak_names": true,\n'
+ ' "name_lang": [],\n'
+ ' "fold_names": true,\n'
+ ' "demote_shapes": true,\n'
' "show_values": false\n'
'}\n'
),
diff --git a/pathscope/progress.py b/pathscope/progress.py
new file mode 100644
index 0000000..bdbd4bb
--- /dev/null
+++ b/pathscope/progress.py
@@ -0,0 +1,108 @@
+"""Optional stderr progress reporting (``--progress``).
+
+Progress goes to stderr only, is rate-limited, and never writes to stdout, so
+``--format json`` stays machine-readable. Lines are plain ASCII and are erased
+in place with ``\\r`` only when stderr is a terminal; otherwise each update is
+printed as its own line (CI logs keep a readable history).
+"""
+
+from __future__ import annotations
+
+import sys
+import time
+from typing import Callable, Optional, TextIO
+
+#: Minimum seconds between two updates (rate limit).
+MIN_UPDATE_INTERVAL = 0.25
+
+
+class Progress:
+ """A small, dependency-free progress reporter."""
+
+ def __init__(
+ self,
+ enabled: bool = False,
+ stream: Optional[TextIO] = None,
+ interval: float = MIN_UPDATE_INTERVAL,
+ now: Callable[[], float] = time.monotonic,
+ ) -> None:
+ self.enabled = enabled
+ self.stream = stream if stream is not None else sys.stderr
+ self.interval = interval
+ self.now = now
+ self._last = 0.0
+ self._phase = ""
+ self._total = 0
+ self._count = 0
+ self._started = 0.0
+ self._interactive = False
+ try:
+ self._interactive = bool(self.stream.isatty())
+ except Exception: # pragma: no cover - exotic streams
+ self._interactive = False
+
+ # -- lifecycle --------------------------------------------------------
+ def start(self, phase: str, total: int = 0) -> None:
+ if not self.enabled:
+ return
+ self._phase = phase
+ self._total = max(0, total)
+ self._count = 0
+ self._started = self.now()
+ # Backdate so the first update is always shown, then rate-limit.
+ self._last = self._started - self.interval
+ self._write(self._format(), force=True)
+
+ def update(self, count: int, total: Optional[int] = None) -> None:
+ if not self.enabled:
+ return
+ self._count = count
+ if total is not None:
+ self._total = max(0, total)
+ current = self.now()
+ if current - self._last < self.interval:
+ return
+ self._last = current
+ self._write(self._format())
+
+ def advance(self, step: int = 1) -> None:
+ self.update(self._count + step)
+
+ def finish(self, note: str = "") -> None:
+ if not self.enabled:
+ return
+ elapsed = max(0.0, self.now() - self._started)
+ detail = f" in {elapsed:.2f}s" if elapsed >= 0.01 else ""
+ suffix = f" - {note}" if note else ""
+ self._write(f"{self._phase}: done{detail}{suffix}", force=True, final=True)
+
+ # -- rendering --------------------------------------------------------
+ def _format(self) -> str:
+ if self._total:
+ percent = min(100, int(self._count * 100 / self._total))
+ return f"{self._phase}: {self._count}/{self._total} ({percent}%)"
+ return f"{self._phase}: {self._count}"
+
+ def _write(self, text: str, force: bool = False, final: bool = False) -> None:
+ if not self.enabled and not force:
+ return
+ try:
+ if self._interactive and not final:
+ self.stream.write("\r" + text.ljust(72))
+ if final:
+ self.stream.write("\n")
+ else:
+ self.stream.write(text + "\n")
+ self.stream.flush()
+ except (OSError, ValueError): # pragma: no cover - closed stderr
+ self.enabled = False
+
+
+class NullProgress(Progress):
+ """A disabled progress reporter (used when ``--progress`` is absent)."""
+
+ def __init__(self) -> None: # noqa: D107 - trivial
+ super().__init__(enabled=False)
+
+
+__all__ = ["MIN_UPDATE_INTERVAL", "NullProgress", "Progress"]
diff --git a/pathscope/report.py b/pathscope/report.py
index f52da6a..bb1b5e9 100644
--- a/pathscope/report.py
+++ b/pathscope/report.py
@@ -23,7 +23,16 @@
FORMAT_SARIF = "sarif"
FORMAT_MARKDOWN = "markdown"
FORMAT_HTML = "html"
-FORMATS = (FORMAT_TEXT, FORMAT_JSON, FORMAT_CSV, FORMAT_SARIF, FORMAT_MARKDOWN, FORMAT_HTML)
+FORMAT_JUNIT = "junit"
+FORMATS = (
+ FORMAT_TEXT,
+ FORMAT_JSON,
+ FORMAT_CSV,
+ FORMAT_SARIF,
+ FORMAT_MARKDOWN,
+ FORMAT_HTML,
+ FORMAT_JUNIT,
+)
#: Human label for a confidence band (never an exploitability claim).
CONFIDENCE_LABELS = {
@@ -237,7 +246,12 @@ def build_json_payload(report: Report) -> Dict[str, object]:
"new": report.new_count,
"known": report.known_count,
"resolved": len(report.resolved),
+ "truncated_entries": report.truncated_entries,
},
+ "rules": dict(report.rules),
+ "rules_source": report.rules_source,
+ "name_lang": list(report.name_lang),
+ "stats": dict(report.stats),
"warnings": list(report.warnings),
"findings": [finding.as_dict() for finding in report.findings],
"links": {
@@ -398,6 +412,10 @@ def render_sarif(report: Report) -> str:
def render(report: Report, output_format: str, colors: Palette) -> str:
from .writers import render_html, render_markdown # local import avoids a cycle
+ if output_format == FORMAT_JUNIT:
+ from .ci import render_junit # local import avoids a cycle
+
+ return render_junit(report)
if output_format == FORMAT_JSON:
return render_json(report)
if output_format == FORMAT_CSV:
diff --git a/pathscope/rules.py b/pathscope/rules.py
new file mode 100644
index 0000000..2c7c207
--- /dev/null
+++ b/pathscope/rules.py
@@ -0,0 +1,445 @@
+"""The PathScope rule registry.
+
+Every scoring rule lives here with its default weight, the layer it belongs to
+(``name`` or ``value``) and a one-line description. The registry is the single
+source of truth used by ``--list-rules``, ``--rules overrides.json``,
+``--disable-rule``, ``--explain`` and the README.
+
+Rules are heuristic ranking signals only. None of them is a vulnerability test.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, replace
+from typing import Dict, FrozenSet, List, Optional, Sequence, Tuple
+
+#: ``--list-rules`` group order.
+LAYER_NAME = "name"
+LAYER_VALUE = "value"
+
+# ---------------------------------------------------------------------------
+# Default weights
+# ---------------------------------------------------------------------------
+#: Weight for an exact, strong name term.
+STRONG_NAME_WEIGHT = 35
+#: Extra weight when a strong term is part of a multiword name (``download_file``).
+MULTIWORD_BONUS = 5
+#: Discount for ``name-prefix`` and ``name-suffix`` matches.
+PREFIX_DISCOUNT = 7
+SUFFIX_DISCOUNT = 12
+#: Bonus when a generic name (``image``, ``target`` ...) has a path-like value.
+GENERIC_BONUS = 10
+
+
+@dataclass(frozen=True)
+class RuleSpec:
+ """One rule in the registry."""
+
+ rule: str
+ layer: str
+ weight: int
+ description: str
+
+
+#: Registry order is the order ``--list-rules`` and ``--explain`` use inside a
+#: layer; it is stable so output is deterministic.
+DEFAULT_RULES: Tuple[RuleSpec, ...] = (
+ # --- name layer -------------------------------------------------------
+ RuleSpec(
+ "name-custom",
+ LAYER_NAME,
+ 30,
+ "exact user-configured term from the configuration file",
+ ),
+ RuleSpec(
+ "name-exact",
+ LAYER_NAME,
+ STRONG_NAME_WEIGHT,
+ "parameter name contains a built-in path-related term (+multiword bonus)",
+ ),
+ RuleSpec(
+ "name-compound",
+ LAYER_NAME,
+ STRONG_NAME_WEIGHT,
+ "the whole name is a known path compound",
+ ),
+ RuleSpec(
+ "name-prefix",
+ LAYER_NAME,
+ STRONG_NAME_WEIGHT - PREFIX_DISCOUNT,
+ "name starts with a path-related term (filedata)",
+ ),
+ RuleSpec(
+ "name-suffix",
+ LAYER_NAME,
+ STRONG_NAME_WEIGHT - SUFFIX_DISCOUNT,
+ "name ends with a path-related term (userfile)",
+ ),
+ RuleSpec(
+ "name-generic",
+ LAYER_NAME,
+ 0,
+ "generic name (image/target/ref); only counts with a path-like value",
+ ),
+ RuleSpec(
+ "name-weak",
+ LAYER_NAME,
+ 5,
+ "multiword name without a path term (never enough on its own)",
+ ),
+ RuleSpec(
+ "name-folded",
+ LAYER_NAME,
+ 20,
+ "name matches a path term only after diacritic/compatibility folding",
+ ),
+ RuleSpec(
+ "name-leet",
+ LAYER_NAME,
+ 12,
+ "name matches a path term only after leet expansion (f1le -> file)",
+ ),
+ RuleSpec(
+ "name-i18n",
+ LAYER_NAME,
+ 25,
+ "name contains a path term from another language",
+ ),
+ RuleSpec(
+ "name-i18n-fold",
+ LAYER_NAME,
+ 21,
+ "non-English term matched only after diacritic folding",
+ ),
+ # --- value layer ------------------------------------------------------
+ RuleSpec(
+ "value-traversal",
+ LAYER_VALUE,
+ 30,
+ "'..' used as a path segment",
+ ),
+ RuleSpec(
+ "value-encoded-traversal",
+ LAYER_VALUE,
+ 15,
+ "'..' segment appears only after percent-decoding",
+ ),
+ RuleSpec(
+ "value-encoded-slash",
+ LAYER_VALUE,
+ 12,
+ "encoded slash/backslash (%2f / %5c)",
+ ),
+ RuleSpec(
+ "value-double-encoded",
+ LAYER_VALUE,
+ 10,
+ "two or more decoding passes were required",
+ ),
+ RuleSpec(
+ "value-windows-drive",
+ LAYER_VALUE,
+ 15,
+ "looks like a Windows drive path (C:\\...)",
+ ),
+ RuleSpec(
+ "value-unc",
+ LAYER_VALUE,
+ 15,
+ "looks like a UNC path (\\\\server\\share)",
+ ),
+ RuleSpec(
+ "value-absolute",
+ LAYER_VALUE,
+ 12,
+ "starts with a path separator (absolute-looking)",
+ ),
+ RuleSpec(
+ "value-multi-segment",
+ LAYER_VALUE,
+ 6,
+ "two or more path separators",
+ ),
+ RuleSpec(
+ "value-extension",
+ LAYER_VALUE,
+ 8,
+ "ends with a known file-like extension",
+ ),
+ RuleSpec(
+ "value-path-list",
+ LAYER_VALUE,
+ 5,
+ "semicolon/comma separated list of paths",
+ ),
+ RuleSpec(
+ "value-pairs-with-generic-name",
+ LAYER_VALUE,
+ GENERIC_BONUS,
+ "generic parameter name paired with a path-like value",
+ ),
+ RuleSpec(
+ "value-full-url",
+ LAYER_VALUE,
+ -10,
+ "a full URL rather than a local path",
+ ),
+ # --- value-shape demotion --------------------------------------------
+ RuleSpec(
+ "value-demote-uuid",
+ LAYER_VALUE,
+ -20,
+ "value is a UUID",
+ ),
+ RuleSpec(
+ "value-demote-hash",
+ LAYER_VALUE,
+ -18,
+ "value is a hex digest or long hex string",
+ ),
+ RuleSpec(
+ "value-demote-jwt",
+ LAYER_VALUE,
+ -20,
+ "value is a JWT (three base64url segments)",
+ ),
+ RuleSpec(
+ "value-demote-base64",
+ LAYER_VALUE,
+ -12,
+ "value is a base64 blob",
+ ),
+ RuleSpec(
+ "value-demote-email",
+ LAYER_VALUE,
+ -8,
+ "value is an e-mail address",
+ ),
+ RuleSpec(
+ "value-demote-ip",
+ LAYER_VALUE,
+ -10,
+ "value is an IP address",
+ ),
+ RuleSpec(
+ "value-demote-scalar",
+ LAYER_VALUE,
+ -10,
+ "value is a bool, number or short enum-like token",
+ ),
+)
+
+RULE_INDEX: Dict[str, RuleSpec] = {spec.rule: spec for spec in DEFAULT_RULES}
+RULE_NAMES: Tuple[str, ...] = tuple(spec.rule for spec in DEFAULT_RULES)
+
+#: Rule ids that may never be overridden to a positive number that inverts
+#: their meaning: demotions must stay non-positive.
+DEMOTION_PREFIX = "value-demote-"
+
+#: Bounds for a user-supplied weight.
+MIN_WEIGHT = -100
+MAX_WEIGHT = 100
+
+#: Upper bound on overrides in one file, so a hostile file cannot be huge.
+MAX_OVERRIDES = 200
+
+
+class RuleError(ValueError):
+ """Raised when a rule override file is invalid."""
+
+
+@dataclass(frozen=True)
+class RuleBook:
+ """The effective weights for one run.
+
+ ``weights`` maps every known rule id to its weight; rules missing from a
+ user override file keep their default. ``disabled`` holds rule ids removed
+ from scoring entirely (they also disappear from ``--explain``).
+ """
+
+ weights: Dict[str, int]
+ disabled: FrozenSet[str] = frozenset()
+ source: str = ""
+
+ # -- construction -----------------------------------------------------
+ @classmethod
+ def default(cls) -> "RuleBook":
+ return cls(weights={spec.rule: spec.weight for spec in DEFAULT_RULES})
+
+ @classmethod
+ def with_overrides(
+ cls,
+ overrides: Optional[Dict[str, int]] = None,
+ disabled: Sequence[str] = (),
+ source: str = "",
+ ) -> "RuleBook":
+ """Validate and apply explicit weights plus a disabled set."""
+ book = cls.default()
+ weights = dict(book.weights)
+ for rule, weight in (overrides or {}).items():
+ if rule not in RULE_INDEX:
+ raise RuleError(f"unknown rule '{rule}' (see --list-rules)")
+ if isinstance(weight, bool) or not isinstance(weight, int):
+ raise RuleError(f"weight for '{rule}' must be an integer")
+ if not MIN_WEIGHT <= weight <= MAX_WEIGHT:
+ raise RuleError(
+ f"weight for '{rule}' must be between {MIN_WEIGHT} and {MAX_WEIGHT}"
+ )
+ if rule.startswith(DEMOTION_PREFIX) and weight > 0:
+ raise RuleError(
+ f"'{rule}' is a demotion rule and may not have a positive weight"
+ )
+ weights[rule] = weight
+ disabled_set = frozenset(name.strip().lower() for name in disabled if name)
+ for rule in disabled_set:
+ if rule not in RULE_INDEX:
+ raise RuleError(f"unknown rule '{rule}' (see --list-rules)")
+ return cls(weights=weights, disabled=disabled_set, source=source)
+
+ # -- queries ----------------------------------------------------------
+ def weight(self, rule: str) -> int:
+ """Effective weight (0 when the rule is disabled or unknown)."""
+ if rule in self.disabled:
+ return 0
+ return self.weights.get(rule, RULE_INDEX[rule].weight if rule in RULE_INDEX else 0)
+
+ def is_disabled(self, rule: str) -> bool:
+ return rule in self.disabled
+
+ def default_weight(self, rule: str) -> int:
+ spec = RULE_INDEX.get(rule)
+ return spec.weight if spec else 0
+
+ def overridden(self) -> List[str]:
+ """Rule ids whose effective weight differs from the default."""
+ return [
+ rule
+ for rule in RULE_NAMES
+ if rule not in self.disabled and self.weights.get(rule) != self.default_weight(rule)
+ ]
+
+ def enabled_specs(self) -> List[RuleSpec]:
+ return [spec for spec in DEFAULT_RULES if spec.rule not in self.disabled]
+
+ def as_dict(self) -> Dict[str, int]:
+ return {spec.rule: self.weight(spec.rule) for spec in DEFAULT_RULES}
+
+ def clone(self) -> "RuleBook":
+ return replace(self, weights=dict(self.weights))
+
+
+#: The book used when the user passes nothing.
+DEFAULT_BOOK = RuleBook.default()
+
+
+# ---------------------------------------------------------------------------
+# --rules FILE parsing
+# ---------------------------------------------------------------------------
+def parse_rule_payload(payload: object) -> Dict[str, int]:
+ """Accept ``{"weights": {...}, "disable": [...]}`` or a bare weight map."""
+ if not isinstance(payload, dict):
+ raise RuleError("rule overrides must be a JSON object")
+ raw_weights = payload.get("weights", None)
+ if raw_weights is None:
+ # A bare mapping of rule -> weight is also accepted.
+ raw_weights = {
+ key: value
+ for key, value in payload.items()
+ if key not in ("disable", "tool", "version", "note")
+ }
+ if not isinstance(raw_weights, dict):
+ raise RuleError("'weights' must be a JSON object of rule -> integer")
+ if len(raw_weights) > MAX_OVERRIDES:
+ raise RuleError(f"at most {MAX_OVERRIDES} weight overrides are allowed")
+ weights: Dict[str, int] = {}
+ for rule, weight in raw_weights.items():
+ if not isinstance(rule, str):
+ raise RuleError("rule ids must be strings")
+ weights[rule.strip()] = weight # validated by RuleBook.with_overrides
+ disabled = payload.get("disable", [])
+ if isinstance(disabled, str):
+ disabled = [disabled]
+ if not isinstance(disabled, list) or not all(isinstance(x, str) for x in disabled):
+ raise RuleError("'disable' must be an array of rule ids")
+ # ``disable`` entries are validated and applied by RuleBook.with_overrides.
+ return weights
+
+
+def load_rule_overrides(path: str) -> Tuple[Dict[str, int], List[str]]:
+ """Read a ``--rules`` file. Raises :class:`RuleError`."""
+ try:
+ with open(path, "r", encoding="utf-8-sig") as handle:
+ raw = handle.read()
+ except OSError as exc:
+ raise RuleError(f"cannot read rule overrides '{path}': {exc.strerror or exc}") from exc
+ try:
+ payload = json.loads(raw)
+ except json.JSONDecodeError as exc:
+ raise RuleError(
+ f"rule overrides '{path}' are not valid JSON: line {exc.lineno}: {exc.msg}"
+ ) from exc
+ weights = parse_rule_payload(payload)
+ disabled = payload.get("disable", []) if isinstance(payload, dict) else []
+ if isinstance(disabled, str):
+ disabled = [disabled]
+ return weights, [str(item) for item in disabled]
+
+
+def normalize_rule_id(name: str) -> str:
+ """Map a friendly alias onto a rule id (``traversal`` -> ``value-traversal``)."""
+ key = (name or "").strip().lower()
+ if key in RULE_INDEX:
+ return key
+ if f"value-{key}" in RULE_INDEX:
+ return f"value-{key}"
+ if f"name-{key}" in RULE_INDEX:
+ return f"name-{key}"
+ if f"value-demote-{key}" in RULE_INDEX:
+ return f"value-demote-{key}"
+ return key
+
+
+def format_rule_table(book: Optional[RuleBook] = None) -> List[str]:
+ """Lines for ``--list-rules``: id, effective weight, default, description."""
+ book = book or DEFAULT_BOOK
+ lines: List[str] = []
+ for layer in (LAYER_NAME, LAYER_VALUE):
+ lines.append(f"{layer} rules:")
+ for spec in DEFAULT_RULES:
+ if spec.layer != layer:
+ continue
+ effective = book.weight(spec.rule)
+ if spec.rule in book.disabled:
+ weight = "off"
+ elif effective != spec.weight:
+ weight = f"{effective:+d} (default {spec.weight:+d})"
+ else:
+ weight = f"{spec.weight:+d}"
+ lines.append(f" {spec.rule:<28} {weight:<22} {spec.description}")
+ lines.append("")
+ lines.append("Weights are heuristic ranking points, not exploitability scores.")
+ lines.append("Change them with --rules FILE or remove them with --disable-rule RULE.")
+ return lines
+
+
+__all__ = [
+ "DEFAULT_RULES",
+ "DEFAULT_BOOK",
+ "RuleSpec",
+ "RuleBook",
+ "RuleError",
+ "RULE_INDEX",
+ "RULE_NAMES",
+ "format_rule_table",
+ "load_rule_overrides",
+ "normalize_rule_id",
+ "parse_rule_payload",
+ "STRONG_NAME_WEIGHT",
+ "MULTIWORD_BONUS",
+ "PREFIX_DISCOUNT",
+ "SUFFIX_DISCOUNT",
+ "GENERIC_BONUS",
+ "LAYER_NAME",
+ "LAYER_VALUE",
+]
diff --git a/pathscope/sources.py b/pathscope/sources.py
index 0700020..31fcfef 100644
--- a/pathscope/sources.py
+++ b/pathscope/sources.py
@@ -536,6 +536,11 @@ def load_stdin_har(text: str) -> LoadResult:
"ffuf",
"nuclei",
"recon",
+ "postman",
+ "zap",
+ "mitmproxy",
+ "graphql",
+ "cookies",
)
@@ -566,6 +571,13 @@ def detect_input_format(text: str, path: str = "") -> str:
return INPUT_FORMAT_URLS
from .extra_formats import detect_extra_format # local import avoids a cycle
+ from .tool_formats import detect_tool_format
+
+ # Tool exports (Postman/ZAP/mitmproxy/GraphQL/cookies) are checked before
+ # the recon fallback, which would otherwise claim any text with a URL.
+ tool = detect_tool_format(text, path)
+ if tool:
+ return tool
extra = detect_extra_format(text, path)
if extra:
@@ -573,9 +585,20 @@ def detect_input_format(text: str, path: str = "") -> str:
return INPUT_FORMAT_URLS
+#: Formats handled by :mod:`pathscope.tool_formats`.
+TOOL_FORMATS = ("postman", "zap", "mitmproxy", "graphql", "cookies")
+
+
def _load_extra(path_or_text: str, fmt: str, *, is_path: bool) -> "LoadResult":
from .extra_formats import load_extra_file, load_extra_text # local import
+ if fmt in TOOL_FORMATS:
+ from .tool_formats import load_tool_file, load_tool_text
+
+ if is_path:
+ return load_tool_file(path_or_text, fmt)
+ return load_tool_text(path_or_text, fmt, "stdin")
+
if is_path:
return load_extra_file(path_or_text, fmt)
label = "stdin"
diff --git a/pathscope/tool_formats.py b/pathscope/tool_formats.py
new file mode 100644
index 0000000..fca76c7
--- /dev/null
+++ b/pathscope/tool_formats.py
@@ -0,0 +1,785 @@
+"""More local tool exports: Postman, ZAP, mitmproxy and GraphQL.
+
+Every loader follows the same rules as the rest of PathScope:
+
+* only files the user already has are read;
+* nothing is fetched, replayed, resolved or opened;
+* only parameter *names* (and inert literal values already present in the
+ export) are carried forward, bounded in size;
+* malformed entries become warnings, never crashes.
+
+Formats
+ ``postman`` Postman Collection v2.0 / v2.1 (nested ``item`` folders,
+ ``url.query``, ``urlencoded``/``formdata``/``raw`` bodies)
+ ``zap`` OWASP ZAP JSON history export (``site`` -> ``alerts`` or
+ ``messages``)
+ ``mitmproxy`` mitmproxy ``flow`` JSON export (``request`` with ``query``
+ and ``content``)
+ ``graphql`` GraphQL introspection response, reduced to argument names of
+ queries and mutations
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any, Dict, List, Optional, Tuple
+from urllib.parse import parse_qsl
+
+from .sources import (
+ LOCATION_FORM,
+ LOCATION_JSON,
+ LOCATION_QUERY,
+ HarError,
+ LoadResult,
+ Parameter,
+ Request,
+ URLInfo,
+ URLParseError,
+ _as_text,
+ _json_parameters,
+ canonical,
+ parse_url,
+ query_parameters,
+)
+from .textutil import sanitize_text
+
+INPUT_FORMAT_POSTMAN = "postman"
+INPUT_FORMAT_ZAP = "zap"
+INPUT_FORMAT_MITM = "mitmproxy"
+INPUT_FORMAT_GRAPHQL = "graphql"
+INPUT_FORMAT_COOKIES = "cookies"
+
+#: Identifier used in reports for all these formats.
+SOURCE_POSTMAN = "postman"
+SOURCE_ZAP = "zap"
+SOURCE_MITM = "mitmproxy"
+SOURCE_GRAPHQL = "graphql"
+SOURCE_COOKIES = "cookies"
+
+#: Hard limits (shared with the other readers).
+MAX_COLLECTION_ITEMS = 50000
+MAX_GRAPHQL_DEPTH = 12
+MAX_TEXT_BODY = 4 * 1024 * 1024
+
+#: Netscape cookie-file separator is a TAB; the regex is fixed, not user input.
+_COOKIE_SPLIT_RE = re.compile(r"\t+")
+
+
+# ---------------------------------------------------------------------------
+# Postman Collection v2.0 / v2.1
+# ---------------------------------------------------------------------------
+def looks_like_postman(payload: Any) -> bool:
+ return isinstance(payload, dict) and isinstance(payload.get("info"), dict) and (
+ "schema" in payload["info"] or "item" in payload
+ ) and isinstance(payload.get("item"), list)
+
+
+def _postman_url(raw_url: Any) -> Optional[str]:
+ """Turn a Postman ``url`` (string or object) into a URL string."""
+ if isinstance(raw_url, str):
+ candidate = raw_url.strip()
+ return candidate if candidate.lower().startswith(("http://", "https://")) else None
+ if isinstance(raw_url, dict):
+ if isinstance(raw_url.get("raw"), str) and raw_url["raw"].strip():
+ raw = raw_url["raw"].strip()
+ return raw if raw.lower().startswith(("http://", "https://")) else None
+ host = raw_url.get("host")
+ if isinstance(host, list):
+ host = ".".join(str(part) for part in host)
+ if not isinstance(host, str) or not host:
+ return None
+ path = raw_url.get("path")
+ if isinstance(path, list):
+ path = "/".join(str(part) for part in path)
+ if not isinstance(path, str):
+ path = ""
+ protocol = str(raw_url.get("protocol") or "https").lower()
+ if protocol not in ("http", "https"):
+ protocol = "https"
+ port = raw_url.get("port")
+ netloc = host if not port else f"{host}:{port}"
+ return f"{protocol}://{netloc}/{path.lstrip('/')}"
+ return None
+
+
+def _postman_query(raw_url: Any) -> List[Parameter]:
+ parameters: List[Parameter] = []
+ if isinstance(raw_url, dict) and isinstance(raw_url.get("query"), list):
+ for entry in raw_url["query"]:
+ if not isinstance(entry, dict):
+ continue
+ name = entry.get("key")
+ if not isinstance(name, str) or not name or entry.get("disabled") is True:
+ continue
+ parameters.append(
+ Parameter(name=name, value=_as_text(entry.get("value")), location=LOCATION_QUERY)
+ )
+ return parameters
+
+
+def _postman_body(body: Any, label: str) -> List[Parameter]:
+ parameters: List[Parameter] = []
+ if not isinstance(body, dict):
+ return parameters
+ mode = str(body.get("mode") or "").lower()
+ for key in ("urlencoded", "formdata"):
+ entries = body.get(key)
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ name = entry.get("key")
+ if not isinstance(name, str) or not name or entry.get("disabled") is True:
+ continue
+ value = entry.get("value")
+ if value is None and isinstance(entry.get("src"), str):
+ value = entry["src"]
+ parameters.append(
+ Parameter(name=name, value=_as_text(value), location=LOCATION_FORM)
+ )
+ if mode == "raw" and isinstance(body.get("raw"), str) and body["raw"].strip():
+ raw = body["raw"][:MAX_TEXT_BODY]
+ language = str((body.get("options") or {}).get("raw", {}).get("language") or "").lower()
+ stripped = raw.lstrip()
+ if language == "json" or stripped.startswith(("{", "[")):
+ try:
+ payload = json.loads(raw)
+ except ValueError:
+ return parameters
+ parameters.extend(_json_parameters(payload, [], label))
+ elif "=" in raw:
+ for name, value in parse_qsl(raw, keep_blank_values=True):
+ if name:
+ parameters.append(
+ Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM)
+ )
+ return parameters
+
+
+def _walk_items(items: Any, label: str, warnings: List[str], requests: List[Request]) -> None:
+ if not isinstance(items, list):
+ return
+ stack = list(reversed(items))
+ while stack and len(requests) < MAX_COLLECTION_ITEMS:
+ item = stack.pop()
+ if not isinstance(item, dict):
+ continue
+ if isinstance(item.get("item"), list):
+ # Folder: descend, preserving order.
+ stack.extend(reversed(item["item"]))
+ continue
+ request = item.get("request")
+ name = sanitize_text(str(item.get("name") or ""))
+ if isinstance(request, str):
+ url = request.strip()
+ request = {"url": url}
+ if not isinstance(request, dict):
+ continue
+ url = _postman_url(request.get("url"))
+ if not url:
+ warnings.append(f"{label}: item '{name or '?'}' has no usable URL")
+ continue
+ try:
+ info = parse_url(url)
+ except URLParseError as exc:
+ warnings.append(f"{label}: item '{name or '?'}' skipped ({exc})")
+ continue
+ parameters = list(query_parameters(info.query))
+ parameters.extend(_postman_query(request.get("url")))
+ parameters = _merge_parameters(parameters)
+ parameters.extend(_postman_body(request.get("body"), label))
+ method = str(request.get("method") or "GET").upper()[:12]
+ requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_POSTMAN,
+ source_label=label,
+ parameters=_merge_parameters(parameters),
+ method=method,
+ index=len(requests),
+ )
+ )
+
+
+def load_postman(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse a Postman Collection v2.0/v2.1 export."""
+ 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_postman(payload):
+ raise HarError(
+ f"{label}: not a Postman v2 collection (expected 'info' and 'item')"
+ )
+ result = LoadResult()
+ _walk_items(payload.get("item"), label, result.warnings, result.requests)
+ if not result.requests:
+ result.warnings.append(f"{label}: collection contains no usable requests")
+ return result
+
+
+def load_postman_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_postman(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# OWASP ZAP JSON export
+# ---------------------------------------------------------------------------
+def looks_like_zap(payload: Any) -> bool:
+ if not isinstance(payload, dict):
+ return False
+ if "site" in payload and isinstance(payload["site"], (list, dict)):
+ return True
+ if "alerts" in payload and isinstance(payload["alerts"], list):
+ return True
+ return isinstance(payload.get("@programName"), str) and "ZAP" in str(payload.get("@programName"))
+
+
+def _zap_sites(payload: Any) -> List[Dict[str, Any]]:
+ sites = payload.get("site") if isinstance(payload, dict) else None
+ if isinstance(sites, dict):
+ return [sites]
+ if isinstance(sites, list):
+ return [site for site in sites if isinstance(site, dict)]
+ return []
+
+
+def _zap_message_urls(message: Any) -> List[str]:
+ urls: List[str] = []
+ if not isinstance(message, dict):
+ return urls
+ for key in ("url", "uri", "endpoint", "matched-at", "requestHeader", "requestUri"):
+ value = message.get(key)
+ if isinstance(value, str):
+ match = re.search(r"https?://[^\s\"'<>]+", value)
+ if match:
+ urls.append(match.group(0))
+ break
+ if key == "requestUri" and value.startswith("/"):
+ host = message.get("host") or message.get("hostname") or ""
+ if isinstance(host, str) and host:
+ urls.append(f"http://{host}{value}")
+ break
+ return urls
+
+
+def _zap_request_text(message: Any) -> List[Parameter]:
+ """Parse a recorded request header/body for parameters."""
+ parameters: List[Parameter] = []
+ if not isinstance(message, dict):
+ return parameters
+ header = message.get("requestHeader") or ""
+ body = message.get("requestBody") or message.get("body") or ""
+ if isinstance(header, str):
+ head, _sep, inline_body = header.partition("\n\n")
+ if not isinstance(body, str) or not body:
+ body = inline_body
+ headers: Dict[str, str] = {}
+ for line in head.splitlines():
+ name, _colon, value = line.partition(":")
+ if _colon:
+ headers.setdefault(name.strip().lower(), value.strip())
+ content_type = headers.get("content-type", "").lower()
+ else:
+ content_type = ""
+ if isinstance(body, str) and body:
+ body = body[:MAX_TEXT_BODY]
+ if "application/json" in content_type or body.lstrip().startswith(("{", "[")):
+ try:
+ payload = json.loads(body)
+ except ValueError:
+ payload = None
+ if payload is not None:
+ parameters.extend(_json_parameters(payload, [], "zap"))
+ elif "x-www-form-urlencoded" in content_type or "=" in body:
+ for name, value in parse_qsl(body, keep_blank_values=True):
+ if name:
+ parameters.append(
+ Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM)
+ )
+ return parameters
+
+
+def load_zap(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse a ZAP JSON history/alert export into requests."""
+ 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_zap(payload):
+ raise HarError(
+ f"{label}: not a ZAP JSON export (expected 'site' or 'alerts')"
+ )
+ result = LoadResult()
+ seen: set = set()
+ urls: List[Tuple[str, Any]] = []
+ for site in _zap_sites(payload):
+ for message in site.get("messages") or []:
+ for url in _zap_message_urls(message):
+ urls.append((url, message))
+ if not urls:
+ for alert in payload.get("alerts") or []:
+ if isinstance(alert, dict):
+ for url in _zap_message_urls(alert):
+ urls.append((url, alert))
+ if isinstance(alert.get("instances"), list):
+ for instance in alert["instances"]:
+ for url in _zap_message_urls(instance):
+ urls.append((url, instance))
+ for url, message in urls:
+ if url in seen:
+ continue
+ seen.add(url)
+ try:
+ info = parse_url(url)
+ except URLParseError:
+ result.skipped += 1
+ continue
+ parameters = list(query_parameters(info.query))
+ parameters.extend(_zap_request_text(message))
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_ZAP,
+ source_label=label,
+ parameters=_merge_parameters(parameters),
+ method=str(message.get("method") or "GET").upper()[:12]
+ if isinstance(message, dict)
+ else "GET",
+ index=len(result.requests),
+ )
+ )
+ if not result.requests:
+ result.warnings.append(f"{label}: no usable requests found in ZAP export")
+ return result
+
+
+def load_zap_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_zap(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# mitmproxy flow export (JSON)
+# ---------------------------------------------------------------------------
+def looks_like_mitm(payload: Any) -> bool:
+ entries = payload if isinstance(payload, list) else [payload]
+ for entry in entries[:3]:
+ if not isinstance(entry, dict):
+ continue
+ request = entry.get("request")
+ if isinstance(request, dict) and (
+ "scheme" in request
+ or "host" in request
+ or ("path" in request and "query" in request)
+ or isinstance(request.get("url"), str)
+ ):
+ return True
+ return False
+
+
+def _mitm_url(request: Any) -> Optional[str]:
+ if not isinstance(request, dict):
+ return None
+ url = request.get("url")
+ if isinstance(url, str) and url.lower().startswith(("http://", "https://")):
+ return url
+ scheme = str(request.get("scheme") or "https").lower()
+ if scheme not in ("http", "https"):
+ scheme = "https"
+ host = request.get("host")
+ if not isinstance(host, str) or not host:
+ return None
+ port = request.get("port")
+ netloc = host if not port or str(port) in ("80", "443") else f"{host}:{port}"
+ path = request.get("path") or "/"
+ if not isinstance(path, str):
+ path = "/"
+ query = request.get("query")
+ if isinstance(query, list):
+ pairs = []
+ for entry in query:
+ if isinstance(entry, dict) and isinstance(entry.get("key"), str):
+ pairs.append((entry["key"], _as_text(entry.get("value"))))
+ if pairs:
+ from urllib.parse import urlencode
+
+ path = f"{path}?{urlencode(pairs, doseq=True)}"
+ elif isinstance(query, str) and query:
+ path = f"{path}?{query}"
+ return f"{scheme}://{netloc}{path if path.startswith('/') else '/' + path}"
+
+
+def _mitm_body(request: Any) -> List[Parameter]:
+ if not isinstance(request, dict):
+ return []
+ content = request.get("content")
+ if isinstance(content, dict):
+ text_value = content.get("text")
+ mime = str(content.get("mimeType") or content.get("contentType") or "").lower()
+ else:
+ text_value = content if isinstance(content, str) else None
+ mime = ""
+ if not isinstance(text_value, str) or not text_value.strip():
+ return []
+ body = text_value[:MAX_TEXT_BODY]
+ if "json" in mime or body.lstrip().startswith(("{", "[")):
+ try:
+ payload = json.loads(body)
+ except ValueError:
+ return []
+ return _json_parameters(payload, [], "mitmproxy")
+ if "x-www-form-urlencoded" in mime or "=" in body:
+ parameters = []
+ for name, value in parse_qsl(body, keep_blank_values=True):
+ if name:
+ parameters.append(
+ Parameter(name=sanitize_text(name), value=sanitize_text(value), location=LOCATION_FORM)
+ )
+ return parameters
+ return []
+
+
+def load_mitm(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Parse a mitmproxy ``flow`` JSON export (single flow or a list)."""
+ 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
+ entries = payload if isinstance(payload, list) else [payload]
+ if not looks_like_mitm(payload):
+ raise HarError(
+ f"{label}: not a mitmproxy flow export (expected 'request' objects)"
+ )
+ result = LoadResult()
+ seen: set = set()
+ for entry in entries[:MAX_COLLECTION_ITEMS]:
+ if not isinstance(entry, dict):
+ continue
+ request = entry.get("request")
+ url = _mitm_url(request)
+ if not url:
+ result.skipped += 1
+ continue
+ if url in seen:
+ continue
+ seen.add(url)
+ try:
+ info = parse_url(url)
+ except URLParseError:
+ result.skipped += 1
+ continue
+ parameters = list(query_parameters(info.query))
+ parameters.extend(_mitm_body(request))
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_MITM,
+ source_label=label,
+ parameters=_merge_parameters(parameters),
+ method=str(request.get("method") or "GET").upper()[:12],
+ index=len(result.requests),
+ )
+ )
+ if not result.requests:
+ result.warnings.append(f"{label}: no usable flows found")
+ return result
+
+
+def load_mitm_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_mitm(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# GraphQL introspection
+# ---------------------------------------------------------------------------
+def _graphql_schema(payload: Any) -> Any:
+ if not isinstance(payload, dict):
+ return None
+ schema = payload.get("__schema")
+ if schema is None and isinstance(payload.get("data"), dict):
+ schema = payload["data"].get("__schema")
+ return schema
+
+
+def looks_like_graphql(payload: Any) -> bool:
+ schema = _graphql_schema(payload)
+ if not isinstance(schema, dict):
+ return False
+ types = schema.get("types")
+ return isinstance(schema.get("queryType"), dict) and isinstance(types, (list, dict))
+
+
+def _graphql_arguments(schema: Any, warnings: List[str], label: str) -> List[Parameter]:
+ parameters: List[Parameter] = []
+ if not isinstance(schema, dict):
+ return parameters
+ types = schema.get("types")
+ type_list: List[Dict[str, Any]] = []
+ if isinstance(types, list):
+ type_list = [entry for entry in types if isinstance(entry, dict)]
+ elif isinstance(types, dict):
+ type_list = [entry for entry in types.values() if isinstance(entry, dict)]
+
+ root_names: set = set()
+ for key in ("queryType", "mutationType", "subscriptionType"):
+ node = schema.get(key)
+ if isinstance(node, dict) and isinstance(node.get("name"), str):
+ root_names.add(node["name"])
+
+ def walk_args(args: Any, prefix: str, depth: int) -> None:
+ if depth > MAX_GRAPHQL_DEPTH or not isinstance(args, list):
+ return
+ for arg in args:
+ if not isinstance(arg, dict):
+ continue
+ name = arg.get("name")
+ if not isinstance(name, str) or not name:
+ continue
+ path = f"{prefix}.{name}" if prefix else name
+ parameters.append(
+ Parameter(name=path, value="", location=LOCATION_FORM)
+ )
+ walk_args(arg.get("args"), path, depth + 1)
+
+ for type_entry in type_list:
+ type_name = type_entry.get("name")
+ if not isinstance(type_name, str):
+ continue
+ if root_names and type_name not in root_names:
+ # Only the query/mutation/subscription roots describe entry points.
+ continue
+ for field in type_entry.get("fields") or []:
+ if not isinstance(field, dict) or not isinstance(field.get("name"), str):
+ continue
+ walk_args(field.get("args"), "", 0)
+ return parameters
+
+
+def load_graphql(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Reduce a GraphQL introspection result to per-operation argument names."""
+ 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_graphql(payload):
+ raise HarError(
+ f"{label}: not a GraphQL introspection result (expected '__schema')"
+ )
+ schema = _graphql_schema(payload)
+ result = LoadResult()
+ parameters = _graphql_arguments(schema, result.warnings, label)
+ if not parameters:
+ result.warnings.append(f"{label}: introspection result declares no arguments")
+ return result
+ host = "graphql.local"
+ root_names: Dict[str, Any] = {}
+ for key in ("queryType", "mutationType"):
+ node = (schema or {}).get(key)
+ if isinstance(node, dict) and isinstance(node.get("name"), str):
+ root_names[node["name"]] = key
+
+ # One synthetic request per operation type so findings stay attributable.
+ grouped: Dict[str, List[Parameter]] = {}
+ for parameter in parameters:
+ grouped.setdefault("query", []).append(parameter)
+ for method, entries in grouped.items():
+ info = URLInfo(
+ raw=f"https://{host}/graphql",
+ scheme="https",
+ host=host,
+ port=None,
+ path="/graphql",
+ query="",
+ )
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_GRAPHQL,
+ source_label=label,
+ parameters=entries,
+ method="POST",
+ index=len(result.requests),
+ )
+ )
+ return result
+
+
+def load_graphql_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_graphql(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# Netscape cookie jars (curl/Chromium export)
+# ---------------------------------------------------------------------------
+def looks_like_cookies(text: str) -> bool:
+ lines = [line for line in text.splitlines() if line.strip()]
+ if not lines:
+ return False
+ if lines[0].startswith("# Netscape HTTP Cookie File"):
+ return True
+ tabs = sum(1 for line in lines[:20] if "\t" in line and not line.startswith("#"))
+ return tabs >= 2
+
+
+def load_cookies(text: str, label: str, source_label: Optional[str] = None) -> LoadResult:
+ """Treat a Netscape cookie file as a name-only inventory.
+
+ Cookie values are secrets: they are deliberately discarded. Only the
+ *names* survive, attached to a synthetic request, so a cookie called
+ ``file_path`` can be reviewed without exposing its value.
+ """
+ label = source_label or label
+ result = LoadResult()
+ names: List[str] = []
+ seen: set = set()
+ for line in text.splitlines():
+ line = line.rstrip("\r\n")
+ if not line or line.startswith("#"):
+ continue
+ fields = _COOKIE_SPLIT_RE.split(line)
+ if len(fields) < 7:
+ continue
+ name = sanitize_text(fields[5]).strip()
+ if not name or len(name) > 120 or name in seen:
+ continue
+ seen.add(name)
+ names.append(name)
+ if not names:
+ raise HarError(f"{label}: no cookie names found (expected a Netscape cookie file)")
+ info = URLInfo(
+ raw="https://cookies.local/",
+ scheme="https",
+ host="cookies.local",
+ port=None,
+ path="/",
+ query="",
+ )
+ result.requests.append(
+ Request(
+ url=info,
+ source_type=SOURCE_COOKIES,
+ source_label=label,
+ parameters=[
+ Parameter(name=name, value="", location=LOCATION_FORM) for name in names
+ ],
+ method="GET",
+ index=0,
+ )
+ )
+ return result
+
+
+def load_cookies_file(path: str) -> LoadResult:
+ import os
+
+ from .sources import read_text
+
+ return load_cookies(read_text(path), os.path.basename(path) or path, source_label=path)
+
+
+# ---------------------------------------------------------------------------
+# Shared helpers
+# ---------------------------------------------------------------------------
+def _merge_parameters(parameters: List[Parameter]) -> List[Parameter]:
+ """Drop duplicate (location, canonical name) pairs, keeping the first."""
+ unique: List[Parameter] = []
+ seen = set()
+ for parameter in parameters:
+ key = (parameter.location, canonical(parameter.name))
+ if key in seen:
+ continue
+ seen.add(key)
+ unique.append(parameter)
+ return unique
+
+
+# ---------------------------------------------------------------------------
+# Detection and dispatch
+# ---------------------------------------------------------------------------
+def detect_tool_format(text: str, path: str = "") -> Optional[str]:
+ """Return one of this module's format ids, or ``None``."""
+ stripped = text.lstrip("\ufeff \t\r\n")
+ lowered = (path or "").lower()
+ if stripped.startswith("{") or stripped.startswith("["):
+ try:
+ payload = json.loads(stripped)
+ except ValueError:
+ payload = None
+ if looks_like_postman(payload):
+ return INPUT_FORMAT_POSTMAN
+ if looks_like_zap(payload):
+ return INPUT_FORMAT_ZAP
+ if looks_like_graphql(payload):
+ return INPUT_FORMAT_GRAPHQL
+ if looks_like_mitm(payload):
+ return INPUT_FORMAT_MITM
+ if looks_like_cookies(text):
+ return INPUT_FORMAT_COOKIES
+ return None
+
+
+def load_tool_file(path: str, fmt: str) -> LoadResult:
+ if fmt == INPUT_FORMAT_POSTMAN:
+ return load_postman_file(path)
+ if fmt == INPUT_FORMAT_ZAP:
+ return load_zap_file(path)
+ if fmt == INPUT_FORMAT_MITM:
+ return load_mitm_file(path)
+ if fmt == INPUT_FORMAT_GRAPHQL:
+ return load_graphql_file(path)
+ if fmt == INPUT_FORMAT_COOKIES:
+ return load_cookies_file(path)
+ raise HarError(f"unsupported input format '{fmt}'")
+
+
+def load_tool_text(text: str, fmt: str, label: str) -> LoadResult:
+ if fmt == INPUT_FORMAT_POSTMAN:
+ return load_postman(text, label)
+ if fmt == INPUT_FORMAT_ZAP:
+ return load_zap(text, label)
+ if fmt == INPUT_FORMAT_MITM:
+ return load_mitm(text, label)
+ if fmt == INPUT_FORMAT_GRAPHQL:
+ return load_graphql(text, label)
+ if fmt == INPUT_FORMAT_COOKIES:
+ return load_cookies(text, label)
+ raise HarError(f"unsupported input format '{fmt}'")
+
+
+__all__ = [
+ "INPUT_FORMAT_POSTMAN",
+ "INPUT_FORMAT_ZAP",
+ "INPUT_FORMAT_MITM",
+ "INPUT_FORMAT_GRAPHQL",
+ "INPUT_FORMAT_COOKIES",
+ "detect_tool_format",
+ "load_cookies",
+ "load_graphql",
+ "load_mitm",
+ "load_postman",
+ "load_tool_file",
+ "load_tool_text",
+ "load_zap",
+]
diff --git a/pathscope/valueshape.py b/pathscope/valueshape.py
new file mode 100644
index 0000000..393918a
--- /dev/null
+++ b/pathscope/valueshape.py
@@ -0,0 +1,195 @@
+"""Value-shape demotions.
+
+A parameter called ``file`` whose value is a UUID, a hash, a JWT, a base64
+blob, an e-mail address, an IP address, or a plain bool/number/short enum is
+usually not a filesystem path. These shapes produce *negative* evidence so the
+candidate ranks lower without ever being hidden silently: the demotion rule
+name and the reason appear in ``--explain``, in every report format, and can be
+tuned with ``--rules`` or removed with ``--disable-rule``.
+
+Everything here inspects the value as an inert string. Nothing is decoded into
+a file, fetched, or resolved.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import List, Optional, Tuple
+
+#: Rule ids (kept in sync with :data:`pathscope.rules.DEFAULT_RULES`).
+RULE_UUID = "value-demote-uuid"
+RULE_HASH = "value-demote-hash"
+RULE_JWT = "value-demote-jwt"
+RULE_BASE64 = "value-demote-base64"
+RULE_EMAIL = "value-demote-email"
+RULE_IP = "value-demote-ip"
+RULE_SCALAR = "value-demote-scalar"
+
+#: A canonical UUID, either hyphenated or as 32 bare hex characters.
+UUID_RE = re.compile(
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
+ re.IGNORECASE,
+)
+UUID_BARE_RE = re.compile(r"^[0-9a-f]{32}$", re.IGNORECASE)
+#: MD5 / SHA-1 / SHA-256 / SHA-512 hex digests, or any 32+ hex run.
+HASH_RE = re.compile(r"^[0-9a-f]{32,128}$", re.IGNORECASE)
+HASH_PREFIXED_RE = re.compile(r"^(md5|sha1|sha256|sha512)[:=][0-9a-f]{32,128}$", re.IGNORECASE)
+#: Three base64url segments separated by dots.
+JWT_RE = re.compile(
+ r"^eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{8,}$"
+)
+#: Long base64-looking blob (no separators, mixed case, optional padding).
+BASE64_RE = re.compile(r"^[A-Za-z0-9+/_-]{40,}={0,2}$")
+EMAIL_RE = re.compile(r"^[^@\s/\\]{1,64}@[A-Za-z0-9.-]{3,253}$")
+#: IPv4 literal (no validation of octet ranges beyond three digits).
+IPV4_RE = re.compile(r"^\d{1,3}(?:\.\d{1,3}){3}$")
+#: Bracket-less IPv6 literal, only when it contains at least two colons.
+IPV6_RE = re.compile(r"^[0-9a-f:]{4,45}$", re.IGNORECASE)
+NUMBER_RE = re.compile(r"^-?\d{1,20}(?:\.\d{1,10})?$")
+HEX_RE = re.compile(r"^0x[0-9a-f]{1,16}$", re.IGNORECASE)
+
+#: Short, common enum-like tokens that never name a file on their own.
+ENUM_TOKENS = frozenset(
+ """
+ true false null none nil yes no on off enable enabled disable disabled
+ active inactive all any default auto public private inherit readonly
+ read write admin user guest ascending descending asc desc ascendent
+ """.split()
+)
+#: Longer enum-like tokens that are still not paths.
+ENUM_LONG_TOKENS = frozenset(
+ """
+ undefined unset unknown pending deleted archived completed failed success
+ approved rejected visible hidden internal external ephemeral
+ """.split()
+)
+
+MAX_REASON_VALUE = 40
+
+
+def _short(value: str) -> str:
+ """Short, sanitized excerpt used inside a reason string."""
+ text = value.strip()
+ if len(text) <= MAX_REASON_VALUE:
+ return text
+ return text[: MAX_REASON_VALUE - 1] + "…"
+
+
+def _looks_like_base64(value: str) -> bool:
+ """Heuristic: long, mixed-class, no separators, plausible padding."""
+ if not BASE64_RE.match(value):
+ return False
+ has_upper = any(c.isupper() for c in value)
+ has_lower = any(c.islower() for c in value)
+ has_digit = any(c.isdigit() for c in value)
+ # Require two of the three classes so long lowercase words are not demoted.
+ return sum((has_upper, has_lower, has_digit)) >= 2
+
+
+def _looks_like_ipv6(value: str) -> bool:
+ if value.count(":") < 2:
+ return False
+ if not IPV6_RE.match(value):
+ return False
+ # ``::`` compresses groups; otherwise require the full eight-group form.
+ # This rejects clock times such as ``12:30:45``.
+ if "::" in value:
+ return True
+ return len(value.split(":")) == 8
+
+
+def classify(value: str) -> Optional[Tuple[str, str]]:
+ """Return ``(rule, reason)`` for the strongest matching shape, or ``None``.
+
+ Order matters: JWT before base64, UUID before hash, e-mail before scalar.
+ """
+ text = (value or "").strip().strip("\"'")
+ if not text:
+ return None
+ if JWT_RE.match(text):
+ return RULE_JWT, "value looks like a JWT (three base64url segments) (-20)"
+ if UUID_RE.match(text):
+ return (
+ RULE_UUID,
+ f"value looks like a UUID ('{_short(text)}') rather than a path (-20)",
+ )
+ if HASH_PREFIXED_RE.match(text) or HASH_RE.match(text):
+ kind = "SHA-256" if len(text) == 64 else "a hex digest"
+ return (
+ RULE_HASH,
+ f"value looks like {kind} ('{_short(text)}') rather than a path (-18)",
+ )
+ if UUID_BARE_RE.match(text):
+ return (
+ RULE_UUID,
+ f"value looks like a bare UUID ('{_short(text)}') rather than a path (-20)",
+ )
+ if EMAIL_RE.match(text):
+ return (
+ RULE_EMAIL,
+ f"value looks like an e-mail address ('{_short(text)}') (-8)",
+ )
+ if IPV4_RE.match(text) or _looks_like_ipv6(text):
+ return RULE_IP, f"value looks like an IP address ('{_short(text)}') (-10)"
+ if text.lower() in ENUM_TOKENS:
+ return (
+ RULE_SCALAR,
+ f"value is an enum-like token ('{_short(text)}') rather than a path (-10)",
+ )
+ if text.lower() in ENUM_LONG_TOKENS or text.lower() in ("true", "false", "null"):
+ return (
+ RULE_SCALAR,
+ f"value is a boolean/state token ('{_short(text)}') (-10)",
+ )
+ if NUMBER_RE.match(text):
+ return (
+ RULE_SCALAR,
+ f"value is a plain number ('{_short(text)}') rather than a path (-10)",
+ )
+ if HEX_RE.match(text):
+ return (
+ RULE_SCALAR,
+ f"value is a numeric literal ('{_short(text)}') (-10)",
+ )
+ if _looks_like_base64(text):
+ return (
+ RULE_BASE64,
+ f"value looks like a base64 blob ({len(text)} chars) rather than a path (-12)",
+ )
+ return None
+
+
+def demotions(value: str) -> List[Tuple[str, str]]:
+ """All demotions that apply, as ``[(rule, reason)]`` (usually zero or one)."""
+ match = classify(value)
+ return [match] if match else []
+
+
+def describe_shapes() -> Tuple[str, ...]:
+ """``--help`` summary of the demotion shapes."""
+ return tuple(
+ f" {rule:<24} {reason}"
+ for rule, reason in (
+ (RULE_UUID, "UUID values"),
+ (RULE_HASH, "hex digests / prefixed hashes"),
+ (RULE_JWT, "JWTs"),
+ (RULE_BASE64, "base64 blobs"),
+ (RULE_EMAIL, "e-mail addresses"),
+ (RULE_IP, "IPv4/IPv6 literals"),
+ (RULE_SCALAR, "booleans, numbers, short enums"),
+ )
+ )
+
+
+__all__ = [
+ "RULE_UUID",
+ "RULE_HASH",
+ "RULE_JWT",
+ "RULE_BASE64",
+ "RULE_EMAIL",
+ "RULE_IP",
+ "RULE_SCALAR",
+ "classify",
+ "demotions",
+ "describe_shapes",
+]
diff --git a/pathscope/watch.py b/pathscope/watch.py
new file mode 100644
index 0000000..41808b5
--- /dev/null
+++ b/pathscope/watch.py
@@ -0,0 +1,220 @@
+"""Live re-analysis of a growing capture file (``--watch``).
+
+A proxy or browser keeps appending to a HAR file; this module re-reads it on a
+timer and reports **only** candidates that were not reported before. Nothing is
+sent, no file is opened beyond the capture the user named, and every iteration
+is a normal local parse.
+
+The loop is deliberately synchronous and easy to test: :func:`watch_once`
+performs one stable read + diffuse and returns what changed, while
+:func:`watch_forever` adds the sleeping and Ctrl-C handling.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import sys
+import time
+from dataclasses import dataclass, field
+from typing import Callable, List, Optional, Set, TextIO
+
+from .detector import AnalysisOptions, Finding, Report, analyze_requests
+from .sources import INPUT_FORMAT_AUTO, InputError, LoadResult, load_file
+
+#: Minimum and maximum accepted polling interval, in seconds.
+MIN_INTERVAL = 0.2
+MAX_INTERVAL = 3600.0
+
+
+class WatchError(RuntimeError):
+ """Raised when the watched file cannot be read."""
+
+
+@dataclass
+class WatchState:
+ """Everything the loop remembers between polls."""
+
+ seen_fingerprints: Set[str] = field(default_factory=set)
+ signature: str = ""
+ polls: int = 0
+ reports: int = 0
+ warnings: Set[str] = field(default_factory=set)
+ last_report: Optional[Report] = None
+ skipped: int = 0
+ last_size: int = -1
+
+ def note_size(self, size: int) -> bool:
+ """Return True when the file shrank (rotated/replaced) and reset state."""
+ shrank = self.last_size >= 0 and size < self.last_size
+ if shrank:
+ self.seen_fingerprints.clear()
+ self.warnings.clear()
+ self.last_size = size
+ return shrank
+
+
+def file_signature(path: str) -> str:
+ """Cheap content signature (size + mtime), used to skip unchanged polls."""
+ try:
+ info = os.stat(path)
+ except OSError as exc:
+ raise WatchError(f"cannot stat '{path}': {exc.strerror or exc}") from exc
+ return f"{info.st_size}:{info.st_mtime_ns}"
+
+
+def _content_hash(requests: List[object]) -> str:
+ digest = hashlib.sha256()
+ for request in requests:
+ digest.update(repr(getattr(request, "dedupe_key", request)).encode("utf-8", "replace"))
+ return digest.hexdigest()
+
+
+def watch_once(
+ path: str,
+ options: AnalysisOptions,
+ state: WatchState,
+ input_format: str = INPUT_FORMAT_AUTO,
+) -> tuple:
+ """One poll. Returns ``(new_findings, warnings, loaded_count, changed)``.
+
+ ``changed`` is false when the file has not moved since the previous poll, in
+ which case no parsing happens at all.
+ """
+ signature = file_signature(path)
+ if signature == state.signature:
+ return [], [], 0, False
+ state.signature = signature
+ state.polls += 1
+ size = int(signature.split(":", 1)[0])
+ rotated = state.note_size(size)
+ try:
+ loaded: LoadResult = load_file(path, input_format)
+ except InputError as exc:
+ raise WatchError(str(exc)) from exc
+ except Exception as exc: # noqa: BLE001 - partial writes are normal
+ raise WatchError(f"cannot parse '{path}': {exc}") from exc
+
+ state.skipped = loaded.skipped
+ report = analyze_requests(loaded.requests, options)
+ report.warnings = list(loaded.warnings)
+ report.skipped = loaded.skipped
+ state.last_report = report
+
+ fresh: List[Finding] = []
+ for finding in report.findings:
+ if finding.fingerprint in state.seen_fingerprints:
+ continue
+ state.seen_fingerprints.add(finding.fingerprint)
+ fresh.append(finding)
+ new_warnings = [w for w in loaded.warnings if w not in state.warnings]
+ state.warnings.update(new_warnings)
+ if rotated:
+ # A replaced capture starts a new baseline: everything in it is new.
+ state.seen_fingerprints = {finding.fingerprint for finding in fresh} | {
+ finding.fingerprint for finding in report.findings
+ }
+ if fresh:
+ state.reports += 1
+ return fresh, new_warnings, len(loaded.requests), True
+
+
+def format_watch_batch(
+ findings: List[Finding], stream: TextIO, color: bool = False
+) -> None:
+ """Print a compact one-line-per-new-candidate summary to ``stream``."""
+ for finding in findings:
+ band = finding.confidence.upper()
+ if color:
+ code = {"HIGH": "31", "MEDIUM": "33", "LOW": "36"}.get(band, "0")
+ band = f"\x1b[{code}m{band}\x1b[0m"
+ stream.write(
+ f"[new] {finding.host:<28} {finding.location:<6} "
+ f"{finding.parameter:<20} {band:<10} {finding.score:>3}/100 "
+ f"{finding.rule}\n"
+ )
+ stream.flush()
+
+
+def watch_forever(
+ path: str,
+ options: AnalysisOptions,
+ *,
+ interval: float = 2.0,
+ input_format: str = INPUT_FORMAT_AUTO,
+ stdout: Optional[TextIO] = None,
+ stderr: Optional[TextIO] = None,
+ sleep: Callable[[float], None] = time.sleep,
+ now: Callable[[], float] = time.monotonic,
+ max_polls: Optional[int] = None,
+) -> int:
+ """Poll ``path`` until interrupted (or ``max_polls`` is reached).
+
+ Returns the number of batches emitted. Ctrl-C is handled by the caller.
+ """
+ stdout = stdout or sys.stdout
+ stderr = stderr or sys.stderr
+ interval = max(MIN_INTERVAL, min(MAX_INTERVAL, float(interval)))
+ state = WatchState()
+ started = now()
+ stdout.write(
+ f"Watching {path} every {interval:g}s for new candidates. "
+ "Press Ctrl-C to stop. No requests are sent.\n"
+ )
+ stdout.flush()
+ poll_count = 0
+ shown_waiting = False
+ retries = 0
+ try:
+ while True:
+ poll_count += 1
+ try:
+ fresh, warnings, loaded, changed = watch_once(
+ path, options, state, input_format
+ )
+ except WatchError as exc:
+ retries += 1
+ # Transient failures are expected while a proxy is writing;
+ # report the first few and then stay quiet until it recovers.
+ if retries <= 3:
+ print(f"watch: {exc} (will retry)", file=stderr)
+ fresh, warnings, loaded, changed = [], [], 0, True
+ else:
+ retries = 0
+ if changed:
+ for warning in warnings:
+ print(f"warning: {warning}", file=stderr)
+ if fresh:
+ format_watch_batch(fresh, stdout)
+ shown_waiting = False
+ elif not shown_waiting:
+ stdout.write(
+ f"No candidates yet ({loaded} request(s) analyzed). "
+ "Waiting for changes...\n"
+ )
+ stdout.flush()
+ shown_waiting = True
+ if max_polls is not None and poll_count >= max_polls:
+ break
+ sleep(interval)
+ except KeyboardInterrupt:
+ stdout.write("\n")
+ elapsed = now() - started
+ stdout.write(
+ f"Stopped after {poll_count} poll(s) in {elapsed:.1f}s; "
+ f"{len(state.seen_fingerprints)} candidate(s) seen in total.\n"
+ )
+ stdout.flush()
+ return state.reports
+
+
+__all__ = [
+ "MAX_INTERVAL",
+ "MIN_INTERVAL",
+ "WatchError",
+ "WatchState",
+ "file_signature",
+ "format_watch_batch",
+ "watch_forever",
+ "watch_once",
+]
diff --git a/pathscope/writers.py b/pathscope/writers.py
index 4fecf52..9a26cbf 100644
--- a/pathscope/writers.py
+++ b/pathscope/writers.py
@@ -30,6 +30,14 @@ def writer_for_path(path: str) -> str:
)
+def writer_supports_interactive(path: str) -> bool:
+ """True when ``path`` is an HTML report that can carry the interactive UI."""
+ try:
+ return writer_for_path(path) == "html"
+ except ValueError:
+ return False
+
+
def _status(finding: Finding) -> str:
if finding.status == "known":
return "known" + (f" — {finding.note}" if finding.note else "")
@@ -265,10 +273,289 @@ def render_html(report: Report) -> str:
"""
-def write_report(path: str, report: Report) -> str:
+def write_report(path: str, report: Report, interactive: bool = False) -> str:
"""Write ``report`` to ``path`` and return the writer kind used."""
kind = writer_for_path(path)
- content = render_markdown(report) if kind == "markdown" else render_html(report)
+ if kind == "markdown":
+ content = render_markdown(report)
+ elif interactive:
+ content = render_html_interactive(report)
+ else:
+ content = render_html(report)
with open(path, "w", encoding="utf-8", newline="\n") as handle:
handle.write(content)
return kind
+
+
+# ---------------------------------------------------------------------------
+# Interactive HTML report (--save-report FILE.html --interactive)
+# ---------------------------------------------------------------------------
+#: Interactive features stay dependency-free: a small inline script only.
+INTERACTIVE_SCRIPT = """
+(function () {
+ 'use strict';
+ var table = document.getElementById('findings');
+ if (!table) { return; }
+ var rows = Array.prototype.slice.call(table.tBodies[0].rows);
+ var filter = document.getElementById('filter');
+ var confidence = document.getElementById('confidence');
+ var reviewedOnly = document.getElementById('reviewed-only');
+ var counter = document.getElementById('counter');
+ var state = {};
+
+ function loadState() {
+ try {
+ state = JSON.parse(window.localStorage.getItem('pathscope-reviewed') || '{}');
+ } catch (err) { state = {}; }
+ }
+ function saveState() {
+ try {
+ window.localStorage.setItem('pathscope-reviewed', JSON.stringify(state));
+ } catch (err) { /* storage disabled: review marks stay in-memory */ }
+ }
+ function reviewedCount() {
+ return Object.keys(state).filter(function (key) { return state[key]; }).length;
+ }
+ function apply() {
+ var needle = (filter && filter.value ? filter.value : '').toLowerCase();
+ var band = confidence && confidence.value ? confidence.value : '';
+ var only = reviewedOnly && reviewedOnly.checked;
+ var shown = 0;
+ rows.forEach(function (row) {
+ var text = row.getAttribute('data-search') || '';
+ var rowBand = row.getAttribute('data-confidence') || '';
+ var fingerprint = row.getAttribute('data-fingerprint') || '';
+ var reviewed = !!state[fingerprint];
+ row.classList.toggle('is-reviewed', reviewed);
+ var box = row.querySelector('input[type=checkbox]');
+ if (box) { box.checked = reviewed; }
+ var visible = (!band || rowBand === band) &&
+ (needle === '' || text.indexOf(needle) !== -1) &&
+ (!only || reviewed);
+ row.style.display = visible ? '' : 'none';
+ if (visible) { shown += 1; }
+ });
+ if (counter) {
+ counter.textContent = shown + ' of ' + rows.length +
+ ' shown, ' + reviewedCount() + ' marked reviewed (this browser only)';
+ }
+ }
+ rows.forEach(function (row) {
+ var box = row.querySelector('input[type=checkbox]');
+ if (!box) { return; }
+ box.addEventListener('change', function () {
+ var fingerprint = row.getAttribute('data-fingerprint') || '';
+ state[fingerprint] = box.checked;
+ saveState();
+ apply();
+ });
+ });
+ Array.prototype.forEach.call(table.querySelectorAll('th[data-sort]'), function (th) {
+ th.addEventListener('click', function () {
+ var index = parseInt(th.getAttribute('data-sort'), 10);
+ var numeric = th.getAttribute('data-numeric') === '1';
+ var ascending = th.getAttribute('data-dir') !== 'asc';
+ Array.prototype.forEach.call(table.querySelectorAll('th'), function (other) {
+ other.removeAttribute('data-dir');
+ });
+ th.setAttribute('data-dir', ascending ? 'asc' : 'desc');
+ rows.sort(function (left, right) {
+ var a = left.cells[index] ? left.cells[index].textContent.trim() : '';
+ var b = right.cells[index] ? right.cells[index].textContent.trim() : '';
+ var result = numeric ? (parseFloat(a) || 0) - (parseFloat(b) || 0) : a.localeCompare(b);
+ return ascending ? result : -result;
+ });
+ rows.forEach(function (row) { table.tBodies[0].appendChild(row); });
+ });
+ });
+ if (filter) { filter.addEventListener('input', apply); }
+ if (confidence) { confidence.addEventListener('change', apply); }
+ if (reviewedOnly) { reviewedOnly.addEventListener('change', apply); }
+ Array.prototype.forEach.call(document.querySelectorAll('[data-copy]'), function (button) {
+ button.addEventListener('click', function () {
+ var text = button.getAttribute('data-copy') || '';
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(text);
+ button.textContent = 'copied';
+ setTimeout(function () { button.textContent = 'copy'; }, 1200);
+ }
+ });
+ });
+ loadState();
+ apply();
+})();
+"""
+
+INTERACTIVE_CSS = """
+.controls { display: flex; gap: 1rem; flex-wrap: wrap; align-items: center;
+ margin: 1rem 0; }
+.controls input[type=search] { min-width: 16rem; padding: 0.35rem 0.5rem; }
+.reviewed { color: #2471a3; }
+table.sortable th[data-sort] { cursor: pointer; user-select: none; }
+table.sortable th[data-sort]:after { content: " \\2195"; color: #8888; }
+tr.is-reviewed td { opacity: 0.55; }
+.copy { font-size: 0.75rem; padding: 0.1rem 0.35rem; cursor: pointer; }
+footer { margin-top: 2rem; }
+@media print {
+ .controls, .copy { display: none; }
+ body { max-width: none; }
+ tr { page-break-inside: avoid; }
+}
+"""
+
+
+def render_html_interactive(report: Report) -> str:
+ """A self-contained, sortable/filterable HTML report.
+
+ No external assets and no network calls: the page works from ``file://``.
+ Review checkboxes are stored in ``localStorage`` on the reader's machine;
+ nothing is uploaded. Every dynamic string is escaped exactly like the
+ static report.
+ """
+ counts = report.confidence_counts
+ rows: List[str] = []
+ for finding in report.findings:
+ search = " ".join(
+ [finding.host, finding.parameter, finding.rule, finding.location]
+ + (finding.reasons if not report.show_values else [])
+ ).lower()
+ rows.append(
+ f'
Values included: {'yes' if report.show_values else 'no'}
+
+
+
+
+
+
+
+
Candidates
+{table}
+
Why each candidate was flagged
+{''.join(reasons) if reasons else '
Nothing to explain.
'}
+{resolved_block}
+{warning_block}
+
+
Generated by {PROGRAM} {_esc(__version__)}. Findings are heuristic
+candidates for manual review, not confirmed vulnerabilities. Review marks are
+stored only in this browser (localStorage) and are never sent anywhere.