[GH-ISSUE #3057] [Issue]: Unvalidated sprite-sheet cols/rows silently drop all expressions or crash slicing after a paid generation #1625

Closed
opened 2026-10-21 05:40:59 +07:00 by bsakaguchi · 2 comments
Owner

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

Originally assigned to: @SpicyMarinara on GitHub.

What's wrong

POST /api/sprites/generate-sheet (and its preview) take cols/rows straight from the request body with no validation, clamping, or integer check. The values feed expressions.slice(0, cols * rows) and the cell-slicing math. Two concrete failures occur, both AFTER the (typically paid) provider image generation has already run:

  1. Non-numeric value -> silent empty result. If cols is a non-numeric string, cols * rows is NaN, so slice(0, NaN) becomes slice(0, 0) -> []. The entry guard only checks the RAW body.expressions, not the sliced plan, so the request passes. The slicing loop never iterates, and the handler returns 200 with a populated sheetBase64 but cells: [] — zero sprites, no error.
  2. Fractional value -> 500 crash. With cols: 1.5, idx = row * plan.cols + col is non-integer and left = col * Math.floor(imgWidth / 1.5) can exceed the image width, so sharp .extract() rejects with 'bad extract area', Promise.all rejects, and the handler returns 500 — again only after the image was generated.

How to reproduce (try it yourself)

  1. POST /api/sprites/generate-sheet with a valid connectionId, appearance, expressions: ["happy","sad"], and cols: "x" (any non-numeric).
  2. Or the same with cols: 1.5, rows: 2.

You'll see: case (a) returns 200 with cells: [] and a populated sheetBase64, no error, despite a successful image generation; case (b) generates the image then returns 500 ('... bad extract area').

Expected: a malformed cols/rows is rejected with a 400 BEFORE any provider call, so no generation is wasted; valid requests always slice on positive integers.

Where it is

packages/server/src/routes/sprites.routes.ts:

  • buildSpritePromptPlan lines 1086-1089 — const cols = body.cols ?? 2; const rows = body.rows ?? 3; then slice(0, cols * rows); ?? only catches null/undefined, not a string or fractional number.
  • generate-sheet entry guard line 1688 — validates raw body.expressions only.
  • paid generateImage call line 1824 — runs before slicing.
  • cell-slicing math + loop lines 1860-1885 — Math.floor(imgWidth / plan.cols), idx = row * plan.cols + col, sharp.extract.
  • Preview route same flaw lines 1581-1603. Routes registered without JSON schema at routes/index.ts:72.

What's happening

cols/rows are accepted from untrusted input without coercion to a positive integer. The TS number? type on the body provides no runtime protection (the handler does req.body as SpriteGenerateSheetBody). The entry guard checks only the raw expressions array, not the post-slice plan, and the slicing math assumes positive integers.

Suggested fix

Two surgical changes in sprites.routes.ts:

(A) Coerce inside buildSpritePromptPlan so plan.cols/plan.rows are always safe positive integers for both routes and all internal math. Replace lines 1086-1087 with const cols = coerceSpriteGridDimension(body.cols, 2); / const rows = coerceSpriteGridDimension(body.rows, 3); and add:

const MAX_SPRITE_GRID_DIMENSION = 8; // largest UI preset is 4x4
function coerceSpriteGridDimension(raw: unknown, fallback: number): number {
  const n = Math.trunc(Number(raw));
  if (!Number.isFinite(n) || n < 1) return fallback;
  return Math.min(MAX_SPRITE_GRID_DIMENSION, n);
}

Number(undefined) is NaN, so an omitted value falls back to the existing defaults (2/3) — happy path preserved.

(B) In the /generate-sheet handler, BEFORE any provider work (right after the expressions guard at line 1690), reject only PRESENT-but-invalid values so omitted values still use defaults:

const isInvalidGridDimension = (v: unknown) =>
  v !== undefined && (!Number.isFinite(Number(v)) || Math.trunc(Number(v)) < 1 || Math.trunc(Number(v)) > 8);
if (isInvalidGridDimension(body.cols) || isInvalidGridDimension(body.rows)) {
  return reply.status(400).send({ error: "cols and rows must be positive integers (max 8)" });
}

Then after the plan is built (after line 1711), guard the sliced result:

if (plan.expressions.length === 0) {
  return reply.status(400).send({ error: "No expressions remain after applying the requested grid size" });
}

Regression avoided: the original suggestion to return a 400 from inside buildSpritePromptPlan cannot work — that function returns a SpritePromptPlan, not a Fastify reply, and a throw there would surface as a 500 and also wrongly reject the provider-free preview route. Splitting coercion (in the plan builder, for both routes) from the 400 validation (in the handler, before the provider call) keeps the preview route working and avoids over-rejecting the omitted-value case.


AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.

Originally created by @kolacheee on GitHub (Jun 29, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/3057 Originally assigned to: @SpicyMarinara on GitHub. **What's wrong** `POST /api/sprites/generate-sheet` (and its preview) take `cols`/`rows` straight from the request body with no validation, clamping, or integer check. The values feed `expressions.slice(0, cols * rows)` and the cell-slicing math. Two concrete failures occur, both AFTER the (typically paid) provider image generation has already run: 1. Non-numeric value -> silent empty result. If `cols` is a non-numeric string, `cols * rows` is `NaN`, so `slice(0, NaN)` becomes `slice(0, 0)` -> `[]`. The entry guard only checks the RAW `body.expressions`, not the sliced plan, so the request passes. The slicing loop never iterates, and the handler returns 200 with a populated `sheetBase64` but `cells: []` — zero sprites, no error. 2. Fractional value -> 500 crash. With `cols: 1.5`, `idx = row * plan.cols + col` is non-integer and `left = col * Math.floor(imgWidth / 1.5)` can exceed the image width, so sharp `.extract()` rejects with 'bad extract area', `Promise.all` rejects, and the handler returns 500 — again only after the image was generated. **How to reproduce (try it yourself)** 1. `POST /api/sprites/generate-sheet` with a valid `connectionId`, `appearance`, `expressions: ["happy","sad"]`, and `cols: "x"` (any non-numeric). 2. Or the same with `cols: 1.5, rows: 2`. You'll see: case (a) returns 200 with `cells: []` and a populated `sheetBase64`, no error, despite a successful image generation; case (b) generates the image then returns 500 ('... bad extract area'). Expected: a malformed `cols`/`rows` is rejected with a 400 BEFORE any provider call, so no generation is wasted; valid requests always slice on positive integers. **Where it is** `packages/server/src/routes/sprites.routes.ts`: - `buildSpritePromptPlan` lines 1086-1089 — `const cols = body.cols ?? 2; const rows = body.rows ?? 3;` then `slice(0, cols * rows)`; `??` only catches null/undefined, not a string or fractional number. - generate-sheet entry guard line 1688 — validates raw `body.expressions` only. - paid `generateImage` call line 1824 — runs before slicing. - cell-slicing math + loop lines 1860-1885 — `Math.floor(imgWidth / plan.cols)`, `idx = row * plan.cols + col`, `sharp.extract`. - Preview route same flaw lines 1581-1603. Routes registered without JSON schema at `routes/index.ts:72`. **What's happening** `cols`/`rows` are accepted from untrusted input without coercion to a positive integer. The TS `number?` type on the body provides no runtime protection (the handler does `req.body as SpriteGenerateSheetBody`). The entry guard checks only the raw expressions array, not the post-slice plan, and the slicing math assumes positive integers. **Suggested fix** Two surgical changes in `sprites.routes.ts`: (A) Coerce inside `buildSpritePromptPlan` so `plan.cols`/`plan.rows` are always safe positive integers for both routes and all internal math. Replace lines 1086-1087 with `const cols = coerceSpriteGridDimension(body.cols, 2);` / `const rows = coerceSpriteGridDimension(body.rows, 3);` and add: ```ts const MAX_SPRITE_GRID_DIMENSION = 8; // largest UI preset is 4x4 function coerceSpriteGridDimension(raw: unknown, fallback: number): number { const n = Math.trunc(Number(raw)); if (!Number.isFinite(n) || n < 1) return fallback; return Math.min(MAX_SPRITE_GRID_DIMENSION, n); } ``` `Number(undefined)` is `NaN`, so an omitted value falls back to the existing defaults (2/3) — happy path preserved. (B) In the `/generate-sheet` handler, BEFORE any provider work (right after the expressions guard at line 1690), reject only PRESENT-but-invalid values so omitted values still use defaults: ```ts const isInvalidGridDimension = (v: unknown) => v !== undefined && (!Number.isFinite(Number(v)) || Math.trunc(Number(v)) < 1 || Math.trunc(Number(v)) > 8); if (isInvalidGridDimension(body.cols) || isInvalidGridDimension(body.rows)) { return reply.status(400).send({ error: "cols and rows must be positive integers (max 8)" }); } ``` Then after the plan is built (after line 1711), guard the sliced result: ```ts if (plan.expressions.length === 0) { return reply.status(400).send({ error: "No expressions remain after applying the requested grid size" }); } ``` Regression avoided: the original suggestion to return a 400 from inside `buildSpritePromptPlan` cannot work — that function returns a `SpritePromptPlan`, not a Fastify reply, and a throw there would surface as a 500 and also wrongly reject the provider-free preview route. Splitting coercion (in the plan builder, for both routes) from the 400 validation (in the handler, before the provider call) keeps the preview route working and avoids over-rejecting the omitted-value case. --- *AI-investigated against v2.0.6; cited lines read and confirmed. Please verify before fixing.*
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064

<!-- gh-comment-id:4835429001 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Claiming this for the current staging sweep in draft PR #3064: https://github.com/Pasta-Devs/Marinara-Engine/pull/3064
Author
Owner

@SpicyMarinara commented on GitHub (Jun 29, 2026):

Fixed in PR #3064 on branch codex/issue-sweep-3054-3063 (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.

<!-- gh-comment-id:4835578425 --> @SpicyMarinara commented on GitHub (Jun 29, 2026): Fixed in PR #3064 on branch `codex/issue-sweep-3054-3063` (commit 3ae8ca37). Closing this issue as addressed; the PR remains open for staging review/merge.
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#1625
No description provided.