[GH-ISSUE #2363] [Issue]: Macro engine has no resource bounds — exponential setvar/addvar expansion and unbounded {{roll:NdM}} loop freeze/OOM the renderer #1163

Closed
opened 2026-10-21 05:28:10 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @Romuromylus on GitHub (Jun 5, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2363

Originally assigned to: @Romuromylus on GitHub.

Summary

Severity: Medium — injection / content-driven denial of service.

The macro engine has no resource bounds. Two content-controlled vectors can hang or out-of-memory-crash the renderer during prompt assembly: (1) exponential setvar/addvar re-expansion (a billion-laughs blowup), and (2) the {{roll:NdM}} dice macro looping N times with no upper bound on N. Both are reachable from imported character cards, lorebook entries, personas, and presets.

Expected behavior

Macro resolution should be bounded — a hostile or malformed imported field should not be able to drive cumulative variable size or loop iteration counts unbounded. The engine already has the right pattern for this (MAX_CHARACTER_FIELD_RESOLUTION_DEPTH); the variable-op and roll/random paths should be guarded the same way.

Actual behavior

Vector 1 — exponential variable expansion. In src/engine/shared/macros/macro-engine.ts:841-873, setvar/addvar re-expand their assigned value via resolveMacrosWithState against the shared, mutable ctx.variables, while getvar returns the current raw value:

      case "getvar":
        return ctx.variables[name] ?? "";
      case "setvar":
        ctx.variables[name] = resolveMacrosWithState(
          writeMatch?.[3] ?? "",
          ctx,
          { ...options, trimResult: false },
          state,
        );
        return "";
      case "addvar":
        ctx.variables[name] =
          (ctx.variables[name] ?? "") +
          resolveMacrosWithState(writeMatch?.[3] ?? "", ctx, { ...options, trimResult: false }, state);
        return "";

So {{addvar::z::{{getvar::z}}}} doubles z (z_new = z_old + z_old). replaceBalancedMacros runs each balanced macro left-to-right against the same mutated ctx.variables, so the doublings compound in a single resolve pass. I reproduced this: a 719-byte payload {{setvar::z::AAAA}} followed by 25× {{addvar::z::{{getvar::z}}}} grows z to 134,217,728 bytes (4·2^25) in one pass; ~40 doublings (~1.2 KB of literal input) reaches multiple GB and OOM/freezes the renderer. The only guard in the whole file is MAX_CHARACTER_FIELD_RESOLUTION_DEPTH = 4 (line 79/192), which bounds only character-field substitution. The MacroResolutionState threaded through these paths carries only characterFieldDepth and is never incremented for variable re-expansion. There is no total-output-size cap, no per-expansion iteration cap, and no recursion-depth cap on setvar/addvar/getvar.

Vector 2 — unbounded dice loop. In the same file at :832-838:

  result = result.replace(/\{\{roll:(\d+)d(\d+)\}\}/gi, (_, count, sides) => {
    const n = parseInt(count, 10);
    const s = parseInt(sides, 10);
    let total = 0;
    for (let i = 0; i < n; i++) total += Math.floor(Math.random() * s) + 1;
    return String(total);
  });

n = parseInt(count, 10) is taken straight from the matched digits with no cap, then the loop runs n iterations. A string {{roll:999999999d6}} spins the single-threaded renderer for ~1e9 iterations; a larger literal extends it proportionally toward a multi-minute stall. Linear (not exponential), so lower severity than vector 1, but still a trivial content-driven freeze.

Steps to reproduce

  1. Create or import a character card whose greeting (or a lorebook entry / persona / preset variable) contains {{setvar::z::AAAA}} followed by ~40 repetitions of {{addvar::z::{{getvar::z}}}}.
  2. Open a chat with that card and send a message (triggers prompt assembly → resolveMacros on the greeting via seedPromptVariablesFromGreeting).
  3. Observe the renderer hang / crash as z grows past available memory. (For vector 2, use a greeting containing {{roll:999999999d6}} instead and observe the multi-second-plus freeze.)

Impact area

  • Runtime systems: generation, world-state, visuals, tracker, or haptics
  • React-free engine behavior, contracts, agents, or capability ports

Environment

  • Branch or commit: refactor @ 330f69a8
  • Run mode: Tauri desktop (also applies to the web shell — shared engine code)
  • OS + version: not relevant (static source audit)
  • Node + pnpm versions: not relevant
  • Rust version, if relevant: not relevant
  • Remote Runtime URL configured? not relevant
  • Provider, model, or integration, if relevant: not relevant — triggered by imported content during prompt assembly

Logs, screenshots, or video

Static source audit. Empirically reproduced in isolation: the 719-byte setvar+25×addvar payload grows z to 134,217,728 bytes in a single resolveMacros pass. Cited locations: src/engine/shared/macros/macro-engine.ts:841-873 (variable ops), :832-838 (roll), :79/:192 (the only existing depth guard).

Regression notes

Found via static audit; not a regression. The web build at packages/shared/src/utils/macro-engine.ts has the identical unguarded re-expansion and the identical uncapped roll loop, so both topologies share this pre-existing behavior — the refactor did not break or drop a prior-correct guard.

Additional context

The fix-pattern already exists in this file. Thread a cumulative-output-size budget plus an expansion-iteration / recursion-depth counter through MacroResolutionState (mirroring MAX_CHARACTER_FIELD_RESOLUTION_DEPTH), cap the summed length of all ctx.variables values (e.g. a few hundred KB to 1 MB) and bail out when exceeded, and clamp n (and the {{random:X:Y}} range) to a sane maximum before the loop. Apply the guard to the setvar/addvar/getvar, roll, and random:: re-expansion paths.

Template check

  • I DID NOT read this template and provide the requested details.
Originally created by @Romuromylus on GitHub (Jun 5, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2363 Originally assigned to: @Romuromylus on GitHub. ## Summary **Severity: Medium — injection / content-driven denial of service.** The macro engine has no resource bounds. Two content-controlled vectors can hang or out-of-memory-crash the renderer during prompt assembly: (1) exponential `setvar`/`addvar` re-expansion (a billion-laughs blowup), and (2) the `{{roll:NdM}}` dice macro looping `N` times with no upper bound on `N`. Both are reachable from imported character cards, lorebook entries, personas, and presets. ## Expected behavior Macro resolution should be bounded — a hostile or malformed imported field should not be able to drive cumulative variable size or loop iteration counts unbounded. The engine already has the right pattern for this (`MAX_CHARACTER_FIELD_RESOLUTION_DEPTH`); the variable-op and `roll`/`random` paths should be guarded the same way. ## Actual behavior **Vector 1 — exponential variable expansion.** In `src/engine/shared/macros/macro-engine.ts:841-873`, `setvar`/`addvar` re-expand their assigned value via `resolveMacrosWithState` against the shared, mutable `ctx.variables`, while `getvar` returns the current raw value: ```ts case "getvar": return ctx.variables[name] ?? ""; case "setvar": ctx.variables[name] = resolveMacrosWithState( writeMatch?.[3] ?? "", ctx, { ...options, trimResult: false }, state, ); return ""; case "addvar": ctx.variables[name] = (ctx.variables[name] ?? "") + resolveMacrosWithState(writeMatch?.[3] ?? "", ctx, { ...options, trimResult: false }, state); return ""; ``` So `{{addvar::z::{{getvar::z}}}}` doubles `z` (`z_new = z_old + z_old`). `replaceBalancedMacros` runs each balanced macro left-to-right against the same mutated `ctx.variables`, so the doublings compound in a single resolve pass. I reproduced this: a 719-byte payload `{{setvar::z::AAAA}}` followed by 25× `{{addvar::z::{{getvar::z}}}}` grows `z` to 134,217,728 bytes (`4·2^25`) in one pass; ~40 doublings (~1.2 KB of literal input) reaches multiple GB and OOM/freezes the renderer. The only guard in the whole file is `MAX_CHARACTER_FIELD_RESOLUTION_DEPTH = 4` (line 79/192), which bounds **only** character-field substitution. The `MacroResolutionState` threaded through these paths carries only `characterFieldDepth` and is never incremented for variable re-expansion. There is no total-output-size cap, no per-expansion iteration cap, and no recursion-depth cap on `setvar`/`addvar`/`getvar`. **Vector 2 — unbounded dice loop.** In the same file at `:832-838`: ```ts result = result.replace(/\{\{roll:(\d+)d(\d+)\}\}/gi, (_, count, sides) => { const n = parseInt(count, 10); const s = parseInt(sides, 10); let total = 0; for (let i = 0; i < n; i++) total += Math.floor(Math.random() * s) + 1; return String(total); }); ``` `n = parseInt(count, 10)` is taken straight from the matched digits with no cap, then the loop runs `n` iterations. A string `{{roll:999999999d6}}` spins the single-threaded renderer for ~1e9 iterations; a larger literal extends it proportionally toward a multi-minute stall. Linear (not exponential), so lower severity than vector 1, but still a trivial content-driven freeze. ## Steps to reproduce 1. Create or import a character card whose greeting (or a lorebook entry / persona / preset variable) contains `{{setvar::z::AAAA}}` followed by ~40 repetitions of `{{addvar::z::{{getvar::z}}}}`. 2. Open a chat with that card and send a message (triggers prompt assembly → `resolveMacros` on the greeting via `seedPromptVariablesFromGreeting`). 3. Observe the renderer hang / crash as `z` grows past available memory. (For vector 2, use a greeting containing `{{roll:999999999d6}}` instead and observe the multi-second-plus freeze.) ## Impact area - [x] Runtime systems: generation, world-state, visuals, tracker, or haptics - [x] React-free engine behavior, contracts, agents, or capability ports ## Environment - Branch or commit: refactor @ 330f69a8 - Run mode: Tauri desktop (also applies to the web shell — shared engine code) - OS + version: not relevant (static source audit) - Node + pnpm versions: not relevant - Rust version, if relevant: not relevant - Remote Runtime URL configured? not relevant - Provider, model, or integration, if relevant: not relevant — triggered by imported content during prompt assembly ## Logs, screenshots, or video Static source audit. Empirically reproduced in isolation: the 719-byte `setvar`+25×`addvar` payload grows `z` to 134,217,728 bytes in a single `resolveMacros` pass. Cited locations: `src/engine/shared/macros/macro-engine.ts:841-873` (variable ops), `:832-838` (`roll`), `:79`/`:192` (the only existing depth guard). ## Regression notes Found via static audit; **not a regression**. The web build at `packages/shared/src/utils/macro-engine.ts` has the identical unguarded re-expansion and the identical uncapped `roll` loop, so both topologies share this pre-existing behavior — the refactor did not break or drop a prior-correct guard. ## Additional context The fix-pattern already exists in this file. Thread a cumulative-output-size budget plus an expansion-iteration / recursion-depth counter through `MacroResolutionState` (mirroring `MAX_CHARACTER_FIELD_RESOLUTION_DEPTH`), cap the summed length of all `ctx.variables` values (e.g. a few hundred KB to 1 MB) and bail out when exceeded, and clamp `n` (and the `{{random:X:Y}}` range) to a sane maximum before the loop. Apply the guard to the `setvar`/`addvar`/`getvar`, `roll`, and `random::` re-expansion paths. ## Template check - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:28:10 +07:00
Author
Owner

@Romuromylus commented on GitHub (Jun 6, 2026):

Fixed by #2424, merged into refactor.

<!-- gh-comment-id:4637901660 --> @Romuromylus commented on GitHub (Jun 6, 2026): Fixed by #2424, merged into `refactor`.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1163
No description provided.