• Blog
  • Docs
  • Pricing
  • We’re hiring!
Log inSign up
ianmenethil

ianmenethil

ZenServer

Unlisted
Like
ZenServer
Home
Code
20
.claude
.client
.cursor
.git
.vscode
.vt
scripts
5
src
10
tasks
.gitignore
.vtignore
AGENTS.md
CLAUDE.md
PLAN.md
PROJECT_MAPPING.MD
ZenApp.md
deno.json
env.example
H
main.ts
map.md
Branches
1
Pull requests
Remixes
History
Environment variables
22
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.
Sign up now
Code
/
PLAN.md
Code
/
PLAN.md
Search
7/12/2025
Viewing readonly version of main branch: v664
View latest version
PLAN.md

Plan to Complete Migration to Automatic Validation Style

Current Situation Analysis

Based on careful review of map.md and PROJECT_MAPPING.md:

What's Already Working ✅

  • 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

The Real Problem

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

Required Steps

Step 1: Complete Missing Functions in businessLogic.ts

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

Step 2: Add Missing OpenAPI Functions

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}

Step 3: Enhance Existing Basic Implementations

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

Step 4: Remove Duplicate Files

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

Step 5: Verify Integration

  • 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

Step 6: End-to-End Testing

  • Test complete payment flow (nonce → exchange → callback)
  • Test booking creation and retrieval
  • Test admin token generation
  • Verify all security features work as expected

Key Principles for Migration

  1. Don't rewrite working code - adapt existing implementations
  2. Convert Response objects to plain objects when porting
  3. Remove manual validation (OpenAPI handles it)
  4. Preserve all security features from original implementations
  5. Keep the same business logic but change the return format
  6. USE EXISTING UTILITIES - We have comprehensive utility functions that should be used

Utility Functions to Leverage

From src/utils/crypto.ts:

  • 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

From src/utils/cookies.ts:

  • setCSRFCookies() - Already used in adminHandler.ts
  • validateTokenBasedCSRFToken() - For CSRF validation
  • NOTE: These might not be needed in businessLogic.ts if middleware handles it

From src/utils/ipUtils.ts:

  • getClientIP() - Extract IP from request/context (currently done manually)
  • performIPSecurityCheck() - For IP-based access control
  • anonymizeIP() - For privacy-compliant logging

From src/utils/logger.ts:

  • logInfo(), logError(), logWarn() - Already used throughout
  • withCorrelationId() - For request tracing
  • measureAndLog() - For performance monitoring
  • logSecurityEvent() - For security-sensitive operations

From src/utils/dateUtils.ts:

  • getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS() - For consistent timestamps

From Services:

  • 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

Major Issues Found by Cross-Referencing PROJECT_MAPPING.md

1. UNUSED SERVICE: publicPayNonceService.ts

  • Problem: Both handlers manually implement nonce creation
  • Solution: Use PublicPayNonceService.createPublicPaymentNonce() instead

2. MIDDLEWARE ALREADY HANDLES THINGS WE'RE DUPLICATING:

  • CORS: corsMiddleware() handles this - remove manual addCorsHeaders() calls
  • CSRF: getOriginBasedCSRFMiddleware() provides protection - check if manual CSRF needed
  • Security Headers: secureHeaders.ts adds these automatically
  • Rate Limiting: Already handled by rateLimitMiddleware()

3. DATABASE SCHEMA NOT BEING USED:

  • Security Tables: sys_security_events, sys_blocked_ips, sys_whitelisted_ips defined but unused
  • Webhook Tables: sys_webhooks, sys_webhook_logs exist but not integrated with payment flow
  • Rate Limit Table: sys_rate_limits may not be connected to middleware

4. COMPLETE HANDLERS BEING IGNORED:

  • 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

5. IP SECURITY COMPLETELY UNUSED:

  • Available: performIPSecurityCheck(), IP firewall tables, geographic restrictions
  • Problem: No IP-based security happening despite full implementation

6. LOGGING UNDERUTILIZED:

  • Available: withCorrelationId(), measureAndLog(), logSecurityEvent()
  • Problem: Basic logging instead of structured, traceable logging

CRITICAL SECURITY ISSUES TO FIX FIRST

1. CREDENTIAL LOGGING (HIGH PRIORITY - SECURITY RISK)

  • File: src/services/zenpayFingerprintService.ts lines 47-55
  • Problem: Logging username and password in plaintext
  • Fix: Remove ALL credential logging immediately

2. DATABASE CLASS BYPASS (HIGH PRIORITY)

  • Files: src/handlers/adminHandler.ts lines 388-398, 572-578
  • Problem: Bypassing Database class error handling
  • Fix: ALL database operations MUST use db.execute() or db.query()
  • Never: Construct SQL strings manually

DUPLICATIONS TO REMOVE

