Commit graph

77 commits

Author SHA1 Message Date
0cdc25c4f0 feat: comprehensive security test suite
Add 143 security tests covering all security modules:

Unit Tests (125 tests):
- rate-limiter.unit.spec.ts: limiter creation, request tracking,
  blocking, window reset, IP extraction, header generation
- csrf.unit.spec.ts: token generation/validation, origin checking,
  double submit cookie pattern, referer validation
- ip-allowlist.unit.spec.ts: CIDR matching, wildcards, endpoint-
  specific allowlist/blocklist rules, IP extraction
- data-masking.unit.spec.ts: field detection, pattern matching,
  recursive masking, JWT/connection string/private key handling

API Integration Tests (18 tests):
- security-api.int.spec.ts: rate limiting responses, IP blocking,
  CSRF protection on state-changing endpoints

Test Infrastructure:
- tests/helpers/security-test-utils.ts: CSRF token generators,
  mock request builders, environment setup utilities
- vitest.config.mts: updated to include unit tests
- package.json: added test:unit and test:security scripts
- .github/workflows/security.yml: added security-tests CI job

Also updated detect-secrets.sh to ignore .spec.ts and .test.ts
files which may contain example secrets for testing purposes.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-08 00:20:47 +00:00
82b4a4e558 fix: standardize rate limit headers and remove dead code
- Use rateLimitHeaders() spread on /api/posts success response
  to include X-RateLimit-Limit, X-RateLimit-Reset, Retry-After
  matching /api/search and /api/search/suggestions behavior
- Remove legacy checkRateLimit, RateLimitResult, rateLimitStore,
  and cleanup interval from src/lib/search.ts (dead code after
  migration to central searchLimiter)
- Update tests to use searchLimiter from @/lib/security instead
  of the removed checkRateLimit

All integration tests pass (20 passed, 12 skipped).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-08 00:00:19 +00:00
2fae62eaf3 fix: apply CSRF protection and centralize rate limiting
- Migrate /api/posts from legacy checkRateLimit to central searchLimiter
- Add IP blocklist check and rateLimitHeaders to /api/posts
- Apply CSRF validation to /api/send-email (POST)
- Apply CSRF validation to /api/users/login (POST)
- Apply CSRF validation to /api/auth/login (POST)

CSRF protection uses the Double Submit Cookie pattern which:
- Skips safe methods (GET, HEAD, OPTIONS)
- Allows server-to-server requests with Authorization header
- Validates Origin header for browser requests
- Requires matching tokens in header and cookie for browser POSTs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 23:47:07 +00:00
cb2e903db5 fix: integrate security modules into actual endpoints
Rate Limiting Integration:
- Add authLimiter (5 attempts/15min) to both login routes for brute-force protection
- Migrate search endpoints from local checkRateLimit to central searchLimiter
- Add IP blocklist checks to auth and search endpoints

Data Masking Integration:
- Integrate maskObject/maskString from security module into audit-service
- Auto-mask previousValue, newValue, metadata, and descriptions in audit logs
- Use maskError for error logging

Pre-commit Hook:
- Add "prepare" script to package.json for automatic hook installation
- Hook is now installed automatically on pnpm install

Note: CSRF middleware is available but not enforced on API routes since
Payload CMS uses JWT auth and has built-in CORS/CSRF protection in config.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 23:34:08 +00:00
fc94531931 feat: implement security hardening module
Security Features:
- Central rate-limiter service with Redis support and memory fallback
  - Predefined limiters: publicApi, auth, email, search, form, strict
  - Automatic cleanup of stale entries
- IP allowlist/blocklist for sensitive endpoints
  - CIDR and wildcard support
  - Configurable via SEND_EMAIL_ALLOWED_IPS, BLOCKED_IPS env vars
- CSRF protection with Double Submit Cookie pattern
  - Token endpoint: GET /api/csrf-token
  - Origin header validation
- Data masking service for sensitive data
  - Automatic redaction of passwords, tokens, API keys
  - Safe logger factory for consistent logging
  - Recursive object masking for audit logs

Secret Scanning:
- Pre-commit hook for local secret detection
- GitHub Actions workflow with Gitleaks and CodeQL
- Gitleaks configuration file
- Dependency vulnerability scanning

Updated:
- /api/send-email now uses central rate-limiter and IP allowlist
- Redis lib exports getRedisClient and isRedisAvailable

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 23:04:14 +00:00
0c0892f9de fix: support Express IncomingHttpHeaders for client info extraction
- Add getHeaderValue() helper that works with multiple header formats:
  - Express req.get() method
  - Fetch API headers.get() method
  - Direct IncomingHttpHeaders object access
- Add isRequest() type guard to distinguish PayloadRequest from ClientInfo
- Use extractClientInfo() helper for consistent request/ClientInfo handling
- Apply same fix in auditAuthEvents.ts for hook context

