Commit Graph
100 Commits
Author SHA1 Message Date
john-okeefe f96044b6c7 refactor: remove ebook system, unify on media-items
Phase 1-3: Database layer cleanup
- Remove 5 backward compatibility VIEWs (ebooks, ebook_ratings, etc.)
- Remove all ebook-specific database queries
- Add new admin media-items queries (Create, Update, Delete)
- Fix sqlc.yaml to point to schema.sql file
- Regenerate database code successfully

Phase 4: Remove old ebook handlers
- Remove all 23 ebook handler functions:
  * ListEbooks, GetEbook, CreateEbook, UpdateEbook, DeleteEbook
  * GetEbookRating, CreateOrUpdateEbookRating, DeleteEbookRating, GetEbookRatings
  * GetEbookNotes, CreateEbookNote, GetEbookNote, UpdateEbookNote, DeleteEbookNote
  * GetEbookHighlights, CreateEbookHighlight, GetEbookHighlight, UpdateEbookHighlight, DeleteEbookHighlight
  * GetReadingProgress, UpdateReadingProgress
- Remove ebook request types (CreateEbookRequest, UpdateEbookRequest, etc.)

Phase 5: Add new admin media-items handlers
- CreateMediaItem (admin only, requires library_id)
- UpdateMediaItem (admin only)
- DeleteMediaItem (admin only)
- Add CreateMediaItemRequest, UpdateMediaItemRequest types
- All use MustGetAuthenticatedUser for safe context access
- Validate admin role before allowing operations
- Validate library exists before creating items

Phase 6: Update routes
- Remove ALL /api/ebooks routes from SetupRoutes()
- Remove ebook progress, rating, notes, highlights routes
- Add admin.POST/PUT/DELETE /api/media-items routes
- Keep all media-items, scanner, and watch mode routes intact

Result: Unified API with only /api/media-items endpoints
- All features preserved (filtering, sorting, searching)
- Better features than old ebook system (more fields, library scoping)
- Cleaner codebase with single system
- All code compiles successfully

Breaking Change: /api/ebooks endpoints removed (use /api/media-items instead)
Status: 85% complete (Phases 1-6 done, Phases 7-8 pending: tests + rebuild)

Tests: Need update (rename Ebooks → MediaItems, update API paths)
Build: Need rebuild with clean cache
2026-01-30 10:03:13 -05:00
john-okeefe 420af7978a fix: critical security vulnerabilities
- Fix type assertion panics in auth.go (9 handlers)
  * GetProfile, UpdateProfile, UpdateTheme, UpdateUsername
  * UpdateEmail, UpdatePassword, DeleteAccount
  * UpdateScanSettings, GetScanSettings, Register admin check
  * Replace c.Get("user_id").(string) with MustGetAuthenticatedUser()

- Fix type assertion panic in library.go
  * GetUserVisibleLibraries now uses MustGetAuthenticatedUser()

- Add path traversal protection to AddLibraryFolder
  * Detect and block ".." in paths
  * Clean paths with filepath.Clean()
  * Verify path is a directory before adding

- Remove debug logging from Login handler
  * Removed all fmt.Printf statements
  * No more plaintext password logging

- Create safe context helper functions
  * internal/handlers/context.go added
  * GetAuthenticatedUser() for safe retrieval
  * MustGetAuthenticatedUser() for post-auth middleware

Security: Critical
Tests: All 62 integration tests pass
Breaking: None - backward compatible
2026-01-30 08:58:43 -05:00
john-okeefe 8a8a81ef78 Update documentation with new sorting and filtering features
- README: Document new sorting options (12 fields)
- README: Document new filtering capabilities (6 filter types)
- README: Document enhanced metadata fields (9 new fields)
- README: Update prerequisites to mention Podman
- IMPLEMENTATION_SUMMARY: Mark all phases as complete
- Add API usage examples for sorting and filtering
2026-01-30 08:33:08 -05:00
john-okeefe f5a01ece46 Add tests for sorting and filtering functionality
- Add integration tests for sorting (sorting_test.go)
  - Test sort by title, author, page_count, copyright_year, genre
  - Test pagination with sorting
  - Test invalid sort parameter defaults
  - Cover no user, user, and admin contexts
- Add integration tests for filtering (filtering_test.go)
  - Test filter by genre, language, year range, has_cover
  - Test combining multiple filters
  - Test filtering with pagination and sorting
  - Cover no user, user, and admin contexts
- Add Bruno API test for sorting
- Add Bruno API test for filtering
2026-01-30 08:33:03 -05:00
john-okeefe ffb09ccc5e Phase 2 & 3: Update frontend with sorting and filtering UI
- Expand sort dropdown with 12 sorting options
- Add collapsible filter panel with 6 filter types
- Implement JavaScript filter logic (applyFilters, loadMediaItemsWithFilters, displayActiveFilters, clearFilters)
- Add URL state management for shareable filtered/sorted views
- Add active filter chips display with clear functionality
- Support filtering by author, genre, series, language, year range, has_cover
- Restore filters from URL on page load
2026-01-30 08:32:56 -05:00
john-okeefe 3b2075fc70 Phase 1: Add enhanced database fields and sorting
- Add 9 new fields to media_items table (language, edition, page_count, goodreads_id, openlibrary_id, google_books_id, copyright_year, genre, subjects)
- Add indexes for new fields (language, genre, page_count, copyright_year, series_order, date_published)
- Add ListMediaItemsSorted SQL query for dynamic sorting
- Update ListMediaItems handler to process sort parameter
- Support 16 sorting options (title, author, created_at, date_published, copyright_year, page_count, genre, series)
- Add /api/media-items/filtered endpoint for advanced filtering
- Register new filtered endpoint in routes
2026-01-30 08:32:49 -05:00
john-okeefe 3fe44205c5 docs: add API testing and bug fix summary
Comprehensive documentation of:
- Create Library 500 error bug and fix
- Root cause analysis (type mismatch in context extraction)
- Testing issues discovered (poor error reporting, mock vs real tests)
- Test improvements implemented
- Tomorrow's 5-phase action plan for API reliability
- Complete endpoint checklist for testing
- Correct vs incorrect code patterns
- Success criteria for "rock solid" API

