• 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
/
map.md
Code
/
map.md
Search
7/12/2025
Viewing readonly version of main branch: v664
View latest version
map.md

ZenServer Project Map

This document provides a concise and complete map of all files, classes, and functions within the ZenServer project.

📂 Root Directory

📄 main.ts

The main entry point for the application. It initializes the environment, database, and logging, and starts the API gateway.

📄 openapi.json

The OpenAPI 3.0 specification that defines the entire API contract, including all endpoints, request/response schemas, and security requirements. It is the single source of truth for the API structure.


📂 src/config

📄 environment.ts

Loads and consolidates all application configuration from environment variables and the securityConfig.ts file.

  • environment: A single, exported object containing all configuration variables for the application.
  • validateProductionSecrets(): Re-exported from securityConfig to be called at startup.

📄 securityConfig.ts

Defines and loads all security-sensitive configuration from environment variables.

  • ADMIN_IPS: A list of trusted IP addresses for admin access.
  • ALLOWED_ORIGINS: A list of domains allowed for CORS.
  • ALLOWED_HEADERS: A list of HTTP headers allowed for CORS.
  • COOKIE_*: A comprehensive set of constants for configuring secure cookie behavior (e.g., COOKIE_SESSION_MAX_AGE, COOKIE_SAME_SITE).
  • RATE_LIMIT_*: Per-endpoint rate limiting settings (requests per window).
  • ZP_USERNAME, ZP_PASSWORD, TURNSTILE_SECRET_KEY, etc.: Variables holding all application secrets.
  • validateProductionSecrets(): A crucial function that throws an error if required secrets are missing in a production environment.

📂 src/data

📄 tours.ts

Acts as a static, in-memory database for the application's tour data.

  • Tour (interface): Defines the detailed data structure for a single tour.
  • TOURS (constant): An array of Tour objects containing rich, realistic data for several tours.

📂 src/database

📄 database.ts

The primary database service layer (repository pattern) that abstracts all interaction with the Val Town SQLite database.

  • Database (class):
    • initialize(): Creates all tables from the schema files and inserts sample data.
    • query(): Executes a SELECT query and returns an array of objects.
    • execute(): Runs INSERT, UPDATE, or DELETE statements.
    • storeNonce(), getNonce(), validateAndUseNonce(): A suite of methods for securely managing the lifecycle of payment nonces.
    • getFingerprintStatus(): Checks payment attempt counts for a booking.

📄 schema.ts

Aggregates all schema definition files into a single export.

  • SCHEMA_SQL: A template string combining all CREATE TABLE statements from the other schema files.
  • SAMPLE_BOOKINGS_SQL: INSERT statements to seed the database with sample tour booking data for development.

📄 appTPCoreSchema.ts

Contains the SQL schema for the application's core business logic.

  • APP_TP_CORE_SCHEMA: A template string with CREATE TABLE statements for app_payment_nonces, app_tp_booking_orders, and app_pay_tokens.

📄 sysHookBacksSchema.ts

Contains the SQL schema for managing and logging webhooks.

  • SYS_WEBHOOKS_SCHEMA: A template string with CREATE TABLE statements for sys_webhooks (configuration) and sys_webhook_logs (audit trail).

📄 sysInfraSchema.ts

Contains the SQL schema for system-level security and infrastructure monitoring.

  • SYS_INFRA_SCHEMA: A template string with CREATE TABLE statements for sys_rate_limits, sys_security_events, sys_blocked_ips, and sys_whitelisted_ips.

📂 src/gateway

📄 apiGateway.ts

The main Hono application file. It sets up the middleware pipeline and orchestrates dynamic route registration.

  • app: The OpenAPIHono application instance.
  • Middleware Pipeline: A series of app.use() calls that register middleware in a specific order for logging, security (CORS, CSRF, Rate Limiting), and database context attachment.
  • Dynamic Route Loading: Contains the logic to use createOpenAPILoader to parse the openapi.json spec, automatically create a handler map with createDynamicHandlerMap, and register all routes.
  • Fallback Handler: Registers a fallback route to handle critical server startup errors (e.g., if openapi.json cannot be loaded).

📂 src/handlers

📄 adminHandler.ts

