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:
| Signal | What It Detects |
|---|---|
failed_login | Too many failed login attempts in a time window |
new_device | Login from a device not seen before |
impossible_travel | Login from a location physically impossible given the last login time and distance |
velocity_spike | Abnormally high request rate from one user |
credential_stuffing | Pattern of rapid failed attempts across multiple accounts from one IP |
token_reuse | Attempt to use a token that has been invalidated |
Threat Levels and Actions
| Level | Score Range | Action |
|---|---|---|
safe | 0 | allow |
low | 1-3 | allow (may reduce TTL) |
medium | 4-6 | challenge_mfa |
high | 7-8 | throttle |
critical | 9-10 | block |
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 countsNext Steps
- Smart Model Routing -- use the same Cortex instance for AI routing
- Self-Healing -- auto-fix production issues behind auth
- Error Tracking -- track errors with user context from auth sessions