Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: bound dice rolls on character damage and event routes (#13088)
Adam Eivy3d0b2eaed61a
diff --git a/server/lib/README.md b/server/lib/README.mdindex f306cff9bb..cacd21a4fb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -38,6 +38,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `credentialEnvVars.js` | `isCredentialEnvVarName(name)` / `isNonCredentialEnvVarName(name)` / `isMaskedEnvVar(name, secretEnvVars)`: name-convention classifier for credential env vars (API_KEY, TOKEN, SECRET…), shared by provider response masking and the client readiness check. Pure. || `codeAnimationAcceptance.js` | Code Animation production acceptance: splits run evidence into technical/visual/temporal/sound (unmeasured stays unverified), decides promotability, freezes source/audio/render hashes and detects stale acceptance. Pure. || `codeAnimationContainment.js` | Code Animation production worker containment contract: per-platform enforced mechanism (macOS Seatbelt or Linux bubblewrap, otherwise refusal), deny-by-default profiles and a process-denying Linux seccomp filter, from-scratch worker environment, operator tool-root rules, tool configuration and worker limit schemas. Pure; the runner is `services/codeAnimation/containedWorker.js`. |+| `diceNotation.js` | Dice notation (`NdM[+-K]`) bounds shared by the character routes and `rollDice`: 1–100 dice, 2–1000 sides (#13088). `parseDiceNotation` (null when out of range), the `diceNotationSchema` Zod refinement, and `requireDiceNotation` (400 `ServerError`). || `dockerContainment.js` | Docker containment profile for untrusted install/build/test runs (#12844), pure: digest-pinned Node images and Node-major selection, `buildDockerContainmentRunArgs` (read-only `/src`, work volume, no host env, `--network none` for validate / per-run proxy network for install), `assertDockerMountSource` (refuses engine sockets, the data dir, the home and credential stores), the in-container driver that emits a tracked-file patch, volume-init/proxy/network argv and `.npmrc` registry-host parsing. Runner: `services/dockerContainment.js`. || `dockerContainmentValidation.js` | Zod schemas for Docker containment: the machine-local `dockerContainment` settings slice (limits, extra egress hosts, digest-pinned image overrides) and the `/api/docker-containment` run/pull bodies. Kept out of `validation.js` to keep that closure narrow. || `dockerEgressProxy.js` | The install phase's egress proxy (#12844): `decideEgressConnect` (allowlisted host + port, no IP literals), `isNonPublicAddress`, and `DOCKER_EGRESS_PROXY_SOURCE`, the builtins-only HTTPS CONNECT proxy program the proxy container runs with `node -e`. |diff --git a/server/lib/diceNotation.js b/server/lib/diceNotation.jsnew file mode 100644index 0000000000..e9f58fcb88--- /dev/null+++ b/server/lib/diceNotation.js@@ -0,0 +1,43 @@+/**+ * Dice notation (`NdM` with an optional `+K`/`-K` modifier) shared by the+ * character routes and `rollDice`. The count and sides are bounded because+ * `rollDice` materialises one array entry per die: an unbounded `NdM` lets one+ * request exhaust memory and block the event loop (#13088).+ */+import { z } from 'zod';+import { ServerError } from './errorHandler.js';++export const DICE_MAX_COUNT = 100;+export const DICE_MIN_SIDES = 2;+export const DICE_MAX_SIDES = 1000;++const DICE_PATTERN = /^(\d+)d(\d+)([+-]\d+)?$/;++// Returns `{ count, sides, modifier }` for an in-bounds notation, else `null`.+function parseDiceNotation(notation) {+ const match = DICE_PATTERN.exec(notation);+ if (!match) return null;+ const count = parseInt(match[1], 10);+ const sides = parseInt(match[2], 10);+ if (count < 1 || count > DICE_MAX_COUNT) return null;+ if (sides < DICE_MIN_SIDES || sides > DICE_MAX_SIDES) return null;+ const modifier = match[3] ? parseInt(match[3], 10) : 0;+ return { count, sides, modifier };+}++export const diceNotationSchema = z.string().refine(+ (notation) => parseDiceNotation(notation) !== null,+ `Invalid dice notation (e.g. "1d8", "2d6+3"; 1-${DICE_MAX_COUNT} dice with ${DICE_MIN_SIDES}-${DICE_MAX_SIDES} sides)`+);++/** Parse or throw a 400 — used by `rollDice`, which non-route callers also reach. */+export function requireDiceNotation(notation) {+ const parsed = typeof notation === 'string' ? parseDiceNotation(notation) : null;+ if (!parsed) {+ throw new ServerError(+ `Invalid dice notation: ${notation} (1-${DICE_MAX_COUNT} dice with ${DICE_MIN_SIDES}-${DICE_MAX_SIDES} sides)`,+ { status: 400 }+ );+ }+ return parsed;+}diff --git a/server/lib/diceNotation.test.js b/server/lib/diceNotation.test.jsnew file mode 100644index 0000000000..3b7434742d--- /dev/null+++ b/server/lib/diceNotation.test.js@@ -0,0 +1,20 @@+import { describe, it, expect } from 'vitest';+import { diceNotationSchema, requireDiceNotation } from './diceNotation.js';++describe('diceNotationSchema (#13088)', () => {+ it('accepts in-bounds notation and refuses counts and sides outside 1-100 dice and 2-1000 sides', () => {+ expect(diceNotationSchema.safeParse('2d6+3').success).toBe(true);+ expect(diceNotationSchema.safeParse('1d8').success).toBe(true);+ for (const bad of ['101d6', '0d6', '1d1', '1d1001', '1000000000d6']) {+ expect(diceNotationSchema.safeParse(bad).success).toBe(false);+ }+ });+});++describe('requireDiceNotation (#13088)', () => {+ it('throws a 400 for out-of-bounds notation so non-route callers are bounded too', () => {+ let error;+ try { requireDiceNotation('1000000000d6'); } catch (err) { error = err; }+ expect(error?.status).toBe(400);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 29c8c8c1a6..97ea05eace 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -23,6 +23,7 @@ export * from './codeAnimationPackage.js';export * from './codeAnimationAcceptance.js';export * from './codeAnimationContainment.js';export * from './autofixVerifyContainment.js';+export * from './diceNotation.js';export * from './dockerContainment.js';export * from './dockerContainmentValidation.js';export * from './dockerEgressProxy.js';diff --git a/server/routes/character.js b/server/routes/character.jsindex bf186d435f..16d29ad1fc 100644--- a/server/routes/character.js+++ b/server/routes/character.js@@ -12,6 +12,7 @@ import { z } from 'zod';import { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as characterService from '../services/character.js';+import { diceNotationSchema } from '../lib/diceNotation.js';const router = Router();@@ -32,7 +33,7 @@ const addXPSchema = z.object({});const takeDamageSchema = z.object({- diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/, 'Invalid dice notation (e.g. "1d8", "2d6+3")'),+ diceNotation: diceNotationSchema,description: z.string().max(500).optional()});@@ -43,7 +44,7 @@ const takeRestSchema = z.object({const addEventSchema = z.object({description: z.string().min(1).max(500),xp: z.number().int().min(0).optional(),- diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/).optional()+ diceNotation: diceNotationSchema.optional()});// `?skills=0` / `?metrics=0` opt out of each derived registry's domain fan-out, for consumersdiff --git a/server/routes/character.test.js b/server/routes/character.test.jsindex c12060897a..ab698c807b 100644--- a/server/routes/character.test.js+++ b/server/routes/character.test.js@@ -128,3 +128,23 @@ describe('PUT /api/character', () => {expect(characterService.updateCharacterFields).not.toHaveBeenCalled();});});++describe('dice notation bounds on damage and event routes (#13088)', () => {+ it.each([+ ['/api/character/damage', (notation) => ({ diceNotation: notation }), 'takeDamage'],+ ['/api/character/event', (notation) => ({ description: 'Rolled', diceNotation: notation }), 'addEvent'],+ ])('%s accepts in-bounds notation and refuses out-of-bounds before the service runs', async (url, body, fn) => {+ for (const ok of ['1d8', '2d6+3', '100d1000']) {+ vi.clearAllMocks();+ const res = await request(makeApp()).post(url).send(body(ok));+ expect(res.status).toBe(200);+ expect(characterService[fn]).toHaveBeenCalledTimes(1);+ }+ for (const bad of ['101d6', '0d6', '1d1', '1d1001', '1000000000d6']) {+ vi.clearAllMocks();+ const res = await request(makeApp()).post(url).send(body(bad));+ expect(res.status).toBe(400);+ expect(characterService[fn]).not.toHaveBeenCalled();+ }+ });+});diff --git a/server/services/character.js b/server/services/character.jsindex a9d5cd4eb3..1760d6b834 100644--- a/server/services/character.js+++ b/server/services/character.js@@ -23,6 +23,7 @@ import { getCharacterSkills } from './characterSkills.js';import { getCharacterMetrics } from './characterMetrics.js';import { createSignalContext } from './characterSignals.js';import { createMutex } from '../lib/asyncMutex.js';+import { requireDiceNotation } from '../lib/diceNotation.js';const CHARACTER_FILE = path.join(PATHS.data, 'character.json');@@ -455,12 +456,8 @@ export async function setAvatar(avatarPath) {}export function rollDice(notation) {- const match = notation.match(/^(\d+)d(\d+)([+-]\d+)?$/);- if (!match) throw new Error(`Invalid dice notation: ${notation}`);-- const count = parseInt(match[1], 10);- const sides = parseInt(match[2], 10);- const modifier = match[3] ? parseInt(match[3], 10) : 0;+ // Bounded before the roll loop: one array entry per die (#13088).+ const { count, sides, modifier } = requireDiceNotation(notation);const rolls = [];for (let i = 0; i < count; i++) {diff --git a/server/services/character.test.js b/server/services/character.test.jsindex 001ea85ba7..48ebb08fa8 100644--- a/server/services/character.test.js+++ b/server/services/character.test.js@@ -619,6 +619,8 @@ describe('Character mutation queue (#9817)', () => {it('a rejected mutation neither persists nor wedges the queue', async () => {await expect(characterService.takeDamage('not-dice')).rejects.toThrow(/Invalid dice/);+ // Bounded before the roll loop: an unbounded count must fail fast, not allocate (#13088).+ await expect(characterService.takeDamage('1000000000d6')).rejects.toMatchObject({ status: 400 });store.beforeWrite = async () => { throw new Error('disk full'); };await expect(characterService.addXP(5, 'x', 'x')).rejects.toThrow('disk full');store.beforeWrite = null;