Skip to content

EN Code Structure

dongle edited this page Nov 16, 2026 · 14 revisions

中文 | English

Code Structure

Repository layout for contributors and downstream developers. For conventions (naming, error handling, i18n rules) see AGENTS.md in the repo root and docs/CONTRIBUTING.md.

Tech Stack

Layer Technology
Backend Go 1.27+, Wails v3 bindings
Frontend React 19 + TypeScript + HeroUI v3 (@heroui/react + @heroui/styles, built on React Aria Components) + Tailwind CSS v4 + Vite; @iconify/react icons (Material Symbols / MDI, bundled offline)
Core Mihomo-derived core process (built with the with_gvisor tag; TUN depends on gVisor)
Core library snishaper-core (proxy/rules/DoH/certs/TUN, separate repo, consumed via go.mod)
Packaging Windows MSIX (PFX-signed), 12-target cross-platform CLI matrix

Directory Layout

SniShaper/
├── main.go              # Entry point: session guard (no desktop → bundled CLI mode) + Wails app assembly + tray setup
├── app/                 # Go backend application layer
│   ├── app_api.go       #   App struct and all frontend-bound APIs
│   ├── app_fragment.go  #   TLS fragmentation config API (get/set/reset)
│   ├── app_profiles.go  #   Configuration profiles: named snapshots (list/create/rename/duplicate/switch/import/export)
│   ├── app_recovery.go  #   Startup recovery of a leftover system proxy (crash safety)
│   ├── app_diag.go      #   Diagnostic package export (sanitized snapshot + logs, read-only)
│   ├── app_system.go    #   System proxy toggle (registry writes)
│   ├── autostart_*.go   #   Autostart (Windows: selectable Task Scheduler / service / registry method, see Settings; Linux/macOS: per-OS impls)
│   ├── app_tray*.go     #   Tray: build, session watch (unlock/Explorer-restart recovery), reshow
│   └── app_update*.go   #   Version check (rate-limit-free releases.atom fast path + GitHub API), download (progress events + mirrors) and self-update install
├── core/                # Core process management
│   ├── core_client.go   #   Core process launch, RPC client (token-authenticated)
│   ├── core_api.go      #   In-core RPC service (Ping/Shutdown require token match)
│   ├── core_runtime.go  #   Core runtime assembly (TUN, certificates, rules)
│   └── core_admin_*.go  #   Admin elevation
├── common/              # Cross-platform helpers (open file/URL, paths, crash logs, shared TLS verification types)
├── internal/rulesguard/ # Data-guard tests: built-in rules coverage checks (based on snishaper-core's proxy.MatchDomainScore)
├── internal/cliapp/     # CLI dispatcher (no build tag, shared by both flavours)
│   ├── entry.go         #   Run entry + command routing (reused by the GUI's bundled CLI mode)
│   ├── catalog.go       #   Command catalog (single source of truth for help and TUI)
│   └── tui.go           #   Interactive panel (default only for the standalone CLI binary)
├── cli/                 # Standalone headless CLI (build tag: headless)
│   └── main.go          #   Thin shell entry, delegates to internal/cliapp
├── updater/             # Portable updater (Windows, builds SniShaperUpdater.exe)
│   ├── main.go          #   CLI: -config <json> -package <local package> -sha256 <hash>
│   └── …                #   sha256 verify, extract, Authenticode check, install; zero network requests
├── frontend/src/        # React SPA, 12 pages
│                        #   Dashboard, Proxies, Rules, Routing, DNS,
│                        #   Evolution, Logs, Connections, Profiles,
│                        #   Settings, About, Welcome
│   ├── components/      #   Shared layer: Modal, ToastProvider, Sidebar, WindowControls,
│                        #   Tutorial, RuleForm, ECHProfileForm, NAT64ProfileForm
│   ├── theme/           #   Appearance mode only (light / dark / system -> <html class="dark">)
│   ├── i18n/            #   zh / en / ru copy and useTranslation
│   ├── lib/             #   icons.tsx (iconify icon set), toast.ts, utils.ts
│   └── index.css        #   Global styles: just the Tailwind + HeroUI @imports
├── common/              # Cross-platform helpers (open file/URL, paths, crash logs)
├── rules/config.json    # Site-group rules (effective state, ~3800 lines): MITM/ECH/SNI-fake configs; hand-editable, local edits survive updates
├── rules/config.upstream.json # Upstream backup (created at runtime, gitignored): replaced wholesale by rule updates; "Revert to default" restores from here
├── config/settings.json # App settings: ports, TUN (stack/adapter name), appearance mode, TLS fragmentation, Cloudflare IPs, etc.
└── docs/                # build / Platform / contributing / collaborator agreement docs

The core proxy logic (formerly proxy/ plus the certmanager, cfpool, dohresolver, rules, singtun and tlsfrag packages under pkg/) has been extracted into the standalone library snishaper-core, consumed by this repo via go.mod (currently v0.7.0). Since v0.4.0 sysproxy and evolution also live in that library: pkg/sysproxy is only a thin facade over core's sysproxy.Manager, and the evolution/ directory is gone. Since v0.7.0 rules live in two files: rules/config.json is the hand-editable effective state and rules/config.upstream.json the pristine upstream backup (replaced wholesale on rule updates); the user diff is derived on demand from the two, so local edits and hand edits survive updates automatically. See the Snishaper-Core Library page.

