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

ianmenethil

ZenServer

Unlisted
Like
ZenServer
Home
Code
19
.claude
.client
.cursor
.git
.vscode
.vt
scripts
5
src
10
tasks
tests
.gitignore
.vtignore
CLAUDE.md
README.md
Z1-Server.md
ZenApp.md
deno.json
env.example
H
main.ts
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
/
README.md
Code
/
README.md
Search
7/9/2025
Viewing readonly version of main branch: v589
View latest version
README.md

ZenServer

A secure payment processing API with tour booking functionality, built on Hono framework with OpenAPI-driven development and deployed on Val Town.

Features

  • OpenAPI-First Development: Dynamic route generation and validation from OpenAPI specification
  • Two-Step Nonce Security: Advanced payment security with time-limited nonces and bot protection
  • Comprehensive Security: CSRF protection, rate limiting, Turnstile bot detection, and secure headers
  • Tour Management: Complete tour listing, booking, and payment processing
  • Admin Dashboard: Secure admin endpoints with token-based authentication
  • Real-time Validation: Automatic request/response validation via Zod schemas
  • Val Town Optimized: Designed for serverless deployment on Val Town platform

Quick Start

Prerequisites

  • Val Town Account: Required for deployment
  • Cloudflare Turnstile: For bot protection (free tier available)
  • ZenPay Account: For payment processing integration

Environment Variables

Create a .env file with the following variables:

# Environment APP_ENV=dev # 'dev' or 'prod' LOG_LEVEL=info # 'debug', 'info', 'warn', 'error' # OpenAPI Configuration OPENAPI_LOCAL_PATH=./openapi.json # Local OpenAPI spec path OPENAPI_BLOB_KEY=openapi-spec # Val Town blob storage key OPENAPI_PUBLIC_URL=https://... # Public URL for OpenAPI spec # Authentication ZP_USERNAME=admin # Basic auth username ZP_PASSWORD=secure-password # Basic auth password MASTER_KEY=your-master-api-key # Bearer token for API access # Security TURNSTILE_SECRET_KEY=your-secret-key # Cloudflare Turnstile secret CORS_ORIGINS=https://yourdomain.com # Allowed CORS origins # Payment Integration ZENPAY_API_KEY=your-zenpay-key # ZenPay API key ZENPAY_WEBHOOK_SECRET=webhook-secret # ZenPay webhook secret

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/ZenServer.git cd ZenServer
  2. Configure environment:

    cp src/.env.example src/.env # Edit src/.env with your configuration
  3. Deploy to Val Town:

    • Upload the project to your Val Town val
    • Set environment variables in Val Town dashboard
    • The main entry point is src/main.ts

Local Development

For local development outside Val Town:

# Install Deno curl -fsSL https://deno.land/install.sh | sh # Run the server deno run --allow-all src/main.ts

API Usage

Authentication

API Key Authentication

curl -H "Authorization: Bearer YOUR_API_KEY" \ https://your-val-town-url.web.val.run/api/v1/admin/generate-pay-token

Basic Authentication (Admin)

curl -u admin:password \ https://your-val-town-url.web.val.run/api/v1/admin/generate-pay-token

Payment Flow

Step 1: Create Nonce

curl -X POST https://your-val-town-url.web.val.run/api/v1/create-nonce \ -H "Content-Type: application/json" \ -H "X-XSRF-TOKEN: your-csrf-token" \ -d '{ "tourId": "tour-paris-explorer", "cfToken": "turnstile-token-here", "email_verify": "🍯" }'

Step 2: Exchange Nonce for Fingerprint

curl -X POST https://your-val-town-url.web.val.run/api/v1/payment/exchange-nonce \ -H "Content-Type: application/json" \ -H "X-Payment-Nonce: nonce-from-step-1" \ -d '{ "apiKey": "your-api-key", "mode": "production", "paymentAmount": 299.99, "merchantUniquePaymentId": "booking-123", "timestamp": "2024-01-01T12:00:00Z" }'

Tour Management

List Tours

curl https://your-val-town-url.web.val.run/api/v1/tours

Get Tour Details

curl https://your-val-town-url.web.val.run/api/v1/tours/tour-paris-explorer

Create Booking

curl -X POST https://your-val-town-url.web.val.run/api/v1/create-booking \ -H "Content-Type: application/json" \ -d '{"tourId": "tour-paris-explorer"}'

Architecture

Core Components

  • API Gateway (src/gateway/apiGateway.ts): Main application orchestrator
  • OpenAPI Loader (src/utils/openApiLoader.ts): Dynamic route generation
  • Handlers (src/handlers/): Business logic for endpoints
  • Middleware (src/middleware/): Security, CORS, rate limiting
  • Services (src/services/): Authentication, validation, payment processing
  • Database (src/database/): SQLite integration with Val Town

Security Features

  1. Two-Step Nonce Gating: Prevents replay attacks and ensures human interaction
  2. CSRF Protection: Origin validation + token verification
  3. Rate Limiting: Configurable per-endpoint limits
  4. Bot Protection: Cloudflare Turnstile integration
  5. Secure Headers: Comprehensive security header middleware
  6. Input Validation: Automatic request/response validation