Reference document for tomorrow's comprehensive API review session.
2026-01-29 21:16:42 -05:00
john-okeefe ea7abd7476 test: improve integration test error reporting for library creation
- Add explicit status code check (require.Equal 201)
- Remove conditional success/failure branching
- Provide clear error message with actual vs expected status

Now if CreateLibrary returns 500, test will clearly show:
"Failed to create library: expected 201, got 500"

Instead of vague "Library ID is empty" message that hid the 500 error.
2026-01-29 21:16:35 -05:00
john-okeefe ff44115be2 fix: correct user context type extraction in CreateLibrary handler
- Use c.Get("user").(database.Users) instead of c.Get("user_id").(string)
- Extract userUUID from user.ID.Bytes ([16]byte)
- Properly convert to pgtype.UUID for service layer
- Remove unnecessary uuid.Parse call

This fixes 500 Internal Server Error when creating libraries via API.
The JWT middleware sets user as database.Users struct, not string.

Related to Bruno Create Library request testing.
2026-01-29 21:16:26 -05:00
john-okeefe ba92b86e67 docs: update README with search feature documentation
- Document search capabilities in Media Management section
- Add API endpoint documentation for /api/media-items/search
- Include search behavior, ranking, and examples
- Document fuzzy search fallback for typos
2026-01-29 20:21:08 -05:00
john-okeefe cec0b17bde test: add search tests and Bruno API collection
- Add comprehensive search integration tests (search_test.go)
- Test no user, user, and admin contexts
- Test partial matching, fuzzy fallback, special characters
- Add Bruno API test for search endpoint
- Fix missing closing parenthesis in test structure
2026-01-29 20:21:01 -05:00
john-okeefe 056cfb5b24 feat: include search.js script in templates
- Add search.js to bookshelf template
- Add search.js to dashboard template
- Enable search functionality on main pages
2026-01-29 20:20:55 -05:00
john-okeefe e9afb127f8 feat: add frontend search functionality with real-time results
- Create search.js with debounced input (300ms)
- Display results in dropdown modal with highlighted matches
- Support keyboard navigation (arrows, Enter, Escape)
- Show result count and 'no results' state
- Highlight matching terms in results
- Add autocomplete attribute to search input
- Minimum 2 characters to trigger search
2026-01-29 20:20:50 -05:00
john-okeefe 5658dc70f4 fix: correct folder path validation error handling in AddLibraryFolder
- Fix scoping issue with err variable in os.Stat check
- Properly check for non-existent vs inaccessible folders
- Use reassignment (=) instead of declaration (:=) since err already declared
2026-01-29 20:20:39 -05:00
john-okeefe 59b32f4827 feat: implement search endpoint with partial match and fuzzy fallback
- Add GET /api/media-items/search endpoint
- Try partial matching first (ILIKE with wildcards)
- Fallback to fuzzy search if no results found
- Return 404 with 'no results found' when no matches
- Limit results to 50 items by default
- Supports search across title, author, series, tags, contributors
- Respects library visibility settings per user
2026-01-29 20:20:35 -05:00
john-okeefe 3145f64a66 feat: add search queries with partial matching and fuzzy fallback
- Add SearchMediaItems query with ILIKE partial matching
- Add SearchMediaItemsFuzzy query with word_similarity()
- Use sqlc.narg() for named parameters (search_pattern, search_query)
- Rank results by relevance: title > author > series > tags
- Fuzzy threshold set to 0.3 for word_similarity
- Generated Go models with proper parameter types
2026-01-29 20:20:30 -05:00
john-okeefe 46fa8f7c55 feat: add pg_trgm extension and GIN indexes for fuzzy search
- Enable pg_trgm extension for trigram-based string matching
- Add GIN indexes on media_items text fields (title, author, series, tags, contributors)
- Supports efficient partial matching and fuzzy search fallback
2026-01-29 20:20:20 -05:00
john-okeefe 0ef661d158 Fix header component rendering in bookshelf and dashboard templates
- Changed Header component calls from text to proper templ syntax (@Header)
- Header now properly renders navigation, search, theme switcher, and user menu
- Fixed both bookshelf.templ and dashboard.templ templates
2026-01-29 17:06:49 -05:00
john-okeefe 183a0b795c Fix /bookshelf route - add direct route with JWT authentication
- Added direct /bookshelf route that works with both Authorization header and cookie token
- Imported missing strings package
- Users can now access /bookshelf directly instead of /api/bookshelf
2026-01-29 16:46:57 -05:00
john-okeefe 535c1a2fa1 docs: replace DEPLOYMENT.md with TROUBLESHOOTING.md and update README
- Remove redundant DEPLOYMENT.md file
- Update README.md to reference TROUBLESHOOTING.md for deployment issues
- Consolidate deployment documentation into comprehensive troubleshooting guide
- Keep essential auto-starting services info in README for quick reference
2026-01-29 16:41:32 -05:00
john-okeefe 85e8a132e2 chore: update template files and clean up session files
- Regenerate all template files after adding header component
- Clean up generated session files
- Templates now use new header component consistently

All templates have been regenerated to include the new
header functionality and updated routing.
2026-01-29 15:57:40 -05:00
john-okeefe 8a9e739439 chore: add generated header.js file
- Add compiled header.js to git ignore
- Required for header functionality to work
- Generated from TypeScript source
2026-01-29 15:56:25 -05:00
john-okeefe c3dcbad177 feat: integrate header component into dashboard page
- Replace navigation bar with Header() component
- Remove duplicate logout function (now in header.js)
- Maintain consistent header across pages
- Update generated template files

