# samnet-dev/cfray architecture

> Architecture diagram of the GitHub repository samnet-dev/cfray, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-29). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/samnet-dev/cfray
- Repository: https://github.com/samnet-dev/cfray

## Overview

1. **Repository shape**
   - This is a **single-file Python application** centered on `scanner.py`.
   - The repo has no package tree or backend/frontend split; the architecture is a **monolithic CLI/TUI tool** with several operational modes.
   - Supporting files are minimal: `README.md`, license, and GitHub funding metadata.

2. **Primary runtime boundary**
   - The tool runs on **Python 3.8+** with **zero third-party dependencies**.
   - It is meant to be launched either interactively (`python3 scanner.py`) or headlessly via CLI flags, and also via `uv run --script ...`.
   - Because everything lives in one script, the main architectural boundary is not between modules but between **mode handlers** inside the script.

3. **Main orchestration layer**
   - `scanner.py` appears to own the full control flow:
     - argument parsing
     - interactive menu/TUI navigation
     - mode dispatch
     - results formatting/export
   - The README shows the tool behaves like a **mode-driven orchestrator** rather than a single-purpose scanner.

4. **Input ingestion subsystem**
   - The app accepts multiple input forms that feed the same downstream test pipeline:
     - local text files containing VLESS/VMess URIs
     - subscription URLs, including plain text and base64 subscriptions
     - template URI + address list
     - JSON files with domain/IP data
     - manually entered configs in the TUI
   - These inputs are normalized into a common internal config representation before testing.

5. **Config scanning pipeline**
   - The core scanner workflow is:
     - resolve domain targets to Cloudflare edge IPs
     - deduplicate/group by IP
     - test latency via TCP/TLS handshake
     - run progressive download tests on the survivors
     - score and rank results
   - This is the main data-processing path of the repo: **config input → IP resolution → connectivity tests → speed tests → ranked export**.

6. **Cloudflare clean-IP finder**
   - A separate operational path scans Cloudflare IPv4 ranges directly.
   - It generates or iterates over IPs from published Cloudflare subnets, probes them, validates Cloudflare behavior, and stores reachable endpoints.
   - This subsystem writes discovered endpoints to `results/clean_ips.txt`, which can then be reused by the template-based scanner path.

7. **Xray pipeline test subsystem**
   - This is a higher-level workflow that depends on an **external xray-core binary**.
   - It has three stages:
     - scan for candidate Cloudflare IPs
     - swap them into a provided VLESS/VMess config and verify real tunnel connectivity
     - expand the working set with fragment presets and SNI variations for DPI bypass
   - The pipeline is a separate boundary from the normal scanner because it requires xray execution, not just network probing.

8. **Server deployment subsystem**
   - The deploy mode turns the tool from scanner into **provisioning automation** for Linux VPSs.
   - It installs xray-core, generates server configs, creates a `systemd` service, and can provision TLS or REALITY credentials.
   - This subsystem bridges local CLI automation with remote host configuration and OS-level service management.

9. **Connection management subsystem**
   - After deployment, the tool can manage the installed xray server:
     - add/remove inbounds
     - add users
     - inspect inbound JSON
     - show generated client URIs
     - restart xray
     - view logs
     - uninstall everything
   - This is an administrative layer over the deployed server’s config and systemd service.

10. **Worker proxy generation**
   - The worker mode generates a **Cloudflare Worker script** for WebSocket-based proxying.
   - The output is not a deployed service inside the repo; it is code generation for an external Cloudflare Workers deployment.
   - Data flow here is: existing WS config → generated Worker script → user deploys it externally → Worker URL is fed back to produce an updated config.

11. **Storage and artifacts**
   - Results are written to a `results/` directory, including:
     - CSV test reports
     - top-ranked URIs
     - fully sorted URI lists
     - clean IP lists
   - Deployment state also uses `~/.cfray/` for installed binaries and related local assets.
   - So the repo has two storage surfaces: **project-local output artifacts** and **per-user installation state**.

