reconFTW is a tool designed to perform automated recon on a target domain by running the best set of tools to perform scanning and finding out vulnerabilities
Shell bug-bountybugbountybugbounty-tooldnshackingnucleiosintpenetration-testingpentestpentest-toolpentestingreconreconnaissancescannersecuritysecurity-toolssubdomainsubdomain-enumerationvulnerabilities
docs: map existing codebase
six2dez330442f9982c
diff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.mdnew file mode 100644index 0000000..6aaf177--- /dev/null+++ b/.planning/codebase/ARCHITECTURE.md@@ -0,0 +1,312 @@+<!-- refreshed: 2026-05-13 -->+# Architecture++**Analysis Date:** 2026-05-13++## System Overview++```text+┌─────────────────────────────────────────────────────────────────────────────┐+│ reconftw.sh │+│ macOS re-exec → lib/validation.sh → lib/common.sh → lib/ui.sh │+│ → lib/parallel.sh → modules/* (all sourced on startup) │+│ getopt CLI parse → reconftw.cfg → secrets.cfg → CLI overrides re-applied │+└───────────────────────┬─────────────────────────────────────────────────────┘+ │ opt_mode dispatch (case $opt_mode)+ ┌─────────────┼────────────────────┐+ ▼ ▼ ▼+ ┌──────────┐ ┌──────────┐ ┌────────────────────────┐+ │ passive()│ │ subs_menu│ │ recon() / all() │+ │ -p │ │ -s │ │ -r / -a │+ └──────────┘ └──────────┘ │ OSINT → Subdomains │+ ▼ ▼ │ → Web Detection │+ ┌──────────┐ ┌──────────┐ │ → Web Analysis │+ │ osint() │ │webs_menu │ │ → Finalization │+ │ -n │ │ -w │ └────────────────────────┘+ └──────────┘ └──────────┘ │+ │ ▼+ │ ┌──────────────────┐+ │ │ vulns() (all/-a) │+ │ └──────────────────┘+ ▼+ ┌──────────────────────────────────────┐+ │ Module Functions (leaf operations) │+ │ modules/subdomains.sh sub_passive() │+ │ modules/web.sh webprobe_full │+ │ modules/vulns.sh xss(), sqli() │+ │ modules/osint.sh domain_info() │+ └──────────────────────────────────────┘+ │+ ▼+ ┌──────────────────────────────────────┐+ │ Per-target output tree │+ │ Recon/<domain>/{subdomains,webs, │+ │ hosts,vulns,osint,nuclei_output,...} │+ └──────────────────────────────────────┘+```++## Component Responsibilities++| Component | Responsibility | File |+|-----------|----------------|------|+| Entry point & CLI parser | getopt argument parsing, config sourcing, mode dispatch | `reconftw.sh` |+| Mode orchestration | `start`/`end`, workflow functions (`recon`, `passive`, `all`, `vulns`, `osint`, `subs_menu`, `webs_menu`, `zen_menu`, `monitor_mode`) | `modules/modes.sh` |+| Function lifecycle | `start_func`/`end_func`, checkpointing, logging, notifications, reporting, plugins, health check | `modules/core.sh` |+| Subdomain enumeration | All `sub_*` functions, `subtakeover`, `zonetransfer`, `s3buckets`, `geo_info` | `modules/subdomains.sh` |+| Web analysis | `webprobe_full`, `screenshot`, `nuclei_check`, `fuzz`, `jschecks`, `urlchecks`, `waf_checks`, and 20+ others | `modules/web.sh` |+| Vulnerability scanning | `xss`, `ssrf_checks`, `sqli`, `crlf_checks`, `lfi`, `ssti`, `smuggling`, `fuzzparams`, `nuclei_dast`, and others | `modules/vulns.sh` |+| OSINT collection | `domain_info`, `ip_info`, `emails`, `google_dorks`, `github_leaks`, `github_actions_audit`, `cloud_enum_scan`, etc. | `modules/osint.sh` |+| Shared utilities | `run_command`, `sed_i`, `deleteOutScoped`, `validate_config`, `cache_*`, `checkpoint_*`, `circuit_breaker_*`, rate-limit adaption | `modules/utils.sh` |+| Axiom/distributed mode | `axiom_launch`, `axiom_shutdown`, `axiom_selected`, `resolvers_update`, `ipcidr_target` | `modules/axiom.sh` |+| Parallel execution | `parallel_funcs`, `_throttle_jobs`, job heartbeat, progress live display, log mode output | `lib/parallel.sh` |+| Input validation/sanitization | `sanitize_domain`, `sanitize_ip`, `validate_domain`, `validate_integer`, `_sanitize_list_entry` | `lib/validation.sh` |+| Shared file/counter utilities | `ensure_dirs`, `ensure_webs_all`, `safe_backup`, `count_lines`, `safe_count`, incident tracking | `lib/common.sh` |+| UI presentation layer | `_print_status`, `_print_msg`, `_print_section`, `_print_rule`, `ui_header`, `ui_summary`, TTY detection, color management, JSONL output | `lib/ui.sh` |+| Configuration | All runtime settings (~350 variables); sourced after CLI parse | `reconftw.cfg` |++## Pattern Overview++**Overall:** Monolithic bash orchestrator with sourced modular sub-scripts++**Key Characteristics:**+- Single process: `reconftw.sh` sources all libraries and modules at startup; every function lives in the same shell environment+- No subshell isolation between modules — all state is shared via global variables+- File-based checkpointing: `called_fn_dir/.funcname` sentinel files prevent re-running completed functions across invocations+- CLI-over-config: `reconftw.cfg` provides defaults; CLI flags set `CLI_*` variables that are re-applied after config sourcing to guarantee they cannot be overwritten+- All external tool invocations go through `run_command()` which handles dry-run mode, adaptive rate limiting, axiom dispatch, and debug logging++## Layers++**Entrypoint Layer:**+- Purpose: Bootstrap, macOS re-exec, module loading, getopt CLI parsing, config sourcing, CLI override re-application, mode dispatch+- Location: `reconftw.sh`+- Contains: `normalize_vps_count_args()`, the main `while/case` getopt loop, the config `source` sequence, CLI override if-blocks, the final `case $opt_mode` dispatch+- Depends on: All libraries (sourced first), all modules (sourced second)+- Used by: End user / CI++**Library Layer (pure utilities, no recon logic):**+- Purpose: Reusable utilities with no side effects; loadable independently for tests+- Location: `lib/validation.sh`, `lib/common.sh`, `lib/ui.sh`, `lib/parallel.sh`+- Contains: Input sanitization, file helpers, UI/color/progress, parallel job management+- Depends on: Nothing (source-guarded with `_*_LOADED` pattern)+- Used by: All modules and reconftw.sh++**Module Layer (recon logic):**+- Purpose: Implement all scanning, analysis, and orchestration functions+- Location: `modules/`+- Contains: All recon, vuln, OSINT, web, subdomain functions+- Depends on: Libraries (always loaded first), `reconftw.cfg` variables, external tools on PATH+- Used by: modes.sh orchestrates all others; reconftw.sh dispatches to modes.sh++**Configuration Layer:**+- Purpose: Default runtime values for ~350 flags/paths/limits; can be overridden by `secrets.cfg` and custom config+- Location: `reconftw.cfg`, optionally `secrets.cfg`, optionally `$CUSTOM_CONFIG`+- Contains: Module enable/disable flags, tool flags, API key env-var references, paths, parallelism settings, verbosity, Axiom settings+- Depends on: Nothing+- Used by: Sourced by `reconftw.sh` between CLI parse and CLI override re-application++**Output Layer (runtime-created):**+- Purpose: Store per-target findings in a stable directory hierarchy+- Location: `Recon/<domain>/` (created at `start()` time by `modules/modes.sh`)+- Contains: Standard subdirectories listed below+- Depends on: `start()` in modes.sh creates the directory tree++## Data Flow++### Primary Recon Request Path (`-r` / `--recon`)++1. macOS re-exec with Homebrew bash if needed (`reconftw.sh:40-55`)+2. Source all libs and modules (`reconftw.sh:80-93`)+3. CLI parse via `getopt` into `while/case` loop; sanitize `-d`/`-l` inputs (`reconftw.sh:159-489`)+4. Source `reconftw.cfg` (sets ~350 defaults) (`reconftw.sh:497-500`)+5. Source optional `secrets.cfg` (`reconftw.sh:503`)+6. Re-apply all `CLI_*` overrides so config cannot clobber CLI flags (`reconftw.sh:513-578`)+7. `ui_init()` — TTY detection, color setup, log-format detection (`reconftw.sh:638`)+8. `check_critical_dependencies()` — abort if mandatory tools missing (`reconftw.sh:657-658`)+9. `start()` — create `Recon/<domain>/` tree, init log, cache, incremental state, DNS resolver, plugins (`modules/modes.sh:13-163`)+10. `recon()` — sequential/parallel dispatch across 5 module groups: OSINT → Subdomains → Web Detection → Web Analysis → Finalization (`modules/modes.sh:848-997`)+11. `end()` — AI report (optional), cleanup empty files, Faraday export, screenshot diffs, plugin end event, hotlist build, incremental report, `export_reports()`, `ui_summary()` (`modules/modes.sh:286-485`)++### Function Execution Path (every leaf module function)++1. Guard check: `if [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; then`+2. Optional config-flag guard: `&& [[ $SUBPASSIVE == true ]]`+3. `start_func "${FUNCNAME[0]}" "Description"` — timestamps, per-function start time variable, JSONL log+4. Tool invocations via `run_command <tool> <args>` — handles dry-run, axiom dispatch, adaptive rate, debug log+5. Results written to subdirectory files in `Recon/<domain>/`+6. `end_func "Description" "${FUNCNAME[0]}"` — creates checkpoint file `called_fn_dir/.funcname`, emits `_print_status` badge, records timing++### Parallel Execution Path++1. `parallel_funcs N func1 func2 ...` — launches each function in a background subshell (`lib/parallel.sh`)+2. `_throttle_jobs N` — blocks spawning until running job count < N+3. Heartbeat goroutine calls `_parallel_snapshot()` every `PARALLEL_HEARTBEAT_SECONDS`+4. On completion each job emits output via `_parallel_emit_job_output` using `PARALLEL_LOG_MODE` (summary|tail|full)+5. Exit codes aggregated; non-zero count returned so caller can set `RECON_PARTIAL_RUN=true`++### Axiom Distributed Scan Flow++1. `-v` flag sets `AXIOM=true`; `--vps-count N` sets `AXIOM_FLEET_COUNT`+2. `axiom_launch()` — calls `axiom-fleet2` to provision N VMs, then `axiom-select` (`modules/axiom.sh:122-180`)+3. Module functions detect `axiom_runtime_enabled` and dispatch via `axiom-scan` instead of local tools+4. `run_module_with_axiom_failover fn` wraps each module: if axiom fails mid-run, retries the module locally (`modules/modes.sh:656-700`)+5. `axiom_shutdown()` — tears down fleet if `AXIOM_FLEET_SHUTDOWN=true` (`modules/axiom.sh:182-197`)++**State Management:**+- Global bash variables throughout (no encapsulation). Config vars, target vars (`domain`, `dir`, `called_fn_dir`, `LOGFILE`), and result counters are all globals+- `passive()` saves/restores module-enable globals before overriding them (`modules/modes.sh:549-611`)++## Key Abstractions++**`start_func` / `end_func`:**+- Purpose: Lifecycle wrapper around every leaf scanning function+- Examples: Used in every function in `modules/subdomains.sh`, `modules/web.sh`, `modules/vulns.sh`, `modules/osint.sh`+- Pattern: `start_func "${FUNCNAME[0]}" "description"` at top; `end_func "output path" "${FUNCNAME[0]}"` at bottom; creates checkpoint file on end++**Checkpoint files (`called_fn_dir/.funcname`):**+- Purpose: Prevent re-running completed functions across multiple invocations of the same target+- Location: `Recon/<domain>/.called_fn/.funcname`+- Pattern: Each function tests `[[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]`; `end_func` writes the sentinel via `touch "$called_fn_dir/.${fn}"`++**`run_command` wrapper:**+- Purpose: Universal external-tool gate for dry-run preview, axiom dispatch, adaptive rate limiting, and debug logging+- Location: `modules/utils.sh:468`+- Pattern: All tool calls inside module functions use `run_command <binary> <args>` rather than direct invocation++**Source guard pattern:**+- Purpose: Allow modules to be sourced multiple times (test re-sourcing, `--source-only`) without re-executing+- Pattern: `[[ -n "$_FOO_LOADED" ]] && return 0` at top of each lib file (`lib/common.sh:6`, `lib/parallel.sh:6`, `lib/ui.sh:5`, `lib/validation.sh` — validation uses error-code guards instead)++**`parallel_funcs` batches:**+- Purpose: Run independent module functions concurrently up to `PARALLEL_MAX_JOBS`+- Pattern: `parallel_funcs N func_a func_b func_c` — each function spawned as a background subshell; used in `recon()`, `osint()`, `vulns()` for independent groups++**`run_module_with_axiom_failover`:**+- Purpose: Transparent axiom/local fallback wrapper — if axiom fails during a module, retries locally+- Location: `modules/modes.sh:656`+- Pattern: All module calls inside `subs_menu`, `webs_menu`, `recon`, `passive` use this wrapper++## Entry Points++**`reconftw.sh` (main execution):**+- Location: `reconftw.sh`+- Triggers: Direct execution (`./reconftw.sh -d example.com -r`)+- Responsibilities: Bootstrap, all module loading, CLI parse, config source, mode dispatch++**`--source-only` flag:**+- Location: `reconftw.sh:123-125`+- Triggers: `./reconftw.sh --source-only` (used by bats test `setup()` blocks)+- Responsibilities: Sources all modules without executing any recon++**`start()` function:**+- Location: `modules/modes.sh:13`+- Triggers: Called at the top of most workflow functions (`recon`, `subs_menu`, `passive`, `osint`, `zen_menu`)+- Responsibilities: Create output directory tree, init LOGFILE, init cache/incremental/DNS/plugins, set global `dir` and `called_fn_dir`++**`end()` function:**+- Location: `modules/modes.sh:286`+- Triggers: Called at the bottom of most workflow functions+- Responsibilities: AI report, cleanup, Faraday, screenshot diffs, plugin events, hotlist, `export_reports()`, timing summary++## Output Directory Structure++```+Recon/+└── <domain>/+ ├── subdomains/ # subdomains.txt, zonetransfer.txt, s3buckets.txt, cloud_assets.txt+ ├── hosts/ # ips.txt, ipinfo.txt, favirecon.json, web_full_info*.txt+ ├── webs/ # webs.txt, webs_all.txt, webs_uncommon_ports.txt+ ├── vulns/ # (takeover.txt lives here)+ ├── osint/ # OSINT artifacts (emails, dorks, leaks, metadata)+ ├── nuclei_output/ # info.txt, low.txt, medium.txt, high.txt, critical.txt (+ *_json.txt)+ ├── screenshots/ # *.png, hashes.txt, diff_changed.txt+ ├── js/ # JS analysis outputs+ ├── fuzzing/ # fuzzing artifacts+ ├── gf/ # URL pattern classification outputs+ ├── cms/ # CMS scanner outputs+ ├── report/ # report.json, index.html, findings.jsonl, *.csv+ ├── ai_result/ # reconftw_analysis.json (opt-in AI report)+ ├── assets.jsonl # Asset store (opt-in, ASSET_STORE=true)+ ├── debug.log # Persistent debug log+ ├── hotlist.txt # Risk-scored findings summary+ ├── .log/ # Timestamped run logs: YYYY-MM-DD_HH:MM:SS.txt+ ├── .tmp/ # Temporary working files (optionally deleted on exit)+ ├── .called_fn/ # Checkpoint sentinels (.funcname files)+ └── .incremental/ # Incremental/monitor mode state+```++## Verbosity and Output Controls++**`OUTPUT_VERBOSITY`** (set in `reconftw.cfg`, overridden by `--quiet`/`--verbose`):+- `0` (quiet): Only errors and final summary printed to terminal; banner suppressed+- `1` (normal, default): Errors + warnings printed; `notification()` info/good suppressed+- `2` (verbose): All `notification()` calls, PID info, full parallel output, `start_func` messages, `print_timing_summary`++**`PARALLEL_LOG_MODE`** (`summary`|`tail`|`full`):+- `summary`: One badge line per completed parallel job+- `tail`: Last `PARALLEL_TAIL_LINES` (default 20, doubled on failure) from each job's log+- `full`: Complete captured stdout from each job++**`LOG_FORMAT`** (`plain`|`jsonl`|`jsonl-strict`):+- `jsonl-strict`: Forces `OUTPUT_VERBOSITY=0`, emits only machine-readable JSONL++## Architectural Constraints++- **Threading:** Single-threaded bash with optional background subshells via `parallel_funcs`; `wait -n` (bash 4.3+) used for job throttling in `_throttle_jobs`+- **Global state:** All config vars, `domain`, `dir`, `called_fn_dir`, `LOGFILE`, `start`, `runtime`, `DIFF`, `AXIOM`, and hundreds of module-enable flags are module-level globals; any sourced function can read or mutate them+- **Circular imports:** None by design — reconftw.sh sources libs first, then modules in explicit dependency order (`utils.sh` → `core.sh` → `osint.sh` → `subdomains.sh` → `web.sh` → `vulns.sh` → `axiom.sh` → `modes.sh`)+- **macOS bash version:** reconftw.sh re-execs itself under Homebrew bash ≥ 4 on macOS (system bash is 3.2); `lib/parallel.sh` requires bash 4.3+ for `wait -n`+- **Working directory:** `start()` calls `cd "$dir"` (the per-target output dir) before any module function runs; all relative paths inside modules resolve against the target dir. `reconftw.sh` captures `startdir=${PWD}` before this+- **No subshell isolation per module:** Modules are sourced functions, not subprocess commands. A `return` inside a module returns from the function; an `exit` would kill the whole shell++## Anti-Patterns++### Direct external tool calls without `run_command`++**What happens:** Calling `subfinder -d $domain ...` directly instead of `run_command subfinder -d $domain ...`+**Why it's wrong:** Bypasses dry-run preview, adaptive rate limiting, axiom dispatch detection, and debug-log routing+**Do this instead:** Always use `run_command <binary> <args>` for external tool invocations inside module functions++### Writing checkpoint files manually++**What happens:** Calling `touch "$called_fn_dir/.myfunc"` directly in a function body+**Why it's wrong:** `end_func` already creates the checkpoint and also records timing, emits the status badge, and logs the JSONL event; manual touch skips all of that+**Do this instead:** Call `end_func "description" "${FUNCNAME[0]}"` — it handles the checkpoint, timing, and badge atomically++### Skipping the `[[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]` guard++**What happens:** A leaf function body runs unconditionally without the checkpoint check+**Why it's wrong:** Function will re-run on every invocation even when the target was already scanned, wasting time and API quota+**Do this instead:** Open the function body with the checkpoint guard pattern before any tool invocation++### Overriding config globals without save/restore in workflow functions++**What happens:** A workflow function sets `PORTSCAN_ACTIVE=false` globally without saving/restoring+**Why it's wrong:** The override leaks into subsequent monitor cycles or multi-domain runs+**Do this instead:** Follow the pattern in `passive()` (`modules/modes.sh:549-611`): save all overridden vars to `_saved_*` locals, restore them before returning++## Error Handling++**Strategy:** Fail-soft by default (`set +e` in `reconftw.sh`; `set -o pipefail` retained). Tool failures are logged but do not abort unless `CONTINUE_ON_TOOL_ERROR=false`.++**Patterns:**+- ERR trap in `start()` logs function name, line number, and command to `$LOGFILE` and calls `explain_err()` (`modules/modes.sh:140`)+- Non-zero exit from `parallel_funcs` increments `RECON_OSINT_PARALLEL_FAILURES` and sets `RECON_PARTIAL_RUN=true`+- `run_module_with_axiom_failover` catches axiom mid-run failures and retries locally+- Circuit-breaker helpers (`circuit_breaker_is_open`, `circuit_breaker_record_failure`) in `modules/utils.sh:1190` for persistent tool failures++## Cross-Cutting Concerns++**Logging:** `$LOGFILE` (`Recon/<domain>/.log/<date>_<time>.txt`) receives all `[timestamp] Start/End function:` lines; `$DEBUG_LOG` (`Recon/<domain>/debug.log`) receives stderr from tool invocations when `OUTPUT_VERBOSITY >= 2`. Structured JSONL logging to `$STRUCTURED_LOG_FILE` when `STRUCTURED_LOGGING=true`.++**Secret redaction:** `redact_secrets()` scrubs `REDACT_VARS` env-var values and `REGISTERED_SECRETS` raw values from any string; used in dry-run previews and xtrace lines routed through `_trace_redact_stream` (`modules/core.sh:64-103`)++**Validation:** All user-supplied domain/IP/list inputs pass through `lib/validation.sh` sanitizers (`sanitize_domain`, `sanitize_ip`, `_sanitize_list_entry`) before any use, injecting protection against command injection++**Notifications:** `notification()` in `modules/core.sh:1302` gates level+verbosity checks before printing and optionally forwards to `notify` (Slack/Telegram/Discord via the `notify` tool) when `NOTIFICATION=true`++**Plugins:** `plugins_load()` sources `plugins/*.sh` at `start()` time; `plugins_emit start|end` called at workflow boundaries (`modules/core.sh:1603`)++---++*Architecture analysis: 2026-05-13*diff --git a/.planning/codebase/CONCERNS.md b/.planning/codebase/CONCERNS.mdnew file mode 100644index 0000000..0994e10--- /dev/null+++ b/.planning/codebase/CONCERNS.md@@ -0,0 +1,376 @@+# Codebase Concerns++**Analysis Date:** 2026-05-13++---++## Security Concerns++### eval in safe_count() Legacy Fallback++**What happens:** `safe_count()` has a documented TODO fallback that runs `eval "$1"` when `$1` is not a file path.+**Files:** `lib/common.sh:760`+**Risk:** Any caller that passes a pipeline string instead of a file path triggers the `eval` branch. If that string is ever derived from external data (tool output, domain names), it becomes an injection vector.+**Current mitigation:** The `if [[ -f "$1" ]]` guard means the file path is the hot path. The eval branch is only hit for legacy callers.+**Fix approach:** Complete the `TODO: migrate remaining callers to pass file paths` at `lib/common.sh:759`. After migration, remove the `else` branch entirely.++---++### bash -lc with Config-Controlled Strings++**What happens:** `run_with_heartbeat_shell()` passes its second argument to `/bin/bash -lc "$shell_cmd"`. The axiom `AXIOM_POST_START` config variable is also executed via `bash -lc "$AXIOM_POST_START"`.+**Files:** `lib/common.sh:745`, `modules/axiom.sh:166`, `modules/core.sh:1663`, `modules/core.sh:1673`+**Risk:** `AXIOM_POST_START` comes verbatim from `reconftw.cfg`. A malicious or accidentally corrupted config value is executed as a shell command. The `run_with_heartbeat_shell` call path is also reachable with user-supplied data if a caller builds the string from tool output.+**Current mitigation:** None — these are treated as trusted config values.+**Recommendation:** Document clearly in `reconftw.cfg` that `AXIOM_POST_START` is executed as a shell command. Consider validating it against an allowlist of safe paths.++---++### Unquoted AXIOM_EXTRA_ARGS — Inconsistent Quoting++**What happens:** `AXIOM_EXTRA_ARGS` is quoted as `"$AXIOM_EXTRA_ARGS"` in some axiom-scan calls but left unquoted (bare `$AXIOM_EXTRA_ARGS`) in many others.+**Files:** `modules/subdomains.sh:672`, `modules/subdomains.sh:737`, `modules/subdomains.sh:745`, `modules/subdomains.sh:768`, `modules/subdomains.sh:1233`, `modules/subdomains.sh:1366`, `modules/subdomains.sh:1666`, `modules/subdomains.sh:1742`, `modules/subdomains.sh:1905`, `modules/subdomains.sh:1926`, `modules/subdomains.sh:1944`, `modules/subdomains.sh:1990`, `modules/subdomains.sh:2068`, `modules/web.sh`+**Risk:** Word splitting on an unquoted `$AXIOM_EXTRA_ARGS` is intentional (it must expand to multiple tokens), but this pattern is indistinguishable from accidental unquoting. A future maintainer may introduce a value with spaces that breaks argument parsing. The inconsistency (some sites quote it, some don't) makes the intent unclear.+**Fix approach:** Use a Bash array `AXIOM_EXTRA_ARGS_ARR=() ; [[ -n "$AXIOM_EXTRA_ARGS" ]] && read -ra AXIOM_EXTRA_ARGS_ARR <<< "$AXIOM_EXTRA_ARGS"` and expand as `"${AXIOM_EXTRA_ARGS_ARR[@]}"`.++---++### Axiom Mantra Module Path Stale in Axiom Branch++**What happens:** The local install path was fixed to lowercase `brosck/mantra` in commit `f64383c2`, but the axiom-exec remote install path still uses the old `Brosck/mantra` capitalization.+**Files:** `modules/web.sh:2340`+**Risk:** When running in Axiom mode the remote `go install` will fail with a 404/module-not-found error because GitHub path matching is case-sensitive for module paths. The fallback `axiom-scan` at line 2341 will then run with no module installed.+**Fix approach:** Change `github.com/Brosck/mantra@latest` to `github.com/brosck/mantra@latest` at `modules/web.sh:2340`.++---++### GitHub Token File Passed Directly on Command Line++**What happens:** `GITHUB_TOKENS` (the path to a token file) is passed as `-t "$GITHUB_TOKENS"` to tools like `github-subdomains`, `gitdorks_go`, and `github-endpoints`. The token is also extracted inline as `GH_TOKEN=$(head -n 1 "$GITHUB_TOKENS")` and passed via `--token "$GH_TOKEN"`.+**Files:** `modules/osint.sh:44`, `modules/osint.sh:49`, `modules/osint.sh:79-86`, `modules/osint.sh:275-281`, `modules/subdomains.sh:521-523`, `modules/web.sh:1902`+**Risk:** `GH_TOKEN` appearing as a CLI argument is visible in `ps aux` output for the duration of the subprocess. The token is registered via `register_secret()` for log redaction, which is correct, but the process list exposure is separate from log redaction.+**Current mitigation:** `register_secret "$GH_TOKEN"` is called before use (`modules/osint.sh:80`, `modules/osint.sh:277`). The `REDACT_VARS` array covers `GH_TOKEN` and `GITHUB_TOKEN`.+**Recommendation:** Where tools support a file path instead of a bare token (e.g., `-tf` flag in gitdorks_go), prefer the file form. Document the ps exposure in security notes.++---++### Notification Credentials Stored Plaintext in notify.conf++**What happens:** The Docker image `COPY`s `Docker/notify.conf` to `/root/.config/notify/provider-config.yaml`. Telegram API keys, Discord webhook URLs, and Slack tokens are read from this YAML file at runtime by `sendToNotify()`.+**Files:** `Docker/Dockerfile:122`, `modules/core.sh:1399-1414`, `reconftw.cfg:92`+**Risk:** If the Docker image is committed with a populated `notify.conf`, credentials are baked into the image layer. Credentials are only protected by `register_secret()` in log output — they are not encrypted at rest.+**Current mitigation:** `register_secret()` redacts values in logs. The `reconftw.cfg` comment says to use environment variables. The `secrets.cfg` auto-source pattern provides a gitignored override.+**Recommendation:** Add a `Docker/.gitignore` that ignores `notify.conf`. Document that `notify.conf` must not contain real tokens when building the image. Consider supporting env-var overrides in `sendToNotify()` analogous to the API key pattern in `reconftw.cfg:97-105`.++---++### transfer() Uploads to External bashupload.com++**What happens:** `transfer()` uploads files to `https://bashupload.com`. It is gated by `ALLOW_TRANSFER=true` (default: false, opt-in required).+**Files:** `modules/core.sh:1359-1386`+**Risk:** When `ALLOW_TRANSFER=true` and `SENDZIPNOTIFY=true`, scan results (potentially containing sensitive internal data) are uploaded to a third-party service with no authentication. Data retention and privacy policies of bashupload.com are external to this project.+**Current mitigation:** Hard opt-in via `ALLOW_TRANSFER=true` in config. Disabled by default.+**Recommendation:** Add a warning in `reconftw.cfg` that `ALLOW_TRANSFER=true` sends data to an unauthenticated external service. Document this explicitly in the README.++---++### Installer Downloads and Executes Unverified Scripts++**What happens:** `install_rust_uv()` downloads `https://sh.rustup.rs` and `https://astral.sh/uv/install.sh` to tempfiles and executes them with `sh "$_tmpfile"`. The `verify_sha256()` helper exists but is not called on these scripts.+**Files:** `install.sh:162-181`+**Risk:** If the download is intercepted (MITM, DNS hijack, CDN compromise), the executed script could contain arbitrary code. The commit `71653984` ("remove pinned versions") removed version pinning from Go tools; all 50+ Go tools now install `@latest` with no integrity check.+**Current mitigation:** Downloads are over HTTPS. `verify_sha256()` is defined but only used optionally (returns 0 if no hash tool available, `install.sh:98`).+**Recommendation:** Call `verify_sha256()` with known-good hashes for the rustup and uv bootstrappers. At minimum, document that users should verify hashes manually. Consider a lockfile or pinned versions for critical tools.++---++### sendToNotify Unquoted Variables in curl Calls++**What happens:** `$discord_url` is unquoted in the `curl` call, and `${1}` (filename) is unquoted in multiple places.+**Files:** `modules/core.sh:1410`, `modules/core.sh:1414`+**Risk:** If the Discord URL or filename contains spaces, word splitting will break the curl call or inject extra arguments. A filename with shell metacharacters could cause unexpected behavior.+**Fix approach:** Quote all variables: `"$discord_url"`, `"${1}"`, `"${slack_channel}"`.++---++## Performance Concerns++### Thread Counts Scaled by CPU Core Count Without Upper Bound++**What happens:** `FFUF_THREADS`, `HTTPX_THREADS`, `HTTPX_UNCOMMONPORTS_THREADS`, `KATANA_THREADS`, `DALFOX_THREADS`, `DNSTAKE_THREADS` are all computed as multiples of `AVAILABLE_CORES` with no maximum cap.+**Files:** `reconftw.cfg:349-355`+**Risk:** On a 64-core machine, `DALFOX_THREADS=$((64 * 15))` = 960 threads. This can overwhelm the target, trigger WAF bans, or exhaust the scanning host's file descriptor limits. `DNSTAKE_THREADS` at 10x already carries a comment noting it was reduced.+**Current mitigation:** `PORTSCAN_ACTIVE_OPTIONS` has `--max-retries 2`. Adaptive rate limiting (`ADAPTIVE_RATE_LIMIT=false` by default) can compensate but is opt-in.+**Fix approach:** Add `FFUF_THREADS_MAX`, `HTTPX_THREADS_MAX` caps in `reconftw.cfg`. Apply `min(computed, max_cap)` in the thread assignment logic.++---++### PUREDNS_WILDCARDBATCH_LIMIT at 1.5 Million++**What happens:** `PUREDNS_WILDCARDBATCH_LIMIT=1500000` controls how many unique subdomains puredns processes per wildcard batch.+**Files:** `reconftw.cfg:360`+**Risk:** Very large targets with aggressive permutation wordlists can generate millions of candidates. Processing 1.5M entries per batch is memory-intensive and can exhaust RAM on small VPS instances (the installer warns at <1GB but `MIN_DISK_SPACE_GB` is set to 2GB, not accounting for RAM).+**Recommendation:** Document in `reconftw.cfg` the approximate memory usage at this limit. Consider lowering for the `low` performance profile.++---++### DNS_BRUTE_TIMEOUT and DNS_RESOLVE_TIMEOUT Default to 0 (Disabled)++**What happens:** Both hard-timeout guards default to `0` (disabled). Long DNS brute-force runs against large wordlists can run indefinitely.+**Files:** `reconftw.cfg:387-388`+**Risk:** An interrupted (Ctrl-C) long DNS job leaves partial output files, and the checkpoint mechanism (`called_fn_dir/.funcname`) is not created on incomplete runs, so the function re-runs on next invocation with `DIFF=false`. This wastes time rather than resuming.+**Recommendation:** Set sensible defaults (e.g., `DNS_BRUTE_TIMEOUT=6h`, `DNS_RESOLVE_TIMEOUT=4h`). Document these in the performance tuning section.++---++### Python Venv Dependencies Not Validated at Startup++**What happens:** `GETJSWORDS_VENV` (default: `$SCRIPTPATH/.venv`) is tested with a Python import check at call time inside `jschecks()`. CMSeeK and JSA use hardcoded venv paths. Missing or stale venvs silently skip the step.+**Files:** `modules/web.sh:2354-2382`, `modules/web.sh:1793`, `modules/web.sh:2017`+**Risk:** If a venv is partially broken (e.g., `jsbeautifier` installed but `requests` missing), the skip is silent at verbosity < 2. Users get no output from those tools without knowing why.+**Recommendation:** Add venv health checks to `check_optional_api_keys` / `tools_installed` summary output so venv failures surface in the startup health check.++---++## Tech Debt++### TODO: Migrate safe_count Callers to File Paths++**Issue:** Documented incomplete migration leaving an `eval` fallback alive.+**Files:** `lib/common.sh:759-760`+**Impact:** The `eval` branch is a latent injection vector that grows riskier as more callers are added.+**Fix approach:** Audit all `safe_count` call sites with `grep -rn "safe_count"` and convert pipeline-passing callers to write output to a temp file first.++---++### All Go Tools Install @latest Without Version Pinning++**Issue:** Commit `71653984` ("remove pinned versions") removed all pinned Go tool versions. All ~50 tools in the `gotools` associative array now install `@latest`.+**Files:** `install.sh:292-355`, `install.sh:505`+**Impact:** A breaking upstream change in any tool (API change, renamed flag, removed feature) will silently break the corresponding module. There is no lockfile or checksum verification. CI cannot reproduce the exact tool set from a month ago.+**Fix approach:** Re-introduce pinned versions for stability-critical tools (nuclei, httpx, ffuf, puredns, subfinder). Use a `tools.lock` file pattern or a `go.sum`-style manifest.++---++### Large Monolithic Module Files++**Issue:** Core modules exceed 2000 lines, making code review, testing, and targeted edits difficult.+**Files:** `modules/web.sh` (2965 lines), `modules/subdomains.sh` (2406 lines), `modules/core.sh` (2340 lines), `modules/modes.sh` (1649 lines)+**Impact:** Grep-and-patch workflows are error-prone at this scale. Bats unit tests in `tests/unit/` cannot easily isolate individual functions without extracting them via `awk`/`sed` (see MEMORY.md note on fragile `grep -A N` extraction).+**Fix approach:** No immediate action required, but consider splitting `web.sh` into `web_analysis.sh` and `web_detection.sh` as a first step.++---++### PARALLEL_MAX_JOBS Default Not Documented in reconftw.cfg++**Issue:** `PARALLEL_MAX_JOBS=4` is the default set in `lib/parallel.sh:14` but not exposed in `reconftw.cfg`. Users cannot easily tune it via config without knowing the internal default.+**Files:** `lib/parallel.sh:14`, `reconftw.cfg:302-325`+**Impact:** Advanced users tuning parallelism miss this lever.+**Fix approach:** Add `# PARALLEL_MAX_JOBS=4 # Maximum concurrent jobs across all parallel_funcs batches` to `reconftw.cfg`.++---++### mantra Module Path Stale in axiom-exec Branch++**Issue:** See Security section above. The local tool module path was fixed but the remote `axiom-exec` install path retains the old case.+**Files:** `modules/web.sh:2340`+**Fix approach:** One-line change: `github.com/Brosck/mantra@latest` → `github.com/brosck/mantra@latest`.++---++### fray GitHub Repo No Longer Available++**Issue:** `fray` was moved from GitHub (`dalisecurity/fray`) to PyPI only. The installer has a special case for it (`install.sh:534-537`), but the `pipxtools` map still lists the old GitHub path (`dalisecurity/fray`) for display purposes.+**Files:** `install.sh:375`, `install.sh:534-537`+**Impact:** Low — the installer correctly uses `tool_url="fray"` (PyPI name) for fray. But the map entry is misleading to contributors reading the code.+**Fix approach:** Remove the `dalisecurity/fray` value from the `pipxtools` map entry since it's no longer used.++---++## Known Bugs / Reliability Issues++### Checkpoint Files Not Created on Interrupted Runs++**What happens:** `end_func()` calls `touch "$called_fn_dir/.${fn}"` to mark a function complete. If a function is interrupted (SIGINT, SIGKILL, tool crash), the checkpoint file is never written.+**Files:** `modules/core.sh:1465`+**Trigger:** Ctrl-C during a long sub-function, OOM kill of a child process, disk-full mid-run.+**Impact:** On re-run with `PRESERVE=true` the function re-executes from the beginning. For expensive functions like `sub_brute` or DNS resolution, this means hours of repeated work.+**Workaround:** `PRESERVE=false` (default) clears all checkpoints on re-run. For large scans where `PRESERVE=true` is set, interrupted functions always restart.+**Recommendation:** Write an `.inprogress_${fn}` sentinel at `start_func` time and rename it to the checkpoint at `end_func` time. On resume, detect `.inprogress_*` files as incomplete.++---++### Disk-Full Detection Is Pre-Flight Only, Not Mid-Run++**What happens:** `check_disk_space()` is called once at the start of each recon mode (`modes.sh:24`). If disk fills during a long permutation or DNS brute run, tools fail silently or write corrupt partial output.+**Files:** `modules/modes.sh:23-27`, `modules/utils.sh:419-436`+**Risk:** Partial output files without disk-full markers can cause subsequent pipeline steps to produce incorrect results (e.g., counting "0 new subdomains" when the actual output was truncated).+**Recommendation:** Periodically check disk space in long-running loops (e.g., before each subdomain resolution batch). Add a trap handler that detects `ENOSPC` write failures.++---++### Checkpoint Race Condition in Parallel Mode++**What happens:** When `parallel_funcs` runs multiple functions concurrently, each function writes its own `called_fn_dir/.funcname` and `.status_funcname` files. There is no file locking on these writes.+**Files:** `modules/core.sh:1465`, `modules/core.sh:1505-1509`, `lib/parallel.sh:397-403`+**Risk:** On NFS or certain local filesystems, concurrent `touch` + `printf` to adjacent files in the same directory can produce race conditions. More practically, if two parallel functions share a common status file name (which they don't today, but could after future refactoring), writes would clobber each other.+**Current mitigation:** Each function writes a uniquely named file (`.$funcname`), so collisions require naming conflicts. The `2>/dev/null || true` error suppression means write failures are silent.+**Recommendation:** Add a warning if `called_fn_dir` is on a network filesystem.++---++### Disk Space Config Default Mismatch++**What happens:** `MIN_DISK_SPACE_GB=2` in `reconftw.cfg:39`, but `modes.sh:23` overrides it with `${MIN_DISK_SPACE_GB:-5}` (5 GB default). The installer warns below 5 GB too. The config comment says `2` but the effective default is `5`.+**Files:** `reconftw.cfg:39`, `modules/modes.sh:23`+**Impact:** Users who read `reconftw.cfg` and see `2` may believe 2 GB is the threshold, but the modes initialization applies 5 GB unless the config value is explicitly set. Misleading documentation.+**Fix approach:** Align `reconftw.cfg:39` to `MIN_DISK_SPACE_GB=5` to match the modes.sh default, or remove the `:-5` fallback in `modes.sh` so the config value is authoritative.++---++## Fragile Areas++### Axiom Fleet Failure Modes++**What happens:** Axiom fleet operations rely on `axiom-ls`, `axiom-select`, `axiom-fleet2`, and `axiom-exec` all succeeding. Partial fleet launches (e.g., N-1 of N nodes provisioned) disable Axiom runtime and fall back to local mode without re-attempting.+**Files:** `modules/axiom.sh:122-180`+**Why fragile:** Cloud provider rate limits, SSH key distribution delays, and network timeouts all cause `axiom_launch` to return failure and invoke `axiom_disable_runtime`. There is no retry for partial fleet launches.+**Safe modification:** Always test Axiom changes with a 1-node fleet first. The `AXIOM_AUTO_FIX_HOSTKEY` mechanism (`modules/axiom.sh:227-249`) is useful but only handles the SSH host-key case, not provisioning failures.++---++### parallel_funcs Batch Flushing++**What happens:** `parallel_funcs` fills a batch to `max_jobs` then waits for all jobs in that batch to complete before starting new ones. This is a barrier synchronization, not a sliding window.+**Files:** `lib/parallel.sh:350-570`+**Why fragile:** If one function in a batch hangs (e.g., a tool that doesn't respect timeouts), the entire batch stalls. The heartbeat loop (`lib/parallel.sh:434-474`) polls alive PIDs every `PARALLEL_HEARTBEAT_SECONDS` but provides no kill mechanism for stuck jobs.+**Recommendation:** Add `PARALLEL_JOB_TIMEOUT_SECONDS` config that kills individual jobs exceeding the limit with `kill -TERM`.++---++### is_in_scope_host vs grep -E DOMAIN_MATCH_REGEX Inconsistency++**What happens:** Two scope-checking mechanisms exist in parallel: the Python-backed `is_in_scope_host()` / `filter_in_scope_hosts()` in `lib/validation.sh`, and the ERE-based `DOMAIN_MATCH_REGEX` from `domain_match_regex()` in `lib/common.sh`. Different code paths use different mechanisms.+**Files:** `lib/validation.sh:192-199`, `lib/common.sh:821-826`, `modules/subdomains.sh:194`, `modules/subdomains.sh:472`+**Risk:** The two implementations must agree on edge cases (trailing dots, wildcards, empty input). A discrepancy means a subdomain accepted by one path is rejected by the other, causing inconsistent output between runs with different code paths.+**Recommendation:** Add a test that cross-checks both mechanisms with the same corpus. Consider deprecating one in favor of the other.++---++### wait -n Requires Bash 4.3+++**What happens:** `_throttle_jobs()` uses `wait -n` to harvest background job slots.+**Files:** `lib/parallel.sh:40`+**Risk:** macOS ships Bash 3.2. The scripts re-exec with Homebrew Bash 4+ at the top of both `reconftw.sh` and `install.sh`, but this mitigation only works if Homebrew Bash is installed. On a macOS system without Homebrew (e.g., CI Docker), `wait -n` silently fails with `|| break`, which exits the throttle loop early and spawns unbounded jobs.+**Current mitigation:** `wait -n 2>/dev/null || break` — the break exits the while loop, bypassing the throttle entirely (no error, just unthrottled spawning).+**Recommendation:** Document the Homebrew Bash requirement for macOS prominently. Add a Bash version assertion before any `wait -n` call.++---++## Scaling Limits++### Resolver File Size Not Validated Before puredns Runs++**What happens:** `puredns` quality degrades sharply if the resolvers file has fewer than ~100 working resolvers. The resolver download is a soft dependency (failure emits a warning but does not abort).+**Files:** `reconftw.cfg:401-402`, `modules/modes.sh:44-46` (health check)+**Current capacity:** `PUREDNS_PUBLIC_LIMIT=5000` QPS, `PUREDNS_TRUSTED_LIMIT=400` QPS.+**Limit:** If the resolvers file has stale entries from the trickest/resolvers list, effective throughput drops. The health check (`modules/modes.sh` startup) warns if resolvers file is missing but does not count valid entries.+**Scaling path:** Enable `generate_resolvers=true` with `dnsvalidator` on VPS deployments. Document the tradeoff in `reconftw.cfg`.++---++### No Per-Target Memory Limit for Permutation Generation++**What happens:** `PERMUTATIONS_LIMIT=2147483648` (2 GB) caps permutation wordlist size before gotator runs. However, gotator and regulator load the wordlist into memory; on very large inputs the 2 GB file size limit does not directly bound RAM usage.+**Files:** `reconftw.cfg:386`+**Scaling path:** Set `PERMUTATIONS_LIMIT` to a lower value (e.g., 500 MB) on instances with less than 8 GB RAM.++---++## Dependencies at Risk++### subwiz (hadriansecurity/subwiz) — Research Tool Maturity++**Risk:** `subwiz` is an ML-based subdomain prediction tool from a security research team. Research tools often have unstable APIs, are abandoned, or break with Python updates. The tool is installed via `uv` from GitHub.+**Files:** `install.sh:370`, `modules/subdomains.sh`+**Impact:** If the GitHub repo is archived or the Python dependency tree breaks, the `subwiz` function silently skips.+**Migration plan:** Monitor upstream activity. The skip behavior on missing tool (`command -v subwiz`) means failure is non-blocking.++---++### fray (PyPI) — External Service Dependency++**Risk:** `fray` payload lists may be fetched from external sources at runtime. The PyPI-only distribution means there is no GitHub source to audit for changes.+**Files:** `install.sh:534-537`, `modules/vulns.sh:1115-1159`+**Impact:** Payload updates could introduce unexpected request patterns. The `FRAY_DELAY=0.5` and `FRAY_MAX_PAYLOADS=20` defaults limit blast radius.++---++### trufflehog — Install via go install @latest++**Risk:** trufflehog is installed via `go install` in the repos section (`install.sh:703`), not via the `gotools` map, so it has a different install path and no version pinning.+**Files:** `install.sh:703`+**Impact:** Breaking changes in trufflehog's CLI between versions can silently break the `github_leaks` function.++---++## Test Coverage Gaps++### No Tests for parallel_funcs Batch Barrier Behavior++**What's not tested:** Whether `parallel_funcs` correctly waits for all jobs in a batch, whether the heartbeat loop polls correctly, and whether job failure propagates the `failed` counter.+**Files:** `lib/parallel.sh:350-570`+**Risk:** Parallel execution bugs (jobs skipped, output interleaved incorrectly, stuck batches) go undetected.+**Priority:** High — parallel mode is default (`PARALLEL_MODE=true`).++---++### No Tests for Disk-Full Handling++**What's not tested:** Tool behavior when `df` reports 0 GB available mid-run, or when `write()` returns `ENOSPC`.+**Files:** `modules/utils.sh:419-436`, `modules/modes.sh:23-27`+**Risk:** Corrupt partial output files from truncated writes could cause false-negative security findings.+**Priority:** Medium.++---++### No Tests for axiom Failure/Fallback Path++**What's not tested:** `axiom_disable_runtime` invocation, fallback to local mode on fleet launch failure, `AXIOM_AUTO_FIX_HOSTKEY` repair logic.+**Files:** `modules/axiom.sh`+**Risk:** Axiom fallback failures are only discovered in production with a live fleet.+**Priority:** Medium — Axiom is optional, but cloud mode is a primary use case.++---++### No Integration Tests for End-to-End Module Pipelines++**What's not tested:** The pipeline from `subdomains.sh` through `web.sh` through `vulns.sh` with real (or mocked) tool output. All existing tests in `tests/unit/` test individual helper functions in isolation.+**Files:** `tests/unit/` (226+ unit tests), `tests/security/` (12 security tests)+**Risk:** Regressions in inter-module data handoff (e.g., webs.txt format changes, scope filter behavior) are undetected until manual testing.+**Priority:** High for new feature development.++---++## Documentation Gaps++### AXIOM_EXTRA_ARGS Not Documented in reconftw.cfg++`reconftw.cfg:418` sets `AXIOM_EXTRA_ARGS=""` with a single example comment. The variable is used in 20+ axiom-scan calls but there is no explanation of which axiom-scan flags are safe to pass here, or that word splitting is intentional.++### ALLOW_TRANSFER Not Present in reconftw.cfg++The `ALLOW_TRANSFER` flag is checked in `modules/core.sh:1362` and mentioned in MEMORY.md, but does not appear in `reconftw.cfg` as a commented-out option. Users must discover it by reading source code.+**Files:** `modules/core.sh:1362`, `reconftw.cfg`++### PARALLEL_MAX_JOBS Not Exposed in reconftw.cfg++See Tech Debt section above. The default of 4 is set only in `lib/parallel.sh:14`.++### RAISE_ULIMIT / ULIMIT_TARGET Not in reconftw.cfg++`RAISE_ULIMIT=true` and `ULIMIT_TARGET=65535` are referenced in `modules/modes.sh:30-32` but not exposed as config options in `reconftw.cfg`.++---++*Concerns audit: 2026-05-13*diff --git a/.planning/codebase/CONVENTIONS.md b/.planning/codebase/CONVENTIONS.mdnew file mode 100644index 0000000..0cb7c2c--- /dev/null+++ b/.planning/codebase/CONVENTIONS.md@@ -0,0 +1,281 @@+# Coding Conventions++**Analysis Date:** 2026-05-13++## Shell Settings++**Entry point** (`reconftw.sh` top of file):+```bash+set -o pipefail+set -E+set +e # fail-soft: individual commands may fail+IFS=$'\n\t'+```++**Libraries** (`lib/*.sh`) use `set -o pipefail` only — not `set -e`, because most functions return non-zero deliberately.++**Modules** (`modules/*.sh`) use NO `set` directives; they inherit from the sourcing shell.++## Source Guard Pattern++Every library file (`lib/`) begins with:+```bash+[[ -n "$_FOO_LOADED" ]] && return 0+declare -r _FOO_LOADED=1+```++Examples:+- `lib/common.sh`: `[[ -n "$_COMMON_SH_LOADED" ]] && return 0`+- `lib/parallel.sh`: `[[ -n "$_PARALLEL_SH_LOADED" ]] && return 0`+- `lib/ui.sh`: `[[ -n "${_UI_SH_LOADED:-}" ]] && return 0`++Tests that need to re-source a library must first unset the guard: `_COMMON_SH_LOADED=""`.++Modules (`modules/*.sh`) use a different guard — they check that `SCRIPTPATH` is set:+```bash+[[ -z "${SCRIPTPATH:-}" ]] && { echo "Error: This module must be sourced by reconftw.sh" >&2; exit 1; }+```++## Function Naming++**Declaration syntax:** Always use `function name() { ... }` form, never the POSIX `name() {` form.++```bash+function start_func() { ... }+function end_func() { ... }+function validate_domain() { ... }+```++Exception: `lib/ui.sh` and `lib/common.sh` helper functions omit `function` keyword to stay consistent with the POSIX-style helpers (`ui_init()`, `ensure_dirs()`, etc.). Both styles appear; prefer `function name()` for any new public API.++**Naming conventions:**+- Public module functions: `snake_case` prefixed with module context (`sub_passive`, `sub_crt`, `geo_info`)+- Private helpers: `_snake_case` prefix (`_print_status`, `_print_error`, `_print_module_start`, `_parallel_emit_job_output`)+- UI layer: `ui_` prefix (`ui_init`, `ui_header`, `ui_summary`, `ui_batch_end`)+- Lifecycle wrappers: `start_func` / `end_func` (call these at top/bottom of every recon function)+- Validation functions: `validate_*` / `sanitize_*` (defined in `lib/validation.sh` and `modules/utils.sh`)++## Variable Naming++**Globals (UPPER_SNAKE_CASE):**+- Config flags: `SUBPASSIVE`, `SUBCRT`, `PARALLEL_MODE`, `OUTPUT_VERBOSITY`+- Runtime state: `LOGFILE`, `SCRIPTPATH`, `DIFF`, `DRY_RUN`, `AXIOM`+- Error codes: `E_SUCCESS=0`, `E_INVALID_DOMAIN=20`, `E_INVALID_IP=21` (readonly, defined in `lib/validation.sh`)++**Locals (lowercase):**+```bash+local file="$1"+local domain="$2"+local count=0+```+Always declare locals with `local`. Always quote variable expansions.++**Color variables** (`bred`, `bgreen`, `bblue`, `byellow`, `yellow`, `reset`, `cyan`) are defined in `reconftw.cfg` and overridden to empty strings in no-color mode by `lib/ui.sh`.++## CLI Flag Pattern++CLI flags are captured as `CLI_*` variables during argument parsing, then re-applied AFTER `reconftw.cfg` is sourced (lines ~513-575 of `reconftw.sh`). This ensures config file defaults do not clobber command-line flags.++```bash+# During parsing (before config load):+'--quiet') CLI_OUTPUT_VERBOSITY=0 ;;+'--verbose') CLI_OUTPUT_VERBOSITY=2 ;;+'--parallel') CLI_PARALLEL_MODE=true ;;++# After config load (reconftw.sh ~line 513):+if [[ -n "${CLI_OUTPUT_VERBOSITY:-}" ]]; then+ OUTPUT_VERBOSITY="${CLI_OUTPUT_VERBOSITY}"+fi+if [[ -n "${CLI_PARALLEL_MODE:-}" ]]; then+ PARALLEL_MODE="${CLI_PARALLEL_MODE}"+fi+```++When adding a new CLI flag: add `CLI_NEWFLAG` during the `getopt` parsing loop, then add a re-apply block after config sourcing.++## Output / UI Conventions++**Status badges:** `OK`, `WARN`, `FAIL`, `SKIP`, `CACHE`, `INFO`, `RUN`++**Status line format** (dot-fill, right-aligned timing):+```+OK sub_passive 12s+WARN sub_crt 3s (no results)+SKIP sub_brute 0s+FAIL sub_dns 7s (see debug.log)+```+Produced by `_print_status STATE "func_name" "duration"` in `lib/common.sh`.++**Section headers** use thin `───` rules:+```bash+_print_section "OSINT" # calls _print_module_start()+```+Output: `── OSINT ────────────────────────────────────────────────────────────────`++**Verbosity gating:**+- `OUTPUT_VERBOSITY=0` (quiet): only errors/FAIL printed+- `OUTPUT_VERBOSITY=1` (normal, default): OK/WARN/FAIL/SKIP status lines+- `OUTPUT_VERBOSITY=2` (verbose): all of the above + INFO messages + start_func messages++The `notification()` function in `modules/core.sh` gates by level:+```bash+# error → always visible+# warn → OUTPUT_VERBOSITY >= 1+# info|good → OUTPUT_VERBOSITY >= 2+```++## Function Lifecycle (start_func / end_func)++Every recon function that runs a tool wraps its body with the lifecycle pair:++```bash+function sub_passive() {+ if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $SUBPASSIVE == true ]]; then+ start_func "${FUNCNAME[0]}" "Passive subdomain enum"+ # ... tool invocations ...+ end_func "Passive subdomain enum" "${FUNCNAME[0]}"+ else+ skip_notification "processed" # or "disabled"+ fi+}+```++- `start_func name desc` — logs to LOGFILE, sets per-function start timestamp, emits INFO at verbosity >= 2+- `end_func message name [status]` — touches checkpoint file, calculates elapsed time, calls `_print_status`+- `skip_notification reason` — emits SKIP/CACHE badge; reasons: `"disabled"`, `"mode"`, `"processed"`, `"processed-visible"`, `"noinput"`++## File Checkpointing (Resumability)++Checkpoint files under `${called_fn_dir}/` prevent functions from re-running on resume:++```bash+# Check pattern used in every module function:+if { [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; } && [[ $FLAG == true ]]; then+```++- `end_func` creates the checkpoint: `touch "$called_fn_dir/.${fn}"`+- DIFF mode (`DIFF=true`) bypasses checkpoint — forces re-execution+- Helper `should_run()` in `lib/common.sh` provides a cleaner gate: `if should_run "FLAG_VAR"; then`++## Error Handling++**`safe_count()`** in `lib/common.sh` — always returns a valid integer:+```bash+NUMOFLINES=$(safe_count "subdomains/subdomains.txt") # preferred: direct file path+```+Falls back to `eval` for legacy pipeline strings (marked TODO for migration).++**Return codes:** Functions return 0 on success, non-zero on failure. Error codes are defined as `readonly` in `reconftw.sh`:+- `E_SUCCESS=0`, `E_GENERAL=1`, `E_MISSING_DEP=2`, `E_INVALID_INPUT=3`++**`_print_error`** goes to stderr and is always visible regardless of verbosity:+```bash+_print_error "Cannot read file: $path"+```++**`print_warnf` / `print_errorf`** for formatted messages:+```bash+print_warnf "Function %s failed (rc=%d)" "$func" "$rc"+print_errorf "Invalid domain: '%s'" "$domain"+```++**`warn_once`** prevents duplicate warning spam:+```bash+warn_once "missing-tool-dnstake" "subtakeover: dnstake not found"+```++## Validation Functions++Canonical validation lives in `lib/validation.sh`. Key functions:++| Function | Purpose |+|----------|---------|+| `validate_domain()` | RFC domain check + injection character rejection |+| `validate_ipv4()` | Octet range validation |+| `validate_integer()` | Numeric range check |+| `validate_boolean()` | Accepts `true`/`false` only (not `1`/`0`/`yes`/`no`) |+| `validate_file_readable()` | Exists + readable + is-a-file |+| `sanitize_interlace_input()` | Removes shell metacharacters from input files (canonical in `lib/validation.sh`) |+| `sanitize_domain()` | Strips URL components, lowercases, rejects injection (in `modules/utils.sh`) |+| `is_in_scope_host()` | Anchored hostname scope check (prevents substring false positives) |+| `filter_in_scope_urls()` | Python3-based URL scope check (scheme, userinfo, host) |++**Injection characters blocked:** `;`, `|`, `&`, `$`, `` ` ``, `\`, `(`, `)`, `{`, `}`++Error codes for validation failures: `E_INVALID_DOMAIN=20`, `E_INVALID_IP=21`, `E_INVALID_PATH=22`, `E_INVALID_URL=23`.++## Path and CWD Conventions++Use subshells instead of `pushd`/`popd`:+```bash+# Correct:+( cd "${output_dir}" && run_tool ... )++# Never:+pushd "${output_dir}"+run_tool ...+popd+```++All `pushd`/`popd` were removed in the 2026-03 audit.++## Parallel Execution++**`parallel_funcs max_jobs func1 func2 ...`** in `lib/parallel.sh` — the canonical way to parallelize module functions:+```bash+parallel_funcs 3 sub_passive sub_crt sub_active+```++Background per-target loops use `_throttle_jobs max`:+```bash+for target in "${targets[@]}"; do+ ( process_target "$target" ) &+ _throttle_jobs "${MAX_CONCURRENT_JOBS:-4}"+done+wait+```++**PARALLEL_LOG_MODE** controls job output: `summary` (default), `tail`, `full`.++**PARALLEL_UI_MODE** controls progress display: `clean` (default), `balanced`, `trace`.++## Import / Sourcing Order++In `reconftw.sh` (lines ~80-93):+1. `lib/validation.sh`+2. `lib/common.sh`+3. `lib/ui.sh`+4. `lib/parallel.sh`+5. `modules/utils.sh`+6. `modules/core.sh`+7. `modules/osint.sh`+8. `modules/subdomains.sh`+9. `modules/web.sh`+10. `modules/vulns.sh`+11. `modules/axiom.sh`+12. `modules/modes.sh`++Libraries must not depend on modules. Modules may depend on libraries and on earlier-sourced modules.++## Logging++- All tool output redirected to `$LOGFILE`: `command ... 2>>"$LOGFILE" >/dev/null`+- Structured JSON logging via `log_json level func message [key=val]` (optional, `STRUCTURED_LOGGING=true`)+- `redact_secrets()` scrubs `REDACT_VARS` and `REGISTERED_SECRETS` from log lines+- `register_secret "$value"` must be called before logging any secret value++## Comments++Functions intended as public API receive a multi-line doc block:+```bash+# Function purpose+# Usage: func_name arg1 [arg2]+# Returns: 0 on success, N on failure+function func_name() { ... }+```++Inline `# shellcheck disable=SC2154` suppresses false-positives for variables defined in `reconftw.cfg`. Suppress only at file level with a comment explaining why.++---++*Convention analysis: 2026-05-13*diff --git a/.planning/codebase/INTEGRATIONS.md b/.planning/codebase/INTEGRATIONS.mdnew file mode 100644index 0000000..37f1d6e--- /dev/null+++ b/.planning/codebase/INTEGRATIONS.md@@ -0,0 +1,255 @@+# External Integrations++**Analysis Date:** 2026-05-13++## APIs & External Services++### Passive Subdomain Intelligence++- **subfinder** — aggregates many passive sources (configured via `~/.config/subfinder/provider-config.yaml`)+ - Supported providers include: SecurityTrails, VirusTotal, Shodan, Censys, BinaryEdge, BEVigil, Chaos/ProjectDiscovery, FOFA, ZoomEye, C99, Fullhunt, IntelX, Netlas, and others+ - Auth: each source's API key in subfinder's own config file (not reconftw.cfg)+- **crt.sh** — certificate transparency log search+ - Used in: `modules/subdomains.sh` (`sub_crt()`)+ - Query: `https://crt.sh/?q=%25.${domain}&output=json`+ - Optional time-fence filter: `DNS_TIME_FENCE_DAYS`+- **ip.thc.org** — subdomain enumeration endpoint+ - Used in: `modules/subdomains.sh` (`sub_passive()`)+ - Query: `https://ip.thc.org/sb/$domain`+- **BuildWith** — Google Analytics relationships+ - Indirectly via `analyticsrelationships` tool++### Host Intelligence & Port Data++- **Shodan** — passive port scan and internet scan data+ - Used in: `modules/web.sh` (`portscanner()`)+ - API: `https://internetdb.shodan.io/${ip}` (free tier, no key) and optional Shodan CLI+ - Auth: `SHODAN_API_KEY` env var or `reconftw.cfg`; Shodan CLI installed via `uv tool install shodan`+ - Also sourced by `smap` (passive Shodan-powered port scan tool)++### Domain & IP Intelligence++- **WhoisXML API** — reverse IP lookup, WHOIS data, IP geolocation+ - Used in: `modules/osint.sh` (`ip_info()`)+ - Endpoints:+ - `https://reverse-ip.whoisxmlapi.com/api/v1?apiKey=...`+ - `https://www.whoisxmlapi.com/whoisserver/WhoisService?apiKey=...`+ - `https://ip-geolocation.whoisxmlapi.com/api/v1?apiKey=...`+ - Auth: `WHOISXML_API` env var or `reconftw.cfg`; skipped if unset++### ProjectDiscovery Cloud Platform (PDCP)++- Used by `asnmap` for ASN-to-CIDR enumeration+ - Used in: `modules/subdomains.sh` (`sub_asn()`)+ - Auth: `PDCP_API_KEY` env var or `reconftw.cfg`; enumeration skipped if key absent++## GitHub API Usage++### Authentication++- Tokens stored one-per-line in `$HOME/Tools/.github_tokens` (`GITHUB_TOKENS` config var)+- GitLab tokens stored in `$HOME/Tools/.gitlab_tokens` (`GITLAB_TOKENS` config var)+- Tools rotate through multiple tokens to avoid rate limiting++### Tools Using GitHub Tokens++- **gitdorks_go** — GitHub code search dork automation+ - Uses `-tf "$GITHUB_TOKENS"` flag+ - Wordlists: `${tools}/gitdorks_go/Dorks/smalldorks.txt` (normal) / `medium_dorks.txt` (DEEP)+ - Configured: `GITHUB_DORKS=true`++- **github-subdomains** — subdomain discovery via GitHub search+ - Token file passed at runtime++- **github-endpoints** — endpoint extraction from GitHub repos++- **enumerepo** — GitHub org repository enumeration+ - Uses `-token-file` (temp file to avoid process list exposure)+ - Output parsed with `jq` for repo URLs++- **trufflehog** — secret scanning in cloned repos+ - Runs `trufflehog git <repo_url>` per discovered repository+ - Output: JSON per repo in `.tmp/github/`++- **ghleaks** — GitHub-wide organization-level secret search+ - Reads token from `$GITHUB_TOKENS`+ - Optional `--exhaustive` flag in DEEP mode++- **gato** — GitHub Actions artifact and workflow audit+ - Used in: `modules/osint.sh` (`github_actions_audit()`)+ - Args: `e --enum_wf_artifacts --skip_sh_runner_enum -O orgs.txt -oJ output.json`+ - Optional: `--include_all_artifact_secrets` controlled by `GATO_INCLUDE_ALL_ARTIFACT_SECRETS`+ - Auth: uses GITHUB_TOKENS++### Secrets Engine Selection++- `SECRETS_ENGINE="titus"` (default) or `"noseyparker"`+- `titus` (praetorian-inc) — Go binary, validates detected secrets against provider APIs when `SECRETS_VALIDATE=true`+- `noseyparker` — Rust binary, external dependency, must be in PATH++## Notification Integrations++All notifications are routed through **projectdiscovery/notify** with config at `~/.config/notify/provider-config.yaml`.++### Slack++- Config vars: `slack_channel`, `slack_auth` (Bearer token)+- Two paths:+ 1. In-band via `notify` (uses YAML config)+ 2. Direct file upload: `curl -F file=@${file} -F channels=${slack_channel} -H "Authorization: Bearer ${slack_auth}" https://slack.com/api/files.upload`+- Controlled by: `NOTIFICATION=true` or `SOFT_NOTIFICATION=true`, `SENDZIPNOTIFY=true`++### Telegram++- Config: YAML block under `telegram:` in `notify.conf` / provider-config.yaml+- API key: `telegram_api_key` field+- Chat ID: `telegram_chat_id` field+- Direct file send (>8MB): `curl -F document=@file https://api.telegram.org/bot${telegram_key}/sendDocument`+- Template in `Docker/notify.conf`++### Discord++- Config: YAML block under `discord:` in provider-config.yaml+- Webhook: `discord_webhook_url`+- Direct file upload via multipart POST to Discord webhook URL++### Burp Collaborator / Out-of-Band (OOB)++- For SSRF checks: `COLLAB_SERVER` env var points to a collaborator-like OOB server+- If unset, `interactsh-client` is launched automatically as fallback+- For blind XSS: `XSS_SERVER` passed to `dalfox -b` flag++### ProjectDiscovery Interactsh++- Used in: `modules/vulns.sh` (`ssrf_checks()`) when `COLLAB_SERVER` is unset+- Launched as background process: `interactsh-client &>.tmp/ssrf_callback.txt &`+- Provides `*.oast.fun` (or similar) domain for OOB callbacks++## Cloud & Distributed Scanning (Axiom / Ax Fleet)++Axiom provides distributed scanning across a fleet of cloud VPS instances.++### ax / axiom (attacksurge/ax)++- Installed to `/root/.axiom/` in Docker; uses SSH for fleet management+- Config: `~/.axiom/axiom.json`, `~/.axiom/configs/`, `~/.axiom/selected.conf`+- CLI tools: `axiom-fleet2`, `axiom-select`, `axiom-scan`, `axiom-exec`, `axiom-ls`, `axiom-rm`, `axiom-build`+- Cloud provider: configurable (DigitalOcean, AWS, GCP, Azure, Linode — depends on axiom account JSON)++### Fleet Configuration (`reconftw.cfg`)++```bash+AXIOM=false # Enable with -v flag at runtime+AXIOM_FLEET_LAUNCH=true # Spin up new fleet automatically+AXIOM_FLEET_NAME="reconFTW" # Fleet name prefix+AXIOM_FLEET_COUNT=10 # Number of VPS instances+AXIOM_FLEET_REGIONS="eu-central" # Preferred region+AXIOM_FLEET_SHUTDOWN=true # Auto-teardown after scan+AXIOM_AUTO_FIX_HOSTKEY=true # Auto-repair SSH known_hosts mismatches+AXIOM_POST_START="" # Optional post-launch hook script+AXIOM_EXTRA_ARGS="" # Extra args passed to axiom-scan calls+```++### Axiom-Scan Usage (modules that support fleet offload)++- `modules/subdomains.sh`: `sub_passive`, `sub_recursive_passive`, `sub_brute`, `s3buckets`+- `modules/vulns.sh`: `xss`, `fuzzparams`, `nuclei_dast`+- `modules/web.sh`: `portscanner` (nmap via `nmapx`), `webprobe_full`+- Resolver paths on fleet instances: `AXIOM_RESOLVERS_PATH="/home/op/lists/resolvers.txt"`, `AXIOM_RESOLVERS_TRUSTED_PATH`++## Vulnerability Management Integration++### Faraday Server++- Import scan results into Faraday vulnerability management platform+- Used in: `modules/subdomains.sh`, `modules/modes.sh`, `modules/web.sh`+- CLI: `faraday-cli tool report -w "$FARADAY_WORKSPACE" --plugin-id nuclei|nmap <file>`+- Config: `FARADAY=false` (opt-in), `FARADAY_WORKSPACE="reconftw"`+- Reports imported: nuclei JSON, nmap XML+- Dependency: `faraday-cli` must be installed separately (not installed by `install.sh`)++## AI Analysis Integration++### reconftw_ai (six2dez/reconftw_ai)++- Python script: `${tools}/reconftw_ai/reconftw_ai.py`+- Venv: `${tools}/reconftw_ai/venv/bin/python3`+- LLM backend: Ollama (local) with configurable model+- Config:+ - `AI_MODEL="llama3:8b"` — Ollama model name+ - `AI_EXECUTABLE="python3"` — fallback Python if venv absent+ - `AI_REPORT_TYPE="md"` — output format (md or txt)+ - `AI_REPORT_PROFILE="bughunter"` — prompt profile (executive, brief, bughunter)+ - `AI_MAX_CHARS_PER_FILE=50000` — truncation limit+ - `AI_REDACT=true` — redact sensitive indicators before sending to model+ - `AI_ALLOW_MODEL_PULL=false` — allow auto-pull of missing models+- Invoked from: `modules/modes.sh` (after full recon scan completes)++## DNS Resolvers Update Channels++- **Public resolvers**: downloaded from `https://raw.githubusercontent.com/trickest/resolvers/main/resolvers.txt`+- **Trusted resolvers**: from `https://gist.githubusercontent.com/six2dez/ae9ed7e5c786461868abd3f2344401b6/raw/trusted_resolvers.txt`+- **dnsvalidator**: optional generation using `https://public-dns.info/nameservers.txt` and massdns resolver lists+- Cache TTL: `CACHE_MAX_AGE_DAYS_RESOLVERS=7` days++## Nuclei Templates Update++- Templates path: `$HOME/nuclei-templates` (`NUCLEI_TEMPLATES_PATH`)+- DAST templates: `${NUCLEI_TEMPLATES_PATH}/dast`+- Auto-update (once per scan session): `nuclei -update-templates -update-template-dir ${NUCLEI_TEMPLATES_PATH}`+- Community templates via `cent` (xm1k3/cent)+- Stamp file prevents repeated updates: `.tmp/.nuclei_updated`++## File Transfer (Optional Opt-in)++- **bashupload.com** — uploads recon result archives when `ALLOW_TRANSFER=true`+ - Function: `transfer()` in `modules/core.sh`+ - Disabled by default; opt-in required to prevent accidental data exfiltration+ - Can chain with `notify`: `transfer "${file}" | notify -silent`++## CI/CD Integration++- **GitHub Actions** (`.github/workflows/tests.yml`)+ - Triggers: push, pull_request, weekly schedule (Sunday 03:00), manual dispatch+ - Jobs: `shellcheck`, `unit-fast`, `integration-smoke`, `macos-smoke`, `integration-full`+ - Ubuntu-latest and macos-latest runners+- **Docker Nightly** (`.github/workflows/docker_nightly.yml`)+ - Pushes updated Docker image automatically++## Environment Configuration++### Required for Core Operation++- None strictly required — all API key features degrade gracefully when keys are absent++### Enables Additional Features++| Variable | Feature | Where Set |+|----------|---------|-----------|+| `SHODAN_API_KEY` | Passive port scan via Shodan CLI | env or `reconftw.cfg` |+| `WHOISXML_API` | Reverse IP, WHOIS, geolocation | env or `reconftw.cfg` |+| `PDCP_API_KEY` | ASN enumeration via asnmap | env or `reconftw.cfg` |+| `XSS_SERVER` | Blind XSS callback server | env or `reconftw.cfg` |+| `COLLAB_SERVER` | SSRF/OOB callback server | env or `reconftw.cfg` |+| `slack_channel` + `slack_auth` | Slack notifications | env or `reconftw.cfg` |+| `$HOME/Tools/.github_tokens` | GitHub dorks, repos, secret scanning | token file |+| `$HOME/Tools/.gitlab_tokens` | GitLab subdomain search | token file |+| `~/.config/notify/provider-config.yaml` | Telegram/Discord/Slack via notify | notify config file |+| `~/.config/subfinder/provider-config.yaml` | All subfinder passive sources | subfinder config |++### Secrets Storage++- Preferred: environment variables (take precedence over file-based config)+- Alternative: `secrets.cfg` in repo root (gitignored, auto-sourced by `reconftw.sh`)+- Template: `secrets.cfg.example`+- GitHub tokens: multi-token file at `$HOME/Tools/.github_tokens` (one per line)+- Docker runtime: pass as `-e KEY=value` at `docker run` time; never baked into image++### Redacted at Runtime++All of the following are scrubbed from log output via `redact_secrets()` in `modules/core.sh`:+`SHODAN_API_KEY`, `WHOISXML_API`, `PDCP_API_KEY`, `GITHUB_TOKEN`, `GH_TOKEN`, `GITLAB_TOKEN`, `DISCORD_WEBHOOK_URL`, `SLACK_WEBHOOK_URL`, `SLACK_BOT_TOKEN`, `TELEGRAM_BOT_TOKEN`, `slack_auth`, `telegram_key`, `telegram_api_key`, `discord_url`, `discord_webhook_url`, `XSS_SERVER`, `COLLAB_SERVER`++---++*Integration audit: 2026-05-13*diff --git a/.planning/codebase/STACK.md b/.planning/codebase/STACK.mdnew file mode 100644index 0000000..fd094bc--- /dev/null+++ b/.planning/codebase/STACK.md@@ -0,0 +1,255 @@+# Technology Stack++**Analysis Date:** 2026-05-13++## Languages++**Primary:**+- Bash 4+ - All core framework logic (`reconftw.sh`, `modules/*.sh`, `lib/*.sh`, `install.sh`)+ - Requires Bash ≥ 4 (uses `mapfile`, associative arrays, `wait -n`)+ - macOS ships Bash 3; installer auto-re-execs with Homebrew Bash 4+ via `/opt/homebrew/bin/bash` or `/usr/local/bin/bash`+ - `set -o pipefail`, `set -E`, `set +e`, `IFS=$'\n\t'` used throughout++**Secondary:**+- Python 3.7+ - Python-backed tools (each runs in isolated `uv venv`): `dorks_hunter`, `CMSeeK`, `EmailHarvester`, `Spoofy`, `SSTImap`, `gato`, `regulator`, `reconftw_ai`, `getjswords.py`+- Go (latest, min ~1.21) - Primary binary language for ~55 security tools installed via `go install @latest`++## Runtime++**Environment:**+- Linux (Debian/Ubuntu/RHEL/Arch) or macOS (Apple Silicon / Intel)+- Docker: Ubuntu 24.04 base image (`Docker/Dockerfile`)+- ARM64/aarch64, ARMv6l/v7l, and x86_64 all supported for Go binary installs++**Shell Features Used:**+- `getopt` (GNU getopt required on macOS via `brew install gnu-getopt`)+- `nproc` / `sysctl -n hw.ncpu` for CPU core auto-detection+- `timeout` / `gtimeout` (macOS Homebrew `coreutils`)+- `gnu-sed` (macOS requires `brew install gnu-sed`)+- `gnu-coreutils` (macOS requires `brew install coreutils`)++**Package Manager:**+- Go tools: `go install` (`GOPATH=$HOME/go`, `GOROOT=/usr/local/go`)+- Python tools: `uv tool install` from GitHub (most) or PyPI (`fray`)+- Python repo venvs: `uv venv venv && uv pip install -r requirements.txt`+- Lockfile: None (always installs `@latest`)++## Frameworks++**Core:**+- No framework — pure Bash with sourced module files+- Module loading order: `lib/validation.sh` → `lib/common.sh` → `lib/ui.sh` → `lib/parallel.sh` → `modules/utils.sh` → `modules/core.sh` → `modules/osint.sh` → `modules/subdomains.sh` → `modules/web.sh` → `modules/vulns.sh` → `modules/axiom.sh` → `modules/modes.sh`++**Testing:**+- bats-core (Bash Automated Testing System)+ - 25 unit test files: `tests/unit/*.bats`+ - 3 security test files: `tests/security/*.bats`+ - Run: `bats tests/unit/`, `bats tests/security/*.bats`++**Build/Dev:**+- GNU make (`Makefile`) — test, lint, format targets+- shellcheck (error-level) — `make lint`, pre-commit hook+- shfmt (4-space indent, `-bn`, `-ci`) — `make fmt`, pre-commit hook+- pre-commit hooks defined in `.pre-commit-config.yaml`+- semgrep: `.github/workflows/semgrep.yml` (CI only)++## Key Dependencies++### Go Tools (installed via `go install @latest`)++**Subdomain Enumeration:**+- `subfinder` (projectdiscovery/subfinder) — passive multi-source subdomain discovery+- `github-subdomains` (gwen001/github-subdomains) — GitHub-based subdomain search+- `gitlab-subdomains` (gwen001/gitlab-subdomains) — GitLab-based subdomain search+- `dnstake` (pwnesia/dnstake) — subdomain takeover detection+- `puredns` (d3mondev/puredns) — mass DNS resolution with wildcard filtering+- `dnsx` (projectdiscovery/dnsx) — DNS toolkit+- `massdns` (blechschmidt/massdns) — via repo clone + build+- `dsieve` (trickest/dsieve) — subdomain filtering+- `enumerepo` (trickest/enumerepo) — GitHub org repo enumeration+- `gotator` (Josue87/gotator) — subdomain permutations+- `analyticsrelationships` (Josue87/analyticsrelationships) — Google Analytics pivoting+- `roboxtractor` (Josue87/roboxtractor) — robots.txt extractor+- `crt` (cemulus/crt) — crt.sh search+- `asnmap` (projectdiscovery/asnmap) — ASN-to-CIDR mapping+- `mapcidr` (projectdiscovery/mapcidr) — CIDR manipulation+- `smap` (s0md3v/smap) — passive Shodan-powered port scan+- `tlsx` (projectdiscovery/tlsx) — TLS certificate harvesting+- `hakip2host` (hakluke/hakip2host) — reverse IP lookup+- `cdncheck` (projectdiscovery/cdncheck) — CDN/WAF IP classification+- `hakoriginfinder` (hakluke/hakoriginfinder) — origin IP discovery behind CDN+- `inscope` (tomnomnom/hacks/inscope) — scope filtering+- `csprecon` (edoardottt/csprecon) — CSP-based subdomain discovery+- `favirecon` (edoardottt/favirecon) — favicon-based tech recon++**HTTP / Web Probing:**+- `httpx` (projectdiscovery/httpx) — multi-probe HTTP toolkit+- `katana` (projectdiscovery/katana) — web crawler+- `ffuf` (ffuf/ffuf) — web fuzzer+- `subjs` (lc/subjs) — JavaScript URL extractor+- `Gxss` (KathanP19/Gxss) — reflected XSS param finder+- `jsluice` (BishopFox/jsluice) — JS secret/URL extractor+- `sourcemapper` (denandz/sourcemapper) — JS source map extractor+- `mantra` (brosck/mantra) — JS/secret scanner+- `urlfinder` (projectdiscovery/urlfinder) — URL discovery+- `xnLinkFinder` (xnl-h4ck3r/xnLinkFinder) — via uv+- `nmapurls` (sdcampbell/nmapurls) — URL extraction from Nmap XML+- `naabu` (projectdiscovery/naabu) — fast port scanner+- `VhostFinder` (wdahlenburg/VhostFinder) — virtual host discovery+- `shortscan` (bitquark/shortscan) — IIS short filename scanner++**Vulnerability Detection:**+- `nuclei` (projectdiscovery/nuclei) — template-based scanner+- `dalfox` (hahwul/dalfox) — XSS scanner+- `crlfuzz` (dwisiswant0/crlfuzz) — CRLF injection scanner+- `Web-Cache-Vulnerability-Scanner` (Hackmanit) — web cache poisoning+- `TInjA` (Hackmanit/TInjA) — SSTI scanner+- `toxicache` (xhzeem/toxicache) — web cache poisoning+- `second-order` (mhmdiaa/second-order) — broken link/second-order injection+- `s3scanner` (sa7mon/s3scanner) — S3/GCS/Azure Blob misconfiguration+- `misconfig-mapper` (intigriti/misconfig-mapper) — third-party misconfiguration+- `sj` (BishopFox/sj) — Swagger/OpenAPI analysis+- `grpcurl` (fullstorydev/grpcurl) — gRPC reflection scanner+- `nerva` (praetorian-inc/nerva) — service fingerprinting+- `brutus` (praetorian-inc/brutus) — credential spraying+- `julius` (praetorian-inc/julius) — LLM endpoint probe+- `titus` (praetorian-inc/titus) — secrets engine++**OSINT / Recon:**+- `notify` (projectdiscovery/notify) — multi-channel notifications+- `interactsh-client` (projectdiscovery/interactsh) — OOB callback server+- `gf` (tomnomnom/gf) — URL pattern grep+- `anew` (tomnomnom/anew) — append new lines only+- `unfurl` (tomnomnom/unfurl) — URL parser+- `qsreplace` (tomnomnom/qsreplace) — querystring replacer+- `gitdorks_go` (damit5/gitdorks_go) — GitHub dork search+- `github-endpoints` (gwen001/github-endpoints) — GitHub endpoint discovery+- `cent` (xm1k3/cent) — nuclei template manager+- `trufflehog` (trufflesecurity/trufflehog) — secrets scanner (via `go install`)++**Spraying / Auth:**+- `brutespray` (x90skysn3k/brutespray) — service credential spraying++### Python Tools (installed via `uv tool install`)++- `dnsvalidator` (vortexau/dnsvalidator) — DNS resolver validation+- `interlace` (pry0cc/interlace) — parallel command runner+- `wafw00f` (EnableSecurity/wafw00f) — WAF fingerprinting+- `commix` (commixproject/commix) — command injection scanner+- `waymore` (xnl-h4ck3r/waymore) — passive URL collection+- `urless` (xnl-h4ck3r/urless) — URL deduplication+- `ghauri` (r0oth3x49/ghauri) — SQLi scanner (optional)+- `xnLinkFinder` (xnl-h4ck3r/xnLinkFinder) — deep link finder+- `xnldorker` (xnl-h4ck3r/xnldorker) — Google dorker+- `porch-pirate` (MandConsultingGroup/porch-pirate) — Postman API leaks+- `p1radup` (iambouali/p1radup) — URL deduplication+- `subwiz` (hadriansecurity/subwiz) — ML-based subdomain prediction+- `arjun` (s0md3v/Arjun) — parameter discovery+- `gqlspection` (doyensec/GQLSpection) — GraphQL deep introspection+- `postleaksNg` (six2dez/postleaksNG) — Postman public leak search+- `cewler` (roys/cewler) — web wordlist generator+- `fray` (dalisecurity/fray) — WAF-aware payload testing (PyPI)++### Repo-Clone Tools (Python venvs, run via `venv/bin/python3`)++- `dorks_hunter` (six2dez/dorks_hunter) — Google dork automation+- `CMSeeK` (Tuhinshubhra/CMSeeK) — CMS fingerprinting+- `cloud_enum` (initstring/cloud_enum) — AWS/GCP/Azure bucket enumeration+- `EmailHarvester` (maldevel/EmailHarvester) — email harvesting+- `SwaggerSpy` (UndeadSec/SwaggerSpy) — Swagger endpoint leak detection+- `LeakSearch` (JoelGMSec/LeakSearch) — credential leak search+- `Spoofy` (MattKeeley/Spoofy) — email spoofing check+- `msftrecon` (Arcanum-Sec/msftrecon) — Microsoft tenant recon+- `Scopify` (Arcanum-Sec/Scopify) — scope management+- `regulator` (cramppet/regulator) — regex-based subdomain permutations+- `SSTImap` (vladko312/SSTImap) — SSTI scanner (alternative engine)+- `gato` (praetorian-inc/gato) — GitHub Actions audit++### Repo-Clone Tools (Go build)++- `ghleaks` (dinosn/ghleaks) — GitHub-wide secret search+- `nomore403` (devploit/nomore403) — 403 bypass+- `ffufPostprocessing` (Damian89/ffufPostprocessing) — ffuf result analysis+- `JSA` (w9w/JSA) — JS analysis+- `ultimate-nmap-parser` (shifty0g/ultimate-nmap-parser) — Nmap XML parser++### System-Level Tools (apt/brew/yum)++- `nmap` — active port scanning+- `massdns` — DNS resolver (also cloned + built from source)+- `jq` — JSON processing throughout all modules+- `exiftool` (perl-Image-ExifTool) — metadata extraction+- `whois` — domain registration lookup+- `sqlmap` — SQL injection (system or via repo clone)+- `testssl.sh` (testssl/testssl.sh) — TLS/SSL misconfiguration testing+- `medusa` — credential brute-force (system install)+- `shodan` CLI — installed via `uv tool install shodan`++### Rust Tools++- `smugglex` (Cargo) — HTTP request smuggling detection+- Rustup installed from `https://sh.rustup.rs`++## Configuration++**Primary Config:**+- `reconftw.cfg` — sourced after CLI parsing; all feature flags, rate limits, timeouts, wordlist paths, API keys, thread counts+- `secrets.cfg` (gitignored, auto-sourced) — API keys and tokens separated from main config+- `secrets.cfg.example` — template showing all supported secret vars++**Config Structure:**+- Feature flags: `OSINT=true`, `SUBDOMAINS_GENERAL=true`, `VULNS_GENERAL=false`, etc.+- Rate limits: `HTTPX_RATELIMIT=150`, `NUCLEI_RATELIMIT=150`, `FFUF_RATELIMIT=0`+- Thread counts: auto-scaled via `AVAILABLE_CORES=$(nproc)` with multipliers per tool+- Timeouts: per-tool in seconds or minutes (`CMSSCAN_TIMEOUT=3600`, `SUBFINDER_ENUM_TIMEOUT=180`)+- Wordlist paths: `fuzz_wordlist`, `lfi_wordlist`, `subs_wordlist` etc. under `${WORDLISTS_DIR}`+- Output: `EXPORT_FORMAT`, `AI_REPORT_TYPE`, `ASSET_STORE`++**CLI Flag Parsing:**+- GNU `getopt` long options, parsed in `reconftw.sh` while/case loop+- All CLI overrides use `CLI_*` pattern and are re-applied after `reconftw.cfg` is sourced+- Full list from `getopt` call: `domain`, `list`, `recon`, `subdomains`, `passive`, `all`, `web`, `osint`, `zen`, `deep`, `help`, `vps`, `vps-count`, `ai`, `check-tools`, `health-check`, `quick-rescan`, `incremental`, `adaptive-rate`, `dry-run`, `parallel`, `no-parallel`, `monitor`, `monitor-interval`, `monitor-cycles`, `refresh-cache`, `gen-resolvers`, `force`, `export`, `report-only`, `no-report`, `parallel-log`, `quiet`, `verbose`, `no-color`, `log-format`, `show-cache`, `banner`, `no-banner`, `legal`++**Environment Variables:**+- `SHODAN_API_KEY`, `WHOISXML_API`, `PDCP_API_KEY`, `XSS_SERVER`, `COLLAB_SERVER` — preferred over config file+- `GOROOT`, `GOPATH`, `PATH` — extended by `reconftw.cfg` for Go and Rust binaries+- `LOGFILE` — per-target log path++**Config Presets:**+- `config/reconftw_full.cfg` — full-scan preset+- `config/reconftw_quick.cfg` — quick-scan preset+- `config/reconftw_stealth.cfg` — low-noise preset++## Build++**Go Version:**+- Default: `go1.23.6` (fetches latest from `https://go.dev/VERSION?m=text`)+- Installed to `/usr/local/go`; set `install_golang=false` in config to skip++**Python Version:**+- Minimum: Python 3.7 (enforced in `install_yum()`)+- Virtual environments per tool via `uv venv`+- Root venv at `.venv/` for `getjswords.py` and similar helpers++## Platform Requirements++**Development (Linux/macOS):**+- Bash ≥ 4.3 (for `wait -n` used in `lib/parallel.sh`)+- Go ≥ 1.21 (tools use SIV module paths like `/v2`, `/v3`)+- Python ≥ 3.7+- `uv` package manager+- Rust / Cargo (for `smugglex`)+- GNU coreutils, getopt, sed (macOS only via Homebrew)+- ~5GB free disk space for Go cache, tools, and repos+- ~1GB RAM minimum (Go compilation)++**Production (Docker):**+- Base image: `ubuntu:24.04`+- Build arg `INSTALL_AXIOM=true` (default) installs axiom fleet tooling+- Ports 85-90 exposed (for headless browser tooling)+- Runs as root (required for raw socket operations by some tools)+- Health check: `./reconftw.sh --health-check`++---++*Stack analysis: 2026-05-13*diff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.mdnew file mode 100644index 0000000..1bc0d69--- /dev/null+++ b/.planning/codebase/STRUCTURE.md@@ -0,0 +1,225 @@+# Codebase Structure++**Analysis Date:** 2026-05-13++## Directory Layout++```+reconftw/+├── reconftw.sh # Main entry point, CLI parser, module loader, mode dispatch+├── reconftw.cfg # Runtime configuration (~350 vars, sourced after CLI parse)+├── secrets.cfg.example # Template for gitignored secrets.cfg (API keys, tokens)+├── install.sh # Tool installer (~59k lines, standalone)+├── banners.txt # ASCII art banner definitions (sourced by core.sh banner_grabber)+├── Makefile # Dev targets: lint, test, format, install+│+├── lib/ # Pure utility libraries (no recon logic)+│ ├── validation.sh # Input sanitization: sanitize_domain, sanitize_ip, validate_*+│ ├── common.sh # File/dir helpers, incident tracking, count_lines, safe_count+│ ├── ui.sh # TTY detection, color management, _print_status/_print_msg, progress+│ └── parallel.sh # parallel_funcs, _throttle_jobs, live progress, job output modes+│+├── modules/ # Recon modules (sourced in dependency order)+│ ├── utils.sh # run_command, validate_config, cache_*, checkpoint_*, rate-limit+│ ├── core.sh # start_func/end_func, banner, tools_installed, logging, reporting+│ ├── osint.sh # domain_info, emails, github_leaks, cloud_enum_scan, etc.+│ ├── subdomains.sh # sub_passive, sub_brute, sub_permut, subtakeover, zonetransfer, etc.+│ ├── web.sh # webprobe_full, screenshot, nuclei_check, fuzz, jschecks, etc.+│ ├── vulns.sh # xss, sqli, ssrf_checks, lfi, ssti, smuggling, nuclei_dast, etc.+│ ├── axiom.sh # axiom_launch, axiom_shutdown, axiom_selected, resolvers_update+│ └── modes.sh # start, end, recon, passive, all, osint, vulns, subs_menu,+│ # webs_menu, zen_menu, multi_recon, monitor_mode, help+│+├── config/ # Static data files read by reconftw.cfg+│ ├── reconftw_full.cfg # Extended config preset (DEEP/all enabled)+│ ├── reconftw_quick.cfg # Quick-scan config preset+│ ├── reconftw_stealth.cfg # Stealth config preset (passive-heavy)+│ ├── sensitive_domains.txt # Domains excluded when EXCLUDE_SENSITIVE=true+│ ├── ssrf_payloads.txt # SSRF payload list for ssrf_checks()+│ ├── tls_ports.txt # TLS ports used by sub_tls() (read into TLS_PORTS var)+│ └── uncommon_ports_web.txt # Non-standard web ports (read into UNCOMMON_PORTS_WEB var)+│+├── data/ # Wordlists and pattern files+│ ├── wordlists/ # Bundled wordlist files for brute-forcing, fuzzing+│ └── patterns/ # Pattern files for URL classification (used by url_gf)+│+├── tests/ # Test suite+│ ├── unit/ # bats unit tests (25 files)+│ ├── security/ # bats security/integration tests (14 files)+│ ├── fixtures/ # Static test fixture files+│ ├── helpers/ # Shared bats helper scripts+│ ├── mocks/ # Mock tool stubs for isolated unit testing+│ ├── run_tests.sh # Test runner wrapper+│ ├── check_artifacts.sh # Verify expected output files exist after a run+│ └── check_artifacts_all.sh+│+├── Recon/ # Runtime output root (created if missing)+│ └── <domain>/ # Per-target output tree (created by start() in modes.sh)+│+├── Docker/ # Dockerfile and docker-compose definitions+├── Terraform/ # Cloud provisioning for Axiom/VPS infrastructure+├── Proxmox/ # Proxmox VM provisioning scripts+├── documentation/ # Extended docs (tool explanations, workflow diagrams)+├── docs/ # mkdocs or similar documentation source+├── images/ # Screenshots used in README.md+├── .cache/ # Runtime cache (resolvers, wordlists, tool metadata; gitignored)+│ ├── resolvers/+│ ├── tools/+│ └── wordlists/+├── .github/ # GitHub Actions workflows and issue templates+├── .planning/ # GSD planning artifacts (codebase maps, phase plans)+└── .venv/ # Python virtualenv for getjswords.py and similar tools+```++## Directory Purposes++**`lib/`:**+- Purpose: Pure, reusable utilities with no recon side effects; safe to source in test harnesses+- Contains: 4 files: `validation.sh`, `common.sh`, `ui.sh`, `parallel.sh`+- Key files: `lib/ui.sh` (all terminal output primitives), `lib/parallel.sh` (all parallel job management)+- Source order: loaded first in `reconftw.sh` before any modules++**`modules/`:**+- Purpose: All reconnaissance, analysis, and orchestration logic+- Contains: 8 files loaded in strict dependency order: `utils.sh` → `core.sh` → `osint.sh` → `subdomains.sh` → `web.sh` → `vulns.sh` → `axiom.sh` → `modes.sh`+- Key files: `modules/core.sh` (function lifecycle), `modules/modes.sh` (all workflow orchestration), `modules/subdomains.sh` (largest enumeration module, 2406 lines)++**`config/`:**+- Purpose: Static configuration presets and data tables; machine-readable by reconftw.cfg+- Contains: 3 cfg preset files (full/quick/stealth), 4 data text files (sensitive_domains, ssrf_payloads, tls_ports, uncommon_ports_web)+- Usage: Preset cfgs passed via `-f config/reconftw_quick.cfg`; data files loaded with `cat ... | tr -d '\n'` in `reconftw.cfg`++**`data/`:**+- Purpose: Bundled wordlists and URL-pattern files shipped with the tool+- Contains: `wordlists/` (brute-force and fuzzing lists), `patterns/` (gf pattern files for url_gf)+- Referenced via `WORDLISTS_DIR="${DATA_DIR}/wordlists"` and `PATTERNS_DIR="${DATA_DIR}/patterns"` set in `reconftw.cfg`++**`tests/`:**+- Purpose: Automated test suite using the bats framework+- Contains: Unit tests (`tests/unit/`), security/integration tests (`tests/security/`), fixtures, helpers, mocks+- Run with: `bats tests/unit/` or `bats tests/security/` or `make test`++**`Recon/`:**+- Purpose: Runtime output root; all per-target output directories are created here+- Contains: Per-domain subdirectories created by `start()` in `modules/modes.sh`+- Generated: Yes, created at runtime+- Committed: Only example outputs committed to repo for illustration++**`.cache/`:**+- Purpose: Resolver lists and wordlist caches managed by `cache_init`/`cache_clean`/`cached_download_typed` in `modules/utils.sh`+- Contains: Downloaded resolver files, wordlists, tool metadata+- Generated: Yes+- Committed: No (in `.gitignore`)++## Key File Locations++**Entry Points:**+- `reconftw.sh`: Main executable; source all libs/modules, parse CLI, dispatch to modes++**Configuration:**+- `reconftw.cfg`: All default settings; sourced at `reconftw.sh:497`+- `secrets.cfg` (gitignored): API keys and tokens; auto-sourced if present at `reconftw.sh:503`+- `config/reconftw_quick.cfg`, `config/reconftw_full.cfg`, `config/reconftw_stealth.cfg`: Preset profiles++**Core Logic:**+- `modules/modes.sh`: Workflow entry points (`start`, `end`, `recon`, `all`, `passive`, `osint`, etc.)+- `modules/core.sh`: `start_func`, `end_func`, `notification`, `generate_consolidated_report`, `export_reports`, `health_check`+- `modules/utils.sh`: `run_command`, `validate_config`, cache helpers, circuit breaker, checkpoint system++**Testing:**+- `tests/unit/`: 25 bats test files covering specific functions+- `tests/security/`: 14 bats test files covering injection, redaction, scope, full-flow smoke tests+- `tests/run_tests.sh`: Convenience runner++**Documentation:**+- `README.md`: Primary end-user documentation+- `CONTRIBUTING.md`: Contributor guide+- `CHANGELOG.md`: Version history+- `documentation/`: Extended per-module documentation++## Naming Conventions++**Files:**+- Module scripts: lowercase `<module>.sh` in `modules/` (e.g., `subdomains.sh`, `vulns.sh`)+- Library scripts: lowercase `<name>.sh` in `lib/` (e.g., `common.sh`, `ui.sh`)+- Config preset files: `reconftw_<profile>.cfg` in `config/`+- Test files: `test_<subject>.bats` in `tests/unit/` and `tests/security/`++**Functions:**+- Leaf recon functions: `lowercase_snake_case` matching the subject tool or technique (e.g., `sub_passive`, `webprobe_full`, `github_leaks`, `nuclei_check`)+- Lifecycle functions: `start_func` / `end_func` / `start_subfunc` / `end_subfunc`+- Internal helpers with underscore prefix: `_subdomains_init`, `_subdomains_enumerate`, `_print_status`, `_throttle_jobs`+- Workflow orchestrators: verb-noun or noun-only (`recon`, `passive`, `subs_menu`, `webs_menu`, `all`, `osint`, `vulns`)++**Configuration Variables:**+- Module enable/disable flags: `UPPERCASE_SCREAMING_SNAKE_CASE` (e.g., `SUBPASSIVE=true`, `VULNS_GENERAL=false`)+- Tool-specific settings: `TOOLNAME_SETTING` (e.g., `NUCLEI_SEVERITY`, `FFUF_RATELIMIT`, `PUREDNS_PUBLIC_LIMIT`)+- CLI override intermediates: `CLI_` prefix (e.g., `CLI_OUTPUT_VERBOSITY`, `CLI_PARALLEL_MODE`, `CLI_AXIOM_FLEET_COUNT`)+- Parallel batch sizing: `PAR_MODULE_GROUP_SIZE` (e.g., `PAR_OSINT_GROUP1_SIZE`, `PAR_VULNS_GROUP2_SIZE`)++## Where to Add New Code++**New leaf recon function (e.g., a new scanning tool):**+- Implementation: Add `function my_tool()` in the relevant module — `modules/subdomains.sh` for enumeration, `modules/web.sh` for web analysis, `modules/vulns.sh` for vuln checks, `modules/osint.sh` for OSINT+- Pattern: Open with checkpoint guard `if [[ ! -f "$called_fn_dir/.${FUNCNAME[0]}" ]] || [[ $DIFF == true ]]; then`, call `start_func "${FUNCNAME[0]}" "Description"`, use `run_command <tool>`, call `end_func "output path" "${FUNCNAME[0]}"`. Close with `fi`.+- Config flag: Add `MYTOOL=true` to `reconftw.cfg`; guard function body with `&& [[ $MYTOOL == true ]]`+- Wiring: Add call to `recon()` or appropriate workflow function in `modules/modes.sh`; wrap with `run_module_with_axiom_failover my_tool` or include in a `parallel_funcs` group++**New workflow mode:**+- Implementation: Add a new `function mymode()` in `modules/modes.sh` following the `start()` / module-calls / `end()` pattern+- Wiring: Add a new `opt_mode` letter and CLI flag in `reconftw.sh` getopt string and `while/case` loop; add the mode dispatch case in the final `case $opt_mode` block++**New configuration variable:**+- Add to `reconftw.cfg` with a descriptive inline comment+- If it can be set via CLI, add a `CLI_MYVAR=""` pre-parse init, a `--my-flag` option to the getopt string, a `case` arm in the CLI parse loop that sets `CLI_MYVAR`, and a re-application block after config sourcing (`reconftw.sh:513-578` pattern)++**New utility function:**+- Pure utilities (no recon side effects, usable in tests): Add to `lib/common.sh`+- Input validation/sanitization: Add to `lib/validation.sh`+- UI/display: Add to `lib/ui.sh`+- Recon-specific helpers used across multiple modules: Add to `modules/utils.sh`++**New test:**+- Unit test for a utility/lib function: Add `test_<subject>.bats` to `tests/unit/`+- Security or integration test: Add `test_<subject>.bats` to `tests/security/`+- Tests source the full script via `source "$project_root/reconftw.sh" --source-only` in the `setup()` block (see `tests/unit/test_utils.bats:17`)++## Special Directories++**`Recon/<domain>/`:**+- Purpose: Complete per-target output for a recon run+- Generated: Yes (created by `start()` in `modules/modes.sh:92`)+- Committed: No (example directories exist in repo for illustration only)+- Subdirectories created at start time: `.log`, `.tmp`, `webs`, `hosts`, `vulns`, `osint`, `screenshots`, `subdomains`++**`Recon/<domain>/.called_fn/`:**+- Purpose: Checkpoint sentinel files (`.funcname`) that prevent function re-execution on subsequent runs+- Generated: Yes+- Committed: No+- Cleared by: `--force` flag removes all sentinels; `DIFF=true` causes functions to run regardless++**`Recon/<domain>/.tmp/`:**+- Purpose: Intermediate working files used within and between module functions+- Generated: Yes+- Committed: No+- Cleaned by: `REMOVETMP=true` config option calls `rm -rf -- "$dir/.tmp"` in `end()`++**`Recon/<domain>/.incremental/`:**+- Purpose: State files for incremental/monitor mode (baseline snapshots, alert fingerprints)+- Generated: Yes, when `INCREMENTAL_MODE=true` or `--monitor`+- Committed: No++**`.cache/`:**+- Purpose: Cached resolvers and wordlists managed by `cache_init`/`cached_download_typed` in `modules/utils.sh`+- Generated: Yes+- Committed: No (gitignored)+- Cleaned by: `cache_clean "$CACHE_MAX_AGE_DAYS"` called in `start()`++**`plugins/` (optional, not committed):**+- Purpose: User-supplied shell scripts sourced at `start()` time via `plugins_load()`; receive `reconftw_plugins start|end domain dir` events+- Generated: User-created+- Committed: No (not in default repo; users create this directory)++---++*Structure analysis: 2026-05-13*diff --git a/.planning/codebase/TESTING.md b/.planning/codebase/TESTING.mdnew file mode 100644index 0000000..5b50e6c--- /dev/null+++ b/.planning/codebase/TESTING.md@@ -0,0 +1,376 @@+# Testing Patterns++**Analysis Date:** 2026-05-13++## Test Framework++**Runner:**+- [bats-core](https://github.com/bats-core/bats-core) (Bash Automated Testing System)+- Config: none (no `bats.run.yaml`; runner invoked directly via `tests/run_tests.sh`)++**Assertion library:**+- Built-in bats `[ ]` / `[[ ]]` expressions plus bats `run` command++**Run Commands:**+```bash+./tests/run_tests.sh --unit # Unit tests only (fastest, CI default)+./tests/run_tests.sh --smoke # Integration smoke subset+./tests/run_tests.sh --integration # Full integration suite+./tests/run_tests.sh --all # Unit + full integration+bats tests/unit/ # Run all unit tests directly+bats tests/unit/test_common.bats # Run single file+bats tests/security/ # Security tests only+```++**Requires bash >= 4** (bats shell auto-detected in `tests/run_tests.sh`; macOS re-execs with Homebrew bash).++## Test File Organization++**Layout:**+```+tests/+├── unit/ # 246 @test blocks across 22 files+├── integration/ # 71 @test blocks across 10 files+├── security/ # 34 @test blocks across 3 files+├── fixtures/ # Expected output snapshots (ui/ and monitor_cycle*)+├── helpers/ # Shared setup helper (common.bash)+├── mocks/ # Executable mock scripts for external tools+└── run_tests.sh # Test runner with --unit / --smoke / --integration+```++**Naming:**+- Files: `test_<area>.bats` (e.g., `test_common.bats`, `test_sanitize.bats`)+- Tests: `@test "verb noun expected behavior"` — plain English description++## Test File Structure++Every `.bats` file follows this structure:+```bash+#!/usr/bin/env bats++setup() {+ # Create temp dir, set up PATH, source libraries+ TEST_DIR=$(mktemp -d)+ cd "$TEST_DIR" || exit 1+ # ... mock and library setup+}++teardown() {+ cd /+ rm -rf "$TEST_DIR"+}++# Group related tests with section comments+###############################################################################+# feature area tests+###############################################################################++@test "description of what should happen" {+ run function_under_test "arg"+ [ "$status" -eq 0 ]+ [[ "$output" == *"expected"* ]]+}+```++`teardown()` always does `cd /` before `rm -rf "$TEST_DIR"` to avoid cwd-deletion issues.++## Two Setup Patterns++### Pattern 1: Isolated library testing (unit tests for lib/)++Source only the specific library. Create a `TEST_DIR` and set up mocks inline:+```bash+setup() {+ source "${BATS_TEST_DIRNAME}/../../lib/common.sh"+ TEST_DIR=$(mktemp -d)+ MOCK_BIN="${TEST_DIR}/mockbin"+ ORIG_PATH="$PATH"+ mkdir -p "$MOCK_BIN"+ create_mock_anew # defined in setup or as helper+ export PATH="${MOCK_BIN}:$ORIG_PATH"+ cd "$TEST_DIR" || exit 1+ yellow="" reset="" bred="" cyan="" # stub color vars+ called_fn_dir="$TEST_DIR/.called_fn"+ LOGFILE="$TEST_DIR/test.log"+ DRY_RUN=false+}+teardown() {+ PATH="$ORIG_PATH"+ cd /+ rm -rf "$TEST_DIR"+}+```+See `tests/unit/test_common.bats` and `tests/unit/test_parallel.bats`.++### Pattern 2: Full reconftw source (module/integration tests)++Uses `tests/helpers/common.bash` or inline equivalent — sources `reconftw.sh --source-only`:+```bash+setup() {+ local project_root+ project_root="$(cd "$(dirname "$BATS_TEST_FILENAME")/../.." && pwd)"+ export tools="$HOME/Tools"+ export LOGFILE="/dev/null"+ export bred='' bblue='' bgreen='' byellow='' yellow='' reset=''+ export NOTIFICATION=false+ export AXIOM=false+ source "$project_root/reconftw.cfg" 2>/dev/null || true+ export SCRIPTPATH="$project_root"+ source "$project_root/reconftw.sh" --source-only+}+```+The `--source-only` flag in `reconftw.sh` causes immediate `return 0` before any execution. After sourcing, all functions are available for testing.+See `tests/unit/test_sanitize.bats`, `tests/security/test_injection.bats`.++### Pattern 3: Extracting individual functions from modules++For testing functions from `modules/core.sh` without triggering the full module:+```bash+# In setup():+eval "$(sed -n '/^function notification()/,/^}/p' "$corefile")"+eval "$(sed -n '/^function start_func()/,/^}/p' "$corefile")"+eval "$(sed -n '/^function end_func()/,/^}/p' "$corefile")"+```+Use `sed -n '/^function name()/,/^}/p'` — NOT `grep -A N` (fragile to line count changes).+See `tests/unit/test_verbosity.bats`.++### Pattern 4: awk extraction for non-function blocks++For extracting variable declarations and multi-block sequences from `modules/core.sh`:+```bash+awk '/^REDACT_VARS=\(/,/^\)/ {print}+ /^REGISTERED_SECRETS=\(\)$/ {print}+ /^function register_secret\(\)/,/^}$/ {print}+ /^function redact_secrets\(\)/,/^}$/ {print}' \+ "$project_root/modules/core.sh" > "$BATS_TMPDIR/_redact.sh"+source "$BATS_TMPDIR/_redact.sh"+```+See `tests/security/test_redact_secrets.bats`.++## Mocking++### PATH Manipulation++The primary mocking strategy: place stub executables in a `MOCK_BIN` directory prepended to `PATH`.++```bash+MOCK_BIN="${TEST_DIR}/mockbin"+mkdir -p "$MOCK_BIN"+export PATH="${MOCK_BIN}:$ORIG_PATH"+```++Restore `PATH` in `teardown()`: `PATH="$ORIG_PATH"`.++### Inline Mock Creation++Mocks written inline in `setup()` or a helper function:+```bash+create_mock_anew() {+ cat >"${MOCK_BIN}/anew" <<'EOF'+#!/usr/bin/env bash+set -euo pipefail+quiet=false+if [[ "${1:-}" == "-q" ]]; then+ quiet=true; shift+fi+target="${1:-}"+touch "$target"+added=0+while IFS= read -r line; do+ [[ -z "$line" ]] && continue+ if ! grep -Fxq "$line" "$target"; then+ echo "$line" >>"$target"+ added=1+ [[ "$quiet" != true ]] && echo "$line"+ fi+done+[[ "$added" -eq 0 ]] && exit 1+exit 0+EOF+ chmod +x "${MOCK_BIN}/anew"+}+```++### Persistent Mocks (`tests/mocks/`)++Pre-built mock scripts checked into `tests/mocks/`:+- `tests/mocks/subfinder` — returns predefined subdomain list+- `tests/mocks/httpx` — returns predefined HTTP probe results+- `tests/mocks/sleep` — no-op (speeds up timing-sensitive tests)++Add `tests/mocks/` to PATH when needed: `export PATH="$SCRIPTPATH/tests/mocks:$PATH"`.++### Stub Functions++For functions called by the code under test that don't need to do anything:+```bash+getElapsedTime() { runtime="0s"; }+record_func_timing() { :; }+log_json() { :; }+```+Defined inline in `setup()`.++### Notify Mock++For notification integration tests:+```bash+create_mock_notify() {+ cat >"$MOCK_BIN/notify" <<'EOF'+#!/usr/bin/env bash+cat >>"${NOTIFY_LOG}"+EOF+ chmod +x "$MOCK_BIN/notify"+}+# Test verifies: [ -s "$NOTIFY_LOG" ] and grep -Fq "[INFO] msg - domain" "$NOTIFY_LOG"+```++## Fixtures++**Location:** `tests/fixtures/`++**UI snapshot fixtures** (`tests/fixtures/ui/`):+- `full_v0.txt`, `full_v1.txt`, `full_v2.txt` — expected output for verbosity 0/1/2 in full mode+- `subdomains_v0.txt`, `subdomains_v1.txt`, `subdomains_v2.txt` — for subdomain mode++Snapshot comparison in `tests/unit/test_ui_snapshots.bats`:+```bash+normalize_output() {+ sed -E 's/[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}/<TS>/g'+}+assert_fixture() {+ run generate_snapshot "$mode_char" "$verbosity"+ local normalized expected+ normalized="$(printf '%s\n' "$output" | normalize_output)"+ expected="$(cat "$fixture_path")"+ if [[ "$normalized" != "$expected" ]]; then+ diff -u <(printf '%s' "$expected") <(printf '%s' "$normalized")+ return 1+ fi+}+```+Timestamps are normalized to `<TS>` before comparison. If UI output changes intentionally, update fixtures to match.++**Monitor fixtures** (`tests/fixtures/monitor_cycle1/`, `monitor_cycle2/`):+- Pre-populated subdomain, web, and nuclei output files for monitor-mode diff tests.++## Test Counts++| Suite | Files | Tests |+|-------|-------|-------|+| `tests/unit/` | 22 | 246 |+| `tests/security/` | 3 | 34 |+| `tests/integration/` | 10 | 71 |+| **Total** | **35** | **351** |++## CI Integration++**File:** `.github/workflows/tests.yml`++**Jobs:**+| Job | Trigger | Command |+|-----|---------|---------|+| `shellcheck` | every push/PR | `shellcheck -S error reconftw.sh modules/*.sh lib/*.sh install.sh` |+| `unit-fast` | every push/PR | `./tests/run_tests.sh --unit` |+| `integration-smoke` | every push/PR (after unit-fast) | `./tests/run_tests.sh --smoke` |+| `macos-smoke` | every push/PR | `./tests/run_tests.sh --unit && ./tests/run_tests.sh --smoke` |+| `integration-full` | weekly cron + manual dispatch | `./tests/run_tests.sh --integration` |++**shellcheck config** (`.shellcheckrc`):+```+external-sources=true+severity=warning+source-path=SCRIPTDIR+source-path=SCRIPTDIR/lib+source-path=SCRIPTDIR/modules+```++## Common Test Patterns++**Testing exit status:**+```bash+run function_name "arg"+[ "$status" -eq 0 ] # success+[ "$status" -ne 0 ] # any failure+[ "$status" -eq 1 ] # specific code+```++**Testing output content:**+```bash+[[ "$output" == *"expected substring"* ]]+[[ "$output" != *"should not appear"* ]]+[ "$output" = "exact match" ]+```++**Testing file side effects:**+```bash+[ -f "$called_fn_dir/.test_func" ] # checkpoint created+[ -s "output.txt" ] # file non-empty+grep -q "expected" "$file"+```++**Checkpoint / DIFF mode testing:**+```bash+@test "should_run_function returns true when checkpoint missing" {+ mkdir -p "$called_fn_dir"+ test_func() { should_run_function; }+ run test_func+ [ "$status" -eq 0 ]+}++@test "should_run_function returns true in DIFF mode even with checkpoint" {+ mkdir -p "$called_fn_dir"+ DIFF=true+ test_func() {+ touch "$called_fn_dir/.test_func"+ should_run_function+ }+ run test_func+ [ "$status" -eq 0 ]+}+```++**Verbosity gating tests:**+```bash+@test "notification suppresses info at verbosity 1" {+ OUTPUT_VERBOSITY=1+ run notification "hello world" info+ [ "$status" -eq 0 ]+ [[ "$output" == "" ]]+}+```++**Async/parallel tests:** Use `parallel_funcs 2 func1 func2` and check file side effects — not timing.++**Security / injection tests:** Verify that dangerous characters in inputs are either stripped or cause non-zero exit:+```bash+@test "sanitize_domain blocks semicolon injection" {+ run sanitize_domain "example.com;whoami"+ [ "$status" -ne 0 ]+}+```++## Coverage Gaps++**Not directly unit-tested:**+- `modules/modes.sh` — mode orchestration functions (`recon()`, `passive()`, `all()`)+- `modules/vulns.sh` — individual vuln scan functions (tool-dependent, no mocks)+- `modules/web.sh` — webprobe functions (tool-dependent)+- `modules/axiom.sh` — Axiom fleet management (requires Axiom infrastructure)+- `install.sh` — installer logic+- `parallel_funcs` behavior under real concurrent load (tested serially in unit tests)+- `run_with_heartbeat()` / `run_with_heartbeat_shell()` — heartbeat timing behavior++**Covered by integration-smoke only (not unit):**+- CLI argument parsing end-to-end+- Config override order (CLI > custom_config.cfg > reconftw.cfg)+- Monitor mode diff logic++**Where to add new tests:**+- Unit tests for new lib/ functions: `tests/unit/test_<lib_name>.bats`+- Unit tests for new module helpers: `tests/unit/test_<module_name>.bats`, using `sed -n '/^function name()/,/^}/p'` extraction+- Security tests for new input paths: `tests/security/test_injection.bats`+- Snapshot tests for UI changes: update `tests/fixtures/ui/` and `tests/unit/test_ui_snapshots.bats`++---++*Testing analysis: 2026-05-13*