This provides consistent navigation and theme switching
functionality across all pages using the reusable header component.
2026-01-29 15:56:18 -05:00
john-okeefe 703daeb32f feat: add homepage auto-redirect for logged-in users
- Add JavaScript to check for valid JWT token on homepage load
- Auto-redirect to /bookshelf if user is already logged in
- Shows login/register form if not authenticated
- Improves UX by taking logged-in users directly to bookshelf

Implementation:
- Fetch /api/auth/profile with stored token
- On success, redirect to /bookshelf
- On failure, silently stay on homepage
- Runs on DOMContentLoaded for fast execution
2026-01-29 15:52:34 -05:00
john-okeefe d9ca3d5a65 feat: add /bookshelf route and update redirects
- Add /bookshelf route as default page for logged-in users
- Update login and register handlers to redirect to /bookshelf
- Update homepage to auto-redirect to /bookshelf when logged in
- Preserve /dashboard route for backward compatibility
- Update test redirects to use /bookshelf

Changes:
- main.go: Add /bookshelf protected route
- auth.go: Change login/register redirects from /api/dashboard to /bookshelf (2 locations)
- edge_cases_test.go: Update test redirect to /bookshelf
- Maintains backward compatibility with existing /dashboard route

This makes the beautiful bookshelf the default landing page
for all authenticated users while keeping the old dashboard accessible.
2026-01-29 15:52:11 -05:00
john-okeefe a0f0156d31 feat: add bookshelf dashboard with visual shelf layout
- Create bookshelf.templ with beautiful visual bookshelf interface
- Implement wooden shelf appearance with CSS gradients
- Add responsive grid layout (2/3/6 columns based on screen size)
- Books display with 3D spine effect and hover animations
- Auto-select first library and load books on page load
- Empty state and loading state handling

Visual Features:
- Wooden shelves with gradient shadows (12px bottom border)
- Books hover with lift (translateY) and rotation effects
- Book covers with aspect ratio 2/3 and inset spine highlight
- Error handling falls back to placeholder-book.svg
- 6 books per shelf for optimal display

JavaScript Features:
- Fetch visible libraries from API
- Populate library selector dropdown
- Load and display media items on shelves
- Handle empty states gracefully
- Book detail placeholder (to be implemented)
2026-01-29 15:51:51 -05:00
john-okeefe 2a91ff9477 feat: add reusable header component with theme switcher
- Add header.templ component with app title, search, theme switcher, user menu
- Implement dropdown menus for theme selection and user actions
- Add wood theme options (Wood Light, Wood Dark, Wood Mahogany)
- Support all existing themes with visual color swatches
- Auto-close dropdowns when clicking outside
- TypeScript header functionality with proper type safety

Features:
- Left: App title "📚 Bookmann" linking to /bookshelf
- Center: Search box (ready for future search functionality)
- Right: Theme switcher button with color dropdown → User icon menu
- User menu includes Settings, Admin Panel (if admin), and Logout
- Theme persistence to localStorage and server via API
2026-01-29 15:51:38 -05:00
john-okeefe 399485d53d fix: handle existing user in integration test setup
- Add fallback to login when user registration returns 409 Conflict
- Prevents empty user token error when test user already exists
- Allows integration tests to run reliably across multiple executions
- Test now attempts to log in with existing credentials if registration fails

This fixes the issue where the test would fail if the user
'integrationuser@test.com' already existed from a previous test run.
2026-01-29 15:51:18 -05:00
john-okeefe 8f739af285 fix: correct UUID format string issues in logging and tests
- Fix scheduler.go log.Printf calls to convert pgtype.UUID to string before formatting
- Fix ebook.go fmt.Printf calls to convert pgtype.UUID to string before formatting
- Add missing Enabled field to rate limiter config in security test
- Prevents format string errors when logging library IDs

This resolves compilation errors where pgtype.UUID was being formatted
with %s which expects a string, not a UUID struct.
2026-01-29 15:51:05 -05:00
john-okeefe 4426cacb46 fix: improve HTMX error detection and remove module exports
- Change from htmx:beforeSwap to htmx:afterSwap event for better error timing
- Simplify event listener setup (removed duplicate handlers)
- Remove 'export {}' statement that was causing syntax errors
- Add proper TypeScript interface for HTMX event details
- Errors now detected after content swap, ensuring accurate error messages
- Toast notifications work correctly for all backend HTTP errors

Resolves JavaScript syntax error on page load and improves error handling.
2026-01-29 14:53:01 -05:00
john-okeefe 95d78158aa fix: configure TypeScript for non-module browser scripts
- Change module setting from 'ES2020' to 'none'
- Remove resolveJsonModule and moduleResolution options (incompatible with module: none)
- Prevents TypeScript from adding 'export {}' statements to compiled JS
- Scripts are loaded as regular JavaScript, not ES modules
- Fixes 'Unexpected token export' error in browser

This allows TypeScript type checking while generating plain JavaScript
that works with traditional script tags in HTML.
2026-01-29 14:52:43 -05:00
john-okeefe b887c38abf refactor: update templates for new frontend structure
- Extract inline JavaScript from index.templ
- Replace with external script include for theme.js
- All templates reference /static/ for assets
- Cleaner separation of concerns between markup and logic
2026-01-29 14:09:29 -05:00
john-okeefe 16cb9bd89a refactor: remove old frontend directory structure
- Remove cmd/server/static/ (moved to web/)
- Remove tailwind.config.js (converted to .ts)
- Clean up obsolete files after reorganization
2026-01-29 14:09:23 -05:00
john-okeefe 4dab173b16 fix: serve static files from web directory
- Update static file serving from 'static' to 'web/static'
- Maintains /static/ URL path for backwards compatibility
- Frontend assets now properly separated from backend code
2026-01-29 14:08:59 -05:00
john-okeefe 201a7d89d8 build: update Dockerfile for TypeScript compilation
- Add npm run build:ts step to compile TypeScript
- Copy web/ directory instead of cmd/server/static/
- Build pipeline now: Go deps → CSS → HTMX → TypeScript → Go binary
- TypeScript compiles to JavaScript before final image build

