Middleware Reference

Detailed API reference for Gatekeeper middleware

init(getOptions)

Creates middleware that initializes the Mira context with service identification, a unique trace ID, and pre-configured OpenAI client.

init(() => ({ serviceId: 'verify' }))  // 'verify' or 'inference'

What it does

  1. Validates required env vars: CF_ACCOUNT_ID, CF_GATEWAY_ID, CF_AIG_TOKEN, CF_AIG_BYOK_ALIAS, USAGE_QUEUE
  2. Validates serviceId (must be 'verify' or 'inference')
  3. Generates a unique traceId (UUID) for request tracing
  4. Creates an OpenAI client configured for Cloudflare AI Gateway
  5. Wraps the OpenAI client to automatically report usage via queue
  6. Sets mira context on the request

Options

PropertyTypeDescription
serviceId'verify' | 'inference'Service identifier for this worker

Mira Context

After init() runs, access the context via c.get('mira'):

interface MiraContext {
  traceId: string;           // Unique request ID (UUID)
  serviceId: string;         // Service identifier ('verify' | 'inference')
  openai: OpenAI;            // Pre-configured OpenAI client with auto usage reporting
}

auth()

Creates middleware that validates API keys and checks account balance. Requires init() to be called first.

auth()  // No options needed - gets serviceId from mira context

What it does

  1. Gets serviceId from mira context (set by init)
  2. Extracts Bearer token from Authorization header
  3. Validates token prefix matches service (e.g., mk_verify_...)
  4. Calls Console Service to validate the full key
  5. Checks if the app has sufficient balance
  6. Sets auth context on the request
  7. Auto-enriches mira context with auth metadata for AI Gateway logging

Auth Context

After auth() runs, access the context via c.get('auth'):

interface AuthContext {
  keyId: string;   // API key identifier
  appId: string;   // App identifier
  userId: string;  // User identifier
}

AI Gateway Metadata

After auth runs, all OpenAI client requests automatically include metadata for logging and billing:

  • serviceId - Service identifier
  • appId - App identifier
  • extra - JSON string containing traceId, requestedModel, keyId, userId

Usage is automatically reported to Console Service via queue after each completion.

Errors Thrown

  • AuthError - When authentication fails (401)
  • InsufficientBalanceError - When app has insufficient balance (402)

rateLimit(options)

Creates middleware that enforces rate limits per API key.

rateLimit({
  rpm: 60,    // Requests per minute
  rpd: 1000,  // Requests per day
})

What it does

  1. Reads rate limit state from KV storage
  2. Checks against per-minute and per-day limits
  3. Increments counters and saves state
  4. Sets rate limit headers on response

Options

PropertyTypeDescription
rpmnumberMaximum requests per minute
rpdnumberMaximum requests per day

Response Headers

X-RateLimit-Limit-Minute: 60
X-RateLimit-Remaining-Minute: 45
X-RateLimit-Limit-Day: 1000
X-RateLimit-Remaining-Day: 955

Errors Thrown

  • RateLimitError - When rate limit is exceeded (429)

Full Example

import { Hono } from 'hono';
import {
  init,
  auth,
  rateLimit,
  AuthError,
  RateLimitError,
  InsufficientBalanceError,
  type AuthContext,
  type MiraContext,
} from '@mira.network/gatekeeper';

type Env = {
  CF_ACCOUNT_ID: string;
  CF_GATEWAY_ID: string;
  CF_AIG_TOKEN: string;        // AI Gateway auth token (cf-aig-authorization)
  CF_AIG_BYOK_ALIAS: string;   // alias of the OpenRouter key stored on the gateway
  CONSOLE_SERVICE: Service;
  RATE_LIMIT_KV: KVNamespace;
  USAGE_QUEUE: Queue;
};

const app = new Hono<{
  Bindings: Env;
  Variables: { auth: AuthContext; mira: MiraContext };
}>();

// Initialize Mira context (reads AI Gateway config from env vars)
app.use('/*', init(() => ({ serviceId: 'verify' })));

// Global error handler
app.onError((err, c) => {
  if (err instanceof AuthError) {
    return c.json({ error: err.message }, 401);
  }
  if (err instanceof RateLimitError) {
    return c.json({ error: err.message, resetAt: err.resetAt }, 429);
  }
  if (err instanceof InsufficientBalanceError) {
    return c.json({ error: 'Insufficient balance', balance: err.balance }, 402);
  }
  console.error(err);
  return c.json({ error: 'Internal error' }, 500);
});

// Health check (no auth required)
app.get('/health', (c) => c.json({ status: 'ok' }));

// Protected routes - auth + rate limit
app.use('/v1/*', auth());
app.use('/v1/*', rateLimit({ rpm: 60, rpd: 1000 }));

app.post('/v1/chat', async (c) => {
  const { openai } = c.get('mira');

  // Use pre-configured OpenAI client
  // Usage is automatically reported via queue after completion
  const completion = await openai.chat.completions.create({
    model: 'openai/gpt-4o-mini',
    messages: [{ role: 'user', content: 'Hello!' }],
  });

  return c.json({ result: completion.choices[0].message.content });
});

export default app;