Gatekeeper

Authentication, rate limiting, and AI Gateway middleware for Hono

@mira.network/gatekeeper provides middleware for building services on the Mira Network with:

  • Initialization - Request tracing, service identification, and OpenAI client setup for AI Gateway
  • Authentication - API key validation via Console Service
  • Balance checking - Balance verification before processing
  • Rate limiting - Per-minute and per-day limits

Installation

npm install @mira.network/gatekeeper

Quick Start

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

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

// 1. Initialize Mira context (top of middleware stack)
app.use('/*', init((c) => ({
  serviceId: 'verify',  // Required: 'verify' or 'inference'
  aiGateway: {
    accountId: c.env.CF_ACCOUNT_ID,
    gatewayId: c.env.CF_GATEWAY_ID,
    token: c.env.CF_AI_GATEWAY_TOKEN,
  },
})));

// 2. Apply auth and rate limiting to protected routes
app.use('/api/*', auth());
app.use('/api/*', rateLimit({ rpm: 60, rpd: 1000 }));

app.post('/api/endpoint', (c) => {
  const { traceId, serviceId, openai } = c.get('mira');
  const { keyId, appId } = c.get('auth');

  // Use pre-configured OpenAI client
  // All requests include traceId, serviceId + auth metadata in AI Gateway logs

  return c.json({ message: 'Success!' });
});

export default app;

Environment Requirements

Gatekeeper requires these Cloudflare bindings:

interface Env {
  // AI Gateway configuration
  CF_ACCOUNT_ID: string;
  CF_GATEWAY_ID: string;
  CF_AI_GATEWAY_TOKEN: string;

  // Service bindings
  CONSOLE_SERVICE: Service;  // For API key validation
  RATE_LIMIT_KV: KVNamespace; // For rate limit state
}

Context Variables

After middleware runs, these are available via c.get():

MiraContext

const mira = c.get('mira');
// {
//   traceId: string;           // Unique request ID (UUID)
//   serviceId: string;         // Service identifier ('verify' | 'inference')
//   openai: OpenAI;            // Pre-configured OpenAI client
//   _aiGatewayConfig: {...};   // Internal config
// }

AuthContext

const auth = c.get('auth');
// {
//   keyId: string;   // API key identifier
//   appId: string;   // App identifier
//   userId: string;  // User identifier
// }

Next Steps