Files
dragonroll/AGENTS.md
Gitea OpenCode Agent 4355986bd1
All checks were successful
Test / test (push) Successful in 1s
Fix issue #30: Make AGENTS.md smaller
2026-10-14 17:07:28 +00:00

17 KiB

AGENTS.md — Dragonroll

Orientation map, kept short on purpose. Read the file you are about to change: this tells you where to look and what will bite you, it does not replace the code. Longer docs: dragonroll-foundry/README.md, discord-bot/README.md, obsidian-plugin/README.md.

1. What this is

Free/open-source helper for tabletop RPG campaigns (campaigns, markdown notes, folders, characters, items, maps, dice widgets, sounds).

  • backend/ — Node + Express 5 + Mongoose 9 (MongoDB) REST API, JWT auth, CommonJS, entry src/index.js.
  • frontend/ — Nuxt 4 / Vue 3 (<script setup>), SCSS, axios, marked, mitt, motion, entry app/app.vue. No routed pages (§5.1).
  • discord-bot/ — Discord bot (slash commands) that talks to the backend with a shared service secret, no login.
  • dragonroll-foundry/ — Foundry VTT module (scripts/api.js) + optional read-only snapshot bridge.
  • obsidian-plugin/ — plain JavaScript Obsidian plugin that imports/pushes campaign notes.
  • tests/ — npm test (node --test, no dependencies installed): Foundry sync toggle and pairing status, map pins, sidebar entries.

No DB seeding, no migrations, no linter/formatter, no Pinia/Vuex. Git: default branch master on a self-hosted Gitea; .gitea/workflows/deploy.yml builds and deploys Docker images on push to master, .gitea/workflows/test.yml runs npm test on every branch.

2. Commands

npm install --prefix backend && npm install --prefix frontend   # root `npm install` = concurrently only
npm run dev            # backend :5000 + frontend :3000 + discord-bot + scripts/run-foundry.js
npm --prefix backend run dev            # or --prefix frontend run dev | build | preview
npm test

No start script in backend/frontend and no lint command. Verification = run the dev server and exercise the flow (GET /api/test returns a JSON hello).

Env: backend/.env (PORT is read but ignored, DB_URI), frontend/.env (NUXT_PUBLIC_API_BASE_URL), both gitignored; the .env.production files are committed. backend/src/index.js loads .env.$NODE_ENV when NODE_ENV is set, otherwise .env. The server always listens on 5000.

3. Backend

src/models/ one Mongoose schema per file · src/routes/ thin Express routers · src/services/ shared infra (keys.js JWT secret, passport.js JwtStrategy, storage.js multer → src/uploads/ served publicly at /api/public, rate-limiter.js 150 req/60 min, service-links.js the service pairing in §4, *-foundry.js Foundry document → Dragonroll field mappers).

