This document outlines the definitive server architecture for ZenServer, a secure payment API backend built with Deno and TypeScript. The architecture is designed to prevent payment fingerprint harvesting while providing comprehensive debug visibility and advanced bot detection through two primary user journeys: a public "browse-and-pay" flow and an admin-driven "shareable link" flow.
The system is stateless from a user perspective, establishing a secure, transient context for each payment attempt rather than relying on traditional user accounts or long-lived sessions. It implements a multi-layered, defense-in-depth security model with 9+ numbered security checks, correlation ID tracking, and debug session management tailored for the Zenpay payment gateway and deployment on Val Town.
New Architecture Features:
- Debug Infrastructure: Comprehensive debug mode with correlation ID tracking
- Honeypot Detection: Advanced bot detection using emoji injection pattern
- Security Visibility: 9+ numbered security checks with success/failure tracking
- Performance Monitoring: Request duration and check timing analysis
- Memory Management: Automatic debug session cleanup
This diagram shows the final component structure with debug infrastructure, designed to handle both public and admin-initiated flows with comprehensive security visibility.
graph TB subgraph "Client & Admin Layer" Browser[Web Browser] AdminClient[Admin Client/Script] end subgraph "API Gateway & Debug Infrastructure" Gateway[API Gateway] DebugManager[Debug Session Manager] CorrelationTracker[Correlation ID Tracker] Middleware[Security Middleware Stack] Router[Request Router] end subgraph "Security & Debug Middleware" CORS[CORS Middleware + Check1-2] Security[Security Middleware + Check3-7] RateLimit[Rate Limit Middleware + Check8] DebugLogger[Debug Logger + Security Checks] end subgraph "Application Layer (Handlers)" TourHandler[Tour/Booking Handler] PaymentHandler[Payment Handler + Check9] WebhookHandler[Webhook Handler] AdminHandler[Admin Handler] end subgraph "Service Layer" NonceService[Nonce Service] PaymentService[Payment Service] TokenService[Pay-Token Service] TurnstileService[Turnstile Verification Service] HoneypotService[Honeypot Detection Service] end subgraph "Debug Infrastructure" DebugSession[Debug Session Storage] CheckTracker[Security Check Tracker] SessionLifecycle[Session Lifecycle Manager] MemoryCleanup[Memory Cleanup Service] end subgraph "Data & External Services" Database[(SQLite Database)] Env[Environment Config] Zenpay[Zenpay Gateway] LogFiles[Debug Log Files] end Browser --> Gateway AdminClient --> Gateway Gateway --> DebugManager DebugManager --> CorrelationTracker CorrelationTracker --> Middleware Middleware --> CORS CORS --> Security Security --> RateLimit RateLimit --> DebugLogger DebugLogger --> Router Router --> TourHandler Router --> PaymentHandler Router --> WebhookHandler Router --> AdminHandler PaymentHandler --> NonceService PaymentHandler --> PaymentService PaymentHandler --> TurnstileService PaymentHandler --> HoneypotService AdminHandler --> TokenService DebugManager --> DebugSession DebugSession --> CheckTracker CheckTracker --> SessionLifecycle SessionLifecycle --> MemoryCleanup NonceService --> Database TokenService --> Database PaymentService --> Env PaymentService --> Zenpay WebhookHandler --> Zenpay DebugLogger --> LogFiles
NEW: The debug infrastructure provides comprehensive visibility into security validation:
graph TD A[Request Arrives] --> B[Debug Session Initialization] B --> C[Generate Correlation ID] C --> D[Create Session Context] D --> E[Middleware Chain Processing] E --> F[Security Check 1: CORS Origin] F --> G[Security Check 2: CORS Validation] G --> H[Security Check 3: User Agent Scan] H --> I[Security Check 4: Referer Validation] I --> J[Security Check 5: Origin Validation] J --> K[Security Check 6: Header Content Scan] K --> L[Security Check 7: Request Size Validation] L --> M[Security Check 8: Rate Limit Validation] M --> N[Security Check 9: Honeypot Detection] N --> O[Handler Processing] O --> P[Response Generation] P --> Q[Debug Session Finalization] Q --> R[Print Security Summary] R --> S[Memory Cleanup] S --> T[Response Sent]
The single entry point for all API requests with comprehensive debug session management. Responsibilities include:
Request Processing:
- Route requests to appropriate handlers
- Apply global middleware stack
- NEW: Initialize debug sessions with correlation IDs
- NEW: Track request lifecycle from start to finish
Debug Integration:
// Debug session initialization
const correlationId = initializeDebugSession(c.req.raw);
c.set('debugCorrelationId', correlationId);
// Pass correlation ID to all middleware
const cors = corsMiddleware(c.req.raw, correlationId);
const sec = await securityMiddleware(c.req.raw, correlationId);
const rate = await rateLimitMiddleware(c.req.raw, correlationId);
// Finalize debug session after response
finalizeDebugSession(correlationId, c.req.raw, c.res);
NEW: Centralized debug session management with correlation tracking:
Key Functions:
initializeDebugSession(request): Creates correlation ID and session contextlogSecurityCheck(correlationId, checkName, result, success, metadata): Records security validationsfinalizeDebugSession(correlationId, request, response): Prints summary and cleanup
Session Storage:
const debugSessions = new Map<string, {
correlationId: string;
startTime: number;
request: { method, url, ip, userAgent };
}>();
const sessionChecks = new Map<string, SecurityCheck[]>();
Purpose: Links all security checks and operations for a single request
Features:
- Unique UUID generation per request
- Distributed across entire middleware chain
- Automatic memory cleanup after request completion
- Performance tracking and timing analysis
Security checks applied in order with comprehensive debug integration:
- Check1: CORS Origin Check - validates request origin
- Check2: CORS Validation Passed - ensures proper CORS headers
- Debug Integration: Logs origin validation success/failure
- Check3: User Agent Security Scan - detects suspicious user agent patterns
- Check4: Referer Validation - validates referer for sensitive endpoints
- Check5: Origin Validation - validates origin for sensitive endpoints
- Check6: Header Content Security Scan - scans headers for malicious content
- Check7: Request Size Validation - enforces 1MB request size limit
- Debug Integration: Each check logged with correlation ID and metadata
- Check8: Rate Limit Validation - IP-based token bucket algorithm
- Scenarios: No rate limit config, within limits, limits exceeded
- Debug Integration: Logs rate limiting decisions and remaining quota
- Endpoints:
/api/v1/tour/{id}&/api/v1/booking/{token} - Security Function: Seeds browser with SESSION and XSRF-TOKEN cookies
- Debug Integration: Tracks cookie seeding and session establishment
- Endpoints:
/api/v1/create-nonce,/api/v1/payment/exchange-nonce - NEW: Check9: Honeypot Bot Detection - validates emoji injection pattern
- Debug Integration: Logs honeypot detection results and fake nonce generation
- Endpoint:
/api/v1/payment/callback - Function: Receives server-to-server callbacks from Zenpay
- Authentication: Verifies ValidationCode for callback authenticity
- Endpoints:
/api/v1/admin/generate-pay-token,/api/v1/admin/* - Authentication: Requires API key for administrative access
- Function: Generates secure pay-tokens for shareable link flow
Manages payment nonce lifecycle with debug visibility:
- Generates cryptographically random nonces
- Enforces strict 60-second TTL
- Ensures single-use via atomic database updates
- Binds nonces to user IP addresses
- NEW: Debug logging for nonce generation and consumption
Advanced bot detection using emoji injection:
- Validates
email_verifyfield contains exact 🍯 emoji - Generates fake nonces for detected bots
- Detection Logic:
- Field missing → Suspicious (log warning)
- Wrong value → Bot detected (return fake nonce)
- Correct emoji → Human verified (proceed normally)
Cryptographic operations with debug tracking:
- Constructs fingerprint payload
- Injects server-side secrets (ZENPAY_USERNAME, ZENPAY_PASSWORD)
- Creates SHA3-512 hash for Zenpay integration
- NEW: Debug logging for fingerprint generation
Cloudflare bot detection with caching:
- Verifies Cloudflare Turnstile tokens
- 90-second response caching for performance
- NEW: Debug logging for Turnstile validation results
Enhanced schema supporting debug infrastructure:
-- Stores booking/tour information
CREATE TABLE tpdemo_app_bookings (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
currency TEXT NOT NULL,
status TEXT DEFAULT 'pending' NOT NULL
);
-- Stores tokens for "shareable link" flow (single-use, admin-generated)
CREATE TABLE tpdemo_app_pay_tokens (
token TEXT PRIMARY KEY,
booking_id TEXT NOT NULL,
issued_at TEXT NOT NULL,
expires_at TEXT NOT NULL, -- 14 days default
used INTEGER DEFAULT 0 NOT NULL,
FOREIGN KEY (booking_id) REFERENCES tpdemo_app_bookings(id)
);
-- Manages single-use payment nonces (60-second TTL)
-- CRITICAL: PRAGMA journal_mode = WAL; required for concurrency
CREATE TABLE tpdemo_app_payment_nonces (
nonce TEXT PRIMARY KEY,
booking_id TEXT NOT NULL,
ip_address TEXT NOT NULL,
issued_at TEXT NOT NULL,
expires_at TEXT NOT NULL, -- 60 seconds after issued_at
used INTEGER DEFAULT 0 NOT NULL
);
-- Performance indexes
CREATE INDEX idx_pay_tokens_expires ON tpdemo_app_pay_tokens(expires_at);
CREATE INDEX idx_payment_nonces_expires ON tpdemo_app_payment_nonces(expires_at);
CREATE INDEX idx_payment_nonces_ip ON tpdemo_app_payment_nonces(ip_address);
In-Memory Debug Session Storage:
- Session metadata and timing information
- Security check results and correlation tracking
- Automatic cleanup prevents memory leaks
- Performance metrics and request duration
All secrets managed through secure environment variables:
# Zenpay Integration ZENPAY_USERNAME="zenpay_username" ZENPAY_PASSWORD="zenpay_password" # Security Configuration TURNSTILE_SECRET_KEY="cloudflare_turnstile_secret" ADMIN_API_KEY="admin_api_key" # Debug Configuration (NEW) DEBUG_MODE=true # Enable debug output LOG_LEVEL=INFO # Logging level # Server Configuration PORT=5000 # Server port
sequenceDiagram participant U as User participant C as Browser participant S as Server participant D as Debug System Note over U,C: User browses site and clicks a tour C->>S: GET /api/v1/tour/123 S->>D: Initialize Debug Session D-->>S: Correlation ID: abc-123 S-->>C: HTML with tour details<br/>🔐 Sets SESSION & XSRF-TOKEN cookies S->>D: Finalize Debug Session Note over U,C: User clicks "Pay Now" C->>S: POST /api/v1/create-nonce<br/>Body: {tourId, cfToken, email_verify: "🍯"} S->>D: Initialize Debug Session D-->>S: Correlation ID: def-456 Note over S: 9 Security Checks Execute S->>D: Check1: ✅ CORS Origin Check S->>D: Check2: ✅ CORS Validation Passed S->>D: Check3: ✅ User Agent Security Scan S->>D: Check4: ✅ Referer Validation S->>D: Check5: ✅ Origin Validation S->>D: Check6: ✅ Header Content Security Scan S->>D: Check7: ✅ Request Size Validation S->>D: Check8: ✅ Rate Limit Validation S->>D: Check9: ✅ Honeypot Bot Detection S-->>C: {"nonce": "..."} S->>D: Print Security Summary & Cleanup C->>S: POST /api/v1/payment/exchange-nonce<br/>Header: X-Payment-Nonce S->>D: Initialize Debug Session S-->>C: {"fingerprint": "..."} S->>D: Finalize Debug Session Note over C: Client initializes Zenpay plugin
sequenceDiagram participant A as Admin participant S as Server participant C as Customer's Browser participant D as Debug System Note over A,S: Admin generates shareable link A->>S: POST /api/v1/admin/generate-pay-token<br/>Authorization: Bearer {api_key}<br/>Body: {"bookingId": "booking_456"} S-->>A: {"shareableUrl": "https://.../booking/a1b2c3d4..."} Note over A,C: Admin sends link to customer C->>S: GET /booking/a1b2c3d4... S->>D: Initialize Debug Session S-->>S: 🔐 Validate pay_token S-->>C: HTML with tour details<br/>🔐 Sets SESSION & XSRF-TOKEN cookies S->>D: Finalize Debug Session Note over C: Flow continues identical to Browse & Pay C->>S: POST /api/v1/create-nonce (with debug tracking) C->>S: POST /api/v1/payment/exchange-nonce (with debug tracking)
🔍 DEBUG SESSION STARTED
Correlation ID: 550e8400-e29b-41d4-a716-446655440000
POST /api/v1/create-nonce
IP: 192.168.1.1
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
───────────────────────────────────────
Check1: ✅ CORS Origin Check
└─ Origin: https://example.com
Check2: ✅ CORS Validation Passed
└─ All CORS headers valid
Check3: ✅ User Agent Security Scan
└─ Clean user agent detected
Check4: ✅ Referer Validation
└─ Valid referer for /api/v1/create-nonce
Check5: ✅ Origin Validation
└─ Valid origin for /api/v1/create-nonce
Check6: ✅ Header Content Security Scan
└─ Headers clean, 5 headers scanned
Check7: ✅ Request Size Validation
└─ Size: 1024 bytes, Limit: 1048576 bytes
Check8: ✅ Rate Limit Validation
└─ Within limits: 3/5 requests per minute
Check9: ✅ Honeypot Bot Detection
└─ Human user verified - honeypot valid
───────────────────────────────────────
🔒 SECURITY CHECKS SUMMARY
Total checks: 9
Passed: 9 | Failed: 0
Response: 200
Duration: 45ms
🔍 DEBUG SESSION ENDED
🔍 DEBUG SESSION STARTED
Correlation ID: 550e8400-e29b-41d4-a716-446655440001
POST /api/v1/create-nonce
IP: 192.168.1.100
User Agent: bot-scanner-v1.0
───────────────────────────────────────
Check1: ✅ CORS Origin Check
Check2: ✅ CORS Validation Passed
Check3: ❌ User Agent Security Scan
└─ Suspicious pattern detected: bot-scanner
Check4: ✅ Referer Validation
Check5: ✅ Origin Validation
Check6: ✅ Header Content Security Scan
Check7: ✅ Request Size Validation
Check8: ✅ Rate Limit Validation
Check9: ❌ Honeypot Bot Detection
└─ Bot detected via invalid honeypot value
───────────────────────────────────────
🔒 SECURITY CHECKS SUMMARY
Total checks: 9
Passed: 7 | Failed: 2
Response: 200 (Fake Nonce)
Duration: 32ms
🔍 DEBUG SESSION ENDED
- Memory Management: Automatic cleanup prevents debug session memory leaks
- Conditional Execution: Debug code only runs when
DEBUG_MODE=true - Correlation ID Efficiency: UUID generation optimized for high throughput
- Log File Management: Automatic cleanup on server restart
- WAL Mode: Enables concurrent reads/writes for nonce table
- Proper Indexing: Optimized queries for token and nonce operations
- Atomic Operations: Single UPDATE queries prevent race conditions
- Pattern Reuse: Security patterns compiled once, reused across requests
- Caching: Turnstile responses cached for 90 seconds
- Efficient Validation: Minimal computational overhead for security checks
Single HTTP Val Configuration:
- Main entry point:
default app.fetchexport - Environment variable configuration
- SQLite database with WAL mode
- Debug log management
Enhanced Development Experience:
- Debug mode enabled by default
- Comprehensive security check visibility
- Real-time correlation ID tracking
- Performance monitoring and timing
This enhanced server architecture provides a robust, multi-layered defense against payment fingerprint harvesting with comprehensive debug visibility and advanced bot detection. The debug infrastructure offers unprecedented insight into security validation processes, making it easier to:
- Monitor Security: Track all 9+ security checks in real-time
- Debug Issues: Correlation IDs link all operations for single requests
- Optimize Performance: Detailed timing and performance metrics
- Detect Threats: Advanced honeypot detection and comprehensive logging
By integrating debug capabilities directly into the security architecture, the system maintains enterprise-grade security while providing the visibility needed for effective monitoring, troubleshooting, and optimization.
Built with security-first design principles, comprehensive debug visibility, and advanced threat detection for enterprise payment processing.