Database Schema

The application uses SQLite with the following main tables:

  • app_tp_booking_orders: Tour booking information
  • sys_pay_tokens: Shareable payment tokens
  • sys_nonces: Security nonces for payment flow
  • sys_infra_hook_backs: Webhook callback logs

Development

Project Structure

src/
├── config/          # Environment configuration
├── data/           # Static data (tours, etc.)
├── database/       # Database schemas and services
├── gateway/        # Main application gateway
├── handlers/       # Route handlers
├── middleware/     # Security middleware
├── services/       # Business logic services
├── types/          # TypeScript type definitions
├── utils/          # Utility functions
└── main.ts         # Application entry point

Adding New Endpoints

  1. Update OpenAPI Spec (openapi.json):

    { "paths": { "/api/v1/your-endpoint": { "post": { "operationId": "yourEndpoint", "summary": "Your endpoint description", "requestBody": { ... }, "responses": { ... } } } } }
  2. Create Handler (src/handlers/yourHandler.ts):

    export async function yourEndpoint(request: Request, db: Database): Promise<Response> { // Your implementation return new Response(JSON.stringify({ success: true }), { status: 200, headers: { "Content-Type": "application/json" } }); }
  3. Register Handler (src/gateway/apiGateway.ts):

    const handlerMap = { // ... existing handlers yourEndpoint: yourHandler.yourEndpoint, };

Testing

Manual Testing

# Test health endpoint curl https://your-val-town-url.web.val.run/api/v1/health # Test documentation curl https://your-val-town-url.web.val.run/api/v1/docs # Test OpenAPI spec curl https://your-val-town-url.web.val.run/api/v1/openapi.json

Integration Testing

Use the Turnstile test page for bot protection testing:

curl https://your-val-town-url.web.val.run/api/v1/turnstile/test

Debugging

Enable debug logging by setting:

LOG_LEVEL=debug

Debug correlation IDs are added to all requests for tracing. Check logs for:

  • correlationId: Unique request identifier
  • endpoint: API endpoint being called
  • method: HTTP method
  • security: Security validation results

Deployment

Val Town Deployment

  1. Upload Project: Copy all files to your Val Town val
  2. Set Environment Variables: Configure in Val Town dashboard
  3. Update OpenAPI Spec: Upload openapi.json to Val Town blob storage
  4. Configure Domains: Set up custom domain if needed

Production Checklist

  • All environment variables configured
  • OpenAPI spec uploaded to blob storage
  • CORS origins configured for production domains
  • Turnstile keys configured for production
  • Rate limits configured appropriately
  • Database tables created
  • Webhook endpoints configured in ZenPay
  • SSL certificates configured
  • Monitoring and logging configured

Security Best Practices

API Security

  • Always use HTTPS in production
  • Store API keys securely
  • Implement proper error handling
  • Validate all inputs
  • Use rate limiting appropriately

Payment Security

  • Never store sensitive payment data
  • Use secure nonces for all payments
  • Implement proper callback validation
  • Log all payment attempts
  • Monitor for suspicious activity

Database Security

  • Use parameterized queries
  • Implement proper access controls
  • Regular security audits
  • Backup strategies
  • Monitor database access

Troubleshooting

Common Issues

OpenAPI Spec Not Loading

# Check blob storage curl https://your-val-town-url.web.val.run/api/v1/openapi.json # Check local file ls -la openapi.json

CORS Issues

# Check CORS configuration curl -H "Origin: https://yourdomain.com" \ -H "Access-Control-Request-Method: POST" \ -H "Access-Control-Request-Headers: Content-Type" \ -X OPTIONS https://your-val-town-url.web.val.run/api/v1/tours

Rate Limiting

# Check rate limit headers curl -I https://your-val-town-url.web.val.run/api/v1/tours

Database Connection

# Check database connectivity curl https://your-val-town-url.web.val.run/api/v1/health

Error Codes

  • 400: Bad Request - Invalid input data
  • 401: Unauthorized - Authentication required
  • 403: Forbidden - Bot detected or access denied
  • 404: Not Found - Resource not found
  • 429: Too Many Requests - Rate limit exceeded
  • 500: Internal Server Error - Server error

Contributing

Development Workflow

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/amazing-feature
  3. Make changes: Follow coding standards
  4. Test thoroughly: Ensure all tests pass
  5. Submit pull request: Include description and tests

Code Standards

  • Use TypeScript for all new code
  • Follow ESLint configuration
  • Add JSDoc comments for functions
  • Include error handling
  • Write comprehensive tests
  • Update documentation

Security Guidelines

  • Never commit secrets or API keys
  • Use environment variables for configuration
  • Validate all inputs
  • Follow secure coding practices
  • Regular security reviews

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Documentation

  • Architecture Overview
  • API Documentation
  • Development Guide
  • Implementation Plan

Community

  • Issues: Report bugs and request features
  • Discussions: Ask questions and share ideas
  • Wiki: Community-maintained documentation

Commercial Support

For enterprise support, custom integrations, or consulting services, please contact the development team.


Built with ❤️ for secure payment processing on Val Town

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.