This fixes the issue where PayloadRequest objects were incorrectly
detected as ClientInfo because IncomingHttpHeaders doesn't have .get()

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 22:34:19 +00:00
47d912016b fix: eliminate duplicate audit entries and add proper client context
- Extend logLoginFailed to accept ClientInfo directly (not just PayloadRequest)
- Add logPasswordReset function for password reset audit logging
- Remove duplicate manual payload.create calls in login routes
- Implement real fallback in auditAfterForgotPassword with structured JSON log
- Login routes now create single audit entry with full IP/User-Agent context

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 22:07:52 +00:00
dfb35566b7 fix: correct auth audit logging - use args.req.payload and override native login
- Fix afterForgotPassword hook to read payload from args.req.payload instead of context
- Create /api/users/login route to override native Payload login endpoint
- Add IP/User-Agent context to failed login audit entries
- Update /api/auth/login with consistent client info logging

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 22:00:36 +00:00
7b8efcff38 fix: complete auth event audit logging
Addresses remaining gaps from the audit review:

1. Register afterForgotPassword hook in Users collection
   - Password reset requests are now properly logged
   - Fixed hook signature (uses context instead of req)

2. Create custom /api/auth/login endpoint
   - Wraps native Payload login
   - Logs failed login attempts via auditLoginFailed
   - Returns proper error responses without exposing details

3. Export auditLoginFailed helper function
   - Can be used by other custom auth handlers
   - Calls logLoginFailed from audit-service

Now all critical auth events are tracked:
- Successful logins (afterLogin hook)
- Failed logins (custom /api/auth/login endpoint)
- Logouts (afterLogout hook)
- Password reset requests (afterForgotPassword hook)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 21:31:11 +00:00
f667792ba7 fix: complete audit logging integration based on audit review
Fixes identified gaps from the monitoring & alerting audit:

1. Auth Events Integration:
   - Add auditAuthEvents.ts hook for login/logout tracking
   - Integrate afterLogin and afterLogout hooks in Users collection
   - Log successful logins, logouts, and password reset requests

2. Rate-Limit Logging:
   - Add logRateLimit calls to /api/send-email endpoint
   - Log when users exceed rate limits

3. Access-Denied Logging:
   - Add logAccessDenied calls to all protected endpoints:
     - /api/send-email
     - /api/email-logs/export
     - /api/email-logs/stats

4. Tenant Delete Sanitizing Fix:
   - Extract sanitizeTenantDoc as reusable function
   - Apply sanitization to auditTenantAfterDelete hook
   - SMTP passwords are now properly masked in delete audit logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 21:24:28 +00:00
6bbbea52fc feat: implement monitoring & alerting system
- Add AuditLogs collection for tracking critical system actions
  - User changes (create, update, delete)
  - Tenant changes with sensitive data masking
  - Login events tracking

- Add Alert Service with multi-channel support
  - Email, Slack, Discord, Console channels
  - Configurable alert levels (info, warning, error, critical)
  - Environment-based configuration

- Add Email failure alerting
  - Automatic alerts on repeated failed emails
  - Per-tenant failure counting with hourly reset

- Add Email-Logs API endpoints
  - GET /api/email-logs/export (CSV/JSON export)
  - GET /api/email-logs/stats (statistics with filters)

- Add audit hooks for Users and Tenants collections
- Update TODO.md with completed monitoring tasks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 20:58:20 +00:00
966af755b4 docs: update CLAUDE.md and TODO.md with recent features
- Add E-Mail system documentation (tenant-specific SMTP, API endpoint)
- Add Redis caching section
- Add complete Collections and Globals overview
- Update project structure with new directories
- Mark Portfolio collections and Email system as completed
- Update environment variables documentation

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 20:22:05 +00:00
19fcb4d837 feat: implement multi-tenant email system with logging
- Add Payload email adapter for system emails (auth, password reset)
- Add EmailLogs collection for tracking all sent emails
- Extend Tenants collection with SMTP configuration fields
- Implement tenant-specific email service with transporter caching
- Add /api/send-email endpoint with:
  - Authentication required
  - Tenant access control (users can only send for their tenants)
  - Rate limiting (10 emails/minute per user)
- Add form submission notification hook with email logging
- Add cache invalidation hook for tenant email config changes

Security:
- SMTP passwords are never returned in API responses
- Passwords are preserved when field is left empty on update
- Only super admins can delete email logs

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-07 20:16:54 +00:00
cef310c1f6 feat: add Portfolio and PortfolioCategories collections
Add collections for photography portfolio website:
- PortfolioCategories: categories with name, slug, cover image, order
- Portfolios: galleries with images, project details, SEO fields
- Both collections are tenant-scoped and localized (DE/EN)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-06 07:19:19 +00:00
f1f3273fa7 docs: update TODO list with recent achievements
- Add Git & GitHub repository setup as completed
- Mark GitHub CLI installation and configuration as done
- Add isSuperAdmin field to Users Collection
- Update Backup System status (manual backups working)
- Add Techstack documentation to completed docs
- Update last modification date to 05.12.2025

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 21:22:03 +00:00
b5ca9ff177 docs: add Git & GitHub section and update deployment workflow
- Add comprehensive Git & GitHub documentation
  - GitHub CLI installation instructions
  - Git configuration (HTTPS and SSH)
  - .gitignore best practices
  - Git workflow and commit conventions
  - Useful Git and GitHub CLI commands
  - Backup via Git (exception handling)

