cm_bot_v2/AGENTS.md

106 lines
5.9 KiB
Markdown

# Repository Guidelines
## Project Structure & Module Organization
- `app/` contains service modules:
- `cm_api.py` (Flask API, serves on `3000`)
- `cm_web_view.py` (Flask UI, container `8000`, host `8001`)
- `cm_telegram.py` (Telegram bot + account monitor thread)
- `cm_transfer_credit.py` (scheduled transfer worker)
- `db.py` (MySQL connection/retry logic)
- `web/` is the Next.js 15 app for the new web view (`cm-web-next` service). Tailwind v4, App Router, TypeScript. Side-by-side with the legacy Flask `cm_web_view.py` until B4 cuts over.
- `docker/<service>/Dockerfile` builds one image per service (`cm-api`, `cm-web`, `cm-web-next`, `cm-telegram`, `cm-transfer`).
- `docker-compose.yml` uses registry images; `docker-compose.override.yml` swaps to local builds.
- `scripts/local_build.sh` starts local compose; `scripts/publish.sh` builds and pushes all images via buildx.
## Reproduce From Scratch (Clean Machine)
1. Install prerequisites:
- Docker Engine + Docker Compose v2
- MySQL 8+ reachable by containers
- Telegram bot token(s) for bot and optional alerting
2. Clone and enter repo:
```bash
git clone <repo-url> cm_bot_v2
cd cm_bot_v2
```
3. Create `.env` at repo root for compose interpolation:
```bash
CM_IMAGE_PREFIX=local
DOCKER_IMAGE_TAG=dev
TELEGRAM_BOT_TOKEN=<required>
TELEGRAM_ALERT_CHAT_ID=<optional>
TELEGRAM_ALERT_BOT_TOKEN=<optional>
CM_TRANSFER_MAX_THREADS=1
```
4. Prepare the local dev DB and stack:
```bash
cp envs/dev/.env.example .env
# Edit .env if you want the bot CLI to actually call cm99.net
# (CM_AGENT_ID / CM_AGENT_PASSWORD / CM_SECURITY_PIN).
bash scripts/dev.sh up
```
This brings up `mysql` (port `127.0.0.1:3306`), `api-server`, and
`web-view`. The schema and a 4-row seed are applied automatically
from `docker/mysql/init.d/`. Bots (`telegram-bot`, `transfer-bot`)
are gated behind a compose `bots` profile and do not start in dev.
## Auth
- The Next.js dashboard (`cm-web-next`) gates every route except `/cm-auth` behind a session cookie.
- **Password sign-in** uses `CM_AGENT_ID` and `CM_AGENT_PASSWORD` from the deployment's `.env` (constant-time compare). No separate user table.
- **WebAuthn passkey** sign-in is the preferred path on devices with platform authenticators (Face ID, Touch ID, Android fingerprint). Enroll one at `/cm-passkeys` after the first password login.
- Session: signed `httpOnly` cookie (`cm_auth`), 30-day rolling. Requires `CM_AUTH_SECRET` env var (≥32 chars). Generate with `openssl rand -hex 32`.
- Passkey storage: `/data/auth/passkeys.json` inside the container, mounted from the `${CM_DEPLOY_NAME}-web-next-auth-data` named volume. Atomic writes; persists across container restarts and image rebuilds.
- "Forgot password" recovery: look at the deployment's `.env`. There's no email reset flow.
- Rotating `CM_AUTH_SECRET` invalidates all sessions (forces everyone to re-login).
## Dev Tier (Local Development)
- Lifecycle: `bash scripts/dev.sh {up,down,reset-db,logs,status}`.
- URLs: `http://localhost:8000/` (legacy Flask UI), `http://localhost:8010/` (new Next.js scaffold). Both run side-by-side until the B4 cutover retires the Flask version.
- Bot CLI: `bash scripts/bot_cli.sh` (drops into the TUI menu) or
`bash scripts/bot_cli.sh <subcommand>` (e.g., `register`, `set-pin <link>`,
`monitor-once --target 5`). The CLI runs in your local `.venv` and
connects to the dev mysql at `127.0.0.1:3306`.
- The auto-create monitor does NOT run in dev (it lives in `telegram-bot`,
which is gated by the `bots` profile). Use `bot_cli.sh monitor-once` to
exercise the same code path manually.
- Tests: `.venv/bin/python -m unittest tests.test_debug_enabled tests.test_bot_cli -v`.
## Build, Test, and Development Commands
- `python3 -m venv .venv && source .venv/bin/activate && pip install -r requirements.txt`: optional non-Docker local env.
- `docker compose -f docker-compose.yml -f docker-compose.override.yml up --build`: local dev stack.
- `docker compose up -d`: run prebuilt/published images.
- `bash scripts/publish.sh <tag>`: build + push all service images (`gitea.04080616.xyz/yiekheng`).
## Verification Checklist
- API responds: `curl http://localhost:3000/acc/`
- Web UI loads: open `http://localhost:8000` (dev) or `http://localhost:8001` (rex prod) / `http://localhost:8005` (siong prod).
- Service logs are clean:
```bash
docker compose logs -f api-server web-view telegram-bot transfer-bot
```
- Telegram bot validates with `/menu` and `/9` in chat after startup.
## Coding Style & Naming Conventions
- Python 3.9, 4-space indentation, snake_case for variables/functions, module names as `cm_<role>.py`.
- Preserve existing class names (`CM_API`, `CM_BOT`, `CM_BOT_HAL`).
- Keep environment variable names uppercase and document new ones in this file.
- No enforced formatter/linter in-repo; match the surrounding style in touched files.
## Testing Guidelines
- No automated test suite is currently committed.
- Required minimum before PR: run verification checklist above on local compose.
- For logic-heavy changes, add `pytest` tests under `tests/` and include execution command/results in PR.
## Commit & Pull Request Guidelines
- Use short, focused commit subjects in imperative tone (existing history: `Fix ...`, `Update ...`, `Refactor ...`).
- Keep each commit scoped to one behavior change.
- PR must include:
- problem statement and solution summary,
- services/files affected,
- required env/config changes,
- API/log evidence (and UI screenshot if `cm_web_view.py` changed).
## Security & Configuration Tips
- Never commit real secrets in `.env`.
- `CM_DEBUG` defaults to `false` for both Flask services. Set it to `true` only in local development; rex/siong production env files must leave it unset (the Werkzeug debugger is RCE if reachable).
- Keep container clocks mounted (`/etc/timezone`, `/etc/localtime`) as compose currently defines to avoid schedule drift.