Skip to content

Developer Guide

chodeus edited this page Oct 22, 2026 · 6 revisions

🏠 Home › Developer Guide

Developer Guide

For scripting against CHUB, extending it, or auditing it. Just running it? Start at Home.

On this page

Architecture

The React frontend talks to FastAPI over /api. The API and the scheduler run the modules, which talk to your media stack. State lives in SQLite and config.yml.

flowchart LR
    UI["Browser<br/>(React + Vite)"] -->|/api| API["FastAPI<br/>(backend/api)"]
    API --> MOD["Modules<br/>(backend/modules)"]
    SCHED["Scheduler"] --> MOD
    API --> DB[("SQLite + config.yml")]
    MOD --> DB
    MOD --> EXT["Radarr · Sonarr · Lidarr<br/>Plex · Google Drive<br/>fanart.tv · TMDB"]
Loading

Repo layout

backend/
  api/         FastAPI routers — one file per resource (posters/ is a package)
  modules/     Scheduled/on-demand modules — one file each
  util/        Config, auth, logging, rate limiting, path safety, SSRF guard, database/
  extensions/  Self-registering extension manifests (cl2k, poster_self_heal)
frontend/
  src/         React 19 app, bundled by Vite
deploy/        Dockerfile, compose.yaml, Unraid template
scripts/       start.sh (container entrypoint) and helper scripts
tests/         pytest suite
main.py        Entry point — starts scheduler, worker, HTTP server
config/        Bare-metal CONFIG_DIR (/config in Docker):
  config.yml   Runtime config, validated by Pydantic on load
  chub.db      SQLite — jobs, media cache, history, health snapshots

Running locally

git clone https://github.com/chodeus/chub.git
cd chub
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt -r requirements-dev.txt
python3 main.py           # backend on :8000

cd frontend
npm install
npm run dev               # Vite dev server on :5174, proxies /api

Use Python 3.14 and Node.js 24.22.0+, the versions CI and the image use. Shortcut: make bootstrap installs everything (it also adds requirements-cl2k.txt), and make dev starts both servers.

Tests & linters (CI runs the first five)

  • ruff check . — Python lint
  • python3 -m pytest tests/ — backend tests (needs requirements-dev.txt)
  • npm run lint (in frontend/) — JS lint
  • npm run test:run (in frontend/) — Vitest suite
  • npm run build (in frontend/) — production bundle sanity check
  • make lint / make test — backend and frontend together

Writing a module

  1. Create backend/modules/my_module.py:

    from backend.util.base_module import ChubModule
    
    class MyModule(ChubModule):
        def run(self):
            self.logger.info("starting")
            for item in self.work():
                if self.is_cancelled():
                    return
                self.process(item)
  2. Add a Pydantic config model in backend/util/config.py and attach it to ChubConfig:

    class MyModuleConfig(BaseModel):
        log_level: str = "info"
        dry_run: bool = False
    
    class ChubConfig(BaseModel):
        my_module: MyModuleConfig = Field(default_factory=MyModuleConfig)
  3. Register the class in backend/modules/__init__.py — import it and add it to the MODULES dict:

    from .my_module import MyModule
    
    MODULES = {
        # ...existing modules...
        "my_module": MyModule,
    }
  4. Add the key to the frontend lists so the UI shows it: moduleOrder in frontend/src/utils/constants/constants.js (Schedule and Notifications pages), CORE_CONFIG_MODULE_KEYS in frontend/src/hooks/useModuleSchema.js (settings form), and a { name, key, description } entry in CORE_SETTINGS_MODULES in frontend/src/utils/constants/settings_schema.js.

  5. Restart the dev server or rebuild the container.

Cancellation. Check self.is_cancelled() in any long loop and return when it's true.

Progress. In long phases, call self._report_progress(pct) so the job's percentage moves (poster_renamerr.py has a multi-phase example).

Heartbeat lines. Use self.logger.heartbeat(msg) for repetitive progress lines; the Logs page hides them by default.

One-shot migrations. When a column's meaning changes, add self._apply_once(conn, name, sql, requires_table=...) in backend/util/database/schema.py. The name (ISO date + snake_case, e.g. 20260522_null_has_content_default_rows) is recorded so it runs once.

Extensions

Optional tools — the CL2K poster maker (cl2k) and poster self-heal (poster_self_heal) — self-register through a manifest: backend/extensions/<name>/manifest.py and frontend/src/extensions/<name>/manifest.jsx. Registration needs no edits to shared registries. The code lives on main and ships in both images. The :latest image sets CHUB_IMAGE_FLAVOR=lean, which turns off their routes, modules, and UI; their config sections and database tables stay registered, so a config written under :full still loads. The :full image adds their extra dependencies (requirements-cl2k.txt, ImageMagick). See backend/extensions/__init__.py for the hooks (routers, modules, config_fields, tables, stream_prefixes, notification_formatters, and an optional available() check).

Security guards

  • Auth — bcrypt password hashes + per-install JWT secret; AuthMiddleware (backend/api/main.py) validates every /api/* request. Exempt: /api/auth/login, /api/auth/setup, /api/auth/status, /api/setup/status, /api/health*, /api/version (exact — /api/version/check needs a login), static paths, and the two secret-gated webhook ingest routes. With no login stored (first run, or turned off via POST /api/auth/disable) every request is allowed. A token in the URL (?token=) must be a short-lived stream token from POST /api/auth/stream-token (5 minutes, GET only, image/SSE routes only); a session token there gets 403.
  • Rate limiting — token bucket (backend/util/rate_limiter.py); login limiter ~1 attempt / 5s, burst 5, excess returns 429.
  • SSRF guard — backend/util/ssrf_guard.py; rejects reserved/link-local/multicast IPs, cloud-metadata hosts, non-http(s) schemes, and unresolvable hosts on outbound instance probes.
  • Path safety — backend/util/path_safety.py confines directory browsing and file access to roots derived from config and rejects null bytes. Values passed to rclone/jdupes (sync_gdrive locations, jduparr.hash_database) are also refused if they start with -; each module checks its own.
  • Webhook auth — optional general.webhook_secret via X-Webhook-Secret header or ?secret=; duplicate payloads are debounced.
  • Log redaction — backend/util/log_redaction.py scrubs JWTs, Bearer tokens, API/Plex tokens, OAuth secrets, and webhook URLs before they hit disk.
  • API secret redaction — GET /api/config replaces secret leaf keys with ******** (matched by exact key name); on save, fields still equal to ******** keep their on-disk value. GET /api/config/secret?path= reveals one secret on demand, never password_hash or jwt_secret.

Contributing

  1. For anything beyond a small fix, open an issue first to agree the scope.
  2. Fork, branch, and open a PR against main — one feature per PR.
  3. Run the linters and tests, and build the frontend, before pushing.
  4. Use a Conventional Commits title (feat: …, fix: …). release-please writes CHANGELOG.md from it; don't edit that file by hand.

Releases and images. A push to main that changes code publishes :latest and :full once CI passes. release-please keeps a release PR open on main; merging it tags vX.Y.Z and publishes vX.Y.Z, X.Y.Z, and their -full twins, plus fresh :latest and :full.


Next: REST API · Related: Configuration, Modules

Clone this wiki locally