Unlisted
Like
ZenServer
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
Viewing readonly version of main branch: v664View latest version
Based on careful review of map.md and PROJECT_MAPPING.md:
- businessLogic.ts has basic implementations of core payment functions (createNonce, exchangeNonce, handlePaymentCallback)
- Dynamic handler system is already functional
- Documentation system is fully implemented
- adminHandler.ts contains complete, working implementations of all missing functions
We have duplicated functionality where:
- businessLogic.ts has basic/placeholder implementations
- adminHandler.ts has complete, production-ready implementations
- The architecture is sound, just incomplete migration
Replace the "not yet implemented" placeholders with actual implementations from adminHandler.ts:
- createBooking() - Port from adminHandler.ts, adapt to return
{ bookingId }object - getBookingDetails() - Port from adminHandler.ts, adapt to return booking object
- generatePayToken() - Port from adminHandler.ts, adapt to return
{ shareableUrl }object - validatePayToken() - Port from adminHandler.ts, adapt to return validation object
- generateBookingToken() - Port from adminHandler.ts
- verifyTurnstile() - Port from turnstileHandler.ts
Add these functions that exist in openapi.json but not in businessLogic.ts:
- getRoutesV1() - for GET /api/v1/routes
- getBookingById() - for GET /api/v1/booking/{bookingId}
- getBookingByToken() - for GET /api/v1/s/booking/{token}
Upgrade the basic implementations in businessLogic.ts with features from adminHandler.ts:
- createNonce() - Add comprehensive security checks from adminHandler.ts
- exchangeNonce() - Add validation improvements from adminHandler.ts
- handlePaymentCallback() - Add proper validation and status updates from adminHandler.ts
Once all functions are properly implemented in businessLogic.ts:
- Delete
src/handlers/adminHandler.ts - Delete
src/handlers/tourHandler.ts(if it's truly redundant) - Ensure no routes are pointing to the deleted handlers
- Ensure all OpenAPI operationIds have corresponding functions in businessLogic.ts
- Test that dynamicHandler.ts properly routes to all functions
- Verify automatic validation is working for all endpoints
- Test complete payment flow (nonce → exchange → callback)
- Test booking creation and retrieval
- Test admin token generation
- Verify all security features work as expected
- Don't rewrite working code - adapt existing implementations
- Convert Response objects to plain objects when porting
- Remove manual validation (OpenAPI handles it)
- Preserve all security features from original implementations
- Keep the same business logic but change the return format
- USE EXISTING UTILITIES - We have comprehensive utility functions that should be used
- generateNonce() - Already used in adminHandler.ts for secure nonce generation
- generateUUID() - Used for creating booking IDs (currently using crypto.randomUUID() directly)
- generateSecureToken() - Should be used for pay token generation
- hashString() - For secure hashing when needed
- setCSRFCookies() - Already used in adminHandler.ts
- validateTokenBasedCSRFToken() - For CSRF validation
- NOTE: These might not be needed in businessLogic.ts if middleware handles it
- getClientIP() - Extract IP from request/context (currently done manually)
- performIPSecurityCheck() - For IP-based access control
- anonymizeIP() - For privacy-compliant logging
- logInfo(), logError(), logWarn() - Already used throughout
- withCorrelationId() - For request tracing
- measureAndLog() - For performance monitoring
- logSecurityEvent() - For security-sensitive operations
- getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS() - For consistent timestamps
- TurnstileService.validateToken() - Already used in createNonce
- PaymentFingerprintService.generatePaymentHash() - Already used in exchangeNonce
- AuthService.validateApiKey() - For API authentication
- ValidationService - For complex validation logic
- PublicPayNonceService.createPublicPaymentNonce() - UNUSED! Should replace manual nonce creation
- Problem: Both handlers manually implement nonce creation
- Solution: Use
PublicPayNonceService.createPublicPaymentNonce()instead
- CORS:
corsMiddleware()handles this - remove manualaddCorsHeaders()calls - CSRF:
getOriginBasedCSRFMiddleware()provides protection - check if manual CSRF needed - Security Headers:
secureHeaders.tsadds these automatically - Rate Limiting: Already handled by
rateLimitMiddleware()
- Security Tables:
sys_security_events,sys_blocked_ips,sys_whitelisted_ipsdefined but unused - Webhook Tables:
sys_webhooks,sys_webhook_logsexist but not integrated with payment flow - Rate Limit Table:
sys_rate_limitsmay not be connected to middleware
- webhookHandler.ts: Fully implemented but not integrated with payment callbacks
- turnstileHandler.ts: Has
verifyTurnstile()but businessLogic.ts throws "not implemented" - docsHandler.ts: Working perfectly, being used correctly
- Available:
performIPSecurityCheck(), IP firewall tables, geographic restrictions - Problem: No IP-based security happening despite full implementation
- Available:
withCorrelationId(),measureAndLog(),logSecurityEvent() - Problem: Basic logging instead of structured, traceable logging
- File:
src/services/zenpayFingerprintService.tslines 47-55 - Problem: Logging username and password in plaintext
- Fix: Remove ALL credential logging immediately
- Files:
src/handlers/adminHandler.tslines 388-398, 572-578 - Problem: Bypassing Database class error handling
- Fix: ALL database operations MUST use
db.execute()ordb.query() - Never: Construct SQL strings manually
- Remove:
AuthServicewrapper functions (lines 33-35, 146-148) - Use: Direct imports from
src/utils/crypto.ts - Specific:
newPayToken()duplicated in adminHandler.ts lines 86-93
- PublicPayNonceService: Has
createPublicPaymentNonce()but handlers implement manually - AuthService: Re-wraps crypto functions unnecessarily
- Fix: Use services directly, remove manual implementations
- CORS: Middleware handles it - remove ALL
addCorsHeaders()calls - CSRF: Middleware handles it - remove manual CSRF validation
- Security Headers: Middleware adds them - remove manual header additions
- Rate Limiting: Middleware enforces it - remove any manual rate limit code
- Delete ALL files in:
src/handlers/OldFiles/ - Reason: Deprecated duplicates with outdated imports
- Keep: Current implementations are more mature
sys_security_events- Should log all security eventssys_blocked_ips/sys_whitelisted_ips- IP firewall ready but unusedsys_blocked_geos/sys_whitelisted_geos- Geo restrictions ready but unused- Fix: Use
performIPSecurityCheck()from ipUtils.ts
- Tables:
sys_webhooks,sys_webhook_logsexist - Handler:
webhookHandler.tsfully implemented - Problem: Payment callbacks not using this infrastructure
- Fix: Route payment callbacks through webhookHandler
- Available: Full IP validation, CIDR checks, anonymization
- Functions:
getClientIP(),performIPSecurityCheck(),anonymizeIP() - Fix: Replace manual IP extraction with these utilities
- Available:
withCorrelationId(),measureAndLog(),logSecurityEvent() - Current: Basic logging without correlation IDs
- Fix: Wrap handlers with correlation ID tracking
- Problem:
adminHandler.tshas 1,337 lines mixing HTTP and business logic - Solution: Move ALL business logic to
businessLogic.ts - Pattern: Handlers should ONLY handle HTTP concerns
- Always use:
Databaseclass methods - Never: Direct SQL string construction
- Always: Parameterized queries through Database class
- Example:
// CORRECT await db.execute("INSERT INTO table (col) VALUES (?)", [value]); // WRONG await db.execute(`INSERT INTO table (col) VALUES ('${value}')`);
- Use:
PublicPayNonceService.createPublicPaymentNonce() - Use:
TurnstileService.validateToken() - Use:
PaymentFingerprintService.generatePaymentHash() - Use:
ValidationServicefor all complex validation - Use:
AuthService.validateApiKey()consistently
- Remove credential logging from
zenpayFingerprintService.ts - Fix all database operations to use Database class
- Add
logSecurityEvent()calls for all security operations
- Delete entire
src/handlers/OldFiles/directory - Remove
addCorsHeaders()from ALL handlers - Remove manual CSRF validation from handlers
- Remove crypto wrappers from AuthService
- Replace
newPayToken()withgeneratePayToken()from crypto utils
- Add IP security checks using
performIPSecurityCheck() - Log security events to
sys_security_eventstable - Route payment callbacks through webhookHandler
- Use correlation IDs for all request tracking
- createBooking() - Port lines 712-752, return
{ bookingId } - getBookingDetails() - Port lines 907-1089, return booking object
- generatePayToken() - Port lines 758-899, return
{ shareableUrl } - validatePayToken() - Port lines 604-684, return validation object
- verifyTurnstile() - Use existing from turnstileHandler.ts
- getRoutesV1() - Copy logic from
getRoutes() - getBookingById() - Use Database to query by ID
- getBookingByToken() - Port from
getBookingDetails()
- Replace manual IP extraction with
getClientIP() - Replace
crypto.randomUUID()withgenerateUUID() - Use
generateSecureToken()for all token generation - Use
getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS()for timestamps - Use
measureAndLog()for performance tracking
- Progressive security model (CSRF + Turnstile + Rate limiting) ✅
- Nonce-gated payment flow ✅
- Session seeding for tour endpoints (MISSING - needs middleware)
- Parameterized queries (PARTIAL - some handlers bypass)
- Business logic separation (POOR - needs migration)
- Security credentials must NEVER be logged
- Always use Database class, never direct SQL
- Middleware handles CORS/CSRF/Headers - don't duplicate
- Use existing utilities - don't reimplement
- Old files are deprecated - delete them
- Business logic belongs in businessLogic.ts, not handlers
- This is NOT just migration - it's fixing architectural violations
- Security issues must be fixed FIRST before any migration
- Use existing infrastructure instead of reimplementing
- The codebase has good architecture but poor implementation consistency
- CRITICAL: Fix credential logging immediately - this is a security vulnerability