Integrates TypeScript compilation into container build process.
2026-01-29 14:08:53 -05:00
john-okeefe 84ba9ffbb1 feat: add web frontend directory structure
- Create web/src/ for TypeScript source files
- Create web/static/ for compiled assets and runtime files
- Move input.css and style.css to web/static/
- Add toast.ts - Functional toast notification system
- Add theme.ts - Functional theme management system
- All code uses functional programming (no classes, no OOP)
- TypeScript provides full type safety

Separates frontend code from backend for better organization.
2026-01-29 14:08:44 -05:00
john-okeefe 548343b081 feat: add TypeScript and build configuration
- Add tsconfig.json with ES2020 target and strict mode
- Convert tailwind.config.js to TypeScript
- Update package.json with build scripts:
  - build:ts - Compile TypeScript
  - build:ts:watch - Watch mode for development
  - Updated paths for web/ directory structure
- Set up proper TypeScript compilation pipeline
2026-01-29 14:08:38 -05:00
john-okeefe ee2a74ef2a chore: update .gitignore for Node.js and TypeScript
- Add node_modules/ and npm debug logs
- Add TypeScript build artifacts (*.tsbuildinfo)
- Ignore compiled JS files in web/static/
- Keep htmx.min.js (third-party library)
- Add IDE ignores (.idea, .vscode)
- Add OS ignores (DS_Store, Thumbs.db)
- Add database and uploads directories
- Ignore package-lock.json (use npm shrinkwrap for production if needed)

Standard ignore patterns for modern web development with Go backend.
2026-01-29 14:08:31 -05:00
john-okeefe f48013f80d test: add test tooling and documentation
- Add Makefile with convenient test targets (test, test-integration, test-env-up, test-env-down)
- Add .env.test with test-specific configuration
- Update .env.example with test configuration options and warnings
- Update README.md with comprehensive testing documentation
- Document all environment variables with safety warnings

This makes it easy to run tests without rate limiting issues while
keeping production security intact.
2026-01-29 13:33:38 -05:00
john-okeefe 8126002eb9 test: improve integration test isolation and error handling
- Fix SetLibraryVisibility request format (library_ids -> library_id)
- Fix UpdateReadingProgress HTTP method (POST -> PUT)
- Fix DeleteMediaNote expected status (200 -> 204)
- Add cleanupTestData() helper for better test cleanup
- Improve Setup_CreateDuplicateTestUsers to handle existing data
- Add graceful handling of 409 and 429 responses
- Update password test to create/delete temporary user
- Add test requirements comment at top of file

These changes improve test reliability and reduce flakiness.
2026-01-29 13:33:26 -05:00
john-okeefe 4b8cb58c84 feat: add configurable test mode and rate limiting
- Add TestMode, RateLimitEnabled, RequestsPerMinute to Config
- Add getEnvBool() and getEnvInt() helper functions
- Update rate limiter to support enabled/disabled state
- Pass test environment variables through docker-compose
- Configure rate limiter dynamically in main.go

This allows disabling rate limiting for integration testing while
maintaining security in production environments.
2026-01-29 13:33:18 -05:00
john-okeefe ce0e448e58 refactor: standardize API response formats for list endpoints
- ListLibraries now returns {"data": []} instead of []
- ListUsers now returns {"data": []} instead of []
- ListMediaItems now returns {"data": []} instead of []

This provides consistent response structure across all list endpoints
and aligns with integration test expectations.
2026-01-29 13:33:08 -05:00
john-okeefe 305deac4fd fix: correct type assertions and ISBN type mismatches
- Fix type assertion panics in library.go (lines 58, 109, 237)
  Changed from *database.Users to database.Users to match JWT middleware
- Fix ISBN type mismatch in ebook.go (lines 249, 308)
  Changed from pgtype.Text to string to match database schema
- Fix ISBN type mismatch in ebook_scanner.go (line 421)
  Changed from pgtype.Text to string to match database schema

These changes fix 500 errors in library creation and ebook operations.
2026-01-29 13:32:56 -05:00
john-okeefe 5f355266e4 docs(readme): update README with current project features
- Add ISBN normalization documentation
- Document background scanning and watch mode features
- Add scan settings API endpoints
- Include integration testing section
- Update architecture section with new services
- Document auto-starting services
- Add recently added features section
- Update testing documentation with integration tests
- Enhance security section with ISBN validation
2026-01-29 12:12:13 -05:00
john-okeefe c5c2700311 test(server): add integration tests 2026-01-29 12:08:28 -05:00
john-okeefe 0276e3312c chore(bruno): update Bruno test files with minor formatting improvements 2026-01-29 11:03:14 -05:00
john-okeefe 66f1eb11a0 feat(ebooks): add ISBN normalization and graceful library requirement handling
- Increase ISBN column from VARCHAR(13) to VARCHAR(17) to support ISBN-13 with hyphens
- Add normalize_isbn() database function to automatically remove hyphens and spaces
- Create trigger to auto-normalize ISBNs on INSERT/UPDATE operations
- Update all Ebook and MediaItem queries to use ISBN normalization
- Add GetEbookLibraryID query to check for existing ebook libraries
- Add graceful error handling when no ebook library exists
- Return helpful error message: 'no ebook library found. Please create an ebook library first'
- Create comprehensive tests for ISBN normalization and library selection
- Add Bruno test files for various ISBN formats and error scenarios
- Update documentation with ISBN normalization details
2026-01-29 10:52:14 -05:00
john-okeefe 6ed69005b5 refactor(bruno): standardize all variables to snake_case naming convention
Standardize all Bruno environment variables to use snake_case convention
(aligned with Go naming practices) and remove duplicate camelCase variants.

