Commit graph

12 commits

Author SHA1 Message Date
Randall Stillwell
a84373642e fix(security): drop wildcard CORS + redundant OPTIONS from 24 API routes (P0 #5)
Closes P0 #5 (CORS) from PARTIAL → RESOLVED. fix-auth-bypass
Brief 4 (commit 297afca) cleaned login + register; this brief
sweeps the remaining 24 pages/api/** handlers that carried the
identical scaffolded wildcard-CORS + redundant-OPTIONS pattern,
plus adds a blocking forbidden-cors-headers CI job to lock in
the cleanup against future regression.

Per architect Decision 1 — Option B (sweep all 24 in one PR)
chosen over Option A (narrow verify.js-only + queue separate
sweep). Pattern-drift audit (14 of 24 files spot-checked across
parent + architect) found zero drift; mechanical safety
confirmed.

Per Decision 2 — OPTIONS handler deleted entirely (matches
Brief 4 precedent). Same-origin Vercel deployment doesn't
preflight; method check at top of handler returns 405 if any
client ever sends OPTIONS again.

Per Decision 3 — verify.js's overly-permissive Allow-Methods:
'GET, POST, PUT, DELETE, OPTIONS' is moot (deleted under D2);
the handler's existing `if (req.method !== 'GET') return 405`
guard at line 17 (now line ~5) is the remaining gate.

Per Decision 4 — no new per-route tests this convoy. None of
the 24 routes have vitest coverage today; adding handler-level
tests is the queued fill-vitest-handler-coverage convoy.

Per Decision 5 — new `forbidden-cors-headers` CI job added,
modeled verbatim on `forbidden-endpoints`. Blocking (no
`|| true`, no `continue-on-error`). Greps pages/api/ for any
`Access-Control-Allow-(Origin|Methods|Headers)` reappearance
and exits 1 on hit.

Verification:
  - npm run lint: 128 problems (baseline match)
  - npm run test:run: 21/21 vitest pass (no regression)
  - git grep -nE "Access-Control-Allow-..." -- 'pages/api/**':
    zero matches
  - git grep -nE "OPTIONS" -- 'pages/api/**': zero matches
    (post-sweep)
  - new forbidden-cors-headers grep exits 0 against swept tree

No code paths in lib/**, components/**, scripts/**, or test/**
touched. No package.json / lockfile churn. No workflow YAML
beyond the single ci.yml job addition. No AGENTS.md edits
(doc-writer pass at convoy close).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 20:24:47 -05:00
Randall Stillwell
1fca3aa1ca fix(api): return 401 (not 500) on unauthenticated cards-collection writes
Follow-up to fix-auth-bypass Brief 2 (commit 258e479). Brief 2 made
getUserFromRequest return null for unauthenticated requests. POST, PUT,
and DELETE branches of pages/api/collections/[identifier]/cards.js
were dereferencing user.userId without a guard → NPE → HTTP 500.

Security side was already fixed by Brief 2 (no more
anonymous-write-as-admin on collections owned by userId: 1). This patch
adds the cosmetic 500 → 401 cleanup the Brief 2 reviewer flagged.

Three identical 'if (!user) return 401' guards added, one per write
branch. GET branch was already guarded via the ternary pattern.

Sibling endpoints under pages/api/collections/** were re-audited by the
implementer and confirmed correctly guarded (thumbnails, permissions,
activity all have early null checks; [identifier].js uses optional
chaining throughout). No further hotfixes needed for that route group.

Convoy: fix-auth-bypass / Brief 6 (post-architect hotfix)
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:04:55 -05:00
Randall Stillwell
afb79c57d9 Major Scanner Improvements
🔧 Gemini AI Integration:
- Added Google Gemini API as default OCR service
- Auto-configures from GEMINI_AI_API_KEY environment variable
- Fixed Puter.js authentication issues
- Enhanced OCR settings with connection testing

🎨 Redesigned Scanner Queue:
- New thumbnail + content layout with checkbox overlay
- Smart quantity management (duplicates increment quantity)
- Complete card information display from database
- Two-row action layout (primary/secondary actions)
- Floating bottom toolbar for bulk actions
- Real card images from database

�� Enhanced User Experience:
- Fixed Canvas2D performance warnings
- Better error handling and fallbacks
- Improved responsive design
- Database confirmation indicators
- Professional card scanning workflow

📱 Mobile Ready:
- Optimized layouts for mobile scanning
- Touch-friendly controls and interactions
- Improved visual feedback and status indicators
2025-07-29 14:19:48 -05:00
Randall Stillwell
2e172815b9 🎨 Perfect Thumbnail Layout & Clean Up Debug
 Thumbnail Layout Improvements:
- Updated CollectionThumbnail to show 5 cards total (1 main + 4 in 2x2 grid)
- Better visual ratio with filled 2x2 grid on the right side
- Applied consistent design to both /collections and /community/collections
- Improved spacing and proportions for better visual balance

🧹 Code Cleanup:
- Removed debug console.log statements from thumbnails API
- Clean, production-ready code with proper error handling
- Thumbnails API now properly handles Neon SQL result structure

🎯 Final Result:
- 😢 Empty collections → crying emoji placeholder
- 🃏 Collections with cards → white card boxes with real images
- 🖼️ Custom thumbnails → uploaded hero images
- Perfect 5-card layout with balanced proportions

The new thumbnail design is now complete and working perfectly! 🖼️
2025-07-27 14:48:42 -05:00
Randall Stillwell
6dc97aaae5 🔍 Add Debug Logging to Thumbnails API
Added comprehensive debugging to understand the actual structure of thumbnailsResult from Neon SQL queries. This will help identify whether it's an array, object with rows, or something else entirely.
2025-07-27 14:45:37 -05:00
Randall Stillwell
c1554447c7 🔧 Fix Thumbnails API Result Structure
🐛 Bug Fix:
- Fixed thumbnailsResult.map() error in thumbnails API
- Added null safety with (thumbnailsResult || [])
- Updated response to wrap thumbnails in object: { thumbnails }

 Expected Results:
- Thumbnails API should now work without errors
- Collections should display proper thumbnail layouts:
  😢 Empty collections → crying emoji
  🃏 Collections with cards → white card boxes
  🖼️ Custom thumbnails → uploaded images

The new thumbnail layouts should now display correctly! 🎨
2025-07-27 14:32:09 -05:00
Randall Stillwell
560ddcbb8e 🔧 Fix SQL Structure Issues Across All Collection APIs
🐛 Multiple API Fixes:
- Fixed SQL DISTINCT/ORDER BY conflict in thumbnails API
- Fixed SQL result structure (.rows) in cards API
- Fixed SQL result structure (.rows) in permissions API
- Restored accidentally removed code in cards API

 Technical Corrections:
- Removed DISTINCT from thumbnails query to fix ORDER BY conflict
- Updated all APIs to use collectionResult.rows instead of direct access
- Updated all result mappings to use .rows property
- Fixed validation checks to use .rows.length

🎯 Expected Results:
- Thumbnails API should now work without SQL errors
- Cards API should load collection cards properly
- Permissions API should work for collection management
- New card layout thumbnails should display correctly

All collection APIs should now work properly! 🚀
2025-07-27 14:18:49 -05:00
Randall Stillwell
39dbaca07d 🔧 Fix Thumbnails API SQL Result Structure
🐛 Root Cause Found:
- SQL queries return { rows: [...] } structure, not direct arrays
- Code was accessing collectionResult.length instead of collectionResult.rows.length
- This caused undefined results leading to collection.id errors

 Fixes Applied:
- Updated to use collectionResult.rows.length for length checks
- Updated to use collectionResult.rows[0] for collection data
- Added proper SQL error handling with try/catch
- Enhanced validation for SQL result structure

🔧 Technical Improvements:
- Proper error handling for SQL query failures
- Correct access to SQL result structure
- Better validation before accessing collection properties
- Cleaner debug output (removed excessive logging)

This should resolve the 'Cannot read properties of undefined (reading 'id')' error! 🎯
2025-07-27 14:15:29 -05:00
Randall Stillwell
2951efdaa0 🐛 Add Debug Logging for Thumbnails API Error
Added comprehensive debugging to identify why collection.id is undefined:
- Log identifier analysis (slug vs ID detection)
- Log which query path is taken (slug vs numeric ID)
- Log collection result structure and content
- Add validation for collection data before using collection.id
- Better error messages for debugging

This will help identify the root cause of the thumbnails API failure.
2025-07-27 14:11:51 -05:00
Randall Stillwell
f11a7fef36 🧹 Remove Debug Logging - Authentication Issue Fixed
 Ownership Indicators Now Working:
- Bob's collections properly show userRole: 'owner'
- Alice's public collections show userRole: null
- Authentication headers fix resolved the issue

🧹 Cleanup:
- Removed debug console.log statements
- Cleaned up server-side logging
- Restored clean, production-ready code

The authentication issue is fully resolved! Bob now sees proper ownership
indicators (👑 Owner badges) on his collections while Alice's public
collections show as viewable without ownership indicators.
2025-07-27 12:41:14 -05:00
Randall Stillwell
7077fc9e25 🔧 Fix Authentication Headers & Add Debug Logging
🔐 Authentication Fixes:
- Added proper auth headers to collections API calls
- Added auth headers to thumbnail API calls
- Fixed missing Authorization Bearer token in requests

🔍 Enhanced Debug Logging:
- Added server-side logging in collections API
- Added debug logging in thumbnails API
- Log user authentication data
- Log SQL query results
- Log final API responses

This should fix the userRole: null issue by ensuring proper authentication
and help identify any remaining issues with detailed logging.
2025-07-27 12:39:28 -05:00
Randall Stillwell
374ad421f6 🔄 Implement Automatic Redirects and Collection Edit/Delete
🔗 Automatic ID to Slug Redirects:
- Collection detail page now automatically redirects from ID URLs to slug URLs
- Maintains backwards compatibility for all existing links
- SEO-friendly permanent redirects using router.replace()

✏️ Collection Edit/Delete Functionality:
- Added edit modal directly in collection detail page
- Added delete confirmation modal with proper warnings
- Edit functionality updates name, description, image, and visibility
- Automatic slug regeneration when collection name changes
- Proper permission checks (only owners can edit/delete)

🛠️ API Route Restructuring:
- Renamed all [id] routes to [identifier] to resolve Next.js conflicts
- Updated all APIs to handle both slugs and numeric IDs
- Fixed 'different slug names for same dynamic path' error
- Consistent identifier handling across all endpoints

📁 Updated API Endpoints:
- /api/collections/[identifier] - Main collection CRUD
- /api/collections/[identifier]/cards - Collection cards management
- /api/collections/[identifier]/thumbnails - Thumbnail generation
- /api/collections/[identifier]/permissions - Permission management
- /api/collections/[identifier]/activity - Activity tracking

🎨 UI/UX Improvements:
- Edit and Delete buttons only show for collection owners
- Clean modal interfaces with proper form validation
- Loading states and error handling
- Confirmation dialogs for destructive actions
- Consistent styling with fire theme

🔧 Technical Enhancements:
- Smart identifier detection (slug vs numeric ID)
- Proper error handling and user feedback
- Database transaction safety for updates
- Automatic collection timestamp updates
- Permission-based access control

Now users can seamlessly edit collections and get beautiful SEO-friendly URLs! 🚀
2025-07-26 22:16:52 -05:00