Auth chain, order matters (src/index.js): /api/public/* static → /api/user, /api/discord, /api/link, /api/foundry (link + sync, token-authenticated) are mounted before checkAuth = passport.authenticate('jwt', {session:false}); everything after it (/api/campaign|note|folder|actor|item|map|foundry) is JWT-protected. checkAuth is assigned without const (implicit global). New user routes are public unless the handler calls passport.authenticate('jwt', {session:false}) inline (/upload-avatar, /update-settings, /get-settings). JWT: payload {_id, username, name, email, admin, settings}, 48h; req.user is the Mongoose document, so routes use req.user.id.

CORS allows any origin for the service link/sync paths only; the app-wide CORS whitelists http://localhost:3000 and nothing else (production hides behind the nginx same-origin proxy).

Response envelope — always HTTP 200, no real status codes:

{ "status": "ok", ...payload }
{ "status": "error", "msg": "errors.internal" }   // msg is an i18n KEY, not prose

Common keys: errors.missing-data, errors.notfound, errors.internal, unauthorized, login.errors.invalid-credentials, register.errors.email-username-exists. GET /user/has-admin returns status: 'init' when no admin exists yet (→ first-run registration).

Authorization — single-tenant: a campaign belongs to createdBy, everything else hangs off a campaign, and handlers check ownership with a userOwnsCampaign(campaignId, userId) helper that is duplicated per router file (match that unless you refactor all at once). settings, color, description are free-form fields.

Models (* = required; notes and folders are always ordered date: -1):

  • User — name*, username*, email* (both unique), password (bcrypt, 10 rounds), admin, image, setupCode, settings
  • Campaign — name*, createdBy*→User, description, color, settings, foundryWorldId/foundryWorldTitle/foundrySystem, foundrySyncTokenHash (select: false), discordGuildId
  • Note — title, content (markdown source), campaign*, folder (null = root), color
  • Folder — name*, campaign*, parentFolder (null = root, self-ref), color
  • Actor — name*, campaign*, foundryActorId (unique per campaign), plus free-form sheet fields (type, species, className, level, abilityScores, armorClass, speed, proficiencies, traits, spells, image) and inventory[{name,quantity,weight}] (flattened Foundry items, not Item docs)
  • Item — name*, campaign*, foundryItemId (unique per campaign), foundryNames, category, rarity, quantity, weight, properties, description
  • Map — name*, campaign*, image (filename in src/uploads), gridSize/offsetX/offsetY/scale (image px), pins[{note→Note, x, y}] (addressed by the pin's own _id)
  • ServiceLinkRequest — the pending/completed service pairings of §4; DiscordGuildLink maps a Discord guild to the Dragonroll user who claimed it

API surface (all under /api, all {status,msg}):

  • user — register, verify-setup?code=, setup?code=, login ({usermail,password}, accepts username or email → {token}), upload-avatar (multipart image, JWT) / retrieve-avatar?username=, has-admin, update-settings / get-settings. Files fetched from /api/public/<filename>.
  • campaign — create, update, list, retrieve/:id, services + service-unlink (what is linked to a campaign)
  • note — list?campaign= (root notes + folders with parentFolder), subfolder/list?campaign=&folder=, all?campaign= (titles only, for the map pin picker), retrieve/:id, create, update (partial), delete
  • folder — list, create, update, rename, delete (recursive: inner notes go to folder: null, subfolders re-parent then delete)
  • actor — list, create, update (partial, ownership checked), upload-image?actor= (multipart), delete
  • item — list, create, update (partial), delete
  • map — list, create (multipart image or JSON), update (multipart to replace the photo), delete, pin ({id,note,x,y}, re-pinning moves the marker), unpin ({id,pin})
  • foundry — read-only proxy over the bridge (/world, /actors, /characters, /items, /actors/:id, /items/:id, /actors/:id/items), needs FOUNDRY_API_URL

4. Service integrations (Foundry, Discord, Obsidian)

Every external service links to a campaign the same way, never with a Dragonroll login: it calls POST /api/link/start, shows the returned sign-up link, and the user opens it in the frontend (/link/authorize, handled by views/ServiceLinkAuthorize.vue outside the window app), signs in and picks a campaign at POST /api/link/complete; the service then redeems its credential once at POST /api/link/pickup (one-time; losing it means a new link). Proofs differ per service (services/service-links.js): the Discord bot proves itself with the shared secret header, Foundry and Obsidian only hold their link code, so what a link grants is decided by the user. Codes are hashed at rest, expire after 10 min, and Obsidian gets a long-lived (365 d) token back.

Foundry then syncs with that token on /api/foundry/sync/* (routes/foundry-link.js, mounted before the JWT guard; CORS opened for it): snapshot (actors + world items, fullSync also prunes), item-snapshot, item-delete, characters, items, status, map / map-item, delete. Rules:

  • Identity is foundryActorId / foundryItemId (unique per campaign, partial index); a Foundry document carrying the dragonroll-foundry.actorId / .itemId flag adopts the matching Dragonroll row.
  • Items are deduplicated by name — Foundry keeps the same gear once per carrier, so one Item per name; foundryNames keeps Foundry's names so a Dragonroll rename does not resurrect a duplicate. services/item-foundry.js returns null for non-gear types and those are skipped.
  • fullSync preserves Dragonroll edits (only new rows are overwritten); live Foundry events overwrite. Only a full snapshot can prune.
  • Autosync is a Foundry-side setting (autoSync, on by default): off = no CRUD push, no periodic reconcile, no startup snapshot; the actor directory's Dragonroll: Force Sync still upserts the selection (fullSync:false).
  • GET /api/foundry/* (routes/foundry.js) is unrelated: a JWT-protected proxy over the read-only bridge.

5. Frontend

5.1 Not a routed app

There is no app/pages/. app/app.vue renders a shell of managers (Window, Content, Toast, Tooltip, ContextMenu) and boots: GetUser() (JWT in localStorage) → RestoreCampaign() or open main_menu; no user → HasAdmin() ? 'login' : 'register' {firstTime:true}. The one real URL is /link/authorize (and the legacy /discord/authorize), which renders the service link screen instead of the app.

Two kinds of screens: windows (floating draggable/resizable overlays) and content — the campaign workspace (TopBar + ContentSidebar + note column + StatusBar), turned on when Campaign becomes non-null. The note column shows the open notes, or the anchored map (ActivePane / AnchoredMap / AnchorMap in services/Content.js); viewer/map/MapViewerPane.vue renders it both there and in the detached map_viewer window. Right-clicking that map pins a campaign note at the spot (services/MapPins.js translates image px ↔ screen), clicking the marker opens pinned_note.

5.2 The window system

services/WindowDefinitions.js is the registry ({ title: 'i18n.key', component: () => import(...), movable, close?, back? }) and services/Windows.js the runtime: CreateWindow(type, data) (one instance per type), CreateChildWindow(parentId, ...), ClearWindow({type}|{id}), GetWindowWithId, GetFirstWindowId, CallWindow(id, fn, arg), SetSize/SetPosition/ResetPosition(id,'center')/SetMinSize/SetMaxSize/Top, getComponent(type), SetupHandle(id, handleRef). Adding a window = registry entry + component in components/windows/; copy ExampleWindow.vue: props ['data'] (merged window object, props.data.id), and in onMounted call Top(wrapper), SetupHandle(id, handle), SetSize, ResetPosition.

DOM ids these services depend on — do not rename: window-wrapper-{id}, window-handle-{id}, window-resize-handle-{id}, context-menu, mouse-tooltip.

5.3 Services are the state layer

app/services/ are plain ES modules with module-scope ref()s — no DI, no store, singleton by import. Server.js (axios factory: Server().get(...), interceptor adds Authorization: Bearer <localStorage.token>, initApi() from plugins/api.ts), User.js (GetUser/SetUser/LogoutUser/HasAdmin, GetUserSetting/ SetUserSetting server-backed in User.settings), Campaign.js (useCampaignService(), SetCampaign writes localStorage.selectedCampaignId, RestoreCampaign), Content.js (§5.1), Emitter.js (mitt() bus), Toaster.js, Tooltip.js, ContextMenu.js, Sound.js (AddSound binds snap.wav to .sound-click), Marker.js (marked + widgets), ActionRegistry.js (command palette: register/unregister/search/execute), Windows.js / WindowDefinitions.js, MapPins.js, widgets/DiceParser.js.

5.4 Markdown → widgets

Marker.js turns @name\n…\n@end (block), @name[text] (inline) and [[target]] (wiki link) into placeholder divs/spans; Note.vue renders with v-html and then mounts each placeholder with its own createApp(GetWidget(kind, name), {content}) (and unmounts them on re-render). So widgets are isolated mini-apps: they get only the content string and must not rely on the parent app's provides/injection. Register one in widget_map in Marker.js, component in components/viewer/widgets/{inline,display}/. DiceParser.js evaluates \d*d\d+ with adv|dis|kh<N>|kl<N>, + - * / ( ), unary minus, floor division, and returns {total, steps[]} that RollWidgetDisplay.vue draws.

5.5 Event bus

Events in use: toast, push-note, close-note (removes from the open column only), delete-note (closes and removes from the sidebar, and drops map pins — the note's close button must not use it), title-updated, campaign-entry-created / campaign-entry-updated, note-created, note-renamed, folder-saved, folder-deleted, status-bar-update. Payloads are API documents; the UI note shape is {key, title, text, date}, mapped at the boundary as ContentSidebar.fetchCampaignNotes does. Always import { emitter } from '~/services/Emitter' — composables/useEmitter.ts is broken (§8).

5.6 Styling, i18n

colors.scss Sass maps (dark/light, accents katlum/solus/silang) become --color-* CSS variables: always style with var(--color-…), never hardcode hex, and add a new key to both maps. useTheme.ts persists theme/accent and sets data-theme/data-accent on <html>; app.vue forces setTheme('dark'). Icons are white SVGs with .icon (inverted via --color-icon-invert), from /icons/... or the pixelarticons package. Fonts (fonts.scss, 5e-style families) and sounds (/sounds/*.wav) live in public/.

i18n: frontend/i18n/locales/<lang>/<namespace>.json for en (default), es, ca; plugins/i18n.ts nests each file under its filename, so the key is <file>.<path> ($t('windows.login')). Add every new string to all three locales. Namespaces in use: general, login, register, main-menu, settings, windows, campaigns, link, foundry, discord.

6. Conventions

  • Backend: CommonJS; every handler try/catch → {status:'error', msg:'errors.internal'} + console.error.
  • Frontend: Vue 3 <script setup>, PascalCase exported service functions (CreateWindow, GetUser), PascalCase component filenames, kebab-case DOM ids. Both ~/ and @/ resolve to app/ — use what the neighbouring file uses.
  • Components call Server() directly (no api layer); await and .then both appear.
  • Comments mix English and Catalan ("Moure aixo") — do not translate unrelated comments while editing.
  • No formatter: keep diffs minimal and local, the codebase is deliberately rough.

7. Recipes

  • New API resource: models/X.js + routes/x.js (ownership check + {status,msg} envelope), then app.use('/api/x', require('./routes/x')) in src/index.js after checkAuth if it needs auth.
  • New window: WindowDefinitions.js entry + components/windows/X.vue (§5.2) + strings in i18n/locales/*/windows.json (all three locales).
  • New widget: component in components/viewer/widgets/{inline,display}/ + widget_map entry in Marker.js.
  • New palette action: register({id, label, description, execute, isActive?}) from ~/services/ActionRegistry (palette: Ctrl/Cmd+K or /).
  • New theme color: key in both dark and light maps in colors.scss, then var(--color-<key>).

