[PR #2623] [MERGED] fix: W2 audit batch — restore secrets, metadata races, untrusted-input DoS (#2611-#2621) #5692

Closed
opened 2026-10-22 04:18:35 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/2623
Author: @Romuromylus
Created: 6/18/2026
Status: ✅ Merged
Merged: 6/18/2026
Merged by: @SpicyMarinara

Base: staging ← Head: fix/audit-w2-batch-2611-2621


📝 Commits (10+)

  • 87ac248 fix(backup): preserve live secrets on profile restore UPDATE path
  • 733fe0a fix(discord-webhook): suppress mentions on mirrored content
  • 61a2df1 fix(png-parser): read chunk length unsigned and guard the chunk walk
  • 4e0c3d4 fix(import): normalize numeric selectiveLogic/position in native lorebook importer
  • 55d222d fix(knowledge-sources): cache extracted text and make meta writes atomic
  • e815d0d fix(game): preserve field locks and manual overrides on checkpoint load
  • b0a18c7 fix(regex): reject ReDoS-prone prompt regex at apply time and on save
  • 61a4555 fix(retry-agents): abort upstream agent calls on client disconnect
  • 2ff81fd fix(file-store): copy-on-write transaction rollback
  • d4ff900 fix(import): accept unknown in resolvePosition for native importer pass-through

📊 Changes

13 files changed (+324 additions, -114 deletions)

View changed files

📝 packages/client/src/lib/png-parser.ts (+12 -4)
📝 packages/server/src/db/file-backed-store.ts (+46 -5)
📝 packages/server/src/routes/backup.routes.ts (+27 -1)
📝 packages/server/src/routes/chats.routes.ts (+10 -11)
📝 packages/server/src/routes/game.routes.ts (+64 -53)
📝 packages/server/src/routes/generate.routes.ts (+2 -2)
📝 packages/server/src/routes/generate/retry-agents-route.ts (+23 -0)
📝 packages/server/src/routes/knowledge-sources.routes.ts (+117 -31)
📝 packages/server/src/services/discord-webhook.ts (+3 -1)
📝 packages/server/src/services/import/marinara.importer.ts (+3 -2)
📝 packages/server/src/services/import/st-lorebook.importer.ts (+2 -2)
📝 packages/server/src/services/regex/regex-application.ts (+4 -1)
📝 packages/shared/src/schemas/regex.schema.ts (+11 -1)

📄 Description

Linked issue

This PR addresses 11 issues filed from the W2 static audit of staging. The PR base is staging, whose default-branch is main, so Closes # would not auto-fire on merge — these are closed manually after merge:

Refs #2611, #2612, #2613, #2614, #2615, #2616, #2617, #2618, #2619, #2620, #2621

Why this change

All 11 are pre-existing (non-regression) defects the W2 audit surfaced across the server and one client parser. They cluster into a few themes — secret/data loss on restore, metadata/meta lost-write races, untrusted-input DoS, and a leak/perf pair — and each fix mirrors a pattern already present elsewhere in the repo. Grouping them keeps the review in one place; every commit is scoped to a single issue so they remain individually traceable and revertable.

  • #2611 (High, data-loss): Profile restore upserted the redacted export rows over live ones, wiping api_connections.apiKeyEncrypted, agent_configs secret settings, and custom_tools.webhookUrl — secrets that are not in the archive, so the loss is unrecoverable. Now the conflict-UPDATE path omits those columns so the stored value is preserved; fresh inserts still carry the blanks.
  • #2612 (Med, data-loss/perf): FileTableStore.transaction() deep-cloned the whole table map for rollback and restored all of it on throw — dropping concurrent writes to untouched tables and allocating O(total-rows) per call on a hot path (setMemories per agent turn). Rollback is now copy-on-write: a table is snapshotted only on first mutation and only dirty tables are restored.
  • #2613 (Med, data-loss/concurrency): Several game-route handlers persisted chat metadata via the unqueued, blind updateMetadata({ ...staleMeta, ...changes }), racing the queue-serialized patchMetadata. The priority LLM-bearing handlers and /summaries now route through patchMetadata, which re-reads fresh metadata inside the per-chat queue.
  • #2614 (Med, leak): /retry-agents had no abort wiring, so a client disconnect left every in-flight agent LLM call running. Mirrors the main generate route: AbortController, close-listener, context.signal threaded into the agent context, post-start events via trySendSseEvent, listener removed in finally.
  • #2615 (Med, security): Discord mirror posted with no allowed_mentions, so mirrored content could @everyone/@here/role-ping. Now allowed_mentions: { parse: [] } on every body.
  • #2616 (Med, crash/DoS): The client PNG card parser read the chunk length signed, so a crafted high-bit length froze the tab for ~13-16s. Length is now read unsigned with bounds + advance guards.
  • #2617 (Med, perf): Knowledge-retrieval source files (including PDFs) were re-read and re-parsed from disk every generation turn. Extracted text is now cached per file id, keyed on (size, uploadedAt), invalidated on re-upload/delete.
  • #2618 (Low, correctness): The native .marinara.json lorebook importer passed numeric selectiveLogic/position through verbatim; a numeric value silently disabled selective gating. Now routed through the same resolveSelectiveLogic/resolvePosition normalizers the ST importer uses.
  • #2619 (Low, data-loss): /game/checkpoint/load dropped fieldLocks/manualOverrides when cloning the restored snapshot, so locked tracker fields were silently lost on restore. Both are now carried onto the cloned state.
  • #2620 (Low, perf/security ReDoS): Prompt-context regex scripts compiled and ran with no timeout or static safety check. Unsafe patterns are now gated by isPatternSafe at apply time and rejected at the POST/PATCH /regex-scripts validation layer, matching the lorebook regex posture.
  • #2621 (Low, concurrency): Knowledge-source meta.json writes serialized the write but not the read-modify-write, allowing a lost update. writeMeta now takes a mutator that re-reads inside the serialized critical section, mirroring withMetadataPatchQueue.

What changed

  • One commit per issue, scoped to that issue's files. See each commit body for the file:line rationale.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

pnpm check passes locally and the per-package vitest suite passes (focused regression tests added for #2611, #2616, and #2618 — kept local-only per our test-file convention). The boxes above are intentionally left unticked as a reviewer to-do; below is what I verified directly on a build of this branch deployed to my private instance.

Confirmed on the deployed branch (real data, with a full data snapshot taken first):

  • #2611 — secrets preserved on restore (live, conclusive): with 14 API connections all holding real keys, I re-imported every api_connections row with apiKeyEncrypted blanked (exactly what a redacted export contains). The import ran the conflict-UPDATE path on all 14 rows (HTTP 200, connections: 14) and every stored key was preserved byte-for-byte (0 blanked, 0 changed). On the pre-fix code this path blanks all 14. Net change to the data: none.
  • #2613 — converted handler preserves other metadata (live): on a real game chat with 63 metadata keys, the PUT /game/:chatId/notes handler (now routed through patchMetadata) updated gamePlayerNotes while leaving every other key intact (witness key gameActiveState unchanged). Restored afterward.

Still worth a reviewer eyeball in normal use:

  • #2613 concurrency: fire a long side-action (Recruit/Conclude) concurrently with a turn that persists tracker/journal metadata and confirm neither writer's changes are reverted.
  • #2619: lock a tracker field, save + load a checkpoint, run a turn; confirm the locked field is not overwritten.
  • #2620: create a promptOnly regex script with a catastrophic pattern via the API; confirm it is rejected at validation and not run per turn.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

UI evidence (if applicable)

Verified on a build of this branch deployed to my private EasyPanel instance (CI pnpm-validate + container-build-test both green):

  • #2611: import of 14 redacted api_connections rows → HTTP 200, all 14 stored keys preserved (0 blanked / 0 changed); the pre-fix path would have blanked all 14.
  • #2613: PUT /game/:chatId/notes on a 63-key game chat → gamePlayerNotes updated, all other keys (incl. gameActiveState) intact.

After verification the deployment was repointed back to staging, the data snapshot was restored to pre-test state, and the snapshot was removed.

Summary by CodeRabbit

  • Bug Fixes

    • PNG parsing now validates chunk bounds to prevent crashes on malformed files.
    • Profile export/import preserves secrets instead of clearing them.
    • Chat summaries merge atomically to prevent concurrent update conflicts.
    • Regex patterns validated to prevent catastrophic backtracking issues.
    • Agent tasks properly cancel when client disconnects.
    • Discord webhook no longer triggers unintended mentions.
  • New Features

    • Knowledge source text extraction now caches results for improved performance.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/2623 **Author:** [@Romuromylus](https://github.com/Romuromylus) **Created:** 6/18/2026 **Status:** ✅ Merged **Merged:** 6/18/2026 **Merged by:** [@SpicyMarinara](https://github.com/SpicyMarinara) **Base:** `staging` ← **Head:** `fix/audit-w2-batch-2611-2621` --- ### 📝 Commits (10+) - [`87ac248`](https://github.com/Pasta-Devs/Marinara-Engine/commit/87ac248f6a242cfd8a16a1ef88cedede557f021c) fix(backup): preserve live secrets on profile restore UPDATE path - [`733fe0a`](https://github.com/Pasta-Devs/Marinara-Engine/commit/733fe0a4c9e0f619b53e34b536dc846a07874ef7) fix(discord-webhook): suppress mentions on mirrored content - [`61a2df1`](https://github.com/Pasta-Devs/Marinara-Engine/commit/61a2df1df52eeeb04c801fca040b920a1c124e2f) fix(png-parser): read chunk length unsigned and guard the chunk walk - [`4e0c3d4`](https://github.com/Pasta-Devs/Marinara-Engine/commit/4e0c3d428993f1f3ef3d80209eb962de5789c499) fix(import): normalize numeric selectiveLogic/position in native lorebook importer - [`55d222d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/55d222d3b91e7b905e93020c1ea1d02924afcb26) fix(knowledge-sources): cache extracted text and make meta writes atomic - [`e815d0d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/e815d0d54db6c0e838465e2439f16dc6653a48cf) fix(game): preserve field locks and manual overrides on checkpoint load - [`b0a18c7`](https://github.com/Pasta-Devs/Marinara-Engine/commit/b0a18c7df769ea5ef12712f29c612e2198c0717c) fix(regex): reject ReDoS-prone prompt regex at apply time and on save - [`61a4555`](https://github.com/Pasta-Devs/Marinara-Engine/commit/61a4555e6c60d933818fe6b092f9ad577d8b30dd) fix(retry-agents): abort upstream agent calls on client disconnect - [`2ff81fd`](https://github.com/Pasta-Devs/Marinara-Engine/commit/2ff81fddb5ecc18d602b34d5a4a3fbbb0a7244e3) fix(file-store): copy-on-write transaction rollback - [`d4ff900`](https://github.com/Pasta-Devs/Marinara-Engine/commit/d4ff9004f36f376b8de6ee94a04807a64fb4dbb8) fix(import): accept unknown in resolvePosition for native importer pass-through ### 📊 Changes **13 files changed** (+324 additions, -114 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/lib/png-parser.ts` (+12 -4) 📝 `packages/server/src/db/file-backed-store.ts` (+46 -5) 📝 `packages/server/src/routes/backup.routes.ts` (+27 -1) 📝 `packages/server/src/routes/chats.routes.ts` (+10 -11) 📝 `packages/server/src/routes/game.routes.ts` (+64 -53) 📝 `packages/server/src/routes/generate.routes.ts` (+2 -2) 📝 `packages/server/src/routes/generate/retry-agents-route.ts` (+23 -0) 📝 `packages/server/src/routes/knowledge-sources.routes.ts` (+117 -31) 📝 `packages/server/src/services/discord-webhook.ts` (+3 -1) 📝 `packages/server/src/services/import/marinara.importer.ts` (+3 -2) 📝 `packages/server/src/services/import/st-lorebook.importer.ts` (+2 -2) 📝 `packages/server/src/services/regex/regex-application.ts` (+4 -1) 📝 `packages/shared/src/schemas/regex.schema.ts` (+11 -1) </details> ### 📄 Description ## Linked issue This PR addresses 11 issues filed from the W2 static audit of `staging`. The PR base is `staging`, whose default-branch is `main`, so `Closes #` would not auto-fire on merge — these are closed manually after merge: Refs #2611, #2612, #2613, #2614, #2615, #2616, #2617, #2618, #2619, #2620, #2621 ## Why this change All 11 are pre-existing (non-regression) defects the W2 audit surfaced across the server and one client parser. They cluster into a few themes — secret/data loss on restore, metadata/meta lost-write races, untrusted-input DoS, and a leak/perf pair — and each fix mirrors a pattern already present elsewhere in the repo. Grouping them keeps the review in one place; every commit is scoped to a single issue so they remain individually traceable and revertable. - **#2611 (High, data-loss):** Profile restore upserted the *redacted* export rows over live ones, wiping `api_connections.apiKeyEncrypted`, `agent_configs` secret settings, and `custom_tools.webhookUrl` — secrets that are not in the archive, so the loss is unrecoverable. Now the conflict-UPDATE path omits those columns so the stored value is preserved; fresh inserts still carry the blanks. - **#2612 (Med, data-loss/perf):** `FileTableStore.transaction()` deep-cloned the whole table map for rollback and restored all of it on throw — dropping concurrent writes to untouched tables and allocating O(total-rows) per call on a hot path (`setMemories` per agent turn). Rollback is now copy-on-write: a table is snapshotted only on first mutation and only dirty tables are restored. - **#2613 (Med, data-loss/concurrency):** Several game-route handlers persisted chat metadata via the unqueued, blind `updateMetadata({ ...staleMeta, ...changes })`, racing the queue-serialized `patchMetadata`. The priority LLM-bearing handlers and `/summaries` now route through `patchMetadata`, which re-reads fresh metadata inside the per-chat queue. - **#2614 (Med, leak):** `/retry-agents` had no abort wiring, so a client disconnect left every in-flight agent LLM call running. Mirrors the main generate route: `AbortController`, close-listener, `context.signal` threaded into the agent context, post-start events via `trySendSseEvent`, listener removed in `finally`. - **#2615 (Med, security):** Discord mirror posted with no `allowed_mentions`, so mirrored content could `@everyone`/`@here`/role-ping. Now `allowed_mentions: { parse: [] }` on every body. - **#2616 (Med, crash/DoS):** The client PNG card parser read the chunk length signed, so a crafted high-bit length froze the tab for ~13-16s. Length is now read unsigned with bounds + advance guards. - **#2617 (Med, perf):** Knowledge-retrieval source files (including PDFs) were re-read and re-parsed from disk every generation turn. Extracted text is now cached per file id, keyed on `(size, uploadedAt)`, invalidated on re-upload/delete. - **#2618 (Low, correctness):** The native `.marinara.json` lorebook importer passed numeric `selectiveLogic`/`position` through verbatim; a numeric value silently disabled selective gating. Now routed through the same `resolveSelectiveLogic`/`resolvePosition` normalizers the ST importer uses. - **#2619 (Low, data-loss):** `/game/checkpoint/load` dropped `fieldLocks`/`manualOverrides` when cloning the restored snapshot, so locked tracker fields were silently lost on restore. Both are now carried onto the cloned state. - **#2620 (Low, perf/security ReDoS):** Prompt-context regex scripts compiled and ran with no timeout or static safety check. Unsafe patterns are now gated by `isPatternSafe` at apply time and rejected at the `POST/PATCH /regex-scripts` validation layer, matching the lorebook regex posture. - **#2621 (Low, concurrency):** Knowledge-source `meta.json` writes serialized the write but not the read-modify-write, allowing a lost update. `writeMeta` now takes a mutator that re-reads inside the serialized critical section, mirroring `withMetadataPatchQueue`. ## What changed - One commit per issue, scoped to that issue's files. See each commit body for the file:line rationale. ## Validation - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes `pnpm check` passes locally and the per-package vitest suite passes (focused regression tests added for #2611, #2616, and #2618 — kept local-only per our test-file convention). The boxes above are intentionally left unticked as a reviewer to-do; below is what I verified directly on a build of this branch deployed to my private instance. **Confirmed on the deployed branch (real data, with a full data snapshot taken first):** - **#2611 — secrets preserved on restore (live, conclusive):** with 14 API connections all holding real keys, I re-imported every `api_connections` row with `apiKeyEncrypted` blanked (exactly what a redacted export contains). The import ran the conflict-UPDATE path on all 14 rows (HTTP 200, `connections: 14`) and every stored key was preserved byte-for-byte (0 blanked, 0 changed). On the pre-fix code this path blanks all 14. Net change to the data: none. - **#2613 — converted handler preserves other metadata (live):** on a real game chat with 63 metadata keys, the `PUT /game/:chatId/notes` handler (now routed through `patchMetadata`) updated `gamePlayerNotes` while leaving every other key intact (witness key `gameActiveState` unchanged). Restored afterward. **Still worth a reviewer eyeball in normal use:** - **#2613 concurrency:** fire a long side-action (Recruit/Conclude) concurrently with a turn that persists tracker/journal metadata and confirm neither writer's changes are reverted. - **#2619:** lock a tracker field, save + load a checkpoint, run a turn; confirm the locked field is not overwritten. - **#2620:** create a `promptOnly` regex script with a catastrophic pattern via the API; confirm it is rejected at validation and not run per turn. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) ## UI evidence (if applicable) Verified on a build of this branch deployed to my private EasyPanel instance (CI `pnpm-validate` + `container-build-test` both green): - **#2611:** import of 14 redacted `api_connections` rows → HTTP 200, all 14 stored keys preserved (0 blanked / 0 changed); the pre-fix path would have blanked all 14. - **#2613:** `PUT /game/:chatId/notes` on a 63-key game chat → `gamePlayerNotes` updated, all other keys (incl. `gameActiveState`) intact. After verification the deployment was repointed back to `staging`, the data snapshot was restored to pre-test state, and the snapshot was removed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * PNG parsing now validates chunk bounds to prevent crashes on malformed files. * Profile export/import preserves secrets instead of clearing them. * Chat summaries merge atomically to prevent concurrent update conflicts. * Regex patterns validated to prevent catastrophic backtracking issues. * Agent tasks properly cancel when client disconnects. * Discord webhook no longer triggers unintended mentions. * **New Features** * Knowledge source text extraction now caches results for improved performance. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:18:35 +07:00
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#5692
No description provided.