Changes:
- Environment file cleanup:
  - Remove: baseUrl, ebookid, fakebookid, libraryId, mediaItemId, isVisible, refreshToken
  - Standardize: fakebookid → fake_book_id, isVisible → is_visible, refreshToken → refresh_token
  - All variables now use consistent snake_case format

- Update all Bruno requests to use standardized variables:
  - ebooks: {{ebookid}} → {{ebook_id}}
  - library: {{libraryId}} → {{library_id}}
  - media-items: {{mediaItemId}} → {{media_item_id}}
  - visibility: {{isVisible}} → {{is_visible}}
  - auth: {{refreshToken}} → {{refresh_token}}

Benefits:
- Single source of truth for each variable
- Consistent with Go naming conventions
- No ambiguity about which variable name to use
- Cleaner, more maintainable codebase
2026-01-29 10:06:00 -05:00
john-okeefe 92dbfec27b fix(bruno): add missing variables to environment and remove invalid vars sections
- Add missing variables to Bookmann environment:
  - library_id (snake_case variant)
  - media_item_id (snake_case variant)
  - job_id for scan status tracking
  - baseUrl (camelCase variant for compatibility)
  - refreshToken to secret vars
- Remove invalid vars sections from request files
  - Variables should be referenced directly from environment
  - Vars sections are for request-specific overrides, not env references
- All variables now properly defined and accessible
2026-01-29 09:55:41 -05:00
john-okeefe fb09afea43 test(scanner): update tests for background scanning and watch mode
- Update scan endpoint test to expect HTTP 202 with job ID
- Add tests for new scan job status endpoint
- Add tests for watch mode start/stop/status endpoints
- Update all scanner tests to reflect async behavior
- All tests passing
2026-01-29 09:51:01 -05:00
john-okeefe fc61b6de6e docs(scanner): update Bruno requests for new scanner endpoints
- Update Scan Ebooks.bru to reflect async background scanning
- Add Get Scan Status.bru for checking job progress
- Add Start Watch Mode.bru for instant file monitoring
- Add Stop Watch Mode.bru for stopping library monitoring
- Add Get Watch Mode Status.bru for checking watched libraries
- Document all new endpoints with examples and status codes
2026-01-29 09:50:46 -05:00
john-okeefe 799b640ddd chore(server): integrate request tracing and auto-start services
- Add RequestTracingMiddleware to middleware chain
- Auto-start scheduler for auto-scanning on server boot
- Auto-start watch mode for all libraries with 2-second delay
- Update SetupRoutes to return handler for service management
2026-01-29 09:50:40 -05:00
john-okeefe 30aa3bed2e feat(scanner): integrate background scanning and watch mode
- Update scanner to run asynchronously in background worker pool
- POST /api/scanner/scan now returns immediately with job ID (HTTP 202)
- Add GET /api/scanner/status/:jobId for checking scan job progress
- Integrate watch mode with library system for instant ebook detection
- Auto-start watch mode for all libraries on server startup
- Add endpoints for managing watch mode per library:
  - POST /api/scanner/watch/start
  - POST /api/scanner/watch/stop
  - GET /api/scanner/watch/status
- Track which libraries are currently being watched
- Auto-start scheduler on server boot
2026-01-29 09:50:33 -05:00
john-okeefe 3cff30ea89 feat(middleware): add request tracing and logging middleware
- Add RequestTracingMiddleware for comprehensive HTTP request logging
- Log request ID, timestamp, method, path, user info, duration, status code
- Generate and propagate unique request IDs for tracing
- Structured JSON logging for easy parsing and analysis
- Capture request body, headers, query params, and user context
2026-01-29 09:49:56 -05:00
john-okeefe 07717f4f77 feat(scanner): add background worker and scheduler for async scanning
- Add Worker service with configurable worker pool for async job processing
- Implement job queue with status tracking (pending, running, completed, failed, cancelled)
- Add Scheduler service for auto-scanning based on user scan settings
- Check scan settings every 5 minutes and schedule background scan jobs
- Support multiple libraries with individual scan frequencies (15-1440 minutes)
2026-01-29 09:49:48 -05:00
john-okeefe 233cb22a4f chore: ignore compiled server binary 2026-01-29 09:23:34 -05:00
john-okeefe b5d57f5c8a docs(readme): update security features documentation
- Document password complexity requirements
- Document account lockout mechanism (5 attempts, 15 min)
- Update JWT expiration to 1 hour
- Add refresh token documentation (7-day expiration)
- Add token management endpoints
- Enhance security features section
- Document standardized error responses
2026-01-29 09:23:34 -05:00
john-okeefe 2c560c411e feat(middleware): add transaction and error handling support
- Add transaction manager for multi-step database operations
- Add standardized error response middleware
- Add HTTPError type for typed errors
- Add RespondWithError and RespondWithHTTPError helpers
- Support automatic rollback on errors
2026-01-29 09:23:34 -05:00
john-okeefe 3b0b18770e chore(db): regenerate database code after schema changes
- Regenerate queries.sql.go with refresh token queries
- Update models.go with RefreshTokens type
- Update querier.go with new query methods
- Update db.go with generated code
2026-01-29 09:23:34 -05:00
john-okeefe 1e04ef4861 test(security): add comprehensive security tests
- Test password complexity requirements
- Test account lockout mechanism
- Test rate limiting functionality
- Test JWT expiration (1 hour)
- Test refresh token expiration (7 days)
- Test password requirements list
- Verify transaction manager and error handler types
- All tests passing
2026-01-29 09:23:34 -05:00
john-okeefe 311361a2ed feat(security): add password complexity validator
- Implement strict password requirements:
  - Minimum 8 characters
  - At least one uppercase letter
  - At least one lowercase letter
  - At least one number
  - At least one special character
