Skip to content

Architecture

Sam MG Harish edited this page Oct 15, 2026 · 3 revisions

Architecture

Process model

One process. lu77U-MobileSec parses arguments, then calls serve() in web/server.py, which builds the FastAPI app and runs uvicorn on 127.0.0.1.

Inside that process:

  • FastAPI serves the JSON API, the scan WebSocket, and the built React SPA.
  • JobManager (web/jobs.py) runs scans on daemon threads, two at a time.
  • Scan state lives on the filesystem. web/store.py reads and writes meta.json, result.json and (in verbose runs) scan.log inside each scan folder, so state survives a restart.
  • web/checkpoint.py records per-stage and per-region progress inside the scan folder, so an interrupted scan resumes instead of re-running its model calls.
  • Long blocking calls that must not stall the event loop (device checks, PDF conversion, log reads) are dispatched with asyncio.to_thread.

Worker threads are daemons on purpose. A ThreadPoolExecutor registers an atexit hook that blocks interpreter shutdown until each worker finishes its current task, which made Ctrl+C hang while a scan sat in a blocking adb or provider call. Daemon threads are abandoned at exit; cancel_all_active() on shutdown gives in-flight scans a chance to clean up first.

Module map

lu77U_MobileSec/
├── _metadata.py          name/version/author/URLs, resolved from pyproject.toml
├── cli/                  argparse front end; hands off to web.server.serve
├── core/app.py           compatibility shim that also calls serve()
├── web/
│   ├── server.py         port selection, uvicorn, access-log filter
│   ├── app.py            FastAPI factory, CORS, SPA mounting
│   ├── jobs.py           JobManager: threads, pause/resume/cancel, event fan-out
│   ├── store.py          scan folders, meta.json, result.json, scan.log (verbose)
│   ├── checkpoint.py     per-scan resume state (stages + per-region agent files)
│   ├── events.py         contextvar carrying the current scan id
│   ├── serializers.py    builds the result DTO the SPA renders
│   ├── routes/           system, scans, dynamic, settings
│   └── services/         analysis_service (pipeline), settings_service
├── detection/            framework detection + APK metadata extraction
├── framework_detector/   per-framework detectors and scoring
├── decompiler/           JADX / Blutter / hermes-decomp / react-native-decompiler /
│                         ilspycmd / Ghidra wrappers, APK payload extraction,
│                         Dart kernel source recovery, libapp.so snapshot strings,
│                         Metro module splitting,
│                         Xamarin assembly recovery (XALZ/XABA)
├── analyzers/
│   ├── registry.py       framework name -> analyzer class
│   ├── base.py           BaseAnalyzer: shared agent + scanner + enrichment code
│   ├── java_kotlin_analyzer.py   JADX + androguard graph (SAST-first + leads)
│   ├── flutter_analyzer.py       Blutter, kernel source or libapp.so strings + platform layer + overview
│   ├── react_native_analyzer.py  Metro module tree (built-in or hermes-decomp)
│   │                             + platform layer + overview
│   ├── cordova_analyzer.py       assets/www extraction + HTML/JS graph
│   ├── xamarin_analyzer.py       .NET assembly recovery + optional C# decompilation
│   ├── flutter/, react_native/, cordova/, xamarin/   per-framework graph builders
│   │                     (flutter/ and react_native/ also write the scan overview)
│   ├── layout.py         directory names the cross-platform roots share
│   ├── sast/             deterministic scanners: manifest, webview, network config,
│   │                     TLS, injection, secrets, SDK inventory,
│   │                     signature-derived-key, Flutter build mode, Dart TLS,
│   │                     crypto and platform misuse, OAuth, credential storage,
│   │                     hardcoded checks, screen capture, React Native and Dart
│   │                     script rules, Semgrep; plugin-code demotion in the runner
│   └── agent/
│       ├── agent_loop.py     the bounded tool loop
│       ├── tools.py          read/search/native + call-graph navigation tools
│       ├── code_graph.py     class map containers and rendering
│       ├── ownership.py      which packages are the app's own code
│       ├── call_graph.py     method-level caller/callee graph + traversal
│       ├── graph_tables.py   shared vendor-prefix/sink-family tables, kept in their
│       │                     own module so code_graph, ownership and call_graph can
│       │                     all import them without an import cycle
│       ├── partition.py      split the call graph into disjoint regions
│       ├── fanout.py         run one agent per region in parallel, merge
│       ├── file_review.py    after the agents: every flagged file and native library
│       │                     reviewed once, in parts, with no tools
│       ├── native_loading.py which bundled native libraries the app's code loads
│       ├── budget.py         wall-clock Deadline with throttle credit
│       ├── leads.py          SAST findings as a per-region worklist
│       ├── surfaces.py       attack-surface objectives and skills per sink family
│       ├── patterns.py       shared secret/endpoint/string-literal patterns
│       ├── profiles.py       per-framework SourceProfile
│       └── skills_loader.py  core + user skill resolution
├── validation/           gates, claim terms, dedupe, judgment pass, chain builder
├── rules/semgrep/        bundled Android Semgrep rules
├── dynamic_analysis/     adb, Frida, mitmproxy, UI automation, verifier
├── ai/                   provider interface, five API implementations plus one
│                         CLI-backed class driving five subscription CLIs, error
│                         classes, key pool, concurrency gate, Ollama lifecycle/model
│                         discovery
├── report_generator/     JSON export, HTML builder, PDF engines
├── config/               settings, paths, credentials, prompts, constants
├── tools_checker/        readiness checks for JADX/Blutter/hermes-decomp/
│                         react-native-decompiler/Ghidra and the active AI provider
├── utils/                CVSS, scoring, JSON repair, response parsing, output paths,
│                         verbose sink, cancellation
├── skills/               markdown guidance injected into agent prompts
└── frontend/             React + Vite + TypeScript source; builds into web/static