- Update deployment workflow
  - Add detailed 4-step deployment process
  - Show Dev → GitHub → Production flow
  - Include verification steps
  - Document Git setup on both servers
  - Add comprehensive deployment commands

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 21:13:25 +00:00
d053eec21a feat: Redis caching integration 2025-12-05 16:49:57 +00:00
0a8e191747 chore: add database backup for server migration
TEMPORARY: SQL backup for one-time transfer to target server
Will be removed after pull on destination server

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 14:46:33 +00:00
dbe36ad381 feat: add super admin role and update documentation
- Add isSuperAdmin field to Users collection with migration
- Update API documentation with analytics examples
- Add analytics implementation guide
- Update TODO with completed tasks

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 14:26:08 +00:00
d18e58de40 chore: add jobs, backups, and migration history
Jobs:
- Add consentRetentionJob.ts for GDPR consent cleanup
- Add scheduler.ts for background job scheduling

Backups:
- Add database backup files for recovery

Migration backups:
- Archive old migration files for reference

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:24:26 +00:00
eac43f9846 chore: update migrations for localization schema
- Remove old migrations (pre-localization)
- Add 20251130_213501_initial_with_localization migration
- Update migrations index
- Remove unused graphql-playground route

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:20:06 +00:00
a88e4f60d0 test: add E2E and integration tests with documentation
Tests:
- Update frontend.e2e.spec.ts with locale testing
- Add search.e2e.spec.ts for search functionality
- Add i18n.int.spec.ts for localization tests
- Add search.int.spec.ts for search integration
- Update playwright.config.ts

Documentation:
- Add CLAUDE.md with project instructions
- Add docs/ directory with detailed documentation
- Add scripts/ for utility scripts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:19:52 +00:00
51c340e9e7 feat: add i18n, SEO, and frontend infrastructure
Localization:
- Add middleware for locale detection/routing
- Add [locale] dynamic route structure
- Add i18n utility library (DE/EN support)

SEO & Discovery:
- Add robots.ts for search engine directives
- Add sitemap.ts for XML sitemap generation
- Add structuredData.ts for JSON-LD schemas

Utilities:
- Add search.ts for full-text search functionality
- Add tenantAccess.ts for multi-tenant access control
- Add envValidation.ts for environment validation

Frontend:
- Update layout.tsx with locale support
- Update page.tsx for localized content
- Add API routes for frontend functionality
- Add instrumentation.ts for monitoring

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:19:35 +00:00
95c9d2a4bc feat: add content blocks and global settings
Blocks for page builder:
- HeroBlock: hero sections with CTA
- TextBlock: rich text content
- ImageTextBlock: image with text layout
- CardGridBlock: grid of cards
- CTABlock: call-to-action sections
- QuoteBlock: testimonial quotes
- VideoBlock: embedded videos
- DividerBlock: visual separators
- ContactFormBlock: contact forms
- NewsletterBlock: newsletter signup
- ProcessStepsBlock: step-by-step processes
- TimelineBlock: timeline displays
- TestimonialsBlock: testimonial carousels
- PostsListBlock: blog post listings

Globals:
- Navigation: site navigation structure
- SiteSettings: general site configuration
- SEOSettings: default SEO settings per tenant

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:19:15 +00:00
885ec93748 feat: add content collections for multi-tenant CMS
New collections:
- Categories: hierarchical content categorization
- Pages: flexible page builder with blocks
- Posts: blog/news articles with SEO
- Testimonials: customer reviews/quotes

Cookie & Consent management:
- ConsentLogs: GDPR consent tracking
- CookieConfigurations: per-tenant cookie settings
- CookieInventory: cookie registry

Additional:
- NewsletterSubscribers: email subscription management
- PrivacyPolicySettings: privacy policy configuration
- SocialLinks: social media links

Update Media collection with tenant support and image variants

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:18:58 +00:00
82c89f1494 chore: update core configuration and dependencies
- Update payload.config.ts with new collections, blocks, and globals
- Configure i18n with DE/EN localization support
- Add multi-tenant plugin configuration
- Update ecosystem.config.cjs for PM2
- Regenerate payload-types.ts and importMap.js
- Add prettier configuration

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-01 08:18:41 +00:00
9d6cb7e61b Initial commit 2025-11-26 21:18:31 +00:00