# Commander Online multiplayer Magic: The Gathering (Commander) emulator. This repository holds a Nuxt frontend, a Fastify API, and a working Magic rules engine that executes the compiled card effects. You can build or import a Commander deck in the browser and play a 2–4 player match against other clients. ## Stack - **frontend/** — Nuxt 4, Vue 3, TypeScript, server-side rendering - **backend/** — Node 24, Fastify 5, TypeScript, Mongoose - **MongoDB** — accounts, saved decks, playmat and card-back preferences - **Docker Compose** — hot-reloading development stack and standalone production images ## Requirements - Docker with Compose v2 - Node 24 + npm only if you want to run the apps outside Docker - MongoDB reachable on `localhost:27017` (the Compose backend uses host networking to reach it) ## Development Start both services with hot reload: ```bash cp .env.example .env # optional: adjust public URLs and ports docker compose -f docker-compose.dev.yml up --build ``` | Service | URL | | -------- | ---------------------------- | | Frontend | http://localhost:3000 | | API | http://localhost:4000 | | Health | http://localhost:4000/health | | MongoDB | mongodb://localhost:27017 | Source directories are bind-mounted, so edits reload automatically. Dependencies live in named volumes and are synced on container start. If the volumes get into a bad state, reset them with: ```bash docker compose -f docker-compose.dev.yml down -v ``` Stop the stack with `docker compose -f docker-compose.dev.yml down`. ### Without Docker ```bash # terminal 1 cd backend && npm install && npm run dev # terminal 2 cd frontend && npm install && npm run dev ``` The backend listens on port `4000` and the frontend on `3000` by default. It connects to MongoDB at `mongodb://localhost:27017/commander`; start a local MongoDB or set `MONGODB_URI` to point somewhere else. ## Card data Cards come from Scryfall's [Oracle Cards bulk export](https://scryfall.com/docs/api/bulk-data) — one card per Oracle ID, filtered to cards legal in Commander. ```bash cd backend npm run import:cards ``` This downloads the bulk file and writes `backend/data/cards.json` (about 21 MB, not committed). It stores each card's rarity and the formats it is legal in, so re-run it after pulling changes to the importer. Re-run it whenever you want a fresh card pool. In the dev stack the file is visible through the bind mount. For production, run the import before `docker compose build` so the API image includes the data. If the file is missing, the card endpoints return `503` with a reminder to run it. Card art is not bundled. The first time a card's art is requested, the API downloads its image from Scryfall and stores it in `backend/data/images/`. The production Compose stack keeps that directory in the `card_images` named volume, so the cache survives restarts. Delete the directory to reclaim the space; images are downloaded again when needed. ## Card effects Oracle text is compiled into a machine-readable effect AST for the game engine. The compiler is conservative: a line it cannot parse is marked `unsupported` with its original text, never guessed. ```bash cd backend npm run compile:cards # data/card-effects.json + data/card-effects.pseudo.txt npm test ``` `data/card-effects.pseudo.txt` is the human-readable pseudocode view. The pseudocode is also an input format: the frontend editor saves one override file per card under `backend/data/card-overrides/`, and `npm run compile:cards` validates those files and uses them instead of generated output. See [backend/docs/card-effects.md](backend/docs/card-effects.md) for the DSL, current coverage, and how to add support for more cards. The `/cards` page has an **Editor** view and a **Guide** view that summarizes the pseudocode syntax. **Draft with AI** sends the selected card's oracle text to an OpenRouter model and loads the returned pseudocode into the editor without saving it. The model is instructed to answer with pseudocode only — no explanations, Markdown or code fences — and the answer must parse before the API returns it. Set `OPENROUTER_API_KEY` on the backend to enable the button; `OPENROUTER_MODEL` defaults to `google/gemini-2.5-flash-lite`. ## Game engine `backend/src/game/` is a synchronous rules engine built on that AST. It covers zones, turns, priority, the stack, mana and costs, triggered/activated/static abilities, combat, state-based actions, and effect resolution. ```ts import { Game } from './src/game/game.js' import { deckFromOracleIds } from './src/game/catalog.js' const game = new Game({ seed: 1, players: [ { id: 'p1', deck: deckFromOracleIds(decklist1) }, { id: 'p2', deck: deckFromOracleIds(decklist2) }, ], }) game.start() game.playLand('p1', cardId) game.castSpell('p1', spellId, { targets: [{ kind: 'player', id: 'p2' }] }) game.resolveStack() ``` Commander is a first-class format: the commander starts in the command zone, pays `{2}` more for each previous cast from that zone, returns to the command zone instead of the graveyard or exile, and loses the game at 21 combat damage from a single commander. Deck construction checks 100 cards, singleton, color identity, and a legendary-creature commander. See [backend/docs/game-engine.md](backend/docs/game-engine.md) for the action API, turn and combat flow, supported mechanics, and known limitations. The engine tests live in `backend/test/game.test.ts` and `backend/test/commander.test.ts`: ```bash cd backend npx tsx --test test/game.test.ts test/commander.test.ts ``` ## Playing online The frontend has five pages: - `/account` — create an account or sign in. The API stores only a username, a salted password hash, and the player's saved data in MongoDB. - `/` — create a 2–4 player game, join an open lobby, and pick your playmat. - `/decks` — build a deck, import a Moxfield/Archidekt/Arena text export, and export it again. Decks are stored with your account. - `/cards` — the existing card implementation editor and pseudocode guide. - `/games/:id` — lobby and game board. The page can also be used as an invite link; a player with no seat gets a join form. Matches live in the API process and are lost on restart. Each player only receives their own hand and libraries as counts; the server sends personalized state over server-sent events (SSE), and actions come back over `POST`. The browser keeps the login token and a random per-seat game token in `localStorage`/`sessionStorage`; accounts and saved decks, playmat choices, and each deck's card back live in MongoDB. Each player can pick card art or upload a JPEG as their own playmat; the choice is shown to everyone in the match and remembered in the account for new games you host or join. Card backs are chosen per deck in the deck editor and used for that deck's library pile. ## Production Build and run the optimized images: ```bash cp .env.example .env # optional: adjust public URLs and ports docker compose up -d --build ``` | Service | Default URL | | -------- | ---------------------------- | | Frontend | http://localhost:3000 | | API | http://localhost:4000 | ```bash docker compose ps # status and health docker compose logs -f # follow logs docker compose down # stop ``` The production frontend image runs the built Nuxt output directly. The backend image builds TypeScript and installs production dependencies only. ## Configuration | Variable | Default | Used by | Description | | ---------------------- | ----------------------- | ---------------- | ---------------------------------------------------- | | `NUXT_PUBLIC_API_BASE` | `http://localhost:4000` | frontend | Public, browser-facing URL of the API | | `CORS_ORIGIN` | `http://localhost:3000` | backend | Allowed browser origin(s), comma separated | | `MONGODB_URI` | `mongodb://localhost:27017/commander` | backend | MongoDB connection string | | `FRONTEND_PORT` | `3000` | production | Host port for the frontend | | `BACKEND_PORT` | `4000` | production | Host port for the API | | `PORT` | `4000` | backend | Port the API listens on inside the container | | `CARD_OVERRIDES_DIR` | `backend/data/card-overrides` | backend | Where manual implementations are stored | | `OPENROUTER_API_KEY` | — | backend | Enables the editor's AI pseudocode draft | | `OPENROUTER_MODEL` | `google/gemini-2.5-flash-lite` | backend | OpenRouter model used for translation | When deploying to a real host, set `NUXT_PUBLIC_API_BASE` and `CORS_ORIGIN` to your public URLs. Both values are applied at runtime in the production image. ## Project layout ```text . ├── backend/ │ ├── scripts/import-cards.ts # Scryfall bulk importer │ ├── scripts/compile-cards.ts # oracle text -> effect AST + pseudocode │ ├── src/cards.ts # card store, lookup, and search │ ├── src/images.ts # on-disk cache for Scryfall card art │ ├── src/effects/ # effect DSL, compiler, formatter, pseudocode parser │ ├── src/effects/translate.ts # natural language -> pseudocode through OpenRouter │ ├── src/game/ # rules engine, commander rules, match manager │ ├── src/accounts.ts # Mongo models, auth, decks, and preferences │ ├── src/server.ts # Fastify entry point and game/deck routes │ ├── test/ # compiler, pseudocode, engine, and commander tests │ ├── docs/card-effects.md # DSL reference and coverage │ ├── docs/game-engine.md # engine API, rules coverage, limitations │ ├── data/cards.json # generated by npm run import:cards │ ├── data/card-overrides/ # human-authored implementations, one file per card │ ├── Dockerfile # dev, build, and production stages │ └── package.json ├── frontend/ │ ├── app/app.vue # app shell and navigation │ ├── app/assets/main.css # shared theme and layout │ ├── app/pages/index.vue # create/join a game │ ├── app/pages/account.vue # sign in, register, and sign out │ ├── app/pages/decks.vue # deck builder and decklist import/export │ ├── app/pages/games/[id].vue # lobby, board, and live match client │ ├── app/pages/cards.vue # card implementation editor and guide │ ├── app/middleware/auth.ts # redirect signed-out visitors to /account │ ├── app/utils/auth.ts # login token storage and headers │ ├── app/utils/decks.ts # account deck API and validation │ ├── app/components/PseudoGuide.vue # pseudocode guide view │ ├── nuxt.config.ts # runtime config (API base URL) │ ├── Dockerfile # dev, build, and production stages │ └── package.json ├── docker-compose.dev.yml # hot-reload development stack ├── docker-compose.yml # production stack ├── .env.example └── README.md ``` ## API `/auth/me` and every `/me/*` route require the `Authorization: Bearer ` header returned by `/auth/register` or `/auth/login`. | Method | Path | Response | | ------ | --------------------- | ------------------------------------------------------- | | `GET` | `/health` | `{ "status": "ok", "service": "commander-api" }` | | `GET` | `/cards?q=atraxa` | `{ total, cards }` name search, `limit` capped at 200 | | `GET` | `/cards/:oracleId` | One card object, or `404` | | `GET` | `/cards/:oracleId/image` | Card face as JPEG; downloaded from Scryfall once and cached on disk | | `GET` | `/cards/:oracleId/art` | Wide card art crop used for playmats, cached on disk | | `GET` | `/cards?status=needs-work` | Filter by `supported`, `partial`, `unsupported`, `needs-work`, `manual`, `all` | | `GET` | `/cards?format=modern&color=U&type=creature&rarity=rare&cmcMin=1&cmcMax=3` | Format legality, color identity (`WUBRG` includes that color, `C` colorless, `M` multicolor), card type, rarity, and mana value filters | | `GET` | `/cards/:oracleId/implementation` | Card, compiled AST, pseudocode source, manual flag | | `PUT` | `/cards/:oracleId/implementation` | Validate `{ "source": "..." }` and save the override | | `DELETE` | `/cards/:oracleId/implementation` | Delete the override and restore generated output | | `POST` | `/cards/:oracleId/translate` | Ask OpenRouter for pseudocode from the card's oracle text | | `GET` | `/cards/:oracleId/override` | Raw override source, or `404` | | `GET` | `/stats` | Supported, partial, unsupported, and manual counts | | `POST` | `/auth/register` | Create an account with `{ username, password }`, returns `{ token, username }` | | `POST` | `/auth/login` | Sign in with `{ username, password }`, returns `{ token, username }` | | `POST` | `/auth/logout` | Invalidate the current bearer token | | `GET` | `/auth/me` | Current account, requires `Authorization: Bearer ` | | `GET` | `/me/decks` | The account's saved decks | | `PUT` | `/me/decks/:id` | Create or replace a saved deck | | `DELETE` | `/me/decks/:id` | Delete a saved deck | | `POST` | `/me/decks/:id/share` | Create (or reuse) a share link token for a saved deck | | `GET` | `/decks/share/:token` | Public read of a shared deck, used to import a copy | | `GET` | `/me/preferences` | Saved playmat and card back | | `PUT` | `/me/preferences` | Update `{ playmat?, cardBack? }` | | `POST` | `/decks/import` | Parse a text decklist into `{ commander, cards, errors }` | | `POST` | `/cards/resolve` | Resolve exact card names: `{ names: string[] }` | | `GET` | `/games` | Open and active matches | | `POST` | `/games` | Create a match from `{ name, deck, maxPlayers, playmat? }` | | `POST` | `/games/:id/join` | Join a lobby with `{ name, deck, playmat? }` | | `POST` | `/games/:id/leave` | Leave a lobby or forfeit an active game with `{ token }` | | `POST` | `/games/:id/deck` | Change your lobby deck with `{ token, deck }` | | `POST` | `/games/:id/start` | Host starts the match with `{ token }` | | `POST` | `/games/:id/playmat` | Set your playmat with `{ token, playmat: { kind: "card", oracleId } \| { kind: "upload", data } \| { kind: "none" } }` | | `GET` | `/playmats/:id` | Uploaded playmat image | | `POST` | `/games/:id/actions` | Submit `{ token, action }` | | `GET` | `/games/:id/state` | Personalized state, requires `?token=` | | `GET` | `/games/:id/events` | Personalized SSE stream, requires `?token=` | ## Next steps - More compiled effects and rules coverage (prevention, control changes, planeswalkers) - WebSocket transport if SSE backpressure becomes a problem - Persistence for live games and match history - Matchmaking, spectators, and reconnect/afk handling - Partner commanders, companion, and the rest of the Commander variants