Skip to main content
The Gateway API is a Cloudflare Worker that serves as the single entry point for all MetaCogna services. It handles authentication, routing, and request proxying to downstream workers.

Architecture

The Gateway API acts as a reverse proxy with JWT-based authentication, routing requests to specialized workers:

Key Features

JWT Authentication

Secure token-based authentication with SHA-256 credential hashing

Route Proxying

Intelligent routing to BUILD, KV, and CORE services

Error Handling

Unified error response format across all routes

Service Bindings

Secure inter-worker communication via Cloudflare service bindings

Routing Matrix

The gateway routes requests based on URL prefixes:
PrefixRoute TypeTarget ServiceAuthentication
/auth/loginAuthenticationInternalNone (public)
/auth/guestGuest TokenInternalNone (public)
/buildBuild ServiceBUILD_SERVICE_URLRequired (JWT)
/kvKV ServiceKV_SERVICE_URLOptional (if Bearer token provided)
/coreCore ServiceCORE_SERVICE_URLOptional (if Bearer token provided)

Quick Start

Installation

cd gateway-api
bun install

Development

# Run all packages in development mode
bun run dev

Environment Setup

The gateway requires the following environment variables:
  • GATEWAY_JWT_SECRET - Secret key for JWT signing and verification
  • BUILD_SERVICE_URL - URL of the build service worker
  • KV_SERVICE_URL - URL of the KV service worker
  • CORE_SERVICE_URL - URL of the core service worker

R2 Bucket

The gateway uses an R2 bucket (metacogna-accounts) to store admin credentials:
  • Path format: auth/admins/{username}.json
  • Structure: { username, salt, hash, role }

Project Structure

gateway-api/
├── packages/
│   ├── gateway-worker/     # Main gateway worker
│   │   ├── src/index.ts    # Request handler
│   │   └── wrangler.toml   # Cloudflare configuration
│   └── shared/              # Shared utilities
│       └── src/
│           └── gateway.ts   # JWT utilities, schemas
├── docs/
│   └── routing-matrix.md    # Detailed routing documentation
└── scripts/
    └── deploy-gateway.sh    # Deployment script

How It Works

  1. Client Request: Client sends request to api.metacogna.ai/{path}
  2. Authentication: For protected routes, client includes Authorization: Bearer {token} header
  3. Route Matching: Gateway matches URL prefix to route configuration
  4. Token Verification: For protected routes, gateway verifies JWT token
  5. URL Rewriting: Gateway strips route prefix and forwards to target service
  6. Response Proxying: Gateway returns response from downstream service