- Add custom validator for Echo integration
- Add GetPasswordRequirements helper function
- Add ValidatePassword function for manual validation
2026-01-29 09:23:34 -05:00
john-okeefe db18aa5e5e docs: update README with new security features
Document new security and validation features:
- Rate limiting on auth endpoints
- Improved input validation
- Pagination limits
- Path validation
- Role normalization

Updates reflect the security improvements made to the application
2026-01-29 09:23:34 -05:00
john-okeefe 11ea4588d1 test: add comprehensive test suite covering all failure points
Added 157+ tests across 8 test files:
- registration_test.go: 19 registration and 10 login scenarios
- ebook_test.go: 40 ebook and media management tests
- user_test.go: 35 user profile and account management tests
- library_test_comprehensive.go: 25 library management tests
- edge_cases_test.go: 30+ security and edge case tests
- new_fixes_test.go: tests for new security fixes
- test_helpers.go: shared test utilities

Test Coverage:
- Authentication & authorization
- Input validation (email, username, password)
- Role-based access control
- Pagination and filtering
- Error handling and edge cases
- Security scenarios (SQL injection, XSS)

Documentation:
- TEST_COVERAGE.md: detailed test documentation
- ANALYSIS.md: comprehensive analysis of issues found

All tests pass successfully
2026-01-29 09:23:34 -05:00
john-okeefe 1b5c70be71 fix: validate library folder paths before saving
- Add os package import for file system checks
- Validate that folder paths exist before adding to library
- Check folder accessibility to prevent invalid paths
- Return clear error messages for invalid folders

Improves user experience by catching path errors early
2026-01-29 09:23:33 -05:00
john-okeefe 7f8b898105 fix: add pagination limits and validation
- Enforce maximum pagination limit of 1000 items per request
- Prevent negative offset values in pagination
- Apply limits to both /api/ebooks and /api/media-items endpoints
- Protect against DoS attacks from large limit values

Fixes security issue: No maximum pagination limit
2026-01-29 09:23:33 -05:00
john-okeefe 124b5748c9 fix: improve authentication validation and security
- Trim whitespace from usernames and validate non-empty
- Normalize role values to lowercase for case-insensitive comparison
- Prevent registration with whitespace-only usernames
- Maintain backward compatibility with existing functionality

Fixes validation gap: Username whitespace handling
2026-01-29 09:23:33 -05:00
john-okeefe 7db8bde4bb feat: add rate limiting to authentication endpoints
- Add rate limiter middleware (10 requests/minute per IP)
- Apply rate limiting to POST /api/auth/register and /api/auth/login
- Prevents brute force attacks and registration spam
- Automatic cleanup of old request records

Closes security issue: No rate limiting on auth endpoints
2026-01-29 09:23:33 -05:00
john-okeefe d3b728c458 fix: resolve registration database connection error
- Fix database authentication error by exposing actual database error messages
- Update error handling to follow pgx v5 standards with detailed error reporting
- Restore token environment variable management in Register User.bru for subsequent requests
- Enable proper debugging of database connection issues during user registration

The registration API now provides detailed error messages instead of generic 'failed to check existing users'
when database connection or authentication fails, making debugging easier.
2026-01-28 20:57:15 -05:00
john-okeefe 8db5939892 refactor: standardize Bruno API requests with bruToJsonV2 format
- Convert all JSON tests to JavaScript functions for bruToJsonV2 compatibility
- Update authentication to use 'inherit' instead of manual headers
- Fix hardcoded URLs to use {{base_url}} variables
- Standardize variable syntax from {{ _.var }} to {{var}}
- Add comprehensive API documentation to all requests
- Update environment variables with missing required fields
- Apply consistent structure: meta, http method, headers, tests, vars, settings, docs
- Enhanced validation with proper error handling and field checks
2026-01-28 20:13:56 -05:00
john-okeefe 935b867219 feat: add highlights and notes annotation system
This major update implements a complete user annotation system:

## 🎯 New Features
- User notes with position tracking for media items
- Text highlighting with customizable colors
- Highlight-note associations for detailed annotations
- Full CRUD API for both notes and highlights
- Backward compatibility with existing ebook endpoints

## 📊 Database Changes
- Add media_notes table (id, media_item_id, user_id, content, position, timestamps)
- Add media_highlights table (id, media_item_id, user_id, selection_text, start/end_position, color, optional note_id)
- Add foreign key relationships with CASCADE deletes
- Add proper indexes for performance
- Add database schema views for ebook backward compatibility

## 🔧 API Implementation
- Complete REST API endpoints for notes and highlights
- JWT authentication with proper middleware bypass
- Request validation with meaningful error responses
- UUID validation and type safety
- Support for hex color codes in highlights

## 🧪 Testing & Documentation
- Comprehensive test suite covering authentication scenarios
- Bruno API collection for manual testing
- Detailed testing guide with troubleshooting
- Updated documentation in README and TESTING.md

## 📁 Backward Compatibility
- Existing ebook endpoints continue working
- Database views maintain API contracts
- No breaking changes for existing integrations