12. **External services and infrastructure dependencies**
   - The architecture depends materially on several external systems:
     - Cloudflare IP ranges and Cloudflare behavior for scanning
     - Cloudflare CDN/mirror fallback for rate-limited or blocked download tests
     - xray-core for pipeline testing and server deployment
     - certbot for TLS certificate issuance
     - systemd on Linux VPSs
     - Cloudflare Workers for proxy generation
   - These are not optional details; they define the system boundaries and runtime assumptions.

13. **Operational model**
   - The tool is best understood as a **multi-tool proxy operations console**:
     - discovery/scanning
     - validation/ranking
     - proxy server provisioning
     - post-deploy management
     - external proxy relay generation
   - Most modes reuse the same config and output conventions, but differ in their external dependencies and the type of side effect they produce.

14. **Diagramming takeaway**
   - For an architecture diagram, model `scanner.py` as the central control node with five major branches:
     - config ingestion/scanning
     - clean IP discovery
     - xray pipeline testing
     - VPS deployment + connection management
     - Cloudflare Worker generation
   - Surround it with external dependencies: Cloudflare, xray-core, Linux/systemd, certbot, and local `results/` plus `~/.cfray/` persistence.

Main entry points: [`scanner.py`](https://github.com/samnet-dev/cfray/blob/main/scanner.py) (scanner.py)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_repo["cfray"]
  node_scanner["scanner.py<br/>CLI/TUI orchestrator<br/>[scanner.py]"]
  node_args["Args<br/>CLI flags"]
  node_menu(("Menu<br/>interactive UI"))
  node_ingest["Ingest<br/>config input"]
  node_resolve{{"Resolve<br/>target mapping"}}
  node_latency(("Latency<br/>connectivity test"))
  node_speed(("Speed<br/>download test"))
  node_rank["Rank<br/>scoring"]
  node_cleanip{{"Clean IPs<br/>cloudflare scan"}}
  node_xraytest{{"Xray Test<br/>pipeline"}}
  node_fragments["Fragments<br/>bypass tuning"]
  node_deploy{{"Deploy<br/>server provision"}}
  node_manage["Manage<br/>admin ops"]
  node_worker["Worker<br/>codegen"]
  node_results[("results/<br/>artifact store")]
  node_state[("~/.cfray/<br/>local state")]
  node_cloudflare{{"Cloudflare<br/>external network"}}
  node_xray{{"xray-core<br/>external binary"}}
  node_systemd["systemd<br/>linux service"]
  node_certbot["certbot<br/>tls issuer"]
end

node_scanner -->|"parses"| node_args
node_scanner -->|"drives"| node_menu
node_scanner -->|"accepts"| node_ingest
node_ingest -->|"normalizes"| node_resolve
node_resolve -->|"feeds"| node_latency
node_latency -->|"survivors"| node_speed
node_speed -->|"scores"| node_rank
node_rank -->|"writes"| node_results
node_scanner -->|"runs"| node_cleanip
node_cleanip -->|"probes"| node_cloudflare
node_cleanip -->|"stores"| node_results
node_scanner -->|"dispatches"| node_xraytest
node_xraytest -->|"requires"| node_xray
node_xraytest -->|"expands"| node_fragments
node_xraytest -->|"exports"| node_results
node_scanner -->|"starts"| node_deploy
node_deploy -->|"installs"| node_xray
node_deploy -->|"registers"| node_systemd
node_deploy -->|"optionally uses"| node_certbot
node_deploy -->|"persists"| node_state
node_scanner -->|"administers"| node_manage
node_manage -->|"controls"| node_systemd
node_manage -->|"updates"| node_xray
node_manage -->|"reads"| node_state
node_scanner -->|"generates"| node_worker
node_worker -->|"targets"| node_cloudflare
node_worker -->|"hand-off"| node_results
node_scanner -->|"depends on"| node_cloudflare

click node_scanner "https://github.com/samnet-dev/cfray/blob/main/scanner.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_scanner,node_args,node_menu,node_ingest,node_resolve,node_latency,node_speed,node_rank,node_cleanip,node_xraytest,node_fragments,node_deploy,node_manage,node_worker,node_results,node_state,node_cloudflare,node_xray,node_systemd,node_certbot toneBlue
```

## Components

### cfray

Single-file Python proxy operations console

- [scanner.py](https://github.com/samnet-dev/cfray/blob/main/scanner.py): CLI/TUI orchestrator · Main entrypoint with mode dispatch, input handling, and result output · `scanner.py`
- **Args**: CLI flags · Command-line and script entry parsing
- **Menu**: interactive UI · Interactive navigation for mode selection and manual entry
- **Ingest**: config input · Normalizes files, subscriptions, templates, JSON, and manual configs
- **Resolve**: target mapping · Turns domains into candidate edge IPs and groups by address
- **Latency**: connectivity test · Probes TCP/TLS reachability and response time
- **Speed**: download test · Runs progressive downloads on surviving candidates
- **Rank**: scoring · Scores and orders working configs by performance
- **Clean IPs**: cloudflare scan · Scans Cloudflare IPv4 ranges and records reachable endpoints
- **Xray Test**: pipeline · Validates candidate configs through external xray-core
- **Fragments**: bypass tuning · Expands the working set with fragment presets and SNI variants
- **Deploy**: server provision · Installs xray-core and provisions server configs on Linux VPS
- **Manage**: admin ops · Adds users and inbounds, inspects JSON, restarts, logs, uninstalls
- **Worker**: codegen · Generates Cloudflare Worker scripts for WS proxy relay
- **results/**: artifact store · Project-local reports, ranked URIs, and clean IP lists
- **~/.cfray/**: local state · Per-user binaries and deployment assets
- **Cloudflare**: external network · IP ranges, CDN behavior, and worker platform used by scanning and relay
- **xray-core**: external binary · Runtime required for tunnel validation and deployed server
- **systemd**: linux service · Service manager for deployed xray server
- **certbot**: tls issuer · Certificate issuance for TLS deployment flows

## Connections

- scanner.py → Args: parses · Reads CLI flags and script invocation options
- scanner.py → Menu: drives · Provides interactive mode selection and manual control
- scanner.py → Ingest: accepts · Loads configs from files, subscriptions, templates, JSON, and manual entry
- Ingest → Resolve: normalizes · Converts inputs into a common candidate representation
- Resolve → Latency: feeds · Produces grouped IP candidates for probing
- Latency → Speed: survivors · Only reachable endpoints advance to throughput tests
- Speed → Rank: scores · Measured performance becomes ranked output
- Rank → results/: writes · Exports CSV reports and sorted URI lists
- scanner.py → Clean IPs: runs · Separate path for discovering reusable Cloudflare endpoints
- Clean IPs → Cloudflare: probes · Iterates Cloudflare ranges and validates edge behavior
- Clean IPs → results/: stores · Writes reachable endpoints to clean IP artifacts
- scanner.py → Xray Test: dispatches · Launches the xray-backed validation pipeline
- Xray Test → xray-core: requires · Depends on external xray-core binary execution
- Xray Test → Fragments: expands · Applies fragment and SNI variations for bypass tuning
- Xray Test → results/: exports · Produces validated working config outputs
- scanner.py → Deploy: starts · Provisioning mode for remote Linux VPS setup
- Deploy → xray-core: installs · Installs and configures xray-core on target host
- Deploy → systemd: registers · Creates and manages the service unit
- Deploy → certbot: optionally uses · Obtains TLS certificates when TLS mode is selected
- Deploy → ~/.cfray/: persists · Stores installed binaries and local deployment assets
- scanner.py → Manage: administers · Post-deploy xray server management surface
- Manage → systemd: controls · Restarts and inspects the running service
- Manage → xray-core: updates · Edits xray inbound and user configuration
- Manage → ~/.cfray/: reads · Uses saved local installation assets
- scanner.py → Worker: generates · Produces Cloudflare Worker proxy code from WS config
- Worker → Cloudflare: targets · Output is meant for external Workers deployment
- Worker → results/: hand-off · Generated script or derived config artifacts can be saved or reused
- scanner.py → Cloudflare: depends on · Core scanning and relay flows rely on Cloudflare infrastructure
