How G0DM0D3 API Authentication Works: Bearer Tokens, Constant-Time Validation, and Tiered Access

The G0DM0D3 API implements bearer-token authentication via an Express middleware that validates API keys against environment variables using constant-time comparison, enriches requests with tier metadata, and hashes keys for rate-limit bucketing.

The elder-plinius/G0DM0D3 repository provides a secure, tiered API access system designed for both production deployments and local development. Understanding how G0DM0D3 API authentication works is critical for correctly configuring client access and interpreting the middleware's security behaviors. The authentication flow centers on api/middleware/auth.ts, which processes incoming requests before they reach protected endpoints.

Environment Variable Configuration

The authentication system reads valid API keys from environment variables at startup. The middleware checks for GODMODE_API_KEYS (a comma-separated list) or GODMODE_API_KEY (a single key) in api/middleware/auth.ts lines 4-7. If neither variable is present, the system enters open-development mode and disables authentication, allowing all requests to proceed with default free-tier access.

Bearer Token Extraction and Validation

For every incoming request, the middleware inspects the Authorization header. It expects the format Bearer <your-api-key>. If the header is missing or malformed, the middleware immediately rejects the request with a 401 Unauthorized status (lines 68-73).

When a properly formatted bearer token is present, the system extracts the key and prepares for cryptographic verification. This extraction occurs before any validation logic to ensure consistent header parsing across all request paths.

Constant-Time Key Verification

To prevent timing attacks that could leak valid key information through response latency analysis, the middleware uses timingSafeEqual for comparison (lines 33-40). This Node.js cryptographic function compares the supplied API key against the configured list in constant time, regardless of how many characters match.

If the provided key does not match any entry in the configured list, the middleware returns 403 Forbidden (lines 78-82). This distinction is important: 401 indicates a missing or malformed authentication header, while 403 indicates that the credentials provided are invalid or insufficient.

Tier Resolution and Request Enrichment

Upon successful authentication, the middleware performs several enrichment steps on the request object:

  1. Key Hashing – The raw API key is hashed using SHA-256, and the first 16 hex characters are stored as req.apiKeyId (lines 42-47). This identifier enables rate-limit bucketing without exposing the original key in logs or memory dumps.

  2. Tier Lookup – The system resolves the caller's tier (free, pro, or enterprise) by querying the tier system defined in api/lib/tiers.ts (lines 36-40). Keys not explicitly mapped default to the free tier.

  3. Configuration Attachment – The middleware attaches req.tier (the tier name) and req.tierConfig (the full configuration object containing rate limits and model permissions) to the request object (lines 85-92).

Downstream middleware such as api/middleware/tierGate.ts uses this metadata to enforce tier-specific rate limits and feature access controls.

Open Development Mode

When no API keys are configured in the environment, the middleware logs a startup warning and treats every incoming request as anonymous. In this mode, all requests automatically receive the free tier configuration (lines 47-53). This behavior facilitates local development and testing without requiring credential management, though it should never be enabled in production environments.

Implementation Examples

Client-Side Authentication

Clients must include the API key in the Authorization header using the bearer scheme:

fetch('https://api.godmode.example.com/v1/chat', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: 'Bearer YOUR_API_KEY_HERE',
  },
  body: JSON.stringify({ prompt: 'Explain quantum tunneling' })
})
  .then(res => {
    if (res.status === 401) throw new Error('Missing or malformed auth header');
    if (res.status === 403) throw new Error('Invalid API key');
    return res.json();
  })
  .then(console.log);

Server-Side Middleware Wiring

The Express server in api/server.ts registers the authentication middleware before protected routes:

import express from 'express';
import { apiKeyAuth } from './middleware/auth';
import { tierGate } from './middleware/tierGate';

const app = express();
app.use(express.json());

// Health check remains publicly accessible
app.get('/v1/health', (req, res) => res.json({ ok: true }));

// Protect subsequent routes
app.use(apiKeyAuth);  // Validates bearer tokens
app.use(tierGate);    // Applies tier-specific rate limits

app.post('/v1/chat', (req, res) => {
  // Access enriched request properties
  console.log(req.apiKeyId);      // Hashed key identifier
  console.log(req.tier);          // 'free', 'pro', or 'enterprise'
  console.log(req.tierConfig);    // Tier-specific limits and permissions
  
  // Process authenticated request...
});

Summary

  • G0DM0D3 API authentication relies on environment-configured API keys read from GODMODE_API_KEY or GODMODE_API_KEYS variables in api/middleware/auth.ts.
  • The system requires bearer tokens in the Authorization header, returning 401 for missing headers and 403 for invalid keys.
  • Constant-time comparison via timingSafeEqual prevents timing attacks during key validation.
  • Successful authentication enriches the request object with req.apiKeyId (SHA-256 hash), req.tier, and req.tierConfig for downstream rate limiting and feature gating.
  • Open-development mode disables authentication when no keys are configured, defaulting all traffic to the free tier.

Frequently Asked Questions

What happens if I don't configure any API key environment variables?

If neither GODMODE_API_KEY nor GODMODE_API_KEYS is set, the middleware logs a warning at startup and enters open-development mode. All requests are treated as anonymous and assigned the free tier automatically, bypassing authentication entirely. This mode is intended for local development only.

Why does the middleware use timingSafeEqual instead of a simple string comparison?

The middleware uses timingSafeEqual (lines 33-40 in api/middleware/auth.ts) to perform constant-time comparison of API keys. Standard string comparisons short-circuit when they encounter a mismatch, creating timing differences that attackers could measure to guess valid keys byte-by-byte. Constant-time comparison eliminates this side channel.

How does the API determine which tier to assign to an authenticated request?

After validating the API key, the middleware calls the tier resolution system in api/lib/tiers.ts (lines 36-40). It maps the raw API key to a tier configuration (free, pro, or enterprise). Keys without explicit mappings default to the free tier, and anonymous requests in open-development mode also receive free tier access.

What is the difference between the 401 and 403 HTTP status codes in this authentication system?

The middleware returns 401 Unauthorized when the Authorization header is missing, empty, or does not follow the Bearer <token> format (lines 68-73). It returns 403 Forbidden when the header is present and well-formed, but the provided API key does not match any key in the configured list (lines 78-82). This follows standard HTTP semantics where 401 indicates authentication is required or malformed, while 403 indicates the credentials are invalid.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →