8000 fix: enforce attack rules and harden storage, from the engine audit (part 2) by Mnehmos · Pull Request #114 · Mnehmos/mnehmos.rpg.mcp · GitHub
[go: up one dir, main page]

Skip to content

fix: enforce attack rules and harden storage, from the engine audit (part 2) - #114

Merged
Mnehmos merged 14 commits into
mainfrom
claude/practical-cannon-cel9je
Nov 10, 2026
Merged

Mnehmos merged 14 commits into
mainfrom
claude/practical-cannon-cel9je

Conversation

@Mnehmos
@Mnehmos Mnehmos commented Nov 9, 2026
Copy link
Copy Markdown
Owner

Follow-up to #113: the remaining findings from the engine audit. Each fix was written test-first; the combat and deletion changes were also checked against a local HTTP server.

Combat: the engine now decides what an attack can do

Before Now
A combatant could attack any number of times during someone else's turn (warning only). An off-turn attack resolves as the attacker's reaction: one per round, and it no longer spends its action. A second one is an error.
A melee attack landed on a target 17 squares away. The target must be within reach: 5ft for melee, or the new optional range (feet) for ranged and reach attacks. Only checked when both combatants have a position.
attackBonus: 999, damage: 9999 was accepted. Supplied numbers are bounded: attackBonus -20..30, dc 1..40, damage at most 1000 (dice counted at their maximum).
Opportunity attacks derived attack bonus and AC from initiative. They use the attacker's attackBonus and the mover's ac when the encounter has them.

Storage and hosting

  • Handle pool: eviction no longer closes a campaign database while a call is running on it, and DELETE /campaign waits for the call in flight. Cap is configurable with RPG_MAX_OPEN_DATABASES (default 64).
  • World cache: in-memory worlds are keyed by the verified tenant as well as the (guessable) world id, and the cache is bounded (RPG_MAX_CACHED_WORLDS, default 32). Evicted worlds are restored from their database snapshot.
  • Corruption: a hosted campaign database that fails its integrity check is refused and left untouched, instead of being quarantined and replaced with an empty one. Local single-user databases keep the old behaviour.
  • Audit log: keeps the newest RPG_AUDIT_LOG_MAX_ROWS rows per campaign (default 5000); it was never pruned.
  • Tokens: transport tokens are compared in constant time on HTTP, WebSocket and TCP.

Housekeeping

  • CI drops Node 18 (better-sqlite3 12 requires 20+), moves to actions/*@v4; package.json declares engines.
  • The HTTP transport logged tool registration on every request; it logs once.
  • Tool and test counts corrected in CLAUDE.md and the README; repo URLs point at Mnehmos/mnehmos.rpg.mcp.

Contract changes for rpg-mcp-live

  • combat_action attack at a target more than 5ft away now needs range (feet). Without it the call returns isError: true with a message saying exactly that.
  • A second off-turn attack by the same combatant in a round returns isError: true. The first still succeeds and still carries the off_turn_action note.
  • attackBonus, dc and damage outside the bounds above return isError: true.
  • A corrupted campaign database now makes that campaign's calls fail instead of returning an empty campaign.
  • Audit rows older than the newest 5000 per campaign are deleted.

Not in this PR

  • zod 4. The remaining npm audit advisory needs it. A trial upgrade produced 51 type errors, 18 of them in meta-tools.ts, which reads zod internals to build the schemas load_tool_schema returns. That is the contract surface for the web service, so it needs its own PR with a before/after schema comparison.
  • /health still returns the commit SHA unauthenticated. Left alone: the value is low-sensitivity for a public repo and the web service may read it.
  • The WebSocket transport still accepts its token in the query string (browsers cannot set headers on a WebSocket; it is a local transport).
  • dc can still be supplied lower than the target's AC, within the bounds.

Testing

  • New: tests/server/combat-rules.test.ts, tests/storage/pool-safety.test.ts, tests/storage/corruption.test.ts, tests/server/world-manager.test.ts, tests/server/transport/auth.test.ts, plus retention cases in tests/storage/audit.repo.test.ts.
  • Existin 8000 g fixtures updated where they relied on the old behaviour: attackers placed out of reach, and attackBonus: 50/100 used as a guaranteed hit.
  • Full suite locally: 2370 passed, 7 skipped, 3 failed. The 3 are tests/server/websocket.test.ts, which cannot bind :: in the sandbox this ran in (no IPv6); they passed in CI on fix: close two server-kill paths and three combat integrity gaps from the engine audit #113.

Note on history

The first four commits listed are the ones already squash-merged as #113. The branch could not be force-pushed, so that history was merged in with the tree left unchanged; the diff against main is only the new work.


Generated by Claude Code

claude added 14 commits November 9, 2026 20:42
…e server

An exploding one-sided die (1d1!) never stopped exploding, and dice counts
were unbounded, so one math_manage call could freeze or kill the process
for every campaign. Dice are now capped at 1000 dice of 1000 sides at every
parser, exploding dice need at least 2 sides, and exact distributions are
refused when too large to compute.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
subscribe_to_events left a callback pointing at the per-request HTTP
transport. The next combat event in any campaign made it reject with
'Not connected'; the unhandled rejection shut the process down, and the
shutdown path exited 0, so the host never restarted it.

- Crashes now exit 1; requested stops still exit 0.
- A subscriber whose connection is gone is dropped, not left to reject.
- Subscribers only receive events from their own campaign.
- On the stateless HTTP transport, where nothing can be pushed after the
  response, subscribe_to_events makes no subscription and points the
  caller at poll_events.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- Moves are validated (destination, path, remaining movement) before
  opportunity attacks resolve. A refused move used to cost the mover hit
  points and the attacker its reaction, then report success. It is now an
  error, so the call rolls back.
- Negative damage is rejected; it was subtracted as healing with no cap
  at max HP (a 7 HP goblin reached 107). Dice damage with a penalty
  floors at zero, and applyDamage/heal ignore negative amounts.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
npm audit fix: clears the advisories in @modelcontextprotocol/sdk and its
transitive dependencies. The remaining zod advisory needs a breaking move
to zod 4 and is left for a separate change.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
- An attack outside the attacker's turn now resolves as its reaction, one
  per round, and no longer spends its action. It used to be a warning
  only, so a combatant could attack any number of times off turn.
- A target must be within reach: 5ft for melee, or the new optional
  `range` (feet) for ranged and reach attacks. Checked only when both
  combatants have a position.
- Caller-supplied attackBonus, dc and damage are bounded (-20..30, 1..40,
  1000 damage), so one call can no longer decide the outcome.
- Opportunity attacks use the attacker's attack bonus and the mover's AC
  when known instead of deriving both from initiative.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…g call

Pool eviction closed the least recently used handle even when a call was
mid-transaction on it, and DELETE /campaign did the same. Eviction now
skips handles that are in use, and erasure waits for the call in flight.
The pool cap can be set with RPG_MAX_OPEN_DATABASES (default 64).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Cached worlds were keyed by a guessable id alone and never evicted, so one
campaign could read another's world by id and memory grew for the life of
the process. Entries are now keyed by the verified tenant too, and the
cache keeps the most recently used worlds (RPG_MAX_CACHED_WORLDS, default
32); the rest are restored from their database snapshot on demand.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
…ng it

A hosted campaign that failed its integrity check was quarantined and
swapped for an empty database, so the game looked deleted and play
continued into a second file. Campaign databases now fail to open and the
files are left untouched. Local single-user databases keep the
quarantine-and-recreate behaviour.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
audit_logs stored arguments and results for every tool call and was never
pruned. It now keeps the newest RPG_AUDIT_LOG_MAX_ROWS rows (default 5000).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
… URLs

better-sqlite3 12 requires Node 20+, so CI no longer tests 18 and
package.json declares the engine. The HTTP transport builds a server per
request and logged tool registration every time; it now logs once.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
The tool's outer input schema dropped the new range argument before it
reached the handler, so a ranged attack could not be made over MCP.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
The earlier commits on this branch were squash-merged as #113. This merge
keeps the current tree exactly as it is; it only records that history so
the branch can be pushed without rewriting it.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
@coderabbitai
coderabbitai Bot commented Nov 9, 2026 •
Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@repowise-bot
repowise-bot Bot commented Nov 9, 2026
Copy link
Copy Markdown

Worth a look: 1 thing to check below.

  1. This PR introduces 6 new health notes across 4 files: 5× untested complexity, 1× dry violation (see all)

↪️ 1 symbol moved unchanged from unit-of-work.ts to db-locks.ts.

✅ Health of changed files: 5.2 → 5.5 (+0.3; structure +0.3) Average full file score (structure and history) of 26 changed code files, weighted by size before this PR; not the repository score.

Tests (estimate): no test imports src/server/transport/tcp.ts
From the import graph; connect coverage for measured lines.


View on Repowise
Set up coverage → · Plain markdown for agents · Reviews (1) · Last reviewed commit: chore: merge already-merged branch history so the branch fast-forwards

Settings and updates

Silence one PR with [skip repowise] in the title · Bot settings
/repowise recheck reviews the current head again
/repowise review deep runs the deep review on it
/repowise remember <text> tells the reviewer what to leave out next time (reply on a finding to scope it to that file)
/repowise help lists the commands
⭐ Star Repowise · 📥 Install on another repo

@Mnehmos
Mnehmos marked this pull request as ready for review November 10, 2026 00:55
@Mnehmos
Mnehmos merged commit 8592c91 into main Nov 10, 2026
4 checks passed
@chatgpt-codex-connector
chatgpt-codex-connector Bot commented Nov 10, 2026 •
Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-10T00:57:36.511707Z cbc9e67 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cbc9e6795f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/storage/index.ts
Comment on lines +304 to +307
for (const [campaignId, db] of [...pool]) {
if (pool.size <= cap) return;
if (isDatabaseBusy(db)) continue;
pool.delete(campaignId);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Exclude the newly opened connection from eviction

When all existing pooled connections are busy and another campaign opens a database, this loop skips the busy connections and closes the newly opened connection, which has not acquired its lock yet. openCampaignDb() then returns that closed handle. I reproduced this with RPG_MAX_OPEN_DATABASES=1, one suspended atomic() call, and a second campaign: its first query fails with The database connection is not open. Protect the connection being returned and allow the pool to exceed its cap when no older idle connection is available.

Useful? React with 👍 / 👎.

Comment on lines +52 to +55
const cap = maxCachedWorlds();
while (this.worlds.size > cap) {
const oldest = this.worlds.keys().next().value as string | undefined;
if (oldest === undefined || oldest === key) break;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore evicted worlds before reporting their state

Once this eviction removes a generated world, world_manage's handleGetState() still reads only worldManager.get() and does not restore its persisted snapshot, unlike the map handlers in src/server/tools.ts. Consequently, generating enough worlds anywhere in the process makes an existing world's successful get_state response report zero tiles and regions. I reproduced this with a cache cap of one: a 400-tile, 10-region world reports both counts as zero after generating another world. Update this reader to load the snapshot or derive accurate counts from durable data before introducing eviction.

Useful? React with 👍 / 👎.

Mnehmos pushed a commit that referenced this pull request Nov 10, 2026
Tree unchanged. The earlier commits on this branch were squash-merged as
#113 and #114.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Mnehmos pushed a commit that referenced this pull request Nov 10, 2026
Tree unchanged. The earlier commits on this branch were squash-merged as
#113, #114 and #115.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FWeViVwVRAxVuCWaf7UQS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

0