This document provides a concise and complete map of all files, classes, and functions within the ZenServer project.
The main entry point for the application. It initializes the environment, database, and logging, and starts the API gateway.
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.
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 fromsecurityConfigto be called at startup.
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.
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 ofTourobjects containing rich, realistic data for several tours.
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 aSELECTquery and returns an array of objects.execute(): RunsINSERT,UPDATE, orDELETEstatements.storeNonce(),getNonce(),validateAndUseNonce(): A suite of methods for securely managing the lifecycle of payment nonces.getFingerprintStatus(): Checks payment attempt counts for a booking.
Aggregates all schema definition files into a single export.
SCHEMA_SQL: A template string combining allCREATE TABLEstatements from the other schema files.SAMPLE_BOOKINGS_SQL:INSERTstatements to seed the database with sample tour booking data for development.
Contains the SQL schema for the application's core business logic.
APP_TP_CORE_SCHEMA: A template string withCREATE TABLEstatements forapp_payment_nonces,app_tp_booking_orders, andapp_pay_tokens.
Contains the SQL schema for managing and logging webhooks.
SYS_WEBHOOKS_SCHEMA: A template string withCREATE TABLEstatements forsys_webhooks(configuration) andsys_webhook_logs(audit trail).
Contains the SQL schema for system-level security and infrastructure monitoring.
SYS_INFRA_SCHEMA: A template string withCREATE TABLEstatements forsys_rate_limits,sys_security_events,sys_blocked_ips, andsys_whitelisted_ips.
The main Hono application file. It sets up the middleware pipeline and orchestrates dynamic route registration.
app: TheOpenAPIHonoapplication 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
createOpenAPILoaderto parse theopenapi.jsonspec, automatically create a handler map withcreateDynamicHandlerMap, and register all routes. - Fallback Handler: Registers a fallback route to handle critical server startup errors (e.g., if
openapi.jsoncannot be loaded).
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.
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.
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.
The core of the dynamic routing system.
extractOperationIds(): Scans the OpenAPI spec and returns a list of alloperationIds.createDynamicHandlerMap(): Creates a map where eachoperationIdis a key and its value is a generic handler function that delegates to the corresponding function inbusinessLogic.ts.
Provides the global error handling middleware for the application.
globalErrorHandler(): A function that catches all unhandled errors, logs them, and returns a standardized500JSON response.
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.
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.
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.
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.
createBasicAuthMiddleware(): Creates Hono middleware for HTTP Basic Authentication using credentials from the environment.
createBearerAuthMiddleware(): Creates Hono middleware for Bearer Token authentication using a static API key from the environment.
corsMiddleware(): Handles CORS preflight (OPTIONS) requests and validates theOriginheader on all incoming requests.
getCSPHeader(): Builds theContent-Security-Policyheader string based on the environment (dev vs. prod).cspMiddleware(): A Hono middleware that applies the CSP header to responses.
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.
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.
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.
rateLimitMiddleware(): A middleware that provides per-endpoint rate limiting based on the client's IP address, using an in-memory cache.
requestIdMiddleware: Assigns a uniqueX-Request-Idto every incoming request.requestLoggerMiddleware: Logs the details of every request and its corresponding response, including the request ID, status, and duration.
createSecureHeadersMiddleware(): A Hono middleware that applies a suite of important security-related HTTP headers (like HSTS, X-Frame-Options, etc.) to every response.
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.
AuthService(class): Provides static methods for handling various authentication and authorization tasks, such as validating API keys and different types of tokens.
PublicPayNonceService(class): A service dedicated to managing the lifecycle of public payment nonces, including creation, validation, and status checking.
TurnstileService(class): A service that abstracts the interaction with the Cloudflare Turnstile API for verifying tokens.
ValidationService(class): A central place for complex, reusable validation logic, such as validating the format of a Turnstile token.
PaymentFingerprintService(class): A service responsible for generating the unique payment "fingerprint" required by the Zenpay payment gateway.
Defines and exports the core TypeScript types and interfaces used throughout the application, such as AppContext, Booking, and PaymentNonce.
A placeholder file intended to hold types that are automatically generated from the OpenAPI specification in the future.
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.
generateNonce(),generateUUID(),generateSecureToken(): A suite of functions for generating various cryptographic tokens and identifiers.hashString(): A function for securely hashing strings using SHA-512.
getCurrentDateTimeInSydneyInYYYYMMDDTHHMMSS(): A utility function that returns the current date and time formatted for the Sydney timezone, used for consistent timestamps in logging.
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.
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.
A placeholder file containing commented-out code for future JWT (JSON Web Token) functionality.
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.
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.
A placeholder file containing commented-out code for future reverse proxy functionality.