scripts/build_frontend.sh  npm ci + vite build into web/static
scripts/preflight.sh       runs all five push gates, as the pre-push hook and CI do
scripts/check_commit_message.py
                           the commit message push gate, also run by the commit-msg hook
scripts/check_comment_style.py
                           the commenting-standard push gate
scripts/codeql_scan.sh     the CodeQL push gate; scripts/codeql/ holds its custom
                           JavaScript suite and local query pack
scripts/verify_install.sh  the clean-install push gate: fresh venv, pip install -e .,
                           -v and -V
.githooks/                 commit-msg and pre-push, enabled by scripts/install_hooks.sh
tests/                     pytest suite (no device, model or network access)

Scan lifecycle

flowchart TD
    A[POST /api/scans] --> B[prepare_scan: folder + meta.json]
    B --> C[JobManager._run on a daemon thread]
    C --> D[MobileSecurityDetector.detect]
    D --> E{registry.get_analyzer_class}
    E -- none registered --> R[Detection-only result]
    E -- registered --> P{analyzer.preflight}
    P -- tool not configured --> R
    P -- ready --> F[Decompile / extract]
    F --> S1[Java/Kotlin only: deterministic scanners, then the leads worklist]
    S1 --> G[Code graph: ownership, class map, call graph]
    G --> H[Partition into regions]
    H --> I[One agent per region, in parallel, budgeted]
    I --> I2[File review: each flagged file and native library once]
    I2 --> S3[Other frameworks: deterministic scanners, merged with the AI findings]
    S3 --> J[Merge, dedupe, attach code context]
    J --> K{Device available and<br/>dynamic verification on?}
    K -- no --> L[Record reason, skip phase 2]
    K -- yes --> M[run_dynamic_verification]
    M --> N[Findings annotated with verdicts]
    N --> O[On-device session: env checks + UI exploration]
    O --> Q[Runtime findings appended]
    L --> V[Validation gates + model review]
    Q --> V
    V --> W[Chain building]
    W --> X[JSONExporter]
    R --> X
    X --> Y[build_result DTO]
    Y --> Z[save result.json + meta summary]
Loading

Only the Java/Kotlin analyzer runs the scanners before the agents, so their hits become the agents' worklist; the Flutter, React Native, Cordova and Xamarin analyzers run them after the agents and the file review, and merge the two sets. AnalysisService.run() in web/services/analysis_service.py is the only place this sequence is expressed. Everything below it is UI-agnostic.

Progress phases

The worker emits (phase, percent, message) events. The UI shows both the name and the bar.

Phase Percent Emitted by
starting 3 JobManager
detecting 10 AnalysisService
analyzing 40 AnalysisService
extracting 35 Flutter / React Native / Cordova / Xamarin analyzers (payload out of the APK)
decompiling 45, 50, 52, 54, 55, 58 Whichever analyzer is active (JADX, Blutter or kernel-source recovery, the Metro splitter or hermes-decomp, ILSpy; JADX again for a Flutter or React Native platform layer)
sast 60 Java/Kotlin analyzer (deterministic scanners, before the agent)
agentic_start 62, 64 Whichever analyzer is active
agentic 64 → 82 Region fan-out, one event per completed region; 81 when the file review starts
agentic_done 82, 84 Whichever analyzer is active (84 = scanners, for the non-Java frameworks that run them after)
device_check 63 AnalysisService (phase 2 entry)
installing 65 verifier
dynamic_verify 70 verifier
dynamic_done 88 AnalysisService
device_check, app_info, frida_setup, http_check, visual_check, ui_interact, runtime_analysis 88 → 91 DynamicAnalyzer, remapped into the session band
session_done 91 AnalysisService
validating 88 AnalysisService (gates + model review)
chaining 90, 91 AnalysisService (chain building)
reporting 92 AnalysisService
finalizing 98 AnalysisService
done 100 JobManager

