# Session Security and Persistence Fixes Implementation Plan > **For agentic workers:** Execute inline with test-first checkpoints. **Goal:** Remove cross-user stale chat exposure, verify existing persistence/rate limits, and close remaining backend validation gaps. **Architecture:** Keep the existing backend Supabase service and explicit ownership checks. Reset all frontend conversation state on every auth transition. Move the chat-session listing route before the parameterized chat route. Add deterministic backend tests for validation and ownership helpers. **Tech Stack:** Express 5, Supabase JS, React 19, Vite, Node test runner. ## Global Constraints - Do not expose service credentials to frontend code. - Keep explicit `req.user.uid` ownership checks even when using the service-role client. - Do not update React state during render. - Verify each behavioral change with a focused test or runtime smoke check. ### Task 1: Backend route and validation coverage **Files:** - Create: `backend/src/routes/chatValidation.js` - Create: `backend/test/chatValidation.test.js` - Modify: `backend/src/routes/chat.js` - [ ] Write failing tests for valid/invalid metadata, empty/oversized text, and owned/unowned session decisions. - [ ] Run `node --test backend/test/chatValidation.test.js` and confirm the missing helper fails. - [ ] Implement minimal pure validation/ownership helpers. - [ ] Use helpers in the chat POST path and preserve 404 ownership behavior. - [ ] Run the focused test and confirm pass. ### Task 2: Frontend auth transition cleanup **Files:** - Create: `frontend/src/appState.js` - Create: `frontend/test/appState.test.js` - Modify: `frontend/src/App.jsx` - [ ] Write failing tests for reset state after sign-out and sign-in. - [ ] Run the focused test and confirm failure. - [ ] Implement a pure reset-state helper and call it from the auth effect, aborting active requests and clearing sessions on sign-out. - [ ] Keep reset side effects inside `useEffect`, not render. - [ ] Run the focused test and frontend build. ### Task 3: Route ordering and existing infrastructure verification **Files:** - Modify: `backend/src/routes/chat.js` only if needed. - [ ] Place `GET /sessions` before `GET /:chatId`. - [ ] Verify rate-limit middleware is installed and mounted on auth/chat/sessions. - [ ] Verify migration and database service configuration without committing credentials. - [ ] Run backend syntax/tests and frontend build. ### Task 4: Runtime verification - [ ] Start local Supabase/backend/frontend where available. - [ ] Exercise health, unauthorized protected routes, rate-limit boundary, and browser sign-out/sign-in state reset. - [ ] Report exact observed outputs and any unavailable checks.