A complete implementation of the admin, payment, and booking logic. (Note: This is a duplicate of older logic).

  • createNonce(): Generates and stores a payment nonce.
  • exchangeNonce(): Validates a nonce and returns a payment fingerprint.
  • handlePaymentCallback(): Processes a webhook from the payment gateway.
  • createBooking(): Creates a new booking record.
  • getBookingDetails(): Retrieves booking information.
  • generatePayToken(): Creates a one-time payment link token.

📄 businessLogic.ts

The target for the dynamic handler system. It maps operationIds from the OpenAPI spec to functions.

  • listTours(), getTourDetails(), createNonce(), etc.: Implementations for the API's business logic. Many functions in the current version are placeholders that throw a "not yet implemented" error.

📄 docsHandler.ts

A class-based handler responsible for serving all user-facing API documentation.

  • DocsHandler (class):
    • serveSwaggerDocs(): Serves a modern Swagger UI.
    • serveRedocDocs(): Serves a three-panel ReDoc documentation page.
    • serveFiberplanePlayground(): Serves a custom, interactive API playground.

📄 dynamicHandler.ts

The core of the dynamic routing system.

  • extractOperationIds(): Scans the OpenAPI spec and returns a list of all operationIds.
  • createDynamicHandlerMap(): Creates a map where each operationId is a key and its value is a generic handler function that delegates to the corresponding function in businessLogic.ts.

📄 errorHandler.ts

Provides the global error handling middleware for the application.

  • globalErrorHandler(): A function that catches all unhandled errors, logs them, and returns a standardized 500 JSON response.

📄 fallbackHandler.ts

Provides a "safe mode" for the server if it fails to start correctly.

  • registerFallbackHandler(): Registers a catch-all route that is activated if the OpenAPI spec fails to load. It serves a helpful HTML error page explaining the problem.

📄 tourHandler.ts

Implements the logic for tour-related API endpoints.

  • getTourDetails(): Fetches and returns data for a specific tour.
  • listTours(): Fetches and returns a list of all available tours, with support for pagination.

📄 turnstileHandler.ts

Handles all interactions with Cloudflare Turnstile for bot protection.

  • TurnstileHandler (class):
    • serveTurnstileTestPage(): Serves a self-contained HTML page for testing the Turnstile integration.
    • verifyTurnstile(): The backend endpoint that takes a Turnstile token from a client and verifies it with Cloudflare's API.

📄 webhookHandler.ts

Provides handlers for receiving incoming webhooks and callbacks.

  • WebhookHandler (class):
    • handleWebhook(): A generic endpoint for receiving webhooks, validating them, and logging them to the database and blob storage for auditing.
    • handleCallback(): A generic endpoint for handling callbacks from services like OAuth or payment gateways, with CSRF protection.

📂 src/middleware

📄 basicAuth.ts

  • createBasicAuthMiddleware(): Creates Hono middleware for HTTP Basic Authentication using credentials from the environment.

📄 bearerAuth.ts

  • createBearerAuthMiddleware(): Creates Hono middleware for Bearer Token authentication using a static API key from the environment.

📄 cors.ts

  • corsMiddleware(): Handles CORS preflight (OPTIONS) requests and validates the Origin header on all incoming requests.

📄 csp.ts

  • getCSPHeader(): Builds the Content-Security-Policy header string based on the environment (dev vs. prod).
  • cspMiddleware(): A Hono middleware that applies the CSP header to responses.

📄 csrf.ts

  • getOriginBasedCSRFMiddleware(): The main export, which provides origin-based CSRF protection using Hono's built-in library.
  • createTokenBasedCSRFSession(), validateTokenBasedCSRFToken(): Functions for managing token-based CSRF protection (double-submit cookies) for more sensitive actions.

📄 debugger.ts

  • createDebugMiddleware(): A Hono middleware that captures detailed information about requests and responses for debugging purposes in a development environment.
  • initializeDebugSession(), finalizeDebugSession(): Functions to trace a logical flow across multiple requests.
  • logSecurityCheck(): A helper to log the success or failure of individual security checks within a request's lifecycle.

📄 ipRestriction.ts

  • ipRestrictionMiddleware(): A Hono middleware that provides IP-based access control, checking requests against configurable allow/deny lists.
  • adminIPRestrictionMiddleware(): A pre-configured version that restricts access to the admin IPs defined in the environment.

