How AIRouter keeps your keys, traffic, and data safe
AIRouter runs on Cloudflare Pages Functions and Lightbase. Every layer — authentication, authorization, rate limiting, cache invalidation, audit logging, transport security, and secret management — is enforced by default. This page documents each layer so you can verify, audit, and extend it.
Authentication
Authentication is backed by Lightbase. AIRouter exposes a thin proxy at/api/auth/* that wraps Lightbase's/api/v1/auth/signup, /api/v1/auth/login, and/api/v1/auth/me endpoints. The Lightbase project API key for AIRouter is held only in the Pages Function environment and is never shipped to the browser.
- Signup: email + password. Optional name. Creates the Lightbase user and bootstraps the AIRouter user, organization, membership, subscription, and system_settings in a single transaction.
- Login: email + password, optional MFA (TOTP) via the
mfaCodefield. Lightbase supports MFA, backup codes, and (configured per project) OAuth. - Dashboard sessions: HTTP-only, Secure, SameSite=Lax cookies (
air_access15 minutes,air_refresh30 days). No JS access. - Tenant API: bearer tokens of the form
air_sk_...sent in theAuthorizationheader. Hashed with SHA-256 before storage; the plaintext secret is shown exactly once at creation.
Authorization
Authorization is enforced at two layers: role (for dashboard / admin endpoints) and scope (for tenant API endpoints). Both are checked on every request before the routing pipeline runs.
RBAC roles
| Role | Permissions |
|---|---|
owner | Everything, including billing, member management, and delete org. The signup creator is the owner. |
admin | Manage providers, credentials, routing rules, combos, API keys, and members. Cannot change the org plan or delete the org. |
member | View usage, manage own API keys, use the dashboard. Cannot manage credentials or routing rules. |
viewer | View-only access across the dashboard. |
API key scopes
Each tenant API key has a scopes array. The router checks that the request endpoint's scope is in the array (or that the array contains *). Available scopes: chat, embeddings, images, audio,video, rerank, moderations, files,search, batches, *.
Two further restrictions apply per key: allowedProviders (only credentials whoseproviderId is in the list are visible to the router) and allowedModels(only requests whose model matches the list, or for which the list contains*, are accepted).
Rate limiting
Rate limiting is enforced per API key with a token bucket per minute plus a daily counter. Both are isolate-local; on a cache miss the engine falls back to Lightbase to confirm the key's rateLimitPerMin and rateLimitPerDay. The default for the free plan is 60 RPM and 10 000 RPD.
- Per-minute: token bucket of size
rateLimitPerMin, refilled at one token per60 / rateLimitPerMinseconds. A 429 is returned when the bucket is empty. - Per-day: hard counter that resets on the Lightbase monthly cron. A 429 is returned when the daily limit is reached.
- Per-IP: optional stricter limit on top of the per-key limit, configurable per org.
- Per-isolate: counters live in the Pages Function isolate. Cold starts may briefly exceed limits by one or two requests before the Lightbase re-sync.
The rate limiter is implemented in src/lib/server/security/rateLimit.ts and is invoked by every tenant API endpoint after authentication.
Cache invalidation
AIRouter aggressively caches credentials, routing rules, org context, and API keys in per-isolate memory with short TTLs. When an admin mutates state via the dashboard, the admin endpoint calls invalidateOrg(orgId) / invalidateApiKey(keyHash)/ invalidateAll() from src/lib/server/cache.ts.
For cross-isolate invalidation (a single Pages Function isolate cannot reach other isolates), an HMAC-signed internal endpoint is exposed:POST /api/internal/invalidate. The body is{orgId?, keyHash?, all?}. The X-AIRouter-Sig header must equal the hex-encoded HMAC-SHA256 of the body using CACHE_INVALIDATION_HMAC_KEY.
# Compute the HMAC signature:
SIG=$(printf '{"orgId":"org_abc"}' \
| openssl dgst -sha256 -hmac "$CACHE_INVALIDATION_HMAC_KEY" -hex \
| awk '{print $NF}')
curl -X POST https://airouter-beta.pages.dev/api/internal/invalidate \
-H "X-AIRouter-Sig: $SIG" \
-H "Content-Type: application/json" \
-d '{"orgId":"org_abc"}'Audit logging
Every admin action is recorded in the audit_logs collection in Lightbase. Each record contains the actor's user id, the org id, the action name (e.g.,credential.create, route.update, key.revoke), the before/after payload (with secrets redacted), the client IP, the user agent, and a timestamp. The dashboard surfaces audit logs at /app/audit-log.
Every tenant API call is recorded in usage_records with the org id, API key id, provider id, credential id, endpoint, model, token counts, cost, latency, status, client IP, user agent, and routing rule id. These power the usage dashboard and the per-key metrics.
CSRF protection
The dashboard uses a double-submit cookie pattern. Every state-changing admin request must include a CSRF token both as a cookie (air_csrf) and in a header (X-AIRouter-CSRF). The middleware insrc/lib/server/middleware/csrf.ts verifies that the two values match and that the request is same-origin. GET requests do not require the token.
The dashboard client reads the air_csrf cookie (which is not HTTP-only) and attaches the header on every fetch. Other origins cannot read the cookie thanks to SameSite=Lax and the cookie domain. Non-browser clients (those without aCookie header) bypass CSRF, since they rely on a bearer token instead.
CSP, CORS, HSTS
Content-Security-Policy
All pages ship a strict CSP enforced by the Astro middleware atsrc/middleware.ts. script-src is limited to selfplus the Astro inline runtime; style-src to self plus the Astro inline styles; img-src to self plus data URIs and the upstream image provider domains; connect-src to self plus the API origin. No unsafe-inline, no unsafe-eval.
CORS
The Astro middleware handles CORS preflight (OPTIONS 204) for/api/v1/* against a same-origin allow-list. Cross-origin requests to/api/admin/* and /api/auth/* are denied with a 403.
HSTS
Cloudflare enforces HTTPS at the edge. The middleware addsStrict-Transport-Security: max-age=63072000; includeSubDomains; preload on every response. Plain HTTP requests are redirected to HTTPS at the Cloudflare edge.
IP allow-list
Each organization can optionally configure an IP allow-list viasystem_settings.enforceIpAllowList and system_settings.ipAllowList. When enforcement is on, every tenant API request is checked against the list (theCF-Connecting-IP header, falling back to X-Forwarded-For). A 403 is returned if the client IP is not in the list. The list supports both individual IPv4 / IPv6 addresses and CIDR ranges.
The IP allow-list is checked after authentication but before scope and rate-limit checks. Toggle it in /app/settings.
Secret management
AIRouter uses four platform-level secrets and one per-credential secret per credential. All are stored in the Cloudflare Pages production environment (set via the Cloudflare dashboard or via scripts/deploy-cloudflare.ts).
| Secret | Purpose | Rotation notes |
|---|---|---|
LIGHTBASE_API_KEY | Service-account key for the AIRouter Lightbase project. Used for all server-side reads/writes. | Rotate in the Lightbase dashboard; redeploy to update the Pages env var. Keep private. |
SESSION_SECRET | Used to sign / verify dashboard session artifacts if cookies need to be re-validated locally. | Rotating invalidates all dashboard sessions (forces re-login). |
ENCRYPTION_KEY | 32-byte key used for any client-side cache encryption and for envelope encryption of credentials if Lightbase field-level encryption is not used. | Rotating invalidates any data encrypted with the previous key. Plan a re-encrypt step. |
CACHE_INVALIDATION_HMAC_KEY | HMAC-SHA256 key for the /api/internal/invalidate endpoint. Allows external callers to flush caches. | Rotating invalidates any caller still using the old key. Distribute the new key to callers. |
Per-credential secrets (provider API keys) are stored in theprovider_credentials collection. The dashboard masks them as ***and exposes only a credentialLast4 field. They are never returned in full to the browser.
Lightbase field-level encryption
Lightbase supports field-level encryption on collection columns. AIRouter enables encryption on the credential field of theprovider_credentials collection, so the plaintext API keys are encrypted at rest with a key managed by Lightbase. The Lightbase API decrypts on read for callers that have the API key; the field is opaque to other callers.
Note: encrypted fields cannot be filtered by value in Lightbase. AIRouter uses thekeyHash field (SHA-256 of the plaintext API key, not encrypted) for authentication lookups against tenant_api_keys. The hash is one-way; the plaintext key is never recoverable from it.
Security checklist before going live
- All four platform secrets set in the Cloudflare Pages production environment (Lightbase key, session secret, encryption key, HMAC key).
- Lightbase project has MFA enabled for the service account owner.
- Dashboard CSRF middleware deployed (verify with a manual cross-origin POST).
- CSP header present on a production response (check the network tab).
- HSTS header present and preload-ready.
- Per-org IP allow-list enabled for any tenant with a known IP range.
- API keys scoped to the minimum scope set (avoid
*in production). - Audit log retention configured (default 90 days).
- Usage records retention configured (default 365 days).