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/gatekeeperQuick 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 (reads AI Gateway config from env vars)
app.use('/*', init(() => ({ serviceId: 'verify' })));
// 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', async (c) => {
const { traceId, serviceId, openai } = c.get('mira');
const { keyId, appId } = c.get('auth');
// Use pre-configured OpenAI client
// Usage is automatically reported via queue after each request
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;Environment Requirements
Gatekeeper requires these Cloudflare bindings:
interface Env {
// AI Gateway configuration
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
// Service bindings
CONSOLE_SERVICE: Service; // For API key validation
RATE_LIMIT_KV: KVNamespace; // For rate limit state
USAGE_QUEUE: Queue; // For async usage reporting
}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 with auto usage reporting
// }AuthContext
const auth = c.get('auth');
// {
// keyId: string; // API key identifier
// appId: string; // App identifier
// userId: string; // User identifier
// }Next Steps
- Middleware Reference - Detailed API for each middleware
- Error Handling - Error types and handling patterns