Faction management toolkit for Torn.com — real-time member tracking, war coordination, training guides, market analysis, and 25+ tools. Built with FastAPI + Next.js 15.
  • TypeScript 51.3%
  • Python 47.7%
  • JavaScript 0.4%
  • Shell 0.2%
  • CSS 0.2%
Find a file
Paweł Orzech 9848345434
Full read-only hub demo at /demo, hub window on the landing, new favicon (1.96.0) (#177)
* feat(landing): read-only window into the hub with its own screens (WIP for /demo)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* feat(demo): demo mode core: tab-scoped flag, local /api layer, sample identity

/demo turns on a sessionStorage flag on the platform and local hosts only.
While it is on, a fetch wrapper installed before hydration answers every
same-origin /api request from a lazily imported fixture registry, refuses
writes with a read-only 403 and stubs the claims SSE and chat socket.
Auth, tenant, avatar cache, admin session and the api client never read
or write the visitor's real session keys in demo mode; Sentry and Umami
events are off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* feat(demo): demo empty states, safety tests, pinned-nav migration guard

Settings, Subscription and Administration show a short demo notice
instead of tools that only make sense for a real workspace. The sidebar
hides the operator link and the footer hides the Umami link in the demo;
the banner and these checks read the flag through a hydration-safe hook.

Safety tests seed a full real session, walk dashboard, admin, settings
and sign-out in demo mode and require localStorage and cookies to be
byte-identical afterwards. That caught the pinned-nav migration flag
being written for the real account, now skipped in the demo. /demo on a
workspace host refuses and a hand-set flag is ignored there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* feat(landing): link the full demo from the hub window and the nav (1.96.0)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* feat(demo): fixtures for every nav page, one coherent sample faction

Warfare (enemies, spy, targets, claims, off-limits, stakeout, bounties,
wars, chain and reports), economy and training (market, stocks, loot,
revives, travel, companies, director, training, stats, awards) and
faction (dashboard, team, faction HQ, schedule, activity, OCs, armoury,
analytics, notifications, news, chat, inbox), all derived from one seed
so the same member has the same numbers everywhere. Handlers are typed
against the api client's return types, or against the page's own shape
where the client declares unknown.

A coverage test renders every NAV_GROUPS page (plus chat and inbox)
through the real api client and the demo layer and fails on any 404
fallback, any /api call reaching the network or any error alert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* fix(demo): act as the demo only where the network layer is installed

The browser walk showed seven shell requests reaching the server once:
the /demo page itself had set the flag, took on the demo identity and
polled before its reload, with no fetch wrapper in that document.
isDemoMode() now also requires this document's runtime to be active, so
a page that was running when the flag appeared stays a normal page.

Also: the dashboard hides the workspace setup checklist and the shell
hides the install prompt in the demo.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* fix(demo): no Umami custom events, narrower link guard, sign-up ends the demo

Web vitals, perf marks and command-palette events called Umami directly,
past trackEvent; demo tabs now send pageviews only. The Torn link guard
now swallows only profile, faction and attack links, so item market,
stocks and the API key page still open. Opening onboarding, login,
platform or the sign-in handoff with the flag on clears it, so a reload
there reaches the real API instead of the read-only 403.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* feat(brand): new TornHub favicon and app icons (T with the live dot)

Replaces the old TM Hub monogram: dark T and the landing's green live dot
on a light tile, so the tab icon stands out on dark browser chrome at 16px.
Adds the SVG as the first favicon; regenerates the 192/512 PNGs, a
full-bleed 180px apple-touch icon, maskable icons inside the 80% safe zone
and a white monochrome notification badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

* fix(landing): teaser enemies are Rival_*, matching the full demo

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNVGq9qjzxt63k612Ar6s6

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 00:29:24 +01:00
.github chore: remove Playwright, replace its coverage with a Claude in Chrome walk list (#149) 2026-11-11 15:50:52 +01:00
.jules fix(security): escape chat-search snippets + restrict extension-auth postMessage origin 2026-06-24 15:46:21 +02:00
api perf: index-driven stats leaderboards, narrow chain rebuild (1.93.2) (#174) 2026-11-22 22:06:16 +01:00
docs TornHub 1.90.0: monitoring (Sentry crons/replay-on-error/release, Kuma push, deep health, weekly digest, Umami funnel) (#166) 2026-11-22 18:22:55 +01:00
extension TornHub at tornhub.app: sales landing, terms/privacy, universal Companion, platform fixes (1.88.0) (#160) 2026-11-22 16:38:55 +01:00
frontend Full read-only hub demo at /demo, hub window on the landing, new favicon (1.96.0) (#177) 2026-11-23 00:29:24 +01:00
ops Operator console at admin.tornhub.app (passkey-only), bans/suspend/comp/extend (1.88.3) (#163) 2026-11-22 17:32:52 +01:00
scripts perf: index-driven stats leaderboards, narrow chain rebuild (1.93.2) (#174) 2026-11-22 22:06:16 +01:00
static chore(cleanup): untrack Plans drafts, superpowers history, favicon, dead frontend 2026-09-13 22:52:39 +02:00
tests Landing overhaul for tornhub.app, applied app-wide (1.94.0) (#175) 2026-11-22 23:01:13 +01:00
.dockerignore ci: run independent release gates in parallel, list every failure (#159) 2026-11-22 01:11:37 +01:00
.env.example TornHub 1.90.0: monitoring (Sentry crons/replay-on-error/release, Kuma push, deep health, weekly digest, Umami funnel) (#166) 2026-11-22 18:22:55 +01:00
.gitignore chore: remove Playwright, replace its coverage with a Claude in Chrome walk list (#149) 2026-11-11 15:50:52 +01:00
.gitleaks.toml TornHub 1.89.0: sign in once with your Torn key, pick your workspace (#164) 2026-11-22 17:48:48 +01:00
.mcp.json feat: MCP server embedded in FastAPI — 30 tools for faction management 2026-04-11 14:53:33 +02:00
.pre-commit-config.yaml ci(security): add gitleaks secret scanning (CI + pre-commit) 2026-06-24 15:39:10 +02:00
.python-version fix: clearer Enemies page — hospital order by time left, lead-based war banner, Companion connect hint (#152) 2026-11-14 21:31:47 +01:00
AGENTS.md fix: announcement expiry, latest stat snapshots, accurate MCP tool contracts 2026-09-25 00:41:03 +02:00
CLAUDE.md TornHub 1.92.0: Lato, Barlow Semi Condensed, Red Hat Mono (#171) 2026-11-22 19:32:19 +01:00
docker-compose.yml feat: multi-stage Docker build, FastAPI serves Next.js export 2026-03-28 15:54:25 +01:00
Dockerfile TornHub 1.90.0: monitoring (Sentry crons/replay-on-error/release, Kuma push, deep health, weekly digest, Umami funnel) (#166) 2026-11-22 18:22:55 +01:00
lighthouserc.json Fix personal workspace features and data scope (#137) 2026-09-24 11:27:34 +02:00
nginx.conf fix(nginx): never cache 404s for hashed static chunks during deploys (1.93.1) (#173) 2026-11-22 20:17:55 +01:00
plan.md fix: harden multitenant SaaS boundaries 2026-07-26 10:38:35 +02:00
pyproject.toml Operator console at admin.tornhub.app (passkey-only), bans/suspend/comp/extend (1.88.3) (#163) 2026-11-22 17:32:52 +01:00
README.md chore: remove Playwright, replace its coverage with a Claude in Chrome walk list (#149) 2026-11-11 15:50:52 +01:00
start.sh fix(enemies): stop the Enemy page crashing when you load a faction 2026-07-23 17:30:35 +02:00
uv.lock TornHub 1.89.1: cross-worker bans, expiry sweep fix, console hardening, dependency updates (#165) 2026-11-22 18:11:00 +01:00

TM Hub login screen

TM Hub

An operational toolkit for Torn.com factions.
War coordination, member readiness, faction intelligence, economic tools, live chat, and in-game Companion overlays in one self-hosted platform.

Python 3.12 Next.js 16 React 19 Pytest coverage gate

Important

The production instance at hub.tri.ovh is the private, legacy single-tenant deployment for The Masters [TM], faction 11559. The repository also contains the tested multi-tenant control plane, per-tenant data isolation, onboarding, and Xanax billing flows, but the SaaS launch lock and all component flags are off by default. See Multi-tenancy status before changing those boundaries.

What TM Hub is

TM Hub turns Torn, TornStats, and YATA data into decisions faction members and leaders can act on. It is designed around four rules:

  • Explain the decision. Say what a number means and what the player should do next.
  • Teach the mechanic. Pair each tool with the guidance a player needs to use it, rather than showing raw API data.
  • Show provenance. Distinguish live, cached, imported, and estimated data.
  • Fail clearly. Show explicit loading, empty, stale, and error states when an upstream service is down.

Product surfaces

Faction operations

Surface What it provides
Dashboard and team Live faction state, readiness, status, energy/cooldowns, travel, hospital, chain, OC, loot, and chat summaries
Ranked wars Current opponent, score and progress, enemy threat estimates, target claims, off-limits coordination, reports, and history
Chain tracker Chain discovery, member contribution, bonus hits, assists, timeline, analytics, and war reports
Chain reports Torn's official report for each completed chain: every bonus hit and who took it, per-member respect and attack mix, and the members who hit nothing
Organized crime OC assignments, participant roles, readiness, checkpoint pass rates, crime-experience ranking, and chat digest
Armoury competitions Deposit-based competitions by item/category, polling, leaderboards, and admin controls
Scheduling and notifications Faction schedule, announcements, inbox, web push/PDA delivery, and configurable notification groups
Faction chat Channels, threads, search, reactions, pins, mentions, presence, bots, assist calls, and live WebSocket updates
Faction HQ Lifetime faction stats, purchased upgrades, hall-of-fame placings, the position and ability matrix, and the bank ledger

Intelligence and player tools

Surface What it provides
Spy Central Player/faction lookup, TornStats and YATA intelligence, local spy history, stat estimates, and admin curation
Targets, stakeout, and activity Tagged target lists, player status watch, activity heatmaps, flight tracking, hit calling, and mug-opportunity scoring
Stats and training Stat snapshots, growth leaderboards, gym formulas, happy jumps, energy planning, and SE/Xanax comparisons
Market and travel Torn item catalog, live prices and market listings, margins and taxes, foreign stock, travel timing, and profitability
Stocks, bounties, and revives Portfolio/ROI views, bounty prioritization, revive history, success rates, and leaderboards
Company tools Faction company directory plus director-only employee, application, stock, train, trend, and runway analysis
Awards and guides Honor/medal progress, circulation context, FAQ, game guides, and curated userscripts

TM Hub Companion

extension/ is a separately built userscript that brings authenticated TM Hub data into Torn pages. It supports overlays for faction intelligence, flights, activity, hit calling, chat, and related shortcuts; rollout-heavy features are controlled through the authenticated feature-flag contract. Its token is independently issued and revocable, and the production bundle is built into /companion.user.js as part of the Docker image.

Screenshots

Dashboard Team
TM Hub dashboard in dark mode Faction team overview
Training Market
Training guide and calculators Market scanner and profit calculations
NPC loot Light theme
NPC loot levels and reservations TM Hub dashboard in light mode

Player names in the screenshots are anonymized.

Architecture

flowchart LR
    B["Browser / installed PWA"] --> N["nginx :8000"]
    C["TM Hub Companion on torn.com"] --> N
    N -->|"static HTML, JS, CSS"| S["Next.js static export"]
    N -->|"HTTP, SSE, WebSocket"| A["FastAPI via Gunicorn<br/>2 Uvicorn workers"]
    A --> T["Torn API v1/v2<br/>TornStats · YATA"]
    A --> D["SQLite WAL<br/>repository layer"]
    A --> R["Redis<br/>pub/sub · leader lease · shared limits"]
    L["One APScheduler leader"] --> A
    D --> BK["Optional encrypted B2 backups"]

Runtime model

  • Frontend: Next.js 16 App Router, React 19, TypeScript, Tailwind CSS v4, and Chart.js. output: "export" produces static assets; there is no Next.js server in production.
  • API: Python 3.12 and FastAPI with 32 feature routers and approximately 240 HTTP/WebSocket route handlers.
  • Persistence: SQLite in WAL mode through thread-local pooled repository connections. The 59 numbered migrations run automatically at startup.
  • Background work: APScheduler 4 jobs run only in the elected worker. Production uses a Redis lease; a single-host deployment without Redis falls back to a POSIX file lock. Losing a Redis lease stops that scheduler before another worker takes over.
  • Realtime and shared state: Redis provides cross-worker chat pub/sub, presence, scheduler leadership, shared rate limits, and distributed cache support. Single-worker development can run without Redis.
  • Edge: nginx serves precompressed static assets, proxies API/WebSocket traffic, and includes the canonical host in its cache key. The final image pins and validates a SQLite runtime containing the WAL-reset corruption fix.
  • Observability: optional Sentry-compatible backend and browser reporting with secret/PII scrubbing, request analytics, Companion RUM, health checks, and production-image load tests.

Authentication and authorization

  1. A member submits a Torn API key to POST /api/keys.
  2. The backend validates the key and faction membership, then stores it encrypted with Fernet.
  3. The backend issues a signed session JWT, sets a Secure, HttpOnly, SameSite=Strict cookie in production, and keeps bearer-token compatibility for the current web client and Companion.
  4. Protected requests bind the JWT subject to X-Player-Id; revoked JWTs and deactivated faction members are rejected immediately.
  5. Admin and platform sessions use separate token types and cookies. Tenant roles are owner → admin → member; the legacy faction retains its explicit break-glass superadmin allowlist.

When multi-tenancy is enabled, the validated request host selects a control-plane tenant and an isolated tenant database. Tenant/faction JWT claims, repositories, caches, rate limits, schedulers, WebSockets, SSE streams, backups, and realtime channels are all checked against that context. Unknown or mismatched hosts fail closed.

Repository layout

api/
├── main.py                  FastAPI app, lifespan, middleware, legacy core routes
├── config.py                Environment and feature-flag configuration
├── auth.py / tenancy.py     JWT, revocation, roles, host and tenant boundaries
├── torn_client.py           Async Torn/TornStats/YATA client and caches
├── db/
│   ├── migrations/          59 startup-applied SQL migrations
│   └── repos/               SQLite repository layer
├── routers/                 32 domain routers
└── scheduler/               Leader election and background jobs

frontend/
├── src/app/                 Static-exported application routes
├── src/components/          Domain and shared React components
├── src/hooks/               Data-fetching and UI hooks
└── src/lib/api-client.ts    Same-origin API client and auth lifecycle

extension/                   TM Hub Companion userscript, tests and build
ops/k6/                      Load-test scenarios
scripts/                     Migration, restore, calibration and verification tools
docs/                        ADRs, threat model, runbooks and engineering evidence

Local development

Prerequisites

  • Python 3.12+
  • uv
  • Node.js 22.19+ and npm (the Docker build itself uses Node 20)
  • Docker for the production-like full-stack image
  • Redis for multi-worker/realtime parity; optional when running one API worker

Install

git clone https://github.com/pawelorzech/tm-war-room.git
cd tm-war-room

uv sync --extra dev
npm --prefix frontend ci
npm --prefix extension ci

cp .env.example .env

Set at least TORN_API_KEY. In production, ENCRYPTION_KEY and JWT_SECRET are mandatory; development generates ephemeral values when APP_VERSION=dev.

Run individual development servers

# FastAPI on http://localhost:8000
TORN_API_KEY=xxx uv run uvicorn api.main:app --reload --port 8000

# Next.js UI development server on http://localhost:3000
npm --prefix frontend run dev

# Rebuild the Companion on changes
npm --prefix extension run build:watch

The browser client uses same-origin /api/* requests. Use a local reverse proxy when developing the UI against the separate API process, or run the production-like image below for an integrated stack.

Run a production-like image

docker build -t tm-hub .
docker run --rm \
  --name tm-hub-local \
  --env-file .env \
  -e WEB_CONCURRENCY=1 \
  -p 8000:8000 \
  -v tm-hub-data:/app/data \
  tm-hub

Open http://localhost:8000. Use REDIS_URL and more than one worker only when Redis is reachable.

Configuration

The minimal starter file is .env.example; runtime defaults and feature gates live in api/config.py. Important groups are:

Group Variables Notes
Torn TORN_API_KEY, TORNSTATS_API_KEY, FACTION_ID, CACHE_TTL FACTION_ID defaults to The Masters (11559)
Secrets ENCRYPTION_KEY, JWT_SECRET, SUPERADMIN_IDS, MCP_SECRET Primary encryption/signing keys fail fast outside APP_VERSION=dev
Runtime APP_VERSION, REDIS_URL, WEB_CONCURRENCY, FORWARDED_ALLOW_IPS Production defaults to two workers; shared state requires Redis
Push and storage VAPID_*, B2_*, BACKUP_ENCRYPTION_KEY, BACKUP_RETENTION_DAYS Backups use a separate encryption key and should use restricted private-bucket credentials
Observability SENTRY_DSN, SENTRY_TRACES_SAMPLE_RATE, NEXT_PUBLIC_SENTRY_DSN, ENABLE_RUM All are optional; RUM is feature-flagged
Companion features ENABLE_FF_SCORE, ENABLE_FLIGHTS, ENABLE_ACTIVITY, ENABLE_HIT_CALLING Runtime flags exposed through the authenticated Companion contract
SaaS launch SAAS_ENABLED, MULTITENANCY_ENABLED, BILLING_ENABLED, ONBOARDING_ENABLED, NEXT_PUBLIC_SAAS_ENABLED Umbrella and component flags default to 0; provisioning also defaults to dry-run

Do not enable the SaaS flags from this table alone. Follow the migration runbook, threat model, and current launch checklist.

Verification

Backend

# Full suite; v1.76.0 collects 1,944 tests
uv run pytest tests/ -v

# CI-equivalent parallel run with coverage ratchet
uv run pytest -n auto --dist loadfile \
  --cov=api --cov-report=term --cov-report=xml --cov-fail-under=68.8

Frontend

npm --prefix frontend run typecheck
npm --prefix frontend run lint
npm --prefix frontend run test:coverage
npm --prefix frontend run build
npm --prefix frontend run size:routes

UI regression is a manual Claude in Chrome walk, not an automated suite: see docs/ui-regression-walk.md.

Companion

npm --prefix extension run typecheck
npm --prefix extension run test:coverage
npm --prefix extension run test:mutation
npm --prefix extension run size

Run scripts/local_ci.sh on the operator's computer for all release gates, including the production Docker image, pinned SQLite runtime, WAL concurrency, nginx, k6, Companion API contracts, Gitleaks and the mobile Lighthouse budget. Pushes and pull requests do not launch GitHub runners. The GitHub workflows remain available only as manually dispatched fallbacks.

Deployment

master is the production branch:

flowchart LR
    M["Review and merge to master"] --> L["Local release script on operator computer"]
    L --> CI["Tests, coverage, static export,<br/>mutation, size and security gates"]
    CI --> IMG["Production image + SQLite/nginx/k6 validation"]
    IMG --> C["Local Coolify API trigger, build and rollout"]
    C --> P["hub.tri.ovh"]

scripts/local_deploy.sh --deploy requires a clean local master matching origin/master, runs every local gate, then triggers Coolify with locally held credentials. A production rollout is not complete until the authenticated browser walkthrough and evidence checklist in CLAUDE.md has passed.

Legacy redirects remain:

URL Destination
rw.tri.ovh https://hub.tri.ovh/team
train.tri.ovh https://hub.tri.ovh/training

Engineering documentation

License

Private software built for The Masters [TM]. It is not licensed for public redistribution.