Data Flow

Frontend (React HashRouter)
   │  Wails bindings: EventsOn subscriptions + async Go method calls
   ▼
App API (app/app_api.go)
   │
   ├──► snishaper-core/proxy  Proxy server (HTTP + SOCKS5 mixed port, mode dispatch, rule matching)
   ├──► core/                 Core process (TUN, gVisor stack, auto-routing, DNS hijack)
   └──► snishaper-core        Certificates / DoH / CF IP pool / GFWList / TUN dataplane
  • Frontend state sync: the backend emits app:state / app:state_changed events via emitFrontendState(); the frontend subscribes and refreshes.
  • TLS fragmentation settings fall back across three levels: per-rule frag > global fragment section in settings.json > tlsfrag.DefaultTLSRF* presets; NumRecords=1 with NumSegments>=2 means TCP-only fragmentation (bytes untouched, cut point moved before the SNI).
  • TUN data plane: TUN only sniffs domains for routing rebuild (reads the first packet for SNI when fake-ip reverse lookup fails) and never rewrites the ClientHello — the TLS transcript hash covers the entire handshake, and modifying bytes in transit causes bad record MAC errors. SNI masquerading happens only at the TLS endpoint (MITM outbound replay).
  • Upstream dial DoH fallback: when all primary candidates (rule upstream / CF IP pool / DoH resolution) fail, the target domain is re-resolved via DoH and retried once (never via system DNS — under TUN it returns fake-ip); only after the fallback fails does the proxy answer 502, logged with a 502 (local) marker to distinguish local errors from pass-through upstream status codes.
  • Core RPC isolation: the core and its client authenticate with a one-shot token (Ping/Shutdown both verify it), so overlapping instances cannot kill a freshly started core.
  • Upstream requests go through the system proxy: every request to upstream services (GitHub) — notices, update checks/downloads — prefers the system proxy (UpstreamProxyFunc() in pkg/sysproxy, probe result cached with TTL) and falls back to a direct connection when it is unreachable.
  • Self-update split: the main app handles version checks (the releases.atom fast path avoids GitHub API rate limits; the API is called once only when a newer release exists) and downloads (progress events + mirrors); the SniShaperUpdater.exe only verifies the sha256, extracts and installs (-package/-sha256) — it makes zero network requests. Installation has two modes: if the package contains an Inno Setup installer it runs via runas; a flat portable package (contains snishaper.exe, no installer) is installed by closing the app processes, overwriting the application directory in place, and relaunching the app (the running updater renames itself aside first; the old copy is deleted on reboot; config/settings.json and rules/config.json are user data and are preserved, not overwritten — they are managed from the in-app pages).

Frontend Styling Conventions

The frontend is unified on HeroUI v3 (React Aria Components) + Tailwind CSS v4; MUI and emotion have been removed entirely.

  • Import every component from @heroui/react and use the dot-notation subcomponents (Card.Header, Modal.Dialog, Select.Trigger, Table.Row). Do not use the v2 flat subcomponents or import from @nextui-org/*.
  • Appearance is decided solely by HeroUI's default variants, sizes and default theme: no sx, styled(), makeStyles or createTheme visual customization, and no overrides of .heroui-* BEM classes or --heroui-* / OKLCH variables.
  • HeroUI ships no layout components; lay out with Tailwind utilities (flex / grid / gap-* / p-*) and never reach inside a HeroUI component to change how it renders.
  • v3 needs no <Provider> wrapper. Dark mode uses the official mechanism, i.e. <html class="dark">, applied by applyThemeMode() in src/theme/index.ts. The app offers only Light / Dark / Follow system (localStorage.appearance-mode plus the backend SetAppearanceMode) and no longer ships multiple color themes.
  • Interactive props follow React Aria semantics: onPress on buttons, isSelected + onChange on switches, selectedKey + onSelectionChange on pickers, isDisabled for disabled state and isPending for loading state.
  • Global styles are just the two @imports in src/index.css (tailwindcss first, then @heroui/styles), with no visual patches layered on top.
  • Validation order: cd frontend && ./node_modules/.bin/tsc --noEmit then bun run build.

Build and Test

  • Full build: .\build_windows.ps1 -Build all -Silent (add -BuildMsix for an MSIX package)
  • Backend / frontend only: -Build backend / -Build frontend
  • Go build check: go build -tags with_gvisor ./...
  • Frontend type check (authoritative): cd frontend && ./node_modules/.bin/tsc --noEmit
  • Headless CLI: see the build section of the CLI Reference

Contributing Notes

  • Commit messages in English, conventional-commit style (feat: / fix: / refactor: ...).
  • New UI copy must be added to the zh / en / ru i18n JSON files in the same change, with matching placeholders.
  • Changes to security-sensitive areas (certificates, TUN, system proxy, core RPC token) require maintainer review; collaborator terms are in docs/COLLABORATOR_AGREEMENT.md.

Clone this wiki locally