Skip to main content

Technology Stack

Hono Framework

Ultra-fast web framework optimized for edge runtimes

Cloudflare Workers

Serverless edge runtime with V8 isolates

TypeScript 5.3

Type-safe development with strict mode

Zod

Runtime type validation and schema parsing

Dependencies

package.json
{
  "dependencies": {
    "hono": "^3.12.0",
    "@solana/web3.js": "^1.87.6",
    "@solana/spl-token": "^0.4.3",
    "zod": "^3.22.4",
    "@hono/zod-validator": "^0.2.1",
    "bs58": "^5.0.0",
    "tweetnacl": "^1.0.3"
  }
}

Project Structure

packages/worker/
├── src/
│   ├── index.ts                      # Hono app entry point
│   │
│   ├── middleware/                   # Request middleware
│   │   ├── auth.ts                   # JWT & API key authentication
│   │   ├── rate-limit.ts             # Rate limiting with KV
│   │   ├── cache.ts                  # Response caching
│   │   ├── error-handler.ts          # Global error handler
│   │   ├── request-logger.ts         # Request logging
│   │   └── performance.ts            # Performance monitoring
│   │
│   ├── routes/                       # API routes
│   │   ├── health.ts                 # Health check endpoints
│   │   ├── auth.ts                   # GitHub OAuth flow
│   │   ├── idl.ts                    # IDL management
│   │   ├── api.ts                    # Public API endpoints
│   │   └── llms.ts                   # LLM-optimized endpoints
│   │
│   ├── services/                     # Business logic
│   │   ├── idl-parser.ts             # IDL validation & parsing
│   │   ├── tx-builder.ts             # Transaction serialization
│   │   ├── doc-generator.ts          # Markdown documentation
│   │   ├── pda.ts                    # PDA derivation utilities
│   │   ├── jwt.ts                    # JWT signing/verification
│   │   ├── validation.ts             # Input validation
│   │   └── logger.ts                 # Structured logging
│   │
│   ├── types/                        # TypeScript types
│   │   └── index.ts                  # Shared type definitions
│   │
│   └── utils/                        # Helper utilities
│       ├── crypto.ts                 # Cryptographic functions
│       └── errors.ts                 # Custom error classes

├── tests/                            # Unit tests
├── wrangler.toml                     # Worker configuration
├── tsconfig.json                     # TypeScript config
└── package.json

Hono Application Setup

Main Entry Point

index.ts
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import type { D1Database, KVNamespace } from '@cloudflare/workers-types'

// Middleware
import { errorHandler } from './middleware/error-handler'
import { apiRateLimit } from './middleware/rate-limit'
import { requestLogger } from './middleware/request-logger'
import { publicApiCache } from './middleware/cache'
import { performanceMonitor, compressionHeaders } from './middleware/performance'

// Routes
import healthRoutes from './routes/health'
import idlRoutes from './routes/idl'
import apiRoutes from './routes/api'
import authRoutes from './routes/auth'
import llmsRoutes from './routes/llms'

type Env = {
  Variables: Record<string, unknown>
  Bindings: {
    DB: D1Database
    IDLS: KVNamespace
    CACHE: KVNamespace
    GITHUB_OAUTH_ID: string
    GITHUB_OAUTH_SECRET: string
    JWT_SECRET: string
    SOLANA_RPC_URL: string
    FRONTEND_URL: string
    API_BASE_URL: string
    CORS_ORIGIN: string
  }
}

const app = new Hono<Env>()

// Global Middleware (applied to all routes)
app.use('*', performanceMonitor)
app.use('*', compressionHeaders)
app.use('*', logger())
app.use('*', errorHandler)
app.use(
  '*',
  cors({
    origin: (origin: string) => {
      const corsOrigins = [
        'https://orquestra.dev',
        'http://localhost:3000',
        'http://localhost:5173',
      ]
      return corsOrigins.includes(origin) ? origin : corsOrigins[0]
    },
    allowHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    credentials: true,
  }),
)

// Route Mounting
app.route('/health', healthRoutes)
app.route('/auth', authRoutes)
app.route('/', llmsRoutes)

// API-specific middleware
app.use('/api/*', requestLogger)
app.use('/api/*', apiRateLimit)
app.use('/api/*', publicApiCache)
app.route('/api/idl', idlRoutes)
app.route('/api', apiRoutes)

// 404 handler
app.all('*', (c) => {
  return c.json({ error: 'Not Found' }, 404)
})

export default app

Middleware Layer

Authentication Middleware

