npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

forthres-audit

v1.0.14

Published

Official Forthres Audit runtime for the artifacts/analysis ecosystem

Readme

Forthres Security - @forthres/audit Documentation

Official application security runtime for the Forthres ecosystem.

Forthres Audit is the analysis and reporting engine behind the Forthres SaaS platform. It combines a Node.js control plane with Python scanning modules to run guided security assessments, persist scan history, generate enterprise reports, and expose programmatic scan workflows through API and CLI surfaces.

Install

npm install -g @forthres/audit

Run the health check:

forthres-audit --doctor

Run

 forthres-audit scan https://www.example.com.br/ 

Logs

 ______ ___  ____  ______ _   _ ____  _____ ____  
|  ____/ _ \\|  _ \\|__  __| | | |  _ \\| ____/ ___| 
| |__ | | | | |_) |  | |  | |_| | |_) |  _| \\___ \\ 
|  __|| |_| |  _ <   | |  |  _  |  _ <| |___ ___) |
|_|    \\___/|_| \\_\\  |_|  |_| |_|_| \\_\\_____|____/ 
  Security  •  Web Vulnerabillity  •  Evidence

╭──────────────────────────────────────────╮
│                                          │
│  TARGET      https://[email protected]/  │
│  BACKEND     http://localhost:8000       │
│  MODE        PUBLIC SNIPER PIPELINE      │
│                                          │
╰──────────────────────────────────────────╯

⬢ Pipeline started - scan 5a9b6442-b7b6-4628-a88b-ff51b767d80d
  ∙  Target allowlisted and queued: https://ww......
  ∙  findings=0 critical=0 high=0 medium=0 low=0
  ∙  init -> running
  ∙  ghost_recon -> running
  ⬢  ghost_recon -> completed
  ∙  ingest -> running
  ∙  findings=12 critical=0 high=0 medium=0 low=0
  ∙  findings=20 critical=0 high=0 medium=1 low=2
  ∙  findings=41 critical=0 high=0 medium=11 low=11
  ∙  findings=43 critical=0 high=0 medium=13 low=11
  ∙  findings=46 critical=0 high=0 medium=16 low=11
  ⬢  ingest -> completed
  ⬢  waf_study -> completed
  ∙  exploit -> running
  ⬢  exploit -> completed
  ∙  decision_intel -> running
  ⬢  decision_intel -> completed
  ⬢  adversarial -> completed
  ∙  chain_intel -> running
  ∙  findings=53 critical=7 high=0 medium=16 low=11
  ∙  findings=54 critical=8 high=0 medium=16 low=11
  ⬢  chain_intel -> completed
  ∙  hacker_reasoning -> running
  ∙  findings=55 critical=8 high=0 medium=17 low=11
  ∙  findings=58 critical=10 high=1 medium=17 low=11
  ⬢  hacker_reasoning -> completed
  ⬢  auto_chain -> completed
  ∙  offensive -> running
  ∙  findings=59 critical=10 high=1 medium=18 low=11
  ⬢  offensive -> completed
  ∙  persistence_optional -> skipped
  ⬢  incident_absorber -> completed
  ∙  db_validation -> running
  ∙  findings=60 critical=10 high=1 medium=19 low=11
  ⬢  db_validation -> completed
  ∙  infra_ssrf -> running
  ⬢  infra_ssrf -> completed
  ∙  persistence_assessment -> running
  ⬢  persistence_assessment -> completed
  ◇  sniper_decision -> error (non-blocking)
  ◇  autonomous_consolidator -> error (non-blocking)
  ⬢  telemetry -> completed
  ⬢  Scan completed - 5a9b6442-b7b6-4628-a88b-ff51b767d80d

╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│                                                                                                                 ││   Status        COMPLETED                                                                                       ││   Verdict       Critical exposure detected                                                                      ││   Critical      10                                                                                              ││   High          1                                                                                               ││   Duration      n/a                                                                                             ││   Leak Signals  possible cloud/iam exposure · possible credential exposure · possible pii/user data exposure    ││                                                                                                                 │╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
  ◈  Critical findings
  ◈  SSRF Credential Chain: Redis CONFIG (requirepass) (chain_exploitation)
  ◈  DB Access via Credential Pivot: PostgreSQL Version via Error (chain_exploitation)
  ◈  DB Access via Credential Pivot: PostgreSQL Version via Error (chain_exploitation)
  ◈  DB Access via Credential Pivot: PostgreSQL Version via Error (chain_exploitation)
  ◇  High-risk findings
  ◇  DB Reflection: Redis KEYS Dump  Customer Data Reachable (Hacker Reasoning Dictionary)

What Forthres Audit Delivers

Forthres Audit is designed to help teams validate the external security posture of web applications and internet-facing assets with a practical operator workflow.

Core outcomes:

  • Surface mapping of target applications and exposed assets.
  • Detection of common exposure patterns in client-side code and application responses.
  • Session-backed SaaS workflow for authenticated users, plans, and scan history.
  • API-key based scan orchestration for external integrations.
  • Real-time scan lifecycle streaming over Socket.IO.
  • PDF report generation for stakeholder-ready delivery.
  • Admin-only advanced scan routes for deeper operator workflows.
  • PostgreSQL-backed persistence for users, scans, plans, logs, and billing-related metadata.

In practice, the platform currently provides:

  • Standard scan orchestration through scanner.orchestrator.
  • Sniper and operator-focused flows exposed by admin routes and dedicated scanner entrypoints.
  • JavaScript secret and exposure analysis within the Python scanner pipeline.
  • Payment/report unlock plumbing in the SaaS runtime.
  • Allowlist, rate-limit, and authenticated access controls around scan execution.

Product Positioning in the Forthres Ecosystem

Forthres is structured as an application security SaaS ecosystem, and this package is the audit engine that powers it.

Typical ecosystem roles:

  • @forthres/audit: runtime responsible for analysis, scanning, reporting, and scan APIs.
  • Forthres SaaS frontend: customer-facing dashboard, authentication, billing, and user workflows.
  • Forthres platform services: orchestration, hosting, storage, monitoring, and deployment-specific integrations.

If you are publishing or deploying the ecosystem in the cloud, this service should generally be treated as its own backend workload. It has its own runtime concerns, environment variables, persistence requirements, and operational profile.

Real Feature Map

This section reflects the current repository behavior rather than aspirational roadmap claims.

1. Scan Execution

  • Standard authenticated scan flow over Socket.IO via start_scan.
  • API-triggered scan creation through /api/v1/scan.
  • Scan status retrieval through /api/v1/scan/:id.
  • Scan persistence with lifecycle status, counts, telemetry, and report payloads.

2. Scanner Runtime

  • Python-powered assessment pipeline launched from the Node runtime.
  • Structured event streaming from Python back to the Node server.
  • Findings, assets, progress logs, and final report capture.
  • Support for advanced scanner entrypoints used by admin/operator flows.

3. SaaS Workflow

  • User registration, login, logout, and session-based authentication.
  • Plan enforcement and monthly scan quotas.
  • API key generation and retrieval for authenticated users.
  • Payment-related paths for report unlock and checkout flows.

4. Reporting

  • Enterprise PDF report generation via server-side PDF composition.
  • Scan history endpoints for end-user retrieval.
  • Persistent report telemetry associated with completed scans.

5. Admin and Operator Capabilities

  • Admin routes for operational visibility.
  • Advanced scan execution paths for higher-privilege workflows.
  • Credential/data relay and ingestion support for internal operator use.
  • Additional abuse/infrastructure helper modules present in the codebase.

High-Level Architecture

Client / SaaS UI / API Consumer
            |
            v
     Node.js Control Plane
     - Express
     - Socket.IO
     - Sessions
     - Plan enforcement
     - Report generation
     - Scan persistence
            |
            v
      Python Scan Runtime
      - Orchestrator
      - Scanner modules
      - Findings/events
      - Final report payload
            |
            v
        PostgreSQL

