@erikey/node
v0.1.1
Published
Node.js SDK for Erikey - Server-side authentication and API key management
Maintainers
Readme
@auth-ai/node
Node.js SDK for Auth.ai - Comprehensive server-side authentication and API key management.
Features
- 🔐 Multi-Strategy Session Validation
- JWT (stateless, fastest)
- Bearer tokens
- Cookie-based sessions
- 🔑 API Key Management
- Create, verify, revoke API keys
- Usage tracking and analytics
- Permission-based access control
- 👥 Admin Operations
- User management (CRUD)
- Organization management
- Permission management
- 🚀 Framework Support
- Express middleware
- Hono middleware
- Framework-agnostic core
- 📦 Tree-Shakeable
- Modular exports
- Import only what you need
Installation
npm install @auth-ai/node
# or
pnpm add @auth-ai/node
# or
yarn add @auth-ai/nodeQuick Start
import { createAuthClient } from '@auth-ai/node';
// Create client
const authClient = createAuthClient({
authUrl: 'https://api.auth.ai',
apiKey: process.env.AUTH_AI_API_KEY, // Optional for admin operations
});
// Validate session
const result = await authClient.validateSession(request);
if (result.session) {
console.log('Authenticated user:', result.session.user);
}Zero-Config API Key Verification
For simple, zero-configuration API key verification (Unkey-style):
import { verifyKey } from '@erikey/node';
// Simple verification
const { result, error } = await verifyKey({ key: 'your-api-key' });
if (error) {
console.error('Verification failed:', error.message);
return;
}
console.log('Valid key:', result.valid);
console.log('Owner:', result.ownerId);
console.log('Permissions:', result.permissions);Identity Grouping
Use the identity parameter to group multiple API keys for shared rate limiting:
// Keys with the same identity share rate limits
const { result, error } = await verifyKey({
key: 'your-api-key',
identity: 'mobile-app' // Groups keys for shared rate limiting
});Use Cases for Identity Grouping:
- Multiple rotating keys: Group backup keys for the same application
- Environment separation:
"production","staging","development" - API tier isolation:
"public-api","internal-api","webhooks"
Permission Checking
const { result, error } = await verifyKey({
key: 'your-api-key',
requiredPermissions: ['users.read', 'users.write']
});
if (error?.code === 'INSUFFICIENT_PERMISSIONS') {
console.log('Missing permissions:', error.details?.missingPermissions);
}Cost Tracking
const { result, error } = await verifyKey({
key: 'your-api-key',
ratelimits: [
{ name: 'requests', cost: 1 },
{ name: 'tokens', cost: 150 } // Track token usage
]
});
console.log('Rate limits:', result.ratelimit);Session Validation
Auto-Detection (Recommended)
// Automatically detects JWT, Bearer, or Cookie
const result = await authClient.validateSession(request);
if (result.session) {
console.log('User:', result.session.user);
console.log('Strategy used:', result.strategy); // 'jwt' | 'bearer' | 'cookie'
} else {
console.error('Error:', result.error);
}Explicit Strategy
// JWT validation (fastest, no API call)
const jwtResult = await authClient.validateJWT(token);
// Bearer token (requires API call)
const bearerResult = await authClient.validateBearer(token);
// Cookie (requires API call)
const cookieResult = await authClient.validateCookie(cookieHeader);Require Authentication
try {
const session = await authClient.requireAuth(request);
// Session guaranteed to exist here
console.log('User:', session.user);
} catch (error) {
console.error('Not authenticated:', error.message);
}API Key Management
Create API Key
const apiKey = await authClient.keys.create({
name: 'Production API',
userId: 'user-123',
expiresIn: 365 * 24 * 60 * 60, // 1 year in seconds
permissions: [
{ resource: 'api', actions: ['read', 'write'] }
],
metadata: {
environment: 'production'
}
});
console.log('API Key:', apiKey.key);Verify API Key
const result = await authClient.keys.verify(apiKey, {
trackUsage: true, // Increment usage counter
requiredPermissions: [
{ resource: 'api', actions: ['read'] }
]
});
if (result.valid) {
console.log('Valid key:', result.key);
} else {
console.error('Invalid:', result.error);
}Usage Analytics
const stats = await authClient.keys.getUsage(keyId);
console.log('Total requests:', stats.totalRequests);
console.log('Last used:', stats.lastUsed);
console.log('Requests by day:', stats.requestsByDay);Manage Keys
// List keys
const keys = await authClient.keys.list(userId);
// Update key
await authClient.keys.update(keyId, {
name: 'Updated Name',
metadata: { updated: true }
});
// Revoke key
await authClient.keys.revoke(keyId);Admin Operations
User Management
// List users
const { users, total } = await authClient.admin.users.list({
limit: 10,
offset: 0,
sortBy: 'createdAt',
sortOrder: 'desc'
});
// Create user
const user = await authClient.admin.users.create({
email: '[email protected]',
password: 'secure-password',
name: 'John Doe',
emailVerified: true
});
// Update user
await authClient.admin.users.update(userId, {
name: 'Jane Doe',
emailVerified: true
});
// Delete user
await authClient.admin.users.delete(userId);Permissions
// Check permission
const hasPermission = await authClient.admin.users.hasPermission(
userId,
'admin.users.create'
);
// Grant permissions
await authClient.admin.users.grantPermissions(userId, [
'admin.users.read',
'admin.users.create'
]);
// Revoke permissions
await authClient.admin.users.revokePermissions(userId, [
'admin.users.delete'
]);Organization Management
// List organizations
const orgs = await authClient.admin.organizations.list();
// Create organization
const org = await authClient.admin.organizations.create({
name: 'Acme Corp',
slug: 'acme-corp',
logo: 'https://example.com/logo.png'
});
// Add member
await authClient.admin.organizations.addMember(
orgId,
userId,
'admin' // role
);
// Remove member
await authClient.admin.organizations.removeMember(orgId, userId);Middleware
Express
import express from 'express';
import { createAuthMiddleware } from '@auth-ai/node/middleware';
const app = express();
// Require authentication
app.use('/api/protected', createAuthMiddleware({
authUrl: 'https://api.auth.ai',
optional: false // Reject unauthenticated requests
}));
// Optional authentication
app.use('/api/public', createAuthMiddleware({
authUrl: 'https://api.auth.ai',
optional: true // Allow unauthenticated requests
}));
// Access session in routes
app.get('/api/protected/me', (req, res) => {
res.json({ user: req.user }); // Injected by middleware
});Hono
import { Hono } from 'hono';
import { createAuthMiddleware } from '@auth-ai/node/middleware';
const app = new Hono();
// Add middleware
const auth = createAuthMiddleware({
authUrl: 'https://api.auth.ai'
});
app.use('/api/protected/*', auth);
// Access session in routes
app.get('/api/protected/me', (c) => {
const user = c.get('user');
return c.json({ user });
});Cloudflare Workers
import { createAuthClient } from '@auth-ai/node';
export default {
async fetch(request: Request, env: Env) {
const authClient = createAuthClient({
authUrl: 'https://api.auth.ai'
});
// Validate session
const result = await authClient.validateSession(request);
if (!result.session) {
return new Response('Unauthorized', { status: 401 });
}
// Track API key usage if present
const apiKey = request.headers.get('X-API-Key');
if (apiKey) {
await authClient.keys.verify(apiKey, { trackUsage: true });
}
// Process authenticated request
return new Response(JSON.stringify({ user: result.session.user }));
}
};Configuration
const authClient = createAuthClient({
// Base URL for Auth.ai API (default: 'https://api.auth.ai')
authUrl: 'https://api.auth.ai',
// API key for server-to-server authentication (optional)
apiKey: process.env.AUTH_AI_API_KEY,
// Validation strategy configuration
validation: {
strategies: ['jwt', 'bearer', 'cookie'], // Enabled strategies
preferJWT: true, // Try JWT first for performance
jwksCacheTTL: 3600 // JWKS cache duration in seconds
},
// Cookie configuration
cookie: {
prefix: 'auth-ai', // Cookie prefix
sessionName: 'session-token' // Session cookie name
},
// JWT configuration
jwt: {
issuer: 'https://api.auth.ai',
audience: 'https://api.auth.ai'
}
});Modular Imports
Import only what you need for smaller bundle sizes:
// Just validation
import { SessionValidator } from '@auth-ai/node/validator';
// Just API keys
import { APIKeyClient } from '@auth-ai/node/keys';
// Just middleware
import { createExpressMiddleware } from '@auth-ai/node/middleware';TypeScript Support
Full TypeScript support with comprehensive types:
import type {
Session,
User,
APIKey,
ValidationResult,
AuthAIConfig
} from '@auth-ai/node';License
MIT