📄 rateLimit.ts

  • rateLimitMiddleware(): A middleware that provides per-endpoint rate limiting based on the client's IP address, using an in-memory cache.

📄 requestLogger.ts

  • requestIdMiddleware: Assigns a unique X-Request-Id to every incoming request.
  • requestLoggerMiddleware: Logs the details of every request and its corresponding response, including the request ID, status, and duration.

📄 secureHeaders.ts

  • createSecureHeadersMiddleware(): A Hono middleware that applies a suite of important security-related HTTP headers (like HSTS, X-Frame-Options, etc.) to every response.

📄 security.ts

  • securityMiddleware(): A middleware that performs a series of basic, heuristic security checks on every request, such as scanning for suspicious User-Agent strings and validating the request body size.

📂 src/services

📄 authService.ts

  • AuthService (class): Provides static methods for handling various authentication and authorization tasks, such as validating API keys and different types of tokens.

📄 publicPayNonceService.ts

  • PublicPayNonceService (class): A service dedicated to managing the lifecycle of public payment nonces, including creation, validation, and status checking.

📄 turnstileService.ts

  • TurnstileService (class): A service that abstracts the interaction with the Cloudflare Turnstile API for verifying tokens.

📄 validationService.ts

  • ValidationService (class): A central place for complex, reusable validation logic, such as validating the format of a Turnstile token.

📄 zenpayFingerprintService.ts

  • PaymentFingerprintService (class): A service responsible for generating the unique payment "fingerprint" required by the Zenpay payment gateway.

📂 src/types

📄 index.ts

Defines and exports the core TypeScript types and interfaces used throughout the application, such as AppContext, Booking, and PaymentNonce.

📄 generated-types.ts

A placeholder file intended to hold types that are automatically generated from the OpenAPI specification in the future.


📂 src/utils

📄 cookies.ts

  • setCookie(), getCookie(): Low-level utility functions for setting and parsing HTTP cookies.
  • setCSRFCookies(), validateTokenBasedCSRFToken(): Higher-level functions specifically for managing the double-submit CSRF cookies.

📄 crypto.ts

  • generateNonce(), generateUUID(), generateSecureToken(): A suite of functions for generating various cryptographic tokens and identifiers.
  • hashString(): A function for securely hashing strings using SHA-512.

📄 dateUtils.ts

  • getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS(): A utility function that returns the current date and time formatted for the Sydney timezone, used for consistent timestamps in logging.

📄 imageUtils.ts

  • getImageUrl(): A function that constructs the full URL for an image based on the environment's base URL.
  • getTourImageUrls(): A helper that returns a set of image URLs for a specific tour, using a predefined map.

📄 ipUtils.ts

  • getClientIP(): A crucial utility that reliably determines a client's real IP address by checking a prioritized list of headers.
  • isValidIP(), isPrivateIP(), isIPInCIDR(): A suite of functions for validating and classifying IP addresses.
  • performIPSecurityCheck(): A function that checks an IP against allow/deny lists.

📄 jwt.ts

A placeholder file containing commented-out code for future JWT (JSON Web Token) functionality.

📄 logger.ts

A comprehensive, structured logging system built on top of Deno's standard log module.

  • initializeLogging(): Sets up the logger with different handlers for development (console + files) and production (console only).
  • logDebug(), logInfo(), logWarn(), logError(): The core logging functions.
  • withCorrelationId(): A wrapper to ensure all logs within a specific context share the same unique ID.
  • measureAndLog(): A utility for logging the performance of a given function.

📄 openApiLoader.ts

The core of the dynamic routing system.

  • OpenAPILoader (class): Manages loading the spec, converting schemas, and registering routes.
  • createOpenAPILoader(): The main factory function that intelligently loads the spec from the local filesystem or Val Town blob storage based on the environment.
  • SchemaConverter (class): Translates OpenAPI schemas to Zod schemas for validation.
  • RouteGenerator (class): Creates Hono-compatible route configurations from the OpenAPI spec.

📄 proxy.ts

A placeholder file containing commented-out code for future reverse proxy functionality.

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.