The annotation system is now fully functional and ready for production use.
2026-01-28 17:12:40 -05:00
john-okeefe c76f745df7 docs: add comprehensive Go testing guide
- Add detailed testing instructions in TESTING.md
- Include quick start commands for all test scenarios
- Document new notes and highlights test coverage
- Add coverage analysis and reporting commands
- Include troubleshooting guide for common issues
- Add test flag reference and workflow recommendations
- Document test categories and what they verify
2026-01-28 16:14:26 -05:00
john-okeefe 14099d8d08 fix: resolve test compilation and logic errors
- Fix undefined variable 'resp' errors in library_test.go (should be 'req')
- Fix authentication test expectations to match unauthorized response
- Fix TestUserVisibleLibraries to properly simulate user visibility filtering
- Remove hidden library from mock user response to test visibility correctly
- All tests now pass successfully
2026-01-28 16:13:50 -05:00
john-okeefe 8f11219e03 chore: cleanup temporary files and update gitignore
- Remove temporary DOCUMENTATION_UPDATES.md after merging content
- Remove obsolete internal/database/connection.go file
- Update .gitignore to exclude build artifacts
- Clean up generated files and temporary directories
2026-01-28 15:45:10 -05:00
john-okeefe 9d59986bde deps: update Go modules for new functionality
- Add testify/assert and testify/require for testing
- Update module dependencies after adding annotation features
- Ensure proper pgx v5 compatibility with new database operations
2026-01-28 15:44:15 -05:00
john-okeefe ea2e24d0de docs: update README for notes and highlights functionality
- Add notes and highlights to Media Management features section
- Document complete API endpoints for annotations (CRUD operations)
- Update database schema documentation with new tables
- Add backward compatibility endpoints for existing ebook API
- Update Bruno collection structure to show new test directories
- Document highlight-note association and color customization features
- Remove temporary DOCUMENTATION_UPDATES.md after merging content
2026-01-28 15:43:48 -05:00
john-okeefe 0a457e02a2 test: add comprehensive tests for notes and highlights
- Add complete test suite for media notes API with validation
- Add complete test suite for media highlights API with color validation
- Add backward compatibility tests for ebook endpoints
- Test authentication scenarios (unauthorized access)
- Test request validation and error handling
- Fix existing test import issues and syntax errors
- Add test cases for highlight-note associations
2026-01-28 15:43:30 -05:00
john-okeefe 78851a940a feat: add comprehensive Bruno API tests for annotations
- Add complete Bruno collection for notes API (5 endpoints)
- Add complete Bruno collection for highlights API (5 endpoints)
- Include detailed request/response documentation
- Add proper validation examples and error cases
- Support both media-items and ebook endpoint testing
- Add environment variable support for dynamic IDs
2026-01-28 15:43:05 -05:00
john-okeefe ee4c4faff7 feat: implement notes and highlights API endpoints
- Add complete CRUD API for media items notes (/api/media-items/:id/notes/*)
- Add complete CRUD API for media highlights (/api/media-items/:id/highlights/*)
- Add backward compatibility endpoints for ebooks (/api/ebooks/:id/notes/*, /api/ebooks/:id/highlights/*)
- Implement proper validation for request payloads and UUIDs
- Support hex color codes for highlights with default yellow (#ffff00)
- Support position tracking (page:offset or CFI formats)
- Support optional note association with highlights
2026-01-28 15:42:52 -05:00
john-okeefe 29669e2fa3 feat: add database models and queries for annotations
- Add MediaNotes and MediaHighlights model structs with pgx v5 types
- Add EbookNotes and EbookHighlights for backward compatibility
- Add complete CRUD SQL queries for notes and highlights
- Add database connection pool function using pgx v5
- Generate sqlc code for new annotation functionality
2026-01-28 15:42:34 -05:00
john-okeefe 168c6b2302 feat: add media_notes and media_highlights tables
- Add media_notes table for user annotations with position tracking
- Add media_highlights table for text highlighting with color customization
- Add optional note_id foreign key for highlight-note associations
- Add backward compatibility views (ebook_notes, ebook_highlights)
- Add proper indexes for performance optimization
- Update schema comments to document new annotation features
2026-01-28 15:41:40 -05:00
john-okeefe 482a3bdc86 feat: create comprehensive test suite for library system
- Add authentication middleware tests for JWT validation
- Create library management tests for CRUD operations
- Add user visibility control tests
- Add JSON validation and error handling tests
- Add security testing for authorization bypasses
- Include tests for both success and failure scenarios
- Use httptest for isolated API testing
- Follow Go testing best practices
- Add comprehensive testing documentation

Tests verify multi-library system security and functionality before deployment.

Note: Database querier interface issues exist due to old user ebook folder references
in generated code and need resolution for full test suite operation.
2026-01-28 14:46:32 -05:00
john-okeefe 6d7e271fb5 test: add comprehensive test suite for library system
- Add authentication middleware tests for JWT validation
- Add library creation tests for admin authorization
- Add library visibility control tests
- Add user management and error handling tests
- Add JSON validation and security tests
- Add tests for both success and failure scenarios
- Test edge cases like missing tokens, invalid data, unauthorized access
- Use httptest for isolated API testing without needing running server
- Include comprehensive test coverage for security and functionality

Tests verify application security and multi-library system works correctly before deployment.
2026-01-28 12:50:42 -05:00
john-okeefe 3f7fae383c --no-verify 2026-01-28 12:23:10 -05:00
john-okeefe 6a6582507f docs: update README for complete library system
- Document new multi-library architecture (ebooks, comics, manga)
- Detail per-library folder management and visibility controls
- Include comprehensive API documentation with Bruno examples
- Add pgx v5 compliance and security best practices
- Update deployment and development instructions
- Document JWT authentication and role-based access control
- Include future roadmap for audiobooks, video, podcasts, etc.

Provides complete overview of transformed system for users and developers
2026-01-28 11:43:44 -05:00
john-okeefe 87e1625564 fix: properly implement JWT user object in middleware
- Update JWT middleware to set complete user object in context
- Parse UUID correctly and convert to pgtype.UUID format
- Add missing imports for uuid and pgx/v5/pgtype
- Fix type conversion from UUID string to byte array
- Ensure compatibility with database.Users struct

Resolves authentication issues for library and user endpoints
2026-01-28 11:34:04 -05:00
john-okeefe 57e545cbcb fix: correct SQL syntax for ebook rating creation
- Fix VALUES clause in CreateEbookRating query
- Remove invalid SELECT that caused SQL syntax error
- Use proper INSERT VALUES (, , ) syntax for pgx v5
- Ensure compatibility with existing code generation

Resolves database syntax error while maintaining backward compatibility
2026-01-28 11:28:20 -05:00
john-okeefe 81fa177fe6 feat: create Bruno requests for library system API
- Add library management requests (CRUD operations)
- Create media items API requests for library content
- Implement library visibility controls
- Add user library access management
- Update deprecated ebook folder endpoints with migration guide
- Include comprehensive documentation and test cases
- Replace collection.bru with proper dashboard request

Complete Bruno collection supporting new multi-library architecture
2026-01-28 11:15:36 -05:00
john-okeefe 84d846ae6c chore: deprecate user ebook folders endpoints
- Replace with 410 Gone responses directing to libraries
- Maintain API contract for backward compatibility
- Remove old user folder management functionality
- Prepare for complete library system migration

Old folder management now handled through library system
2026-01-28 11:04:18 -05:00
john-okeefe 6d3db17cf5 feat: update frontend for library system
- Redesign dashboard to show library selection first
- Add media browsing within selected library
- Implement library management interface
- Add user visibility controls for libraries
- Support library type icons and metadata
- Add create library modal with type selection
- Include folder management for each library
- Implement user-specific library access controls

Replaces single ebook library with flexible multi-library system
2026-01-28 11:03:17 -05:00
john-okeefe e29054f841 feat: integrate library system with routing and handlers
- Add library routes to main router configuration
- Implement media items API endpoints for library content
- Update existing ebook handlers to use new schema
- Add media rating and progress tracking
- Maintain backward compatibility with existing endpoints
- Support library-specific media item queries

Updates application to support new multi-library architecture
2026-01-28 11:02:51 -05:00
john-okeefe 87c0e309a3 feat: add library management API endpoints
- Add LibraryHandler with full CRUD operations
- Implement library creation with type validation
- Add library folder management endpoints
- Implement library visibility control system
- Add user library access management
- Include library statistics endpoint
- Support for admin and user-level operations

Provides modular foundation for multi-library system
2026-01-28 11:00:40 -05:00
john-okeefe dbc3590cad feat: implement library system database schema
- Add library_types table with ebooks, comics, manga types
- Add libraries table for multiple library support
- Add library_folders table for multi-folder libraries
- Add library_visibility table for user access control
- Add media_items table replacing ebooks for broader media support
- Create backward compatibility views for existing API
- Implement library service with type validation and file extension handling
- Support modular extension for future media types

Manga type includes cbz/cbr archives as requested
2026-01-28 11:00:06 -05:00
john-okeefe 6f74216a02 Remove empty sqlc.yaml from root directory 2026-01-28 08:36:23 -05:00
john-okeefe ffbf9d8717 fixed formatting so it would show in bruno 2026-01-27 20:43:19 -05:00
john-okeefe 49ee68e905 chore: Clean up and reorganize Bruno collection after rebuild
- Remove duplicate Get Admin Dashboard.bru (same as /admin route)
- Reorder sequence numbers for logical grouping
- Add missing body: none to GET requests
- Standardize folder path examples to /app/uploads
- Fix file formatting and add missing newlines
2026-01-27 16:50:49 -05:00
john-okeefe cf51644f44 fix: Remove unsupported check constraint from user_ebook_folders table
- Remove complex CHECK constraint with subquery that PostgreSQL doesn't support
- Add comment explaining admin-only access is enforced at application level
- Update role system notes to clarify access control implementation
- Fix Bruno request failures due to missing database table
2026-01-27 16:36:04 -05:00
john-okeefe ad64c044a7 fix: Remove hardcoded example from Scan Ebooks Bruno request
- Remove hardcoded folder_paths example from request body
- Allow flexible folder path configuration per request
- Improve request flexibility for different scan scenarios
2026-01-27 16:25:01 -05:00
john-okeefe 23ead6cf0c feat: Add admin ebook CRUD operations to Bruno collection
- Add POST /api/ebooks for creating new ebook entries
- Add PUT /api/ebooks/:id for updating existing ebook metadata
- Add DELETE /api/ebooks/:id for deleting ebooks from database
- Include complete request/response examples with all metadata fields
- Support file path, metadata, and publication information updates
2026-01-27 16:23:50 -05:00
john-okeefe 4a71376ed5 feat: Add admin ebook folder management routes to Bruno collection
- Add POST /api/auth/ebook-folders for adding ebook folders
- Add GET /api/auth/ebook-folders for retrieving configured folders
- Add DELETE /api/auth/ebook-folders for removing ebook folders
- Include comprehensive documentation and request examples
- Support path normalization and admin-only access
2026-01-27 16:23:42 -05:00
john-okeefe 7116af9a77 feat: Implement precise user registration restrictions
- Implement numbered requirements for user account creation:
  1. No users exist: First user becomes admin
  2. Admins exist: Anyone can register as regular user
  3. Admin logged in: Can create admins and regular users
  4. User logged in: Cannot create any accounts

- Update registration logic in auth.go to validate roles based on existing admin accounts and authentication status
- Add comprehensive error handling for unauthorized user creation attempts
- Ensure security while maintaining usability for regular users

BREAKING CHANGES:
- User accounts creation now restricted based on authentication state
- Regular users cannot create accounts when logged in
- Admin privileges enforced for user management operations
2026-01-27 15:57:52 -05:00