Supports both JWT tokens and API keys:
middleware/auth.ts
import { Context, Next } from 'hono'
import { verifyJWT, type JWTPayload } from '../services/jwt'

/**
 * JWT Authentication Middleware
 * Validates Bearer token from Authorization header
 */
export async function authMiddleware(c: Context, next: Next) {
  const authHeader = c.req.header('Authorization')

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return c.json(
      { error: 'Unauthorized', message: 'Missing or invalid Authorization header' },
      401
    )
  }

  const token = authHeader.slice(7)

  try {
    const jwtSecret = c.env?.JWT_SECRET
    if (!jwtSecret) {
      return c.json({ error: 'Server configuration error' }, 500)
    }

    const payload = await verifyJWT(token, jwtSecret)
    c.set('userId', payload.sub)
    c.set('username', payload.username)
    c.set('jwtPayload', payload)

    await next()
  } catch (err) {
    return c.json(
      { error: 'Unauthorized', message: 'Invalid or expired token' },
      401
    )
  }
}

/**
 * API Key Authentication Middleware
 * Checks X-API-Key header against database
 */
export async function apiKeyMiddleware(c: Context, next: Next) {
  const apiKey = c.req.header('X-API-Key')

  if (!apiKey) {
    return c.json(
      { error: 'Unauthorized', message: 'Missing X-API-Key header' },
      401
    )
  }

  try {
    const db = c.env?.DB
    if (!db) {
      return c.json({ error: 'Server configuration error' }, 500)
    }

    const result = await db
      .prepare(
        `SELECT ak.*, p.user_id, p.name as project_name 
         FROM api_keys ak 
         JOIN projects p ON ak.project_id = p.id 
         WHERE ak.key = ? AND (ak.expires_at IS NULL OR ak.expires_at > datetime('now'))`
      )
      .bind(apiKey)
      .first()

    if (!result) {
      return c.json(
        { error: 'Unauthorized', message: 'Invalid or expired API key' },
        401
      )
    }

    // Update last_used timestamp (async)
    await db
      .prepare('UPDATE api_keys SET last_used = datetime(\'now\') WHERE key = ?')
      .bind(apiKey)
      .run()

    c.set('apiKeyProjectId', result.project_id)
    c.set('apiKeyUserId', result.user_id)

    await next()
  } catch (err) {
    return c.json({ error: 'Authentication failed' }, 500)
  }
}

/**
 * Optional Auth Middleware
 * Sets user context if token present, but doesn't fail if missing
 */
export async function optionalAuthMiddleware(c: Context, next: Next) {
  const authHeader = c.req.header('Authorization')

  if (authHeader?.startsWith('Bearer ')) {
    const token = authHeader.slice(7)
    try {
      const jwtSecret = c.env?.JWT_SECRET
      if (jwtSecret) {
        const payload = await verifyJWT(token, jwtSecret)
        c.set('userId', payload.sub)
        c.set('username', payload.username)
        c.set('jwtPayload', payload)
      }
    } catch {
      // Silently ignore invalid tokens
    }
  }

  await next()
}

Rate Limiting Middleware

Uses Cloudflare KV for distributed rate limiting:
middleware/rate-limit.ts
import { Context, Next } from 'hono'

interface RateLimitOptions {
  limit: number          // Max requests per window
  windowSec: number      // Window duration in seconds
  prefix?: string        // KV key prefix
  keyFn?: (c: Context) => string  // Custom key function
}

interface RateLimitEntry {
  count: number
  resetAt: number
}

const defaultKeyFn = (c: Context): string => {
  const ip = c.req.header('CF-Connecting-IP') || 
             c.req.header('X-Forwarded-For') || 
             'unknown'
  return ip
}

export function rateLimiter(opts: RateLimitOptions) {
  const { limit, windowSec, prefix = 'rl', keyFn = defaultKeyFn } = opts

  return async (c: Context, next: Next) => {
    const cache = c.env?.CACHE
    if (!cache) {
      await next()  // Skip if no KV available
      return
    }

    const identifier = keyFn(c)
    const key = `${prefix}:${identifier}`

    try {
      const raw = await cache.get(key)
      const now = Date.now()

      let entry: RateLimitEntry
      if (raw) {
        entry = JSON.parse(raw)
        if (now > entry.resetAt) {
          entry = { count: 1, resetAt: now + windowSec * 1000 }
        } else {
          entry.count++
        }
      } else {
        entry = { count: 1, resetAt: now + windowSec * 1000 }
      }

      // Set rate limit headers
      const remaining = Math.max(0, limit - entry.count)
      c.header('X-RateLimit-Limit', String(limit))
      c.header('X-RateLimit-Remaining', String(remaining))
      c.header('X-RateLimit-Reset', String(Math.ceil(entry.resetAt / 1000)))

      if (entry.count > limit) {
        const retryAfter = Math.ceil((entry.resetAt - now) / 1000)
        c.header('Retry-After', String(retryAfter))
        return c.json(
          {
            error: 'Too Many Requests',
            message: `Rate limit exceeded. Try again in ${retryAfter} seconds.`,
            retryAfter,
          },
          429
        )
      }

      // Store updated count
      await cache.put(key, JSON.stringify(entry), { 
        expirationTtl: windowSec + 10 
      })
    } catch {
      // On KV errors, allow request through
    }

    await next()
  }
}