Repository Structure

artifacts/analysis/
├── bin/           # CLI entrypoint
├── migrations/    # Database migrations/assets
├── path/          # Python/runtime helpers
├── scanner/       # Python scanners and orchestration
├── server/        # Express API, auth, plans, reports, admin
├── shared/        # Shared schema/types
├── config.py
├── main.py
├── package.json
├── requirements.txt
└── tsconfig.json

Scanner engine

1. Visao Geral da Arquitetura

┌─────────────────────────────────────────────────────────────────┐
│                        USUARIO (Browser)                        │
│  Landing → Dashboard → AdminPanel → ScanHistory → AuthPage     │
└────────────────────────────┬────────────────────────────────────┘
                             │ WebSocket (Socket.io) + REST API
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                    EXPRESS GATEWAY (Node.js)                     │
│                                                                 │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌───────────────┐  │
│  │ routes.ts│  │ admin.ts │  │ auth.ts  │  │ stripe/webhook│  │
│  └────┬─────┘  └────┬─────┘  └──────────┘  └───────────────┘  │
│       │              │                                          │
│  ┌────▼──────────────▼────────────────────────────────────┐    │
│  │           credentialRelay.ts (DataBridge)               │    │
│  └────────────────────────────────────────────────────────┘    │
│       │              │                                          │
│  ┌────▼─────┐   ┌───▼─────────────────────┐                   │
│  │ storage  │   │  PostgreSQL (Drizzle)    │                   │
│  │  .ts     │   │  users/scans/subs/audit  │                   │
│  └──────────┘   └─────────────────────────┘                   │
└────────┬──────────────┬─────────────────────────────────────────┘
         │              │
    spawn python3   spawn python3
         │              │
         ▼              ▼
┌────────────────┐ ┌──────────────────────────────────────────────┐
│  orchestrator  │ │          sniper_pipeline.py                  │
│    .py         │ │  (10-Phase Elite Offensive Pipeline)         │
│  (Standard     │ │                                              │
│   4-Phase)     │ │  + adversarial_engine.py                     │
│                │ │  + chain_intelligence.py                     │
│  Surface       │ │  + hacker_reasoning.py                      │
│  Exposure      │ │  + sniper_engine.py                         │
│  Misconfig     │ │  + attack_reasoning.py                      │
│  Simulation    │ └──────────────────────────────────────────────┘
└────────────────┘

Stack Tecnologico:

  • Frontend: React 18 + Vite + TailwindCSS + Framer Motion + Zustand + wouter
  • Gateway: Express.js + Socket.io + Drizzle ORM
  • Scanner: Python 3 + httpx + dnspython + Selenium/Chromium
  • Database: PostgreSQL (Neon)
  • Payments: Stripe ($5 single scan)
  • Linguagens: 10 idiomas (BR, PT, EN, ES, FR, DE, IT, JA, ZH, KO)

2. Diagrama de Fluxo Principal

2.1 Fluxo do Scan Standard (Usuario Normal)

Usuario                  Frontend                 Gateway                  Python Scanner
  │                        │                        │                          │
  │  Digita URL            │                        │                          │
  │───────────────────────>│                        │                          │
  │                        │  emit("start_scan")    │                          │
  │                        │───────────────────────>│                          │
  │                        │                        │  spawn python3           │
  │                        │                        │  -m scanner.orchestrator │
  │                        │                        │─────────────────────────>│
  │                        │                        │                          │
  │                        │                        │   ┌─── PHASE 1: Surface ─┐
  │                        │                        │   │ DNS Resolution        │
  │                        │                        │   │ Subdomain Enumeration │
  │                        │                        │   │ Port Scanning         │
  │                        │                        │   │ WAF Detection         │
  │                        │                        │   │ → _build_hypothesis() │
  │                        │                        │   └──────────────────────┘
  │                        │                        │          │
  │                        │                        │   ┌─── PHASE 2: Exposure ─┐
  │                        │                        │   │ TLS Validation         │
  │                        │                        │   │ Browser Recon          │
  │                        │                        │   │ JS Secrets Scanner     │
  │                        │                        │   │  → Enterprise Routes   │
  │                        │                        │   │  → Manipulation PoCs   │
  │                        │                        │   │  → Framework Versions  │
  │                        │                        │   └───────────────────────┘
  │                        │                        │          │
  │                        │                        │   ┌─── PHASE 3: Misconfig ─┐
  │                        │                        │   │ Security Headers       │
  │                        │                        │   │ CORS Policy            │
  │                        │                        │   └───────────────────────┘
  │                        │                        │          │
  │                        │                        │   ┌─── PHASE 4: Simulation ┐
  │                        │                        │   │ Rate Limiting          │
  │                        │                        │   │ Auth Flow              │
  │                        │                        │   │ Input Validation       │
  │                        │                        │   │ SSRF/XXE/IDOR/Redirect │
  │                        │                        │   └───────────────────────┘
  │                        │                        │          │
  │                        │                        │  stdout JSON lines        │
  │                        │  socket.emit(event)   │<─────────────────────────│
  │  UI Updates            │<──────────────────────│                          │
  │  (Terminal, HexGrid,   │                        │                          │
  │   Telemetry, Sidebar)  │                        │                          │
  │<───────────────────────│                        │                          │
  │                        │                        │  exit code 0             │
  │                        │                        │<─────────────────────────│
  │                        │  "completed" event     │                          │
  │  ScanCompleteModal     │<──────────────────────│                          │
  │<───────────────────────│  save to DB            │                          │

2.2 Fluxo do Sniper Pipeline (Admin Only)

Admin                    AdminPanel               Gateway (admin.ts)       Python sniper_pipeline
  │                        │                        │                          │
  │  Click "Full Scan"     │                        │                          │
  │───────────────────────>│                        │                          │
  │                        │  POST /admin/sniper/   │                          │
  │                        │  full-scan             │                          │
  │                        │───────────────────────>│                          │
  │                        │                        │  spawn python3           │
  │                        │                        │  -m scanner.sniper_pipeline
  │                        │                        │─────────────────────────>│
  │                        │                        │                          │
  │                        │                        │   Phase 1: INGEST        │
  │                        │                        │    └→ orchestrator run   │
  │                        │                        │    └→ _build_hypothesis()│
  │                        │                        │                          │
  │                        │                        │   Phase 2a: EXPLOIT      │
  │                        │                        │    └→ SniperEngine       │
  │                        │                        │                          │
  │                        │                        │   Phase 2b: DECISION     │
  │                        │                        │    └→ DecisionTree       │
  │                        │                        │                          │
  │                        │                        │   Phase 2c: ADVERSARIAL  │
  │                        │                        │    └→ CostRewardCalc     │
  │                        │                        │    └→ CorrelationGraph   │
  │                        │                        │                          │
  │                        │                        │   ★ RISK SCORE ENGINE    │
  │                        │                        │    └→ score > 0.85?      │
  │                        │                        │       AUTO_DUMP mode     │
  │                        │                        │                          │
  │                        │                        │   Phase 2d: CHAIN INTEL  │
  │                        │                        │    └→ ExploitChains      │
  │                        │                        │                          │
  │                        │                        │   Phase 2e: HACKER REASON│
  │                        │                        │    └→ Kill Chain Playbook│
  │                        │                        │                          │
  │                        │                        │   Phase 2f: INCIDENT     │
  │                        │                        │    └→ IncidentAbsorber   │
  │                        │                        │                          │
  │                        │                        │   Phase 3: DB VALIDATION │
  │                        │                        │    └→ SQL/NoSQL probes   │
  │                        │                        │                          │
  │                        │                        │   Phase 4: INFRA/SSRF    │
  │                        │                        │    └→ Cloud metadata     │
  │                        │                        │    └→ Credential harvest │
  │                        │                        │                          │
  │                        │                        │  pipeline_report JSON    │
  │                        │<─────────────────────────────────────────────────│
  │  Results displayed      │                        │                          │
  │<───────────────────────│                        │                          │