1. Crypto Function Duplications

  • Remove: AuthService wrapper functions (lines 33-35, 146-148)
  • Use: Direct imports from src/utils/crypto.ts
  • Specific: newPayToken() duplicated in adminHandler.ts lines 86-93

2. Service/Utils Duplications

  • PublicPayNonceService: Has createPublicPaymentNonce() but handlers implement manually
  • AuthService: Re-wraps crypto functions unnecessarily
  • Fix: Use services directly, remove manual implementations

3. Middleware vs Handler Duplications

  • 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

4. Old Files to DELETE

  • Delete ALL files in: src/handlers/OldFiles/
  • Reason: Deprecated duplicates with outdated imports
  • Keep: Current implementations are more mature

UNUSED INFRASTRUCTURE TO CONNECT

1. Security Tables (NOT USED AT ALL)

  • sys_security_events - Should log all security events
  • sys_blocked_ips / sys_whitelisted_ips - IP firewall ready but unused
  • sys_blocked_geos / sys_whitelisted_geos - Geo restrictions ready but unused
  • Fix: Use performIPSecurityCheck() from ipUtils.ts

2. Webhook Infrastructure (BUILT BUT NOT CONNECTED)

  • Tables: sys_webhooks, sys_webhook_logs exist
  • Handler: webhookHandler.ts fully implemented
  • Problem: Payment callbacks not using this infrastructure
  • Fix: Route payment callbacks through webhookHandler

3. IP Security System (COMPLETELY UNUSED)

  • Available: Full IP validation, CIDR checks, anonymization
  • Functions: getClientIP(), performIPSecurityCheck(), anonymizeIP()
  • Fix: Replace manual IP extraction with these utilities

4. Advanced Logging (UNDERUTILIZED)

  • Available: withCorrelationId(), measureAndLog(), logSecurityEvent()
  • Current: Basic logging without correlation IDs
  • Fix: Wrap handlers with correlation ID tracking

ARCHITECTURAL FIXES REQUIRED

1. Business Logic Separation

  • Problem: adminHandler.ts has 1,337 lines mixing HTTP and business logic
  • Solution: Move ALL business logic to businessLogic.ts
  • Pattern: Handlers should ONLY handle HTTP concerns

2. Database Usage Pattern

  • Always use: Database class 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}')`);

3. Service Layer Usage

  • Use: PublicPayNonceService.createPublicPaymentNonce()
  • Use: TurnstileService.validateToken()
  • Use: PaymentFingerprintService.generatePaymentHash()
  • Use: ValidationService for all complex validation
  • Use: AuthService.validateApiKey() consistently

SPECIFIC MIGRATION STEPS WITH DETAILS

Step 1: Security Fixes (DO FIRST)

  • Remove credential logging from zenpayFingerprintService.ts
  • Fix all database operations to use Database class
  • Add logSecurityEvent() calls for all security operations

Step 2: Remove Duplications

  • Delete entire src/handlers/OldFiles/ directory
  • Remove addCorsHeaders() from ALL handlers
  • Remove manual CSRF validation from handlers
  • Remove crypto wrappers from AuthService
  • Replace newPayToken() with generatePayToken() from crypto utils

Step 3: Connect Unused Infrastructure

  • Add IP security checks using performIPSecurityCheck()
  • Log security events to sys_security_events table
  • Route payment callbacks through webhookHandler
  • Use correlation IDs for all request tracking

Step 4: Migrate Business Logic (FROM adminHandler.ts TO businessLogic.ts)

  • 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

Step 5: Add Missing OpenAPI Functions

  • getRoutesV1() - Copy logic from getRoutes()
  • getBookingById() - Use Database to query by ID
  • getBookingByToken() - Port from getBookingDetails()

Step 6: Use ALL Utilities Properly

  • Replace manual IP extraction with getClientIP()
  • Replace crypto.randomUUID() with generateUUID()
  • Use generateSecureToken() for all token generation
  • Use getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS() for timestamps
  • Use measureAndLog() for performance tracking

ZenApp.md ALIGNMENT CHECKLIST

  • 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)

DO NOT FORGET

  1. Security credentials must NEVER be logged
  2. Always use Database class, never direct SQL
  3. Middleware handles CORS/CSRF/Headers - don't duplicate
  4. Use existing utilities - don't reimplement
  5. Old files are deprecated - delete them
  6. Business logic belongs in businessLogic.ts, not handlers

Notes

  • 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
FeaturesVersion controlCode intelligenceCLIMCP
Use cases
TeamsAI agentsSlackGTM
DocsShowcaseTemplatesNewestTrendingAPI examplesNPM packages
PricingNewsletterBlogAboutCareers
We’re hiring!
Brandhi@val.townStatus
X (Twitter)
Discord community
GitHub discussions
YouTube channel
Bluesky
Open Source Pledge
Terms of usePrivacy policyAbuse contact
© 2026 Val Town, Inc.