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

ianmenethil

ZenServer

Unlisted
Like
ZenServer
Home
Code
11
.cursor
docs
9
src
10
tasks
tests
.gitignore
.vtignore
README.md
deno.json
H
main.ts
main.tsx
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
/
docs
/
ARCHITECTURE-SERVER.md
Code
/
docs
/
ARCHITECTURE-SERVER.md
Search
7/7/2025
Viewing readonly version of main branch: v318
View latest version
ARCHITECTURE-SERVER.md

ZenServer - Server Architecture v3.5

1. Overview

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

2. System Architecture

2.1. High-Level Component Diagram

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

2.2. Debug Architecture Components

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]

3. Core Components

3.1. API Gateway (src/gateway/apiGateway.ts)

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

3.2. Debug Infrastructure Components

3.2.1. Debug Session Manager (src/middleware/debugger.ts)

NEW: Centralized debug session management with correlation tracking:

Key Functions:

  • initializeDebugSession(request): Creates correlation ID and session context
  • logSecurityCheck(correlationId, checkName, result, success, metadata): Records security validations
  • finalizeDebugSession(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[]>();

3.2.2. Correlation ID Tracker

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

3.3. Enhanced Middleware Stack

Security checks applied in order with comprehensive debug integration:

3.3.1. CORS Middleware (Check1-2)

  • Check1: CORS Origin Check - validates request origin
  • Check2: CORS Validation Passed - ensures proper CORS headers
  • Debug Integration: Logs origin validation success/failure

3.3.2. Security Middleware (Check3-7)

  • 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

3.3.3. Rate Limiting Middleware (Check8)

  • 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

3.4. Request Handlers with Debug Integration

3.4.1. Tour/Booking Handler

  • 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

3.4.2. Payment Handler (Check9)

  • 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

3.4.3. Webhook Handler

  • Endpoint: /api/v1/payment/callback
  • Function: Receives server-to-server callbacks from Zenpay
  • Authentication: Verifies ValidationCode for callback authenticity

3.4.4. Admin Handler

  • 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

3.5. Enhanced Core Services

3.5.1. Nonce Service

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

3.5.2. Honeypot Detection Service (NEW)

Advanced bot detection using emoji injection:

  • Validates email_verify field 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)

3.5.3. Payment Service

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

3.5.4. Turnstile Service

Cloudflare bot detection with caching:

  • Verifies Cloudflare Turnstile tokens
  • 90-second response caching for performance
  • NEW: Debug logging for Turnstile validation results

4. Data Layer

4.1. Database Schema

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

4.2. Debug Storage

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

4.3. Environment Configuration

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

5. Request Flow Diagrams

5.1. Enhanced Flow 1: Public "Browse & Pay" Journey with Debug

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

5.2. Flow 2: Admin-Generated "Shareable Link" Journey

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)

6. Debug Output Examples

6.1. Successful Request Debug Output

πŸ” 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

6.2. Bot Detection Debug Output

πŸ” 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

7. Performance Considerations

7.1. Debug Infrastructure Performance

  • 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

7.2. Database Performance

  • 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

7.3. Security Check Optimization

  • Pattern Reuse: Security patterns compiled once, reused across requests
  • Caching: Turnstile responses cached for 90 seconds
  • Efficient Validation: Minimal computational overhead for security checks

8. Deployment Architecture

8.1. Val Town Deployment

Single HTTP Val Configuration:

  • Main entry point: default app.fetch export
  • Environment variable configuration
  • SQLite database with WAL mode
  • Debug log management

8.2. Local Development

Enhanced Development Experience:

  • Debug mode enabled by default
  • Comprehensive security check visibility
  • Real-time correlation ID tracking
  • Performance monitoring and timing

9. Conclusion

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.

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.