2.3 Fluxo do Combinator (7 Fases — Admin)

┌───────────────────────────────────────────────────────────────────┐
│              SMART AUTH PENETRATOR COMBINATOR v2.0                 │
│                      (server/admin.ts)                            │
├───────────────────────────────────────────────────────────────────┤
│                                                                   │
│  Phase 1: ENDPOINT DISCOVERY                                      │
│  ├─ Probes /login, /admin, /api/auth, /wp-admin, etc.           │
│  ├─ Detects login forms via HTML parsing                         │
│  └─ Classifies: HAS_FORM | NO_FORM | REDIRECT                  │
│       │                                                           │
│  Phase 2: CREDENTIAL ROTATION                                     │
│  ├─ Generates default credential dictionary                      │
│  ├─ admin:admin, test:test, root:root, etc.                     │
│  └─ Attempts login on all discovered forms                       │
│       │                                                           │
│  Phase 3: SSRF INTERNAL AUTH                                      │
│  ├─ Probes internal metadata endpoints                           │
│  ├─ AWS IMDSv1/v2, GCP, Azure metadata                         │
│  └─ Docker/K8s service account tokens                            │
│       │                                                           │
│  Phase 4: TOKEN INJECTION                                         │
│  ├─ Forges JWT tokens with common secrets                        │
│  ├─ Tests admin/role escalation via token manipulation            │
│  └─ Injects forged tokens into admin endpoints                   │
│       │                                                           │
│  Phase 5: SMART REDIRECT                                          │
│  ├─ On 404, redirects attacks to discovered subdomains           │
│  └─ Re-probes subdomain admin panels                             │
│       │                                                           │
│  Phase 6: DEEP EXFILTRATION                                       │
│  ├─ Extracts .env, config files, Redis dumps                    │
│  ├─ Parses DATABASE_URL, SECRET_KEY, API_KEY patterns            │
│  └─ Memory dump fallback for session keys                        │
│       │                                                           │
│  Phase 7: AUTO-LOGIN + RELAY MERGE                                │
│  ├─ Merges credentialRelay (infraSecrets + sessionTokens)        │
│  ├─ Merges with DeepExfil passwords                              │
│  ├─ Generates password variations (reverse, +123, case)          │
│  ├─ Spray attack on all login endpoints                          │
│  └─ Detects breach via Set-Cookie or JWT in response             │
│                                                                   │
└───────────────────────────────────────────────────────────────────┘

2.4 Fluxo de Dados do Credential Relay

┌──────────────────────┐     ┌──────────────────────┐
│   Python Scanner     │     │   Admin Combinator    │
│  (orchestrator.py)   │     │   (admin.ts Ph.6)     │
│                      │     │                       │
│  JS Secrets Found:   │     │  Deep Exfil Found:    │
│  • AWS Keys          │     │  • .env passwords     │
│  • API Tokens        │     │  • DB connection URIs  │
│  • JWTs              │     │  • Redis session keys  │
└────────┬─────────────┘     └───────────┬───────────┘
         │ stdout JSON                    │ direct call
         ▼                               ▼
┌────────────────────────────────────────────────────┐
│              routes.ts (readline handler)           │
│                                                    │
│  SECRET_RELAY_REGEX scans:                         │
│  • description field                               │
│  • evidence field                                  │
│  Matches: AKIA*, sk_live_*, ghp_*, xoxb_*,        │
│           AIza*, eyJ* (JWT), PASSWORD=, TOKEN=     │
│                                                    │
│  → relayIngest(credential)                         │
└─────────────────────┬──────────────────────────────┘
                      ▼
┌────────────────────────────────────────────────────┐
│           credentialRelay.ts (DataBridge)           │
│                                                    │
│  ┌──────────────┐  ┌──────────────┐               │
│  │ credentials  │  │ infraSecrets │               │
│  │ (all raw)    │  │ (passwords)  │               │
│  └──────────────┘  └──────────────┘               │
│  ┌──────────────┐  ┌──────────────┐               │
│  │sessionTokens │  │ dbCredentials│               │
│  │ (JWTs, etc.) │  │ (conn URIs)  │               │
│  └──────────────┘  └──────────────┘               │
│  ┌──────────────┐                                  │
│  │discoveredUsers│                                  │
│  └──────────────┘                                  │
└─────────────────────┬──────────────────────────────┘
                      │
         ┌────────────┼────────────┐
         ▼            ▼            ▼
┌──────────────┐ ┌──────────┐ ┌──────────────┐
│ Phase 7      │ │ Admin UI │ │ GET /api/    │
│ Auto-Login   │ │ DataBridge│ │ admin/       │
│ (spray       │ │ Tab      │ │ databridge   │
│  attack)     │ │          │ │              │
└──────────────┘ └──────────┘ └──────────────┘

3. Estrutura de Arquivos

MSE/
├── client/
│   └── src/
│       ├── App.tsx                    # Roteamento principal (wouter)
│       ├── main.tsx                   # Entry point React
│       ├── index.css                  # Tema cyberpunk (cores, fontes)
│       │
│       ├── pages/
│       │   ├── Landing.tsx            # Pagina inicial marketing
│       │   ├── Dashboard.tsx          # Centro de comando (scan)
│       │   ├── AdminPanel.tsx         # Painel administrativo
│       │   ├── AuthPage.tsx           # Login/Registro
│       │   ├── ScanHistory.tsx        # Historico de scans
│       │   ├── Terms.tsx              # Termos de servico
│       │   ├── Privacy.tsx            # Politica de privacidade
│       │   └── not-found.tsx          # 404
│       │
│       ├── components/
│       │   ├── TargetInput.tsx        # Input de URL alvo
│       │   ├── TerminalEngine.tsx     # Terminal emulado (xterm.js)
│       │   ├── SidebarPhases.tsx      # Sidebar com fases do scan
│       │   ├── TelemetryPanel.tsx     # Graficos de telemetria
│       │   ├── HexGridFindings.tsx    # Grid hex de vulnerabilidades
│       │   ├── ExfiltrationPanel.tsx  # Painel de exfiltracao
│       │   ├── UtilsPanel.tsx         # Utils/Assets expostos
│       │   ├── CyberPanel.tsx         # Container estilizado
│       │   ├── StatusBar.tsx          # Barra de status inferior
│       │   ├── AttackBreadcrumb.tsx   # Breadcrumb visual de ataque
│       │   ├── ScanCompleteModal.tsx  # Modal pos-scan
│       │   ├── PaymentOverlay.tsx     # Overlay de pagamento Stripe
│       │   ├── GlitchLogo.tsx         # Logo animado
│       │   ├── BackgroundLayer.tsx    # Fundo animado
│       │   ├── PageTransition.tsx     # Transicoes de pagina
│       │   └── ui/                    # shadcn/ui primitivos
│       │       ├── button.tsx
│       │       ├── card.tsx
│       │       ├── dialog.tsx
│       │       ├── form.tsx
│       │       ├── input.tsx
│       │       ├── table.tsx
│       │       ├── tabs.tsx
│       │       ├── toast.tsx
│       │       └── ...
│       │
│       ├── hooks/
│       │   ├── useSocket.ts           # WebSocket manager
│       │   ├── useDemoScan.ts         # Scan demonstrativo
│       │   └── use-toast.ts           # Hook de notificacoes
│       │
│       ├── store/
│       │   └── useStore.ts            # Zustand state global
│       │
│       └── lib/
│           ├── queryClient.ts         # TanStack Query config
│           ├── i18n.tsx               # Sistema de traducao
│           └── generateReport.ts      # Gerador de relatorios
│
├── server/
│   ├── index.ts                       # Entry point Express
│   ├── routes.ts                      # Rotas API + Socket.io scan
│   ├── admin.ts                       # Rotas admin + Combinator
│   ├── auth.ts                        # Autenticacao JWT/Session
│   ├── db.ts                          # Conexao PostgreSQL
│   ├── storage.ts                     # Interface CRUD (IStorage)
│   ├── credentialRelay.ts             # DataBridge credential relay
│   ├── stripeClient.ts               # Stripe SDK setup
│   ├── webhookHandlers.ts            # Stripe webhook handlers
│   └── vite.ts                        # Dev server Vite integration
│
├── scanner/
│   ├── orchestrator.py                # Orquestrador principal (4 fases)
│   ├── sniper_pipeline.py            # Pipeline ofensivo (10 fases)
│   ├── sniper_engine.py              # Motor de probes ativos
│   ├── adversarial_engine.py         # FSM adversarial + correlacao
│   ├── chain_intelligence.py         # Cadeias de exploracao
│   ├── hacker_reasoning.py           # Dicionario kill chain
│   ├── attack_reasoning.py           # Raciocinio de ataque
│   │
│   └── modules/
│       ├── base_module.py             # Classe base para modulos
│       ├── surface_mapping.py         # Mapeamento de superficie
│       ├── waf_detector.py            # Deteccao de WAF/CDN
│       ├── tls_validator.py           # Validacao TLS/SSL
│       ├── browser_recon.py           # Recon via Selenium
│       ├── js_secrets_scanner.py      # Scanner de segredos JS
│       ├── headers_analyzer.py        # Headers HTTP de seguranca
│       ├── cors_analyzer.py           # Analise de politica CORS
│       ├── rate_limiter.py            # Teste de rate limiting
│       ├── auth_flow.py               # Validacao de fluxo auth
│       └── input_validation.py        # Testes de input validation
│
├── shared/
│   └── schema.ts                      # Schema Drizzle + tipos TS
│
├── main.py                            # Bridge Python (invocado pelo Node)
├── package.json                       # Dependencias Node.js
├── pyproject.toml                     # Dependencias Python
├── drizzle.config.ts                  # Configuracao Drizzle
├── tailwind.config.ts                 # Configuracao Tailwind
├── vite.config.ts                     # Configuracao Vite
│
└── docs/
    ├── ECOSYSTEM.md                   # ← ESTE ARQUIVO
    └── FLOW_DIAGRAMS.md               # Diagramas de fluxo detalhados

