fix(api): use internal user ID instead of WorkOS ID for conversation …#42
fix(api): use internal user ID instead of WorkOS ID for conversation …#42JStaRFilms wants to merge 5 commits intomainfrom
Conversation
…operations All conversation API routes now look up the internal database user ID from the WorkOS ID before performing operations. This ensures consistency with the database schema where conversations are linked to internal user IDs. Also relaxed message schema validation to support all AI SDK part types (text, image, tool-call, tool-result, reasoning, file, etc.) and added passthrough to prevent sync failures with legitimate messages.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🟢 J Star Code Audit
📄 src/app/api/conversations/[id]/route.tsWarning N+1 Query Pattern in All Routes Warning Missing Ownership Check on PATCH Warning Missing Ownership Check on DELETE 🛠️ Recommended Fixes
📄 src/features/john-gpt/schema.ts🔹 Overly Permissive MessagePartSchemaCategory: LOGIC Using .passthrough() on MessagePartSchema disables validation for AI SDK parts, letting malformed or malicious data into the database. 🛠️ Recommended Fixes
Powered by J Star Sentinel ⚡ |
…lidation - Created `src/lib/user-auth.ts` with `getAuthenticatedUser()` to eliminate N+1 user lookup patterns - Added standard response helpers: `unauthorizedResponse()`, `forbiddenResponse()`, `notFoundResponse()` - Refactored `/api/conversations/[id]/route.ts` to use shared auth helper - Added explicit 403 responses for ownership violations on PATCH/DELETE operations - Hardened `MessagePartSchema` with discriminated union of known AI SDK part types (replaced `.passthrough()`) - Updated documentation with auth helper reference and message schema validation details
🟢 J Star Code Audit
📄 src/app/api/conversations/route.tsWarning N+1 Query Pattern Re-introduced in /conversations Route 🛠️ Recommended Fixes
📄 src/features/john-gpt/schema.ts🔹 MessageSchema.parts Array May Contain Invalid Part TypesCategory: LOGIC MessageSchema allows parts to be optional but does not enforce that every element in the array is validated by the discriminated union, so unknown part types could slip through. 🛠️ Recommended Fixes
📄 src/lib/user-auth.ts🔹 Missing Error Handling for Prisma Lookup FailureCategory: MAINTAINABILITY If prisma.user.findUnique throws (network, schema, etc.), the helper will propagate an unhandled rejection instead of returning null, forcing every caller to wrap in try/catch. 🛠️ Recommended Fixes
Powered by J Star Sentinel ⚡ |
|
/review |
🟢 J Star Code Audit
📄 src/app/api/conversations/route.tsWarning N+1 User Lookup Still Present in /conversations 🔹 Inconsistent Auth Pattern in Route HandlersCategory: LOGIC The /conversations route uses the old withAuth() + manual lookup pattern while /conversations/[id] uses the new helper, creating an inconsistent and error-prone auth flow across the same feature. 🛠️ Recommended Fixes
Powered by J Star Sentinel ⚡ |
|
/review |
🟢 J Star Code Audit
📄 src/app/api/conversations/route.tsWarning N+1 Query Still Present in conversations/route.ts 🔹 Inconsistent Error ResponsesCategory: STYLE This file still returns hand-crafted JSON instead of the new standard helpers (unauthorizedResponse, notFoundResponse). 🛠️ Recommended Fixes
Powered by J Star Sentinel ⚡ |
…e API fetch Previously, loadConversation would return empty cached metadata from list endpoint and skip API fetch. Now validates cache has messages before returning, and fetches from API if cache is empty or metadata-only. Also improves listConversations to await API fetch on empty cache (fresh window scenario) instead of returning empty list, and adds comprehensive debug logging throughout sync operations.
- Add isRefreshingList flag to prevent concurrent/recursive refreshes - Only notify listeners when actual changes are detected - Fix userId mapping for API responses that don't include userId - Handle null values in optional fields (personaId, selectedModelId) - Add detailed logging for sync payload debugging - Improve Zod validation error logging with formatted output - Ensure messages array defaults to empty array if undefined
Add comprehensive escalation handoff reports documenting two critical issues: - Sidebar conversation loading from database (resolved) - Timestamp updates when viewing conversations (unresolved) Update StorageAndPersistence.md with current system status, working features table, and known issues. Disable Google Drive sync UI in ConversationSidebar (backend remains available). Implement message count tracking in useBranchingChat to prevent timestamp updates on view-only operations. Improve db-sync-manager to detect and fix userId mismatches during conversation sync.
🟢 J Star Code Audit
📄 src/app/api/conversations/[id]/route.ts🔹 Sequential Auth & Param AwaitCategory: PERFORMANCE Auth check and params destructuring run one after another even though they are independent. This adds ~20-40ms per request. 🔹 Sequential DB & Service CallsCategory: PERFORMANCE Conversation fetch and subsequent checks execute in series even when they could be parallelized. 🔹 Sequential Body Parse & ValidationCategory: PERFORMANCE req.json() and schema.parse run sequentially despite being independent CPU/IO tasks. 🔹 Sequential Delete & ResponseCategory: PERFORMANCE Awaiting delete result before returning success response adds unnecessary latency. Warning Missing Ownership Check Warning Missing Ownership Check on DELETE 🛠️ Recommended Fixes
📄 src/features/john-gpt/schema.tsWarning Passthrough Schema Allows Arbitrary Injection 🔹 Nullable content Without Null Union TypeCategory: LOGIC content is marked optional().nullable() but the inferred TypeScript type won’t include null unless the schema is built with z.string().nullable().optional(), causing runtime vs type mismatch. 🔹 ToolResultPartSchema Allows Any ResultCategory: MAINTAINABILITY result: z.any() accepts huge payloads or circular objects that can crash JSON serialization when storing messages in SQLite. 🛠️ Recommended Fixes
📄 src/lib/storage/db-sync-manager.ts🔹 Sequential fetches can run in parallelCategory: PERFORMANCE Lines 18 and 20 fire two independent awaits back-to-back. Wrap them in Promise.all to cut wait time in half. Warning Missing nullish coalescing for userId Caution No integrity check on server conversation list 🛠️ Recommended Fixes
📄 src/lib/user-auth.tsCaution Missing Error Handling in Authentication Flow Warning Silent Failure on Missing Internal User 🔹 Missing Import for Logging UtilityCategory: MAINTAINABILITY The authentication module has no logging mechanism, making production debugging extremely difficult when authentication issues occur. 🛠️ Recommended Fixes
Powered by J Star Sentinel ⚡ |
…operations
All conversation API routes now look up the internal database user ID from the WorkOS ID before performing operations. This ensures consistency with the database schema where conversations are linked to internal user IDs.
Also relaxed message schema validation to support all AI SDK part types (text, image, tool-call, tool-result, reasoning, file, etc.) and added passthrough to prevent sync failures with legitimate messages.