JWT auth at the edge with threat detection — rate limiting, impossible travel, and credential stuffing protection.

Edge Authentication

The Cortex class from @codmir/cortex combines JWT authentication with real-time threat detection. It runs at the edge, assesses every login attempt for fraud signals, and automatically adjusts token TTL or blocks suspicious requests.

Create a Cortex Instance

import { createCortex } from '@codmir/cortex';

const cortex = createCortex({
  auth: {
    jwtSecret: process.env.JWT_SECRET!,
    jwtIssuer: 'my-app',
    accessTokenTtl: 900,          // 15 minutes
    refreshTokenTtl: 30 * 86400,  // 30 days
  },
  threat: {
    maxFailedAttempts: 5,
    failedAttemptWindowMs: 15 * 60 * 1000, // 15 minutes
    velocityThreshold: 10,
    velocityWindowMs: 60 * 1000,           // 1 minute
    impossibleTravelSpeedKmh: 1000,
    minTtlSeconds: 60,
    maxTtlSeconds: 3600,
  },
  models: [],
  router: {},
  scheduler: {},
  healer: {},
  mesh: {},
});

Create a Session

Issue tokens when a user logs in:

const { accessToken, refreshToken, cortexSessionId } = await cortex.createSession(
  {
    id: 'user-123',
    email: 'user@example.com',
    name: 'Jane Developer',
    role: 'admin',
  },
  {
    ip: request.headers['x-forwarded-for'] as string,
    userAgent: request.headers['user-agent'] as string,
    deviceId: request.headers['x-device-id'] as string,
  },
);

// Return tokens to client
return {
  accessToken,
  refreshToken,
  sessionId: cortexSessionId,
};

Authenticate Requests

Validate tokens on every request. The authenticate method verifies the JWT and runs threat assessment in a single call:

const session = await cortex.authenticate(
  request.headers.authorization?.replace('Bearer ', '') ?? '',
  {
    userId: 'user-123',
    ip: request.ip,
    deviceId: request.headers['x-device-id'] as string,
    userAgent: request.headers['user-agent'] as string,
    location: { lat: 37.7749, lon: -122.4194 }, // Optional geolocation
  },
);

if (!session) {
  return { status: 401, body: 'Unauthorized' };
}

// Session includes threat assessment
console.log(session.threatAssessment.level);  // 'safe' | 'low' | 'medium' | 'high' | 'critical'
console.log(session.threatAssessment.action); // 'allow' | 'challenge_mfa' | 'throttle' | 'block'
console.log(session.userId);

Threat Detection

The ThreatDetector analyzes authentication events for these signals:

SignalWhat It Detects
failed_loginToo many failed login attempts in a time window
new_deviceLogin from a device not seen before
impossible_travelLogin from a location physically impossible given the last login time and distance
velocity_spikeAbnormally high request rate from one user
credential_stuffingPattern of rapid failed attempts across multiple accounts from one IP
token_reuseAttempt to use a token that has been invalidated

Threat Levels and Actions

LevelScore RangeAction
safe0allow
low1-3allow (may reduce TTL)
medium4-6challenge_mfa
high7-8throttle
critical9-10block

Standalone Threat Assessment

Run threat detection without full authentication:

const assessment = cortex.assessThreat({
  userId: 'user-123',
  ip: '203.0.113.42',
  success: false,
  timestamp: Date.now(),
  location: { lat: 40.7128, lon: -74.0060 },
  userAgent: 'Mozilla/5.0...',
});

if (assessment.requiresMfa) {
  // Prompt for MFA
}

if (assessment.adjustedTtl) {
  // Use shorter token TTL
}

Token Refresh

Refresh expired access tokens using the refresh token:

const newTokens = await cortex.refresh({
  refreshToken: request.body.refreshToken,
  ip: request.ip,
  userAgent: request.headers['user-agent'] as string,
});

if (!newTokens) {
  return { status: 401, body: 'Refresh token expired or invalid' };
}

return {
  accessToken: newTokens.accessToken,
  refreshToken: newTokens.refreshToken,
};

Logout

Invalidate the session:

await cortex.logout(accessToken);

Observability

Listen for auth and threat events:

cortex.on((event) => {
  switch (event.type) {
    case 'auth':
      console.log('Auth result:', event.payload.authResult.valid);
      console.log('Threat:', event.payload.assessment.level);
      break;
    case 'threat':
      console.warn('Threat blocked:', event.payload.userId);
      break;
  }
});

Get the full intelligence report including threat stats:

const report = cortex.getIntelligenceReport();
console.log(report.threat); // Failed attempts, blocked IPs, signal counts

Next Steps