// Presets
export const apiRateLimit = rateLimiter({
  limit: 100,
  windowSec: 60,
  prefix: 'rl:api',
})

export const authRateLimit = rateLimiter({
  limit: 20,
  windowSec: 60,
  prefix: 'rl:auth',
})

export const uploadRateLimit = rateLimiter({
  limit: 10,
  windowSec: 60,
  prefix: 'rl:upload',
})

Response Caching Middleware

Caches GET responses in KV:
middleware/cache.ts
import { createMiddleware } from 'hono/factory'
import type { KVNamespace } from '@cloudflare/workers-types'

interface CacheOptions {
  ttl?: number           // TTL in seconds (default: 300)
  prefix?: string        // Key prefix
  includeQuery?: boolean // Include query params in key
}

export function responseCache(opts: CacheOptions = {}) {
  const { ttl = 300, prefix = 'resp', includeQuery = true } = opts

  return createMiddleware(async (c, next) => {
    // Only cache GET requests
    if (c.req.method !== 'GET') {
      await next()
      return
    }

    // Skip cache for authenticated requests
    const authHeader = c.req.header('Authorization')
    const apiKeyHeader = c.req.header('X-API-Key')
    if (authHeader || apiKeyHeader) {
      await next()
      return
    }

    const cache = c.env?.CACHE as KVNamespace | undefined
    if (!cache) {
      await next()
      return
    }

    // Build cache key
    const path = c.req.path
    const query = includeQuery ? c.req.query().toString() : ''
    const cacheKey = `${prefix}:${path}${query ? `?${query}` : ''}`

    try {
      // Check cache
      const cached = await cache.get(cacheKey)
      if (cached) {
        const parsed = JSON.parse(cached)
        c.header('X-Cache', 'HIT')
        c.header('Content-Type', parsed.contentType)
        return c.body(parsed.body, parsed.status)
      }
    } catch {
      // Cache read error — proceed without cache
    }

    await next()

    // Cache successful responses
    if (c.res.status >= 200 && c.res.status < 300) {
      try {
        const cloned = c.res.clone()
        const body = await cloned.text()
        const contentType = cloned.headers.get('Content-Type') || 'application/json'

        const entry = JSON.stringify({
          body,
          contentType,
          status: cloned.status,
        })

        // Store async — don't block response
        c.executionCtx?.waitUntil(
          cache.put(cacheKey, entry, { expirationTtl: ttl })
        )

        c.header('X-Cache', 'MISS')
      } catch {
        // Cache write error — ignore
      }
    }
  })
}

// Presets
export const publicApiCache = responseCache({
  ttl: 300,      // 5 minutes
  prefix: 'api',
})

export const docsCache = responseCache({
  ttl: 3600,     // 1 hour
  prefix: 'docs',
})

Service Layer

JWT Service

Web Crypto API for edge compatibility:
services/jwt.ts
export interface JWTPayload {
  sub: string        // user ID
  username: string
  iat: number        // issued at
  exp: number        // expiration
}

const encoder = new TextEncoder()

async function getKey(secret: string): Promise<CryptoKey> {
  return crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign', 'verify']
  )
}

function base64UrlEncode(data: Uint8Array | string): string {
  const str = typeof data === 'string' ? data : String.fromCharCode(...data)
  return btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
}

function base64UrlDecode(str: string): string {
  str = str.replace(/-/g, '+').replace(/_/g, '/')
  while (str.length % 4) str += '='
  return atob(str)
}

/**
 * Generate JWT token with HS256
 */