4. Frontend — React/Vite

4.1 Rotas

| Rota | Componente | Descricao | |------|-----------|-----------| | / | Landing.tsx | Pagina marketing com CTA | | /dashboard | Dashboard.tsx | Centro de comando principal | | /auth | AuthPage.tsx | Login e registro | | /scans | ScanHistory.tsx | Historico de scans do usuario | | /admin | AdminPanel.tsx | Painel administrativo | | /terms | Terms.tsx | Termos de servico | | /privacy | Privacy.tsx | Politica de privacidade |

4.2 Estado Global (Zustand — useStore.ts)

interface StoreState {
  // Scan
  target: string;
  currentPhase: PhaseName;
  isScanning: boolean;
  isDemoMode: boolean;
  phases: Record<PhaseName, PhaseStatus>;

  // Dados
  logs: LogEntry[];
  findings: Finding[];
  exposedAssets: ExposedAsset[];
  report: ScanReport | null;

  // Telemetria
  progress: number;
  activeModules: number;
  requestsAnalyzed: number;
  threatsDetected: number;
  telemetryHistory: TelemetryPoint[];

  // Sistema
  isConnected: boolean;
}

4.3 Componentes Principais

| Componente | Funcao | Eventos Socket | |-----------|--------|----------------| | TargetInput | Input de URL + botao de scan | start_scan emit | | TerminalEngine | Terminal xterm.js com logs coloridos | log_stream listen | | SidebarPhases | Progresso visual das fases | phase_update listen | | TelemetryPanel | Graficos de progresso tempo-real | telemetry_update listen | | HexGridFindings | Grid hexagonal de findings | finding_detected listen | | ExfiltrationPanel | Preview de dados exfiltrados | finding_detected listen | | UtilsPanel | Assets expostos (secrets, endpoints) | asset_detected listen |

4.4 Cores do Tema

MilGreen:   #4ADE80   (tags [BLOCK], [BOOT])
Red:        #ff003c   (tags [CRIT])
RoyalBlue:  #4169E1   (accent)
Yellow:     #FFD700   (tags [ALERT])
SkyBlue:    #38BDF8   (tags [LOG])
OffWhite:   #F1F2F1   (texto principal)
Dim:        rgb(100,105,100) (tags [DBG])
Orange:     #FF8C00   (tags [THREAT])
Background: #020208   (Full Black Cyber)

5. Backend — Express Gateway

5.1 Arquitetura do Servidor