Percentages are not monotonic across the phase-2 boundary: static analysis reaches 82 before dynamic verification restarts at 63. The phase name is the source of truth.

Event fan-out

JobManager._publish appends every event to a per-scan backlog (capped at 3000, oldest dropped) and pushes it to each subscribed asyncio queue through loop.call_soon_threadsafe. In verbose runs, emit_log also appends each line to scan.log in the scan folder. Verbose output narrates every file the engine reads, so persisting it unconditionally would cost hundreds of megabytes on a large app.

A WebSocket client subscribing mid-scan receives the backlog first, then live events. GET /api/scans/{id}/logs returns the complete on-disk history where one exists, including for scans that ran in a previous process; its persisted flag says whether a log file was written at all.

Verbose log lines reach the same stream through a sink: utils/verbose.register_sink is called at app startup with a callback that looks up the current scan id from a contextvar and calls emit_log. Every verbose_print in the engine therefore shows up in the browser for the scan it belongs to, with no plumbing at the call sites.

Event types on the wire: meta (once on connect), log, progress, status.

Cancellation, pause and resume

Three distinct signals, all landing at a progress checkpoint rather than mid-write:

Signal Effect
cancel_scan Sets a threading.Event. The progress callback raises ScanCancelled, which unwinds the pipeline and stops frida-server. Terminal
pause_scan Sets a separate event. The worker stops at the next checkpoint, keeps everything, and records status: "paused", pause_reason: "user"
resume_scan Re-queues a paused scan; the analyzer seeds from checkpoint/ and skips completed stages and already-reported regions

ScanCancelled is re-raised through every intermediate except Exception handler so best-effort error handling cannot swallow it.

On startup, reconcile_orphans() finds scans left queued or running by a server that is no longer alive. A worker that gets a slot runs a scan only if it is still queued (a stop, a delete or another server's reconciliation may have decided otherwise while it waited), and starting clears any earlier error. A scan records its owner (boot_id, owner_pid) when it is queued, not only when it starts, so a second server on the same machine leaves another live server's queued scans alone; before that, the preflight's clean-install check failed two scans a user's dashboard had queued. An orphan with a usable checkpoint becomes paused with pause_reason: "interrupted", and so does one that was still queued, since it never started and its APK is still in its folder; a running orphan with no checkpoint is failed. auto_resume_interrupted() then re-queues those, if auto_resume is on and the scan has not exceeded the auto-resume retry budget.

A scan whose AI provider stopped answering for a reason outside the app pauses itself rather than finishing with a hollow result. provider_outage() names the reason: provider_quota when every key's quota ran out, provider_unreachable when the provider's host could not be reached when the scan stopped using it (DNS failure, no network, connection refused; the provider clears that marker on its next successful call). AnalysisService.run skips the working-file cleanup, the checkpoint is kept, and the job stores the partial result and records pause_reason with resume_after 5 hours ahead for a quota or 10 minutes ahead for an unreachable host. A background task in web/app.py calls resume_expired_quota_pauses() every 300 seconds; with auto_resume on it re-queues each such scan whose resume_after has passed, up to 20 times between the two reasons (quota_resume_attempts), a budget separate from the interrupted-scan one. Before the unreachable case existed, a resumed scan run while the machine was offline was recorded as completed with no findings and its checkpoint deleted.

Because a JADX run, a Frida download, or a provider call can outlive the 10-second wait in stop_and_delete, _finish_meta checks whether the scan folder still exists before writing. A worker finishing after its scan was deleted discards its result.

A scan stopped mid-analysis still stores a partial result: the findings gathered so far, bucketed by severity, with metadata.partial: true, summary.security_score: null and decompilation_status: "Stopped before completion". An incomplete scan is deliberately not scored.

Error handling

A failed scan records Scan failed (ref: <8 hex chars>). The exception and traceback go to the server-side logger under the same reference. The reference, not the exception text, is what the browser sees.

Clone this wiki locally