export async function generateJWT(
  payload: Omit<JWTPayload, 'iat' | 'exp'>,
  secret: string,
  expiresInSeconds: number = 7 * 24 * 60 * 60  // 7 days
): Promise<string> {
  const now = Math.floor(Date.now() / 1000)

  const fullPayload: JWTPayload = {
    ...payload,
    iat: now,
    exp: now + expiresInSeconds,
  }

  const header = { alg: 'HS256', typ: 'JWT' }
  const headerEncoded = base64UrlEncode(JSON.stringify(header))
  const payloadEncoded = base64UrlEncode(JSON.stringify(fullPayload))
  const signingInput = `${headerEncoded}.${payloadEncoded}`

  const key = await getKey(secret)
  const signature = await crypto.subtle.sign(
    'HMAC',
    key,
    encoder.encode(signingInput)
  )

  const signatureEncoded = base64UrlEncode(new Uint8Array(signature))
  return `${signingInput}.${signatureEncoded}`
}

/**
 * Verify and decode JWT token
 */
export async function verifyJWT(
  token: string,
  secret: string
): Promise<JWTPayload> {
  const parts = token.split('.')
  if (parts.length !== 3) {
    throw new Error('Invalid token format')
  }

  const [headerEncoded, payloadEncoded, signatureEncoded] = parts
  const signingInput = `${headerEncoded}.${payloadEncoded}`

  // Verify signature
  const key = await getKey(secret)
  const signatureStr = base64UrlDecode(signatureEncoded)
  const signatureBytes = new Uint8Array(signatureStr.length)
  for (let i = 0; i < signatureStr.length; i++) {
    signatureBytes[i] = signatureStr.charCodeAt(i)
  }

  const valid = await crypto.subtle.verify(
    'HMAC',
    key,
    signatureBytes,
    encoder.encode(signingInput)
  )
  if (!valid) {
    throw new Error('Invalid token signature')
  }

  // Decode payload
  const payload: JWTPayload = JSON.parse(base64UrlDecode(payloadEncoded))

  // Check expiration
  const now = Math.floor(Date.now() / 1000)
  if (payload.exp && payload.exp < now) {
    throw new Error('Token expired')
  }

  return payload
}

Input Validation Service

Lightweight validation without Zod dependency:
services/validation.ts
export interface ValidationError {
  field: string
  message: string
}

export interface ValidationResult<T> {
  success: boolean
  data?: T
  errors?: ValidationError[]
}

const BASE58_REGEX = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/

export function validateBuildRequest(body: unknown): ValidationResult<any> {
  const errors: ValidationError[] = []

  if (typeof body !== 'object' || !body) {
    return { 
      success: false, 
      errors: [{ field: 'body', message: 'Request body must be a JSON object' }] 
    }
  }

  const data = body as any

  if (!data.payer || typeof data.payer !== 'string') {
    errors.push({ field: 'payer', message: 'Payer public key is required' })
  } else if (!BASE58_REGEX.test(data.payer)) {
    errors.push({ field: 'payer', message: 'Invalid base58 public key' })
  }

  if (!data.accounts || typeof data.accounts !== 'object') {
    errors.push({ field: 'accounts', message: 'Accounts object is required' })
  } else {
    for (const [k, v] of Object.entries(data.accounts)) {
      if (typeof v !== 'string' || !BASE58_REGEX.test(v as string)) {
        errors.push({ 
          field: `accounts.${k}`, 
          message: `Invalid public key for account "${k}"` 
        })
      }
    }
  }

  if (errors.length > 0) {
    return { success: false, errors }
  }

  return {
    success: true,
    data: {
      accounts: data.accounts,
      args: data.args || {},
      payer: data.payer,
    },
  }
}

Cloudflare Workers Runtime

Environment Bindings

interface Env {
  DB: D1Database              // SQLite database
  IDLS: KVNamespace           // IDL cache
  CACHE: KVNamespace          // Response cache
  GITHUB_OAUTH_SECRET: string // Secret (encrypted)
  JWT_SECRET: string          // Secret (encrypted)
  SOLANA_RPC_URL: string      // RPC endpoint
}

Worker Configuration

wrangler.toml
name = "orquestra"
main = "packages/worker/src/index.ts"
compatibility_date = "2024-01-01"

[[d1_databases]]
binding = "DB"
database_name = "orquestra-prod"

[[kv_namespaces]]
binding = "IDLS"

[[kv_namespaces]]
binding = "CACHE"

[env.production.vars]
ENVIRONMENT = "production"
FRONTEND_URL = "https://orquestra.dev"
API_BASE_URL = "https://api.orquestra.dev"

Frontend Architecture

React application and state management

System Architecture

High-level system design and data flow

Security Model

Authentication and security patterns

API Reference

Complete API endpoint documentation

Build docs developers (and LLMs) love