server/index.ts
    │
    ├── Express app setup
    ├── Session middleware (connect-pg-simple)
    ├── Passport.js auth
    ├── Stripe webhook route (raw body)
    │
    ├── server/auth.ts        → /api/auth/*
    ├── server/routes.ts      → /api/* + Socket.io
    ├── server/admin.ts       → /api/admin/*
    └── server/vite.ts        → Dev server proxy

5.2 Middleware Stack

  1. express.json() — body parser
  2. express-session — sessoes PostgreSQL
  3. passport.js — autenticacao local
  4. requireAdmin — middleware admin (verifica user.role === "admin")
  5. Stripe webhook — raw body parser para /api/stripe/webhook

6. Scanner Engine — Python

6.1 Modulos do Orchestrator

orchestrator.py
    │
    ├── PHASE 1: Surface
    │   ├── SurfaceMappingModule    → DNS, ports, subdomains, fingerprint
    │   └── WAFDetectorModule       → WAF/CDN detection, security headers
    │
    ├── → _build_hypothesis()       → Stack detection (16 stacks)
    │                                  Priority vector reordering
    │
    ├── PHASE 2: Exposure
    │   ├── TLSValidatorModule      → TLS version, cipher suites, cert chain
    │   ├── BrowserReconModule      → Selenium headless, JS files, cookies
    │   └── JSSecretsModule         → Secrets, XSS, enterprise routes, frameworks
    │
    ├── PHASE 3: Misconfig
    │   ├── HeadersAnalyzerModule   → 7 security headers + HSTS + CORS headers
    │   └── CORSAnalyzerModule      → Origin reflection, subdomain bypass
    │
    └── PHASE 4: Simulation
        ├── RateLimiterModule       → Burst testing, login rate limiting
        ├── AuthFlowModule          → Admin endpoints, default creds, session
        └── InputValidationModule   → XSS, SQLi, SSRF, XXE, IDOR, redirects

6.2 HypothesisHub (16 Stacks)

Apos a fase Surface, o orchestrator detecta a stack tecnologica do alvo e prioriza vetores de ataque:

| Stack | Vetores Prioritarios | |-------|---------------------| | Express/Node | prototype_pollution, jwt_secret, npm_env_leak | | Django/Python | debug_mode, secret_key, admin_panel | | Laravel/PHP | app_key_leak, debug_bar, telescope | | Next.js | api_routes_exposed, ssr_secrets, env_leak | | Firebase | firebase_config, firestore_rules, auth_bypass | | AWS | iam_keys, s3_bucket, metadata_ssrf | | WordPress | wp_config, xmlrpc, plugin_vulns | | Spring/Java | actuator_endpoints, heapdump, env_leak | | Ruby on Rails | secret_key_base, debug_console, mass_assignment | | .NET/ASP | web_config, elmah, trace_axd | | Flask | debug_mode, secret_key, werkzeug_debugger | | GraphQL | introspection, batching, field_suggestions | | Docker/K8s | api_exposed, service_account, etcd_access | | MongoDB | nosql_injection, admin_panel, connection_string | | Redis | unauth_access, config_set, module_load | | Cloudflare | waf_bypass, origin_leak, cache_poisoning |

6.3 JSSecretsModule — Detalhes

O scanner de segredos JS e o modulo mais complexo do ecossistema:

JSSecretsModule.execute()
    │
    ├── 1. Collect JS files (from BrowserRecon)
    ├── 2. Sort by priority (app.js, main.js, chunk-vendors first)
    ├── 3. Reorder patterns by hypothesis (if stack detected)
    │
    ├── 4. For each JS file:
    │   ├── _scan_content() → SECRET_PATTERNS (37 patterns)
    │   │   ├── AWS Access Keys (AKIA...)
    │   │   ├── Google API Keys (AIza...)
    │   │   ├── GitHub/GitLab Tokens
    │   │   ├── Stripe Keys (sk_live_...)
    │   │   ├── JWTs (eyJ...)
    │   │   ├── Private Keys (PEM)
    │   │   ├── Database URIs
    │   │   ├── Generic _SECRET, _KEY, _PASS
    │   │   └── ... (37 total patterns)
    │   │
    │   ├── _scan_xss_patterns() → XSS_INJECTION_PATTERNS
    │   │   ├── innerHTML assignments
    │   │   ├── eval() with dynamic input
    │   │   ├── document.write concatenation
    │   │   ├── new Function() constructor
    │   │   └── Open redirect patterns
    │   │
    │   └── _find_endpoints() → API route discovery
    │
    ├── 5. Source map audit (.map files)
    ├── 6. Cookie security audit
    │
    ├── 7. _scan_enterprise_routes()
    │   ├── ENTERPRISE_ROUTE_REGISTRY (4 sectors)
    │   ├── MANIPULATION_PAYLOADS (11 PoC types)
    │   ├── REDIS_INFRA_PATTERNS (privilege escalation)
    │   └── Emit findings + assets per route
    │
    └── 8. _scan_framework_versions()
        ├── React, Vue, Angular, jQuery versions
        └── Known CVE matching

7. Sniper Pipeline — Pipeline Ofensivo Avancado

7.1 Fases (10 Fases)

sniper_pipeline.py — SniperPipeline.execute()
    │
    ├── Phase 1: INGEST
    │   ├── Run orchestrator (4-phase standard scan)
    │   ├── Collect all findings + assets
    │   ├── _build_hypothesis() → stack fingerprint
    │   └── Emit stack_hypothesis event
    │
    ├── Phase 2a: EXPLOIT
    │   ├── SniperEngine active validation
    │   ├── Test HIGH/CRITICAL findings
    │   └── Generate confirmed exploits
    │
    ├── Phase 2b: DECISION INTELLIGENCE
    │   ├── Zero-knowledge decision tree
    │   ├── InfraFingerprint (AWS/GCP/Azure/Docker)
    │   ├── BaselineMonitor (drift detection)
    │   └── WAFBypassEngine
    │
    ├── Phase 2c: ADVERSARIAL STATE MACHINE
    │   ├── CostRewardCalculator
    │   │   ├── Vulnerability classification
    │   │   ├── WAF block rate penalty
    │   │   ├── Pivot bonus (SSRF=10, SQLi=9, etc.)
    │   │   ├── Correlation graph multiplier (max 8x)
    │   │   └── Reward/Cost ratio → depth decision
    │   ├── PolymorphicPayloadEngine
    │   ├── PrivilegeEscalationModule
    │   └── IncidentValidator
    │
    ├── ★ RISK SCORE ENGINE (entre 2c e 2d)
    │   ├── Calcula: Σ(severity_weight × confidence) / total
    │   ├── score > 0.85 → AUTO_DUMP mode
    │   ├── 0.50-0.85 → MIXED mode
    │   └── < 0.50 → ACTIVE_EXPLORATION mode
    │
    ├── Phase 2d: CHAIN INTELLIGENCE
    │   ├── WAFProbabilityReasoner
    │   ├── SSRF → credential harvest chains
    │   └── Multi-step exploitation paths
    │
    ├── Phase 2e: HACKER REASONING
    │   ├── Kill chain playbook engine
    │   ├── WAF evasion strategies
    │   ├── Confirmation probes
    │   ├── Escalation graph
    │   └── Adaptive payload generation
    │
    ├── Phase 2f: INCIDENT ABSORBER
    │   ├── Categorize: Financial, Database, Docker, Config
    │   ├── Classify: PCI-DSS, GDPR, SOC2
    │   └── Cost-Reward Matrix
    │
    ├── Phase 3: DB VALIDATION
    │   ├── SQL injection probes
    │   ├── NoSQL injection probes
    │   └── Database version detection
    │
    └── Phase 4: INFRA/SSRF
        ├── Cloud metadata (AWS/GCP/Azure)
        ├── Docker/K8s service accounts
        └── Credential harvest via SSRF

7.2 Report Final do Pipeline

{
  target: string;
  scan_id: string;
  started_at: string;
  completed_at: string;
  phases_completed: string[];
  counts: { total, critical, high, medium, low, info };
  findings: Finding[];
  exposed_assets: Asset[];
  probes: Probe[];
  sniper_report: object;
  decision_intel_report: object;
  adversarial_report: object;
  chain_intel_report: object;
  hacker_reasoning_report: object;
  db_validation_report: object;
  infra_report: object;
  incident_evidence: object;
  risk_score: RiskScoreResult;       // ← Audit Injection 3
  stack_hypothesis: Hypothesis;       // ← Audit Injection 1
  auto_dump_triggered: boolean;       // ← Audit Injection 3
}

8. Combinator — Smart Auth Penetrator

Ver diagrama completo na Secao 2.3.

8.1 Estado do Combinator

interface CombinatorState {
  phase1: { endpoints, loginForms, redirects };
  phase2: { credentials, attempts, breaches };
  phase3: { ssrf_results, metadata_captured };
  phase4: { forged_tokens, injection_results };
  phase5: { subdomain_redirects, re_probes };
  phase6: { exfil_data, env_secrets, redis_dumps };
  phase7: {
    triggered: boolean;
    relay_merge: {
      passwords: string[];    // exfil + relay.infraSecrets
      secrets: string[];      // exfil + relay.sessionTokens
      users: string[];        // discovered + relay.discoveredUsers
      urls: string[];         // exfil + relay.dbCredentials
    };
    auto_login_attempts: number;
    breaches: BreachResult[];
  };
}

9. 4 Audit Injections

9.1 HypothesisHub

Arquivo: scanner/orchestrator.py (STACK_HYPOTHESIS_MAP + _build_hypothesis)
         scanner/modules/js_secrets_scanner.py (HYPOTHESIS_PATTERN_PRIORITY + _reorder_patterns)
         scanner/sniper_pipeline.py (hypothesis no ingest)

Fluxo:
  Surface Findings → _build_hypothesis()
      │
      ├── Detecta stacks via STACK_DETECT_PATTERNS
      │   (16 stacks: express, django, laravel, nextjs, firebase, etc.)
      │
      ├── Gera stack_signature: "express+firebase+aws"
      │
      ├── Mapeia priority_vectors: ["prototype_pollution", "jwt_secret", ...]
      │
      └── JSSecretsModule._reorder_patterns_by_hypothesis()
          └── Reordena SECRET_PATTERNS para priorizar vetores da stack

9.2 Correlation Graph

Arquivo: scanner/adversarial_engine.py (CORRELATION_EDGE_RULES)
         scanner/modules/js_secrets_scanner.py (CORRELATION_HINTS)

10 Regras de Correlacao:
  ┌──────────────────────┬──────────────────────┬───────┐
  │ Hint A               │ Hint B               │ Bonus │
  ├──────────────────────┼──────────────────────┼───────┤
  │ cloud_credential     │ ssrf_vector          │ 3.0x  │
  │ admin_endpoint       │ no_rate_limit        │ 2.5x  │
  │ database_credential  │ sqli_vector          │ 2.8x  │
  │ jwt_secret           │ admin_endpoint       │ 2.0x  │
  │ source_map           │ cloud_credential     │ 1.8x  │
  │ internal_endpoint    │ ssrf_vector          │ 2.5x  │
  │ env_file             │ database_credential  │ 2.2x  │
  │ hardcoded_password   │ admin_endpoint       │ 2.0x  │
  │ firebase_config      │ no_rate_limit        │ 1.5x  │
  │ api_key              │ internal_endpoint    │ 1.6x  │
  └──────────────────────┴──────────────────────┴───────┘

  Bonus total capped at 8.0x

9.3 Risk Score Engine

Arquivo: scanner/sniper_pipeline.py (RiskScoreEngine)

Formula:
  RISK_SCORE = Σ(severity_weight × confidence_value) / total_findings

  Severity Weights:
    critical = 1.0
    high     = 0.75
    medium   = 0.45
    low      = 0.20
    info     = 0.05

  Confidence Values:
    confirmed    = 1.0
    high         = 0.85
    medium       = 0.60
    low          = 0.35
    speculative  = 0.15

  Thresholds:
    > 0.85  → AUTO_DUMP (extraction-first mode)
    0.5-0.85 → MIXED (directed + opportunistic)
    < 0.50  → ACTIVE_EXPLORATION (standard cycle)

9.4 Unified Credential Relay

Arquivo: server/routes.ts (evidence field scanning)
         server/admin.ts (Phase 7 relay merge)
         server/credentialRelay.ts (DataBridge state)

Gap 1 (Fixed): routes.ts agora inclui `evidence` field no regex scan
Gap 2 (Fixed): Phase 7 faz merge completo:
  exfilPasswords += credentialRelay.infraSecrets
  exfilSecrets   += credentialRelay.sessionTokens
  discoveredUsers += credentialRelay.discoveredUsers
  exfilUrls      += credentialRelay.dbCredentials

10. Enterprise Route Intelligence

10.1 Setores

┌────────────────┬──────────┬──────┬─────────────────────────────────┐
│ Setor          │ Severity │ CVSS │ Rotas Monitoradas               │
├────────────────┼──────────┼──────┼─────────────────────────────────┤
│ FINTECH        │ critical │ 9.5  │ /payments/authorize             │
│                │          │      │ /ledger/balance                 │
│                │          │      │ /kyc/verify                     │
│                │          │      │ /transfer/internal              │
│                │          │      │ /auth/mfa/challenge             │
├────────────────┼──────────┼──────┼─────────────────────────────────┤
│ GOVERNMENT     │ critical │ 9.8  │ /citizen/registry               │
│                │          │      │ /tax/declaration                │
│                │          │      │ /benefits/status                │
│                │          │      │ /identity/validate              │
│                │          │      │ /portal/admin/config            │
├────────────────┼──────────┼──────┼─────────────────────────────────┤
│ ECOMMERCE      │ high     │ 8.5  │ /coupons/validate               │
│                │          │      │ /promos/apply                   │
│                │          │      │ /cart/update                    │
│                │          │      │ /checkout/price-override        │
│                │          │      │ /inventory/adjust               │
│                │          │      │ /tickets/book                   │
├────────────────┼──────────┼──────┼─────────────────────────────────┤
│ PRODUCTS       │ high     │ 8.0  │ /products/list                  │
│                │          │      │ /products/details               │
│                │          │      │ /products/search                │
│                │          │      │ /products/pricing/dynamic       │
│                │          │      │ /products/stock/check           │
│                │          │      │ /admin/products/update          │
└────────────────┴──────────┴──────┴─────────────────────────────────┘

10.2 Payloads de Manipulacao (11 Tipos)

| Tipo | Alvo | Impacto | |------|------|---------| | price_manipulation | unit_price, discount_override | Pagamento proximo a zero | | coupon_forge | Coupon 100% OFF ilimitado | Perda financeira total | | transfer_forge | Transferencia para conta atacante | Roubo de fundos | | payment_bypass | Approval forjado + callback | Transacao fraudulenta | | balance_read | Wildcard account query | Enumeracao de saldos | | mfa_bypass | OTP trivial + debug_mode | Bypass de MFA | | data_exfil | Wildcard CPF + campos PII | Vazamento massivo | | record_tamper | Declaracao fiscal modificada | Fraude fiscal | | status_tamper | Beneficio ativado sem auth | Fraude previdenciaria | | config_override | Configuracao admin alterada | Tomada de controle | | stock_drain | Estoque zerado/manipulado | Disrupcao de negocio | | sqli_probe | UNION SELECT / SLEEP() | Exfiltracao de DB |


11. Credential Relay & DataBridge

11.1 Estrutura

// server/credentialRelay.ts
interface DataBridgeState {
  credentials: CapturedCredential[];   // Todos os segredos brutos
  infraSecrets: string[];              // Passwords, cloud keys
  dbCredentials: string[];             // Connection URIs
  sessionTokens: string[];            // JWTs, session cookies
  discoveredUsers: string[];           // Usernames, emails
}

interface CapturedCredential {
  key: string;      // Nome/titulo do segredo
  value: string;    // Valor bruto (ZERO_REDACTION)
  source: string;   // Fonte (scanner, exfil, manual)
  type: string;     // PASSWORD | TOKEN | SECRET | URL
  timestamp: number;
}

11.2 Endpoints

| Metodo | Rota | Descricao | |--------|------|-----------| | GET | /api/admin/databridge | Status completo do relay | | POST | /api/admin/databridge/ingest | Ingestao manual de credenciais |

11.3 Funcoes Exportadas

export { credentialRelay, relayIngest, relayIngestUsers, relayIngestTokens };

12. Banco de Dados — PostgreSQL

12.1 Schema (shared/schema.ts)

┌─────────────────────────────────────────────────────────────┐
│                          users                               │
├──────────────┬──────────┬────────────────────────────────────┤
│ id           │ varchar  │ PK, gen_random_uuid()              │
│ email        │ text     │ NOT NULL, UNIQUE                   │
│ password     │ text     │ NOT NULL (bcrypt hash)             │
│ role         │ text     │ DEFAULT "user"                     │
│ plan         │ text     │ DEFAULT "free"                     │
│ scansThisMonth│ integer │ DEFAULT 0                          │
│ scansResetAt │ timestamp│ DEFAULT now()                      │
│ apiKey       │ text     │ NULLABLE (mse_...)                 │
│ createdAt    │ timestamp│ DEFAULT now()                      │
└──────┬───────┴──────────┴────────────────────────────────────┘
       │ 1:N
       ▼
┌─────────────────────────────────────────────────────────────┐
│                          scans                               │
├──────────────┬──────────┬────────────────────────────────────┤
│ id           │ varchar  │ PK, gen_random_uuid()              │
│ userId       │ varchar  │ FK → users.id                      │
│ target       │ text     │ NOT NULL                           │
│ status       │ text     │ DEFAULT "running"                  │
│ findingsCount│ integer  │ DEFAULT 0                          │
│ criticalCount│ integer  │ DEFAULT 0                          │
│ highCount    │ integer  │ DEFAULT 0                          │
│ mediumCount  │ integer  │ DEFAULT 0                          │
│ lowCount     │ integer  │ DEFAULT 0                          │
│ infoCount    │ integer  │ DEFAULT 0                          │
│ findings     │ jsonb    │ DEFAULT []                         │
│ exposedAssets│ jsonb    │ DEFAULT []                         │
│ telemetry    │ jsonb    │ DEFAULT {}                         │
│ phases       │ jsonb    │ DEFAULT {}                         │
│ consentIp    │ text     │ NULLABLE                           │
│ consentAt    │ timestamp│ NULLABLE                           │
│ completedAt  │ timestamp│ NULLABLE                           │
│ createdAt    │ timestamp│ DEFAULT now()                      │
└──────────────┴──────────┴────────────────────────────────────┘
       │
       │ (users.id)
       ▼
┌─────────────────────────────────────────────────────────────┐
│                      subscriptions                           │
├──────────────────┬──────────┬────────────────────────────────┤
│ id               │ varchar  │ PK, gen_random_uuid()          │
│ userId           │ varchar  │ FK → users.id, NOT NULL        │
│ plan             │ text     │ DEFAULT "free"                 │
│ status           │ text     │ DEFAULT "inactive"             │
│ stripeCustomerId │ text     │ NULLABLE                       │
│ stripeSubscriptionId│ text  │ NULLABLE                       │
│ enabled          │ boolean  │ DEFAULT false                  │
│ createdAt        │ timestamp│ DEFAULT now()                  │
│ expiresAt        │ timestamp│ NULLABLE                       │
└──────────────────┴──────────┴────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                       audit_logs                             │
├──────────────┬──────────┬────────────────────────────────────┤
│ id           │ varchar  │ PK, gen_random_uuid()              │
│ userId       │ varchar  │ FK → users.id, NULLABLE            │
│ action       │ text     │ NOT NULL                           │
│ target       │ text     │ NULLABLE                           │
│ ip           │ text     │ NULLABLE                           │
│ details      │ jsonb    │ NULLABLE                           │
│ createdAt    │ timestamp│ DEFAULT now()                      │
└──────────────┴──────────┴────────────────────────────────────┘

12.2 Operacoes CRUD (IStorage)

interface IStorage {
  // Users
  getUser(id: string): Promise<User | undefined>;
  getUserByEmail(email: string): Promise<User | undefined>;
  createUser(user: InsertUser): Promise<User>;
  updateUser(id: string, updates: Partial<User>): Promise<User>;
  getAllUsers(): Promise<User[]>;

  // Scans
  createScan(scan: InsertScan): Promise<Scan>;
  getScan(id: string): Promise<Scan | undefined>;
  getScansByUser(userId: string): Promise<Scan[]>;
  updateScan(id: string, updates: Partial<Scan>): Promise<Scan>;
  getAllScans(): Promise<Scan[]>;
  getScansByTarget(target: string): Promise<Scan[]>;

  // Subscriptions
  createSubscription(sub: InsertSubscription): Promise<Subscription>;
  getSubscription(userId: string): Promise<Subscription | undefined>;
  updateSubscription(id: string, updates: Partial<Subscription>): Promise<Subscription>;

  // Audit
  createAuditLog(log: InsertAuditLog): Promise<AuditLog>;
  getAuditLogs(userId: string): Promise<AuditLog[]>;
  getAllAuditLogs(): Promise<AuditLog[]>;

  // Admin
  getAdminStats(): Promise<AdminStats>;
}

13. API Reference

13.1 Autenticacao

| Metodo | Rota | Body | Resposta | |--------|------|------|----------| | POST | /api/auth/register | {email, password} | {user} + session | | POST | /api/auth/login | {email, password} | {user} + session | | POST | /api/auth/logout | — | {ok: true} | | GET | /api/auth/me | — | {user} ou 401 |

13.2 Scans

| Metodo | Rota | Descricao | |--------|------|-----------| | GET | /api/scans | Todos os scans do usuario autenticado | | GET | /api/scans/:id | Detalhes de um scan especifico | | POST | /api/checkout/create-session | Criar sessao Stripe ($5) |

13.3 API Publica (API Key)

| Metodo | Rota | Header | Descricao | |--------|------|--------|-----------| | POST | /api/v1/scan | x-api-key | Iniciar scan via API | | GET | /api/v1/scan/:id | x-api-key | Status do scan | | POST | /api/keys/generate | Session | Gerar/rotacionar API key | | GET | /api/keys | Session | Obter API key atual |

13.4 Admin

| Metodo | Rota | Descricao | |--------|------|-----------| | GET | /api/admin/me | Role e email do admin | | POST | /api/admin/bypass | Dev-only: elevar sessao para admin | | GET | /api/admin/stats | Estatisticas globais do sistema | | GET | /api/admin/databridge | Estado do credential relay | | POST | /api/admin/databridge/ingest | Ingerir credenciais manualmente | | GET | /api/admin/users | Listar todos os usuarios | | GET | /api/admin/scans | Ultimos 100 scans | | GET | /api/admin/audit | Ultimos 200 audit logs |

13.5 Sniper Probes (Admin)

| Metodo | Rota | Descricao | |--------|------|-----------| | POST | /api/admin/sniper/price-injection | Probe de manipulacao de preco | | POST | /api/admin/sniper/auth-bypass | Probe de bypass administrativo | | POST | /api/admin/sniper/xss-scanner | Scan de XSS patterns | | POST | /api/admin/sniper/open-redirect | Teste de redirect aberto | | POST | /api/admin/sniper/sqli-probe | Probe de SQL injection | | POST | /api/admin/sniper/full-scan | Pipeline sniper completo |

13.6 Stripe

| Metodo | Rota | Descricao | |--------|------|-----------| | POST | /api/stripe/webhook | Processar eventos Stripe | | GET | /api/stripe/publishable-key | Obter chave publica Stripe |

13.7 WebSocket Events

Client → Server: | Evento | Payload | Descricao | |--------|---------|-----------| | start_scan | {target: string} | Iniciar scan | | abort_scan | — | Abortar scan em andamento |

Server → Client: | Evento | Payload | Descricao | |--------|---------|-----------| | log_stream | {message, level, module} | Log para terminal | | finding_detected | Finding | Nova vulnerabilidade | | asset_detected | ExposedAsset | Novo asset exposto | | phase_update | {phase, status} | Mudanca de fase | | telemetry_update | {progress, activeModules, ...} | Telemetria | | report_generated | ScanReport | Relatorio final | | completed | {scanId, findingsCount} | Scan finalizado | | error | {message} | Erro | | stack_hypothesis | Hypothesis | Stack detectado | | risk_score | RiskScoreResult | Score de risco |


14. Pagamentos — Stripe

14.1 Fluxo de Pagamento

Usuario                    Frontend               Gateway                 Stripe
  │                          │                      │                       │
  │  Click "Buy Scan"       │                      │                       │
  │─────────────────────────>│                      │                       │
  │                          │  POST /checkout/     │                       │
  │                          │  create-session      │                       │
  │                          │─────────────────────>│                       │
  │                          │                      │  stripe.checkout.     │
  │                          │                      │  sessions.create()    │
  │                          │                      │──────────────────────>│
  │                          │                      │                       │
  │                          │                      │  session.url          │
  │                          │                      │<──────────────────────│
  │                          │  redirect to Stripe  │                       │
  │                          │<─────────────────────│                       │
  │  Stripe Checkout         │                      │                       │
  │─────────────────────────────────────────────────────────────────────────>│
  │                          │                      │                       │
  │  Payment complete        │                      │  webhook: checkout.   │
  │                          │                      │  session.completed    │
  │                          │                      │<──────────────────────│
  │                          │                      │  Update subscription  │
  │                          │                      │  Enable scan access   │

14.2 Configuracao

  • Produto: "Single Scan Report" — $5.00 USD
  • Modo: Payment (one-time)
  • Webhook: /api/stripe/webhook
  • Chave publica: via /api/stripe/publishable-key

15. Internacionalizacao

15.1 Idiomas Suportados

BR (Portugues Brasil) | PT (Portugues Portugal)
EN (Ingles)           | ES (Espanhol)
FR (Frances)          | DE (Alemao)
IT (Italiano)         | JA (Japones)
ZH (Chines)           | KO (Coreano)

15.2 Implementacao

// client/src/lib/i18n.tsx
// React Context-based
// useI18n() hook para traducoes
// <I18nProvider> no App.tsx

16. Guia de Manutencao

16.1 Adicionar Novo Modulo de Scanner

  1. Criar arquivo em scanner/modules/novo_modulo.py
  2. Herdar de BaseModule (from scanner.modules.base_module import BaseModule)
  3. Implementar execute(job) retornando lista de Finding
  4. Registrar no PHASE_ORDER em scanner/orchestrator.py
  5. Adicionar patterns relevantes ao NEON_HIGHLIGHT_PATTERNS em HexGridFindings.tsx

16.2 Adicionar Novo Setor Enterprise

  1. Adicionar entrada em ENTERPRISE_ROUTE_REGISTRY em js_secrets_scanner.py
  2. Adicionar payloads correspondentes em MANIPULATION_PAYLOADS
  3. Atualizar NEON_HIGHLIGHT_PATTERNS em HexGridFindings.tsx
  4. Atualizar findings demo em useDemoScan.ts
  5. Atualizar assets demo em useDemoScan.ts

16.3 Adicionar Nova Regra de Correlacao

  1. Adicionar hint em CORRELATION_HINTS em js_secrets_scanner.py
  2. Adicionar regra em CORRELATION_EDGE_RULES em adversarial_engine.py
  3. Definir bonus multiplicador (recomendado: 1.2x — 3.0x)

16.4 Adicionar Nova Stack ao HypothesisHub

  1. Adicionar pattern de deteccao em STACK_DETECT_PATTERNS em orchestrator.py
  2. Adicionar entry em STACK_HYPOTHESIS_MAP com priority_vectors e depriority
  3. Adicionar tech_label legivel

16.5 Modificar Schema do Banco

  1. Editar shared/schema.ts
  2. Atualizar tipos de insert/select
  3. Atualizar IStorage em server/storage.ts
  4. Atualizar DatabaseStorage em server/storage.ts
  5. Rodar npm run db:push (ou npm run db:push --force)
  6. NUNCA alterar tipo de coluna ID existente

16.6 Adicionar Nova Rota de API

  1. Adicionar handler em server/routes.ts (publico) ou server/admin.ts (admin)
  2. Usar storage interface para operacoes CRUD
  3. Validar body com Zod schemas de shared/schema.ts
  4. Atualizar esta documentacao

17. Guia de Integracoes Futuras

17.1 Pontos de Extensao

┌────────────────────────────────────────────────────────────────┐
│                    PONTOS DE EXTENSAO                          │
├────────────────────────────────────────────────────────────────┤
│                                                                │
│  Frontend:                                                     │
│  ├── Novo componente → client/src/components/                 │
│  ├── Nova pagina → client/src/pages/ + App.tsx                │
│  ├── Novo hook → client/src/hooks/                            │
│  └── Nova traducao → client/src/lib/i18n.tsx                  │
│                                                                │
│  Backend:                                                      │
│  ├── Nova rota publica → server/routes.ts                     │
│  ├── Nova rota admin → server/admin.ts                        │
│  ├── Novo webhook handler → server/webhookHandlers.ts         │
│  └── Nova tabela → shared/schema.ts + server/storage.ts      │
│                                                                │
│  Scanner:                                                      │
│  ├── Novo modulo → scanner/modules/                           │
│  ├── Nova fase pipeline → scanner/sniper_pipeline.py          │
│  ├── Novo setor enterprise → ENTERPRISE_ROUTE_REGISTRY        │
│  ├── Novo payload → MANIPULATION_PAYLOADS                     │
│  ├── Nova regra correlacao → CORRELATION_EDGE_RULES           │
│  └── Nova stack hipotese → STACK_HYPOTHESIS_MAP               │
│                                                                │
│  DataBridge:                                                   │
│  ├── Novo tipo credencial → credentialRelay.ts                │
│  └── Novo ingestor → relayIngest* functions                   │
│                                                                │
└────────────────────────────────────────────────────────────────┘

17.2 Integracoes Recomendadas

| Integracao | Proposito | Ponto de Conexao | |-----------|----------|------------------| | Slack/Discord | Alertas de scan critico | server/routes.ts (pos-scan) | | SendGrid/SES | Email de relatorio | server/routes.ts (report_generated) | | S3/R2 | Storage de relatorios PDF | server/admin.ts (dossier) | | Sentry | Monitoramento de erros | server/index.ts | | Redis | Cache de resultados | server/storage.ts | | OpenAI | Analise AI de vulnerabilities | scanner/hacker_reasoning.py | | GitHub | Scan de repositorios | Novo modulo scanner | | Shodan | Enriquecimento de surface | scanner/modules/surface_mapping.py | | VirusTotal | Reputacao de dominio | scanner/modules/surface_mapping.py | | NIST NVD | CVE database lookup | scanner/modules/js_secrets_scanner.py |

17.3 Eventos WebSocket para Integracao

Para integrar sistemas externos, escute estes eventos no Socket.io:

// Exemplo de integracao externa
socket.on('finding_detected', (finding) => {
  if (finding.severity === 'critical') {
    // Enviar alerta para Slack/Discord
    sendSlackAlert(finding);
  }
});

socket.on('completed', (result) => {
  // Gerar e enviar relatorio
  generatePDFReport(result);
});

socket.on('risk_score', (score) => {
  if (score.auto_dump) {
    // Escalar para equipe de seguranca
    escalateToSOC(score);
  }
});

Historico de Versoes

| Data | Versao | Mudancas | |------|--------|----------| | 2026-02-28 | 2.0.0 | 4 Audit Injections (HypothesisHub, Correlation Graph, Risk Score Engine, Credential Relay) | | 2026-02-28 | 1.9.0 | Enterprise Route Intelligence (4 setores, 11 payloads) | | 2026-02-27 | 1.8.0 | Sniper Pipeline 10-Phase + Combinator 7-Phase | | 2026-02-26 | 1.7.0 | Enterprise Dossier PDF generation | | 2026-02-25 | 1.6.0 | DataBridge + Credential Relay | | 2026-02-24 | 1.5.0 | Adversarial Engine + Hacker Reasoning | | 2026-02-23 | 1.4.0 | Stripe integration ($5 single scan) | | 2026-02-22 | 1.3.0 | Internationalization (10 languages) | | 2026-02-21 | 1.2.0 | Admin Panel + Sniper Probes | | 2026-02-20 | 1.1.0 | Browser Recon + JS Secrets Scanner | | 2026-02-19 | 1.0.0 | Initial release (4-phase scanner) |


Motores Atuais e Flags (Atualizado)

  • Motor 11 — Autonomous Consolidator: já integrado no admin (runMotor11 em backend/server/admin.ts). Usa PYTHON_BIN (ou PYTHON) para invocar scanner.autonomous_engine. Mantém eventos no stdout via JSON.
  • Autologin Admin (dev): middleware sempre cria/eleva [email protected] (role=admin, plan=pro). Controle sugerido via env AUTO_ADMIN=1; deixar desativado em produção.
  • Flags de execução
    • STRIPE_DISABLED=1: desliga toda a inicialização Stripe.
    • FORCE_STATIC=1: força servir dist/public mesmo em NODE_ENV=development.
    • DISABLE_SELENIUM=1: (implementar early-return) para pular módulos browser_recon e selenium_xss em ambientes sem Chrome/ChromeDriver.
    • PYTHON_BIN=/caminho/python: define binário Python para o scanner.
    • PGSSLMODE=disable + ssl:false no Pool local para Postgres self‑hosted.
  • Drivers DB: backend/server/db.ts usa pg (pool padrão) e drizzle-orm/node-postgres; Neon/WebSocket removido para evitar wss://localhost/v2 em dev offline.
  • Rota /api/admin/bypass: permanece para testes; cria/eleva [email protected]. Em pr