8. Known landmines (verified in code — do not "fix" silently, never make them worse)

  1. README.md says run ./install.sh / ./start.sh; neither exists. frontend/README.md says the frontend is React; it is Nuxt/Vue.
  2. services/keys.js ships the JWT secret "putyoursecrethere", used in production.
  3. POST /api/user/register responds {status:'ok', code: setupCode} but setupCode is not in scope → caught → the first-run registration actually returns errors.internal. The register UI (RegisterWindow.vue) drives that flow; fix carefully.
  4. POST /api/note/delete has no ownership check (any authenticated user can delete any note id); the other note.js handlers and folder.js do check.
  5. /api/user/* is mounted before the JWT guard: new routes there are public unless they authenticate inline (/api/discord is also before it, but every route there is gated by requireBot, the shared bot-secret header). services/middleware.js's isAdmin is imported but applied to no route.
  6. composables/useEmitter.ts reads $emitter from useNuxtApp() and no plugin provides it — use ~/services/Emitter.
  7. App-wide CORS only whitelists http://localhost:3000; .env.production files are committed with internal hosts; ecosystem.config.js runs npm start, which backend/frontend do not define (PM2 is dead, compose + nginx is the real deploy).
  8. Windows.js: getComponent caches defineAsyncComponent per type for the whole process (restart the dev server if a new window misbehaves), SetupHandle attaches document mouse listeners per window and never removes them, and ClearAll() iterates Object.keys(windows) instead of windows.value.
  9. The frontend treats the JWT as the user cache: settings changes need GetUserSetting/SetUserSetting round-trips, the token payload goes stale.

9. Ports

frontend dev :3000 · backend :5000 (hardcoded) · MongoDB :27017 · nginx :3000 → 80 in compose, proxying / → frontend, /api/ → backend.