@iota-big3/sdk-auth
v1.0.0
Published
Enterprise-grade authentication with Zero Trust architecture
Maintainers
Readme
@iota-big3/sdk-auth
Enterprise-grade authentication with Zero Trust architecture for the IOTA Big3 SDK.
Features
- 🔐 JWT Authentication - Secure token-based authentication
- 🔑 OAuth 2.0 / OIDC - Support for Google, Microsoft, Okta, and more
- 🏢 SAML 2.0 - Enterprise SSO integration
- 📱 Multi-Factor Authentication - TOTP, SMS, Email, WebAuthn
- 🛡️ Zero Trust Security - Continuous verification and risk scoring
- 👥 RBAC & ABAC - Role and attribute-based access control
- 🔒 API Key Management - Secure API key generation and validation
- 📊 Audit Trail - Comprehensive authentication event logging
- ⚡ High Performance - Redis-backed sessions and caching
- 🔄 Token Refresh - Automatic token renewal
Installation
npm install @iota-big3/sdk-auth @iota-big3/sdk-coreSDK Integrations
The auth SDK integrates seamlessly with other IOTA Big3 SDKs to provide a complete authentication solution:
Database Integration (@iota-big3/sdk-database)
Store users, sessions, and auth data persistently:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
database: {
type: "postgres",
host: "localhost",
database: "myapp",
user: "dbuser",
password: "dbpass",
},
});
// Auth data is now persisted to database
// Falls back to in-memory storage if database is unavailableEvent Bus Integration (@iota-big3/sdk-events)
Emit and listen to authentication events across your application:
import { EventBus } from "@iota-big3/sdk-events";
import { AuthManager } from "@iota-big3/sdk-auth";
const eventBus = new EventBus();
const auth = new AuthManager({
jwtSecret: "your-secret",
eventBus,
});
// Listen to auth events
eventBus.on("auth:user.created", (event) => {
console.log("New user:", event.userId, event.email);
});
eventBus.on("auth:login.success", (event) => {
console.log("User logged in:", event.userId, event.method);
});
eventBus.on("auth:security.anomaly_detected", (event) => {
console.log("Security alert:", event.type, event.riskScore);
});
// Auth SDK also listens to events from other SDKs
eventBus.emit("security:threat.detected", {
userId: "user123",
threatType: "credential_stuffing",
severity: "critical",
});
// This will automatically lock the user accountLogging Integration (@iota-big3/sdk-observability)
Comprehensive logging for security and debugging:
const auth = new AuthManager({
jwtSecret: "your-secret",
logging: {
level: "info",
format: "json",
enabled: true,
},
});
// All auth operations are now logged
// Includes structured logging for security eventsCache Integration (@iota-big3/sdk-performance)
High-performance session management and rate limiting:
const auth = new AuthManager({
jwtSecret: "your-secret",
cache: {
type: "redis",
redis: {
host: "localhost",
port: 6379,
},
},
});
// Sessions are cached in Redis for fast access
// Rate limiting uses Redis for distributed trackingCombined Integration Example
import { EventBus } from "@iota-big3/sdk-events";
import { AuthManager } from "@iota-big3/sdk-auth";
// Initialize with all integrations
const eventBus = new EventBus();
const auth = new AuthManager({
jwtSecret: process.env.JWT_SECRET,
// Database for persistence
database: {
type: "postgres",
host: process.env.DB_HOST,
database: process.env.DB_NAME,
},
// Event bus for real-time events
eventBus,
// Logging for monitoring
logging: {
level: "info",
enabled: true,
},
// Cache for performance
cache: {
type: "redis",
redis: {
host: process.env.REDIS_HOST,
},
},
// Enable features
enableRateLimiting: true,
enableRefreshTokens: true,
});
// Set up cross-SDK event handling
eventBus.on("user:profile.updated", async (event) => {
// Sync user metadata in auth system
await auth.updateUserMetadata(event.userId, event.changes);
});
eventBus.on("security:anomaly.detected", async (event) => {
if (event.riskScore > 90) {
// Force re-authentication for high-risk sessions
await auth.requireReAuthentication(event.userId);
}
});
// Auth events are automatically emitted
const user = await auth.registerUser({
email: "[email protected]",
password: "SecurePass123!",
});
// Emits: auth:user.created
const result = await auth.authenticate("[email protected]", "SecurePass123!");
// Emits: auth:login.success, auth:session.createdEvent Reference
Auth SDK emits the following events:
auth:user.created- New user registeredauth:user.updated- User profile updatedauth:user.deleted- User account deletedauth:user.locked- User account lockedauth:login.success- Successful authenticationauth:login.failed- Failed authentication attemptauth:logout.success- User logged outauth:mfa.enabled- MFA method enabledauth:mfa.verified- MFA challenge completedauth:security.anomaly_detected- Suspicious activity detectedauth:security.access_blocked- Access blocked by security rulesauth:permission.granted- Permission check passedauth:permission.denied- Permission check failedauth:session.created- New session startedauth:session.terminated- Session ended
Auth SDK listens to these external events:
user:account.deleted- Clean up auth data when user deletedsecurity:threat.detected- Lock account on critical threatssecurity:anomaly.detected- Force re-auth on high riskcompliance:audit.required- Enable detailed audit logging
Quick Start
import { AuthManager, createDefaultAuthConfig } from "@iota-big3/sdk-auth";
import { SDK } from "@iota-big3/sdk-core";
// Initialize SDK
const sdk = new SDK({
serviceName: "my-service",
industry: "education",
});
// Create auth configuration
const authConfig = createDefaultAuthConfig();
// Initialize AuthManager
const auth = new AuthManager(authConfig, sdk);
// Authenticate user
const tokens = await auth.authenticate("[email protected]", "password");
console.log(tokens.accessToken);
// Validate token
const payload = await auth.validateToken(tokens.accessToken);
console.log(payload.email);
// Check permissions
const user = await auth.findUserById(payload.sub);
const canRead = auth.hasPermission(user, "documents", "read");
// NEW Phase 2g Features:
// 1. Role-based permissions
auth.setRolePermissions({
admin: ["*:*"],
editor: ["read:*", "write:documents"],
viewer: ["read:documents"],
});
// 2. API Key Management
const apiKey = await auth.createAPIKey(user.id, "Production API", {
permissions: ["read:api", "write:api"],
expiresIn: 30 * 24 * 60 * 60, // 30 days
});
// 3. OAuth Integration
import { GoogleOAuthProvider } from "@iota-big3/sdk-auth";
const googleAuth = new GoogleOAuthProvider(clientId, clientSecret);
// 4. Express Middleware
import { requireAuth, requirePermissions } from "@iota-big3/sdk-auth";
app.get("/api/secure", requireAuth(auth), handler);
app.post("/api/admin", requirePermissions(auth, "admin:*"), handler);Integration with Other SDKs
With sdk-database
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
database: {
type: "postgres",
host: "localhost",
database: "myapp",
user: "dbuser",
password: "dbpass",
},
});
// Auth data will be persisted to database automaticallyWith sdk-events
import { EventBus } from "@iota-big3/sdk-events";
import { AuthManager } from "@iota-big3/sdk-auth";
const eventBus = new EventBus();
const auth = new AuthManager(config, eventBus);
// Listen to auth events
eventBus.on("auth:user.registered", (event) => {
console.log("New user registered:", event.data.userId);
});
eventBus.on("auth:user.authenticated", (event) => {
console.log("User logged in:", event.data.userId);
});With sdk-performance (Caching)
const auth = new AuthManager({
jwtSecret: "your-secret",
cache: {
type: "redis",
host: "localhost",
port: 6379,
ttl: 3600, // 1 hour
},
});
// Sessions and rate limiting will use Redis cacheRedis Session Management
// When Redis is configured, AuthManager automatically:
// 1. Stores sessions in Redis with TTL
// 2. Uses Redis for distributed rate limiting
// 3. Enables session sharing across instances
const auth = new AuthManager({
jwtSecret: "your-secret",
cache: {
type: "redis",
host: process.env.REDIS_HOST,
port: 6379,
password: process.env.REDIS_PASSWORD,
},
});
// Sessions are automatically synced across all instances
// Rate limiting works across distributed systems
// Perfect for microservices and serverless deploymentsEnhanced Rate Limiting
The SDK now includes advanced rate limiting features:
// Configure enhanced rate limiting
const auth = new AuthManager({
jwtSecret: "your-secret",
enableRateLimiting: true,
rateLimitConfig: {
windowMs: 15 * 60 * 1000, // 15 minutes
maxRequests: 100,
strategy: "sliding-window", // 'fixed-window' | 'sliding-window'
headers: true, // Include rate limit headers
keyGenerator: (identifier, context) => {
// Custom key generation
if (context?.userId) {
return `user:${context.userId}:${context.endpoint}`;
}
return `ip:${context.ipAddress}:${context.endpoint}`;
},
},
});Rate Limiting Strategies
- Fixed Window: Traditional approach, resets at fixed intervals
- Sliding Window: More accurate, prevents burst attacks at window boundaries
Rate Limiting Middleware
import {
createRateLimitMiddleware,
createAuthenticatedRateLimitMiddleware,
createApiKeyRateLimitMiddleware,
} from "@iota-big3/sdk-auth";
// IP-based rate limiting
app.use(createRateLimitMiddleware(auth));
// User-based rate limiting
app.use(
"/api/protected",
createAuthenticatedRateLimitMiddleware(auth, {
skip: (req) => req.user?.roles?.includes("admin"), // Skip for admins
})
);
// API key rate limiting
app.use("/api/v1", createApiKeyRateLimitMiddleware(auth));Response Headers
When rate limiting is enabled with headers:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890
Retry-After: 60 (only when rate limited)Custom Rate Limit Context
const rateLimitResult = await auth.checkRateLimit("identifier", {
ipAddress: "192.168.1.1",
userId: "user123",
endpoint: "/api/data",
method: "POST",
});
console.log(rateLimitResult.info); // { limit, remaining, resetAt, retryAfter }With sdk-observability
const auth = new AuthManager({
jwtSecret: "your-secret",
logging: {
level: "info",
format: "json",
enabled: true,
},
});
// All auth operations will be loggedComplete Integration Example
import { EventBus } from "@iota-big3/sdk-events";
import { AuthManager } from "@iota-big3/sdk-auth";
// Initialize with all integrations
const eventBus = new EventBus();
const auth = new AuthManager(
{
jwtSecret: process.env.JWT_SECRET,
database: {
type: "postgres",
host: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
},
cache: {
type: "redis",
host: process.env.REDIS_HOST,
port: 6379,
},
logging: {
level: "info",
format: "json",
},
},
eventBus
);
// The SDK automatically:
// - Persists users and sessions to PostgreSQL
// - Caches sessions in Redis for fast validation
// - Logs all operations with structured logging
// - Emits events for other SDKs to react toEvent Integration
sdk-auth emits the following events that other SDKs can listen to:
auth:initialized- Auth manager initialized with integrationsauth:user.registered- New user registeredauth:user.authenticated- User successfully logged inauth:user.logout- User logged outauth:user.cleanup- User data cleaned up (on deletion)auth:user.force_logout- User forcefully logged out (security)auth:token.refreshed- Token refreshedauth:failed_login- Failed login attemptauth:api_key.created- API key createdauth:api_key.revoked- API key revoked
sdk-auth listens to these events from other SDKs:
user:deleted- Cleans up all auth data for deleted usersecurity:threat.detected- Forces logout for compromised user
Configuration
Basic Configuration
const authConfig = {
jwt: {
secret: process.env.JWT_SECRET,
accessTokenExpiry: "1h",
refreshTokenExpiry: "7d",
issuer: "your-app",
audience: "your-api",
},
session: {
secret: process.env.SESSION_SECRET,
maxAge: 86400000, // 24 hours
secure: true,
httpOnly: true,
},
passwordPolicy: {
minLength: 8,
requireUppercase: true,
requireLowercase: true,
requireNumbers: true,
requireSpecialChars: true,
},
};Zero Trust Configuration
const authConfig = {
// ... other config
zeroTrust: {
enabled: true,
deviceTrust: true,
continuousVerification: true,
riskScoring: true,
},
};OAuth/OIDC Integration
const authConfig = {
oauth: {
providers: [
{
name: "google",
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorizationURL: "https://accounts.google.com/o/oauth2/v2/auth",
tokenURL: "https://oauth2.googleapis.com/token",
userInfoURL: "https://www.googleapis.com/oauth2/v2/userinfo",
scope: ["openid", "email", "profile"],
},
],
},
};Multi-Factor Authentication
// Enable MFA for user
await auth.enableMFA(user.id, "totp");
// Generate QR code for TOTP setup
const qrCode = await auth.generateMFAQRCode(user.id);
// Verify MFA token
const valid = await auth.verifyMFAToken(user.id, "123456");API Key Management
// Create API key
const apiKey = await auth.createAPIKey(user.id, "Production API Key", [
{ resource: "documents", action: "read" },
{ resource: "documents", action: "write" },
]);
// Validate API key
const keyData = await auth.validateAPIKey(apiKey.key);Middleware Integration
import express from "express";
import { authMiddleware } from "@iota-big3/sdk-auth/middleware";
const app = express();
// Protect all routes
app.use(authMiddleware(auth));
// Protect specific routes
app.get(
"/api/protected",
authMiddleware(auth, {
permissions: ["documents:read"],
}),
(req, res) => {
res.json({ user: req.user });
}
);Security Best Practices
- Always use environment variables for secrets
- Enable MFA for privileged accounts
- Implement rate limiting on authentication endpoints
- Use secure session configuration in production
- Enable Zero Trust features for sensitive applications
- Regularly rotate JWT secrets and API keys
- Monitor authentication events for anomalies
Compliance
This package supports compliance with:
- SOC 2 - Comprehensive audit logging
- HIPAA - Strong encryption and access controls
- GDPR - Data protection and privacy controls
- FERPA - Educational privacy requirements
Performance
- JWT validation: <1ms
- Session lookup: <5ms (Redis-backed)
- Permission checks: <1ms (in-memory)
- Risk scoring: <10ms
License
MIT
Priority 2: Advanced Auth Features
SAML 2.0 Support
The SDK now includes comprehensive SAML 2.0 support for enterprise SSO:
import { SAMLProvider } from "@iota-big3/sdk-auth";
const samlProvider = new SAMLProvider({
entryPoint: "https://idp.example.com/sso",
issuer: "https://myapp.example.com",
cert: "MIID...", // IdP certificate
callbackUrl: "https://myapp.example.com/auth/saml/callback",
identifierFormat: "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
});
// Express routes
app.get("/auth/saml/login", samlProvider.middleware().login);
app.post("/auth/saml/callback", samlProvider.middleware().callback);
app.get("/auth/saml/metadata", samlProvider.middleware().metadata);
app.get("/auth/saml/logout", samlProvider.middleware().logout);Microsoft & Okta OAuth Providers
New OAuth providers for enterprise identity providers:
Microsoft (Azure AD)
import { MicrosoftOAuthProvider } from "@iota-big3/sdk-auth";
const microsoftProvider = new MicrosoftOAuthProvider({
clientId: process.env.AZURE_CLIENT_ID!,
clientSecret: process.env.AZURE_CLIENT_SECRET!,
redirectUri: "https://myapp.com/auth/microsoft/callback",
tenant: "common", // or specific tenant ID
scopes: ["openid", "profile", "email", "User.Read"],
});
// Get Microsoft Graph user profile
const user = await microsoftProvider.getUserProfile(accessToken);Okta
import { OktaOAuthProvider } from "@iota-big3/sdk-auth";
const oktaProvider = new OktaOAuthProvider({
clientId: process.env.OKTA_CLIENT_ID!,
clientSecret: process.env.OKTA_CLIENT_SECRET!,
domain: "dev-123456.okta.com",
redirectUri: "https://myapp.com/auth/okta/callback",
authorizationServerId: "default",
});
// Okta-specific features
const logoutUrl = oktaProvider.getLogoutUrl(idToken, postLogoutRedirectUri);Comprehensive Audit Trail
Track all authentication events for security and compliance:
const auth = new AuthManager({
jwtSecret: "your-secret",
auditTrailConfig: {
enabled: true,
retention: {
days: 90,
maxRecords: 1000000,
},
filters: {
excludeActions: ["auth:token_refreshed"],
},
anonymize: {
ipAddress: true,
userAgent: false,
},
},
});
// Query audit logs
const auditTrail = auth.getAuditTrail();
const events = await auditTrail.query({
userId: "user123",
action: "auth:login",
startDate: new Date("2023-01-01"),
limit: 100,
});
// Get user activity summary
const summary = await auditTrail.getUserSummary(userId, 30);
console.log(`Failed logins: ${summary.failedLoginCount}`);
// Generate security report
const report = await auditTrail.getSecurityReport(7);
console.log(`Suspicious activities: ${report.suspiciousActivities}`);Audit Events Tracked
auth:login- Successful loginauth:logout- User logoutauth:mfa_enabled- MFA enabledauth:mfa_verified- MFA verificationauth:password_changed- Password changeauth:account_locked- Account lockedauth:role_assigned- Role assignmentauth:api_key_created- API key creationauth:rate_limit_exceeded- Rate limit hitauth:suspicious_activity- Security alerts
Custom Audit Storage
class DatabaseAuditStorage implements AuditStorage {
async store(event: AuditEvent): Promise<void> {
await db.insert("audit_logs", event);
}
async query(options: AuditQueryOptions): Promise<AuditEvent[]> {
return await db.select("audit_logs", options);
}
async cleanup(before: Date): Promise<number> {
return await db.delete("audit_logs", { timestamp: { $lt: before } });
}
}
const auth = new AuthManager({
auditTrailConfig: {
enabled: true,
storage: new DatabaseAuditStorage(),
},
});Phase 2g: Feature Flags & Enhanced Security
Feature Flags System
The SDK includes a comprehensive feature flags system for safe rollout of new features:
import { AuthManager, defaultAuthFeatureFlags } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
featureFlags: defaultAuthFeatureFlags,
featureFlagsStorage: "redis", // or 'memory', 'database'
});
// Check if feature is enabled
const featureFlags = auth.getFeatureFlags();
if (featureFlags.isEnabled("webauthn", { userId: user.id })) {
// Use WebAuthn
}
// Gradual rollout
featureFlags.enable("zero-trust-scoring");
featureFlags.setRolloutPercentage("zero-trust-scoring", 25); // 25% of users
// Enable for specific users/roles
featureFlags.enableFor("delegation", ["user123", "role:admin"]);Available Feature Flags
- webauthn - WebAuthn/FIDO2 passwordless authentication
- sms-mfa - SMS-based multi-factor authentication
- email-mfa - Email-based multi-factor authentication
- zero-trust-scoring - Continuous verification with risk scoring
- saml-signature-verification - Full SAML signature verification
- password-policy - Configurable password requirements
- account-recovery - Self-service password reset
- delegation - User impersonation for admins
- session-anomaly-detection - Detect unusual session behavior
- geo-location-access - Location-based access control
Enhanced SAML Signature Verification
SAML signature verification is now feature-flagged for safe rollout:
// Enable SAML signature verification gradually
const featureFlags = auth.getFeatureFlags();
// Start with 10% of users
featureFlags.setRolloutPercentage("saml-signature-verification", 10);
// Monitor and increase
featureFlags.setRolloutPercentage("saml-signature-verification", 50);
// Full rollout when confident
featureFlags.setRolloutPercentage("saml-signature-verification", 100);Zero Trust Scoring
Implement continuous risk-based authentication:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
zeroTrust: {
lowRiskThreshold: 30,
mediumRiskThreshold: 60,
highRiskThreshold: 80,
weights: {
deviceTrust: 30,
locationTrust: 25,
behaviorTrust: 20,
timeTrust: 15,
networkTrust: 10,
},
},
});
// Calculate risk score during authentication
const riskFactors = {
deviceId: request.deviceId,
isKnownDevice: false,
ipAddress: request.ip,
country: geoIP.country,
isVpn: detectVPN(request.ip),
loginTime: new Date(),
failedAttempts: 0,
authMethod: "password",
};
const riskScore = await auth.calculateRiskScore(userId, riskFactors);
if (riskScore.level === "critical") {
// Block access
return res.status(403).json({
error: "Access denied due to high risk",
recommendations: riskScore.recommendations,
});
}
if (riskScore.level === "high") {
// Require step-up authentication
return res.status(401).json({
error: "Additional verification required",
mfaRequired: true,
});
}
// Make authentication decisions
const zeroTrust = auth.getZeroTrust();
const decision = zeroTrust.makeAuthDecision(riskScore);
if (!decision.allow) {
return res.status(403).json({ error: decision.reason });
}
if (decision.requireMfa) {
// Trigger MFA flow
}
// Apply restrictions if needed
req.restrictions = decision.restrictions; // e.g., ['read-only', 'no-admin']Trusted Device Management
// Add trusted device
await zeroTrust.addTrustedDevice(userId, {
deviceId: "device-uuid",
fingerprint: "browser-fingerprint",
name: "John's MacBook",
platform: "macOS",
browser: "Chrome",
});
// Check if device is trusted
const isTrusted = await zeroTrust.isDeviceTrusted(
userId,
deviceId,
fingerprint
);
// List user's trusted devices
const devices = await zeroTrust.getTrustedDevices(userId);
// Remove trusted device
await zeroTrust.removeTrustedDevice(userId, deviceId);Location-Based Risk Assessment
// Add trusted location
await zeroTrust.addTrustedLocation(userId, {
name: "Home Office",
latitude: 37.7749,
longitude: -122.4194,
radius: 5, // 5km radius
country: "US",
city: "San Francisco",
});
// Check if current location is trusted
const isLocationTrusted = await zeroTrust.isLocationTrusted(
userId,
currentLat,
currentLon
);
// Detect impossible travel
const isPossible = zeroTrust.isPossibleTravel(
{ latitude: prevLat, longitude: prevLon, timestamp: prevTime },
{ latitude: currLat, longitude: currLon, timestamp: currTime },
900 // Max 900 km/h (flight speed)
);Behavioral Analysis
// Update user baseline with login patterns
await zeroTrust.updateUserBaseline(userId, {
loginTime: new Date(),
country: "US",
deviceId: "device-123",
sessionDuration: 120, // minutes
});
// Check if login time is typical
const isTypicalTime = zeroTrust.isTypicalLoginTime(userId, new Date());
// Get user's behavioral baseline
const baseline = await zeroTrust.getUserBaseline(userId);Session Risk Monitoring
// Create risk-aware session
const session = await zeroTrust.createSession(userId, sessionId, {
deviceId: deviceId,
ipAddress: request.ip,
authMethod: "mfa",
});
// Monitor session activities
await zeroTrust.recordSessionActivity(sessionId, {
action: "data_export",
resource: "/api/sensitive-data",
result: "success",
});
// Get current session risk
const sessionRisk = await zeroTrust.getSessionRisk(sessionId);
if (sessionRisk.currentRiskScore.level === "high") {
// Force re-authentication or terminate session
}Risk Policies
Define custom risk policies:
// Add policy for VPN users
await zeroTrust.addRiskPolicy({
id: "vpn-policy",
name: "VPN Access Policy",
enabled: true,
conditions: [{ factor: "isVpn", operator: "eq", value: true }],
actions: [RecommendedAction.REQUIRE_MFA, RecommendedAction.LIMIT_ACCESS],
priority: 1,
});
// Add policy for suspicious countries
await zeroTrust.addRiskPolicy({
id: "country-block",
name: "High-Risk Country Block",
enabled: true,
conditions: [
{ factor: "country", operator: "in", value: ["XX", "YY", "ZZ"] },
{ factor: "isKnownDevice", operator: "eq", value: false },
],
actions: [RecommendedAction.BLOCK_ACCESS],
priority: 0, // Highest priority
});Risk Event Handling
// Listen for risk events
zeroTrust.on("risk:threshold_exceeded", (event) => {
console.log(`Risk threshold exceeded for user ${event.userId}`);
console.log(`Score changed from ${event.previousScore} to ${event.newScore}`);
// Send security alert
sendSecurityAlert({
userId: event.userId,
riskLevel: event.newScore,
recommendedActions: event.recommendedActions,
});
});Integration with Express Middleware
const zeroTrustMiddleware = (requiredLevel: "low" | "medium" = "medium") => {
return async (req, res, next) => {
if (!req.user) return next();
const factors = {
deviceId: req.headers["x-device-id"],
ipAddress: req.ip,
userAgent: req.headers["user-agent"],
// ... collect other factors
};
const riskScore = await auth.calculateRiskScore(req.user.id, factors);
// Store risk score in request
req.riskScore = riskScore;
// Check if risk level is acceptable
const levels = ["low", "medium", "high", "critical"];
const requiredIndex = levels.indexOf(requiredLevel);
const actualIndex = levels.indexOf(riskScore.level);
if (actualIndex > requiredIndex) {
return res.status(403).json({
error: "Risk level too high",
riskLevel: riskScore.level,
recommendations: riskScore.recommendations,
});
}
next();
};
};
// Protect sensitive routes
app.get(
"/api/admin/*",
authenticate,
zeroTrustMiddleware("low"),
adminController
);Phase 2g: Next Generation Features
WebAuthn/FIDO2 Support
Enable passwordless authentication with biometrics and security keys:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
webauthn: {
rpId: "example.com",
rpName: "My App",
origin: "https://example.com",
},
});
// Check if WebAuthn is enabled
const webauthn = auth.getWebAuthn();
if (webauthn) {
// Registration
const regOptions = await webauthn.generateRegistrationOptions({
userId: user.id,
userName: user.email,
userDisplayName: user.name,
rpName: "My App",
rpId: "example.com",
});
// Send options to client for WebAuthn ceremony
// Client returns registration result
const verification = await webauthn.verifyRegistration(
regOptions.challenge,
registrationResult,
user.id
);
if (verification.verified) {
// Credential registered successfully
}
// Authentication
const authOptions = await webauthn.generateAuthenticationOptions({
userId: user.id,
rpId: "example.com",
});
// Client performs authentication ceremony
const authVerification = await webauthn.verifyAuthentication(
authOptions.challenge,
authenticationResult
);
}Managing WebAuthn Credentials
// List user credentials
const credentials = await webauthn.getUserCredentials(userId);
// Update credential name
await webauthn.updateCredentialMetadata(userId, credentialId, {
name: "My YubiKey 5C",
});
// Delete credential
await webauthn.deleteCredential(userId, credentialId);Password Policy Engine
Enforce configurable password requirements:
import { AuthManager, PASSWORD_POLICY_PRESETS } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
passwordPolicy: PASSWORD_POLICY_PRESETS.enterprise,
// or custom policy:
// passwordPolicy: {
// minLength: 12,
// requireUppercase: true,
// requireLowercase: true,
// requireNumbers: true,
// requireSpecialChars: true,
// disallowCommonPasswords: true,
// disallowUserInfo: true
// }
});
const policy = auth.getPasswordPolicy();
if (policy) {
// Validate password
const result = policy.validate(password, {
user: {
email: user.email,
username: user.username,
previousPasswords: user.passwordHistory,
},
});
if (!result.isValid) {
console.log("Password errors:", result.errors);
console.log("Suggestions:", result.suggestions);
console.log("Strength:", result.score);
}
// Generate compliant password
const newPassword = policy.generatePassword({
length: 16,
memorable: true,
words: 4,
separator: "-",
});
}Policy Presets
- minimal: 8+ characters
- standard: 8+ chars, uppercase, lowercase, numbers
- strong: 12+ chars, all character types, no common passwords
- enterprise: 14+ chars, strict requirements, history check, expiry
Password Strength Analysis
const result = policy.validate("MyP@ssw0rd123");
console.log(result.score);
// {
// score: 85,
// strength: 'strong',
// entropy: 78.3,
// crackTime: {
// onlineThrottled: '3 years',
// onlineUnthrottled: '11 days',
// offlineSlow: '19 minutes',
// offlineFast: 'instant'
// }
// }Feature Flag Configuration
All Phase 2g features are protected by feature flags:
const auth = new AuthManager({
jwtSecret: "your-secret",
featureFlags: [
{ name: "webauthn", enabled: true },
{ name: "password-policy", enabled: true },
{ name: "zero-trust-scoring", enabled: false },
{
name: "password-policy",
enabled: true,
rolloutPercentage: 50, // Gradual rollout
},
],
});Express Integration Example
import express from "express";
const app = express();
// WebAuthn registration endpoint
app.post("/auth/webauthn/register/begin", async (req, res) => {
const webauthn = req.authManager.getWebAuthn();
if (!webauthn) {
return res.status(404).json({ error: "WebAuthn not enabled" });
}
const options = await webauthn.generateRegistrationOptions({
userId: req.user.id,
userName: req.user.email,
userDisplayName: req.user.name,
rpName: "My App",
rpId: req.hostname,
});
req.session.challenge = options.challenge;
res.json(options);
});
// Password validation middleware
const validatePassword = async (req, res, next) => {
const policy = req.authManager.getPasswordPolicy();
if (!policy) return next();
const result = policy.validate(req.body.password, {
user: {
email: req.body.email,
username: req.body.username,
},
});
if (!result.isValid) {
return res.status(400).json({
error: "Password does not meet requirements",
errors: result.errors,
suggestions: result.suggestions,
strength: result.score,
});
}
next();
};
app.post("/auth/register", validatePassword, async (req, res) => {
// Registration logic
});SMS/Email MFA
Multi-factor authentication via SMS and Email:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
smsMFA: {
provider: "twilio",
twilioConfig: {
accountSid: process.env.TWILIO_ACCOUNT_SID,
authToken: process.env.TWILIO_AUTH_TOKEN,
fromNumber: "+1234567890",
},
codeLength: 6,
codeExpiry: 5, // minutes
messageTemplate: "Your {appName} code: {code}",
},
emailMFA: {
provider: "smtp",
smtpConfig: {
host: "smtp.example.com",
port: 587,
auth: { user: "user", pass: "pass" },
},
from: "[email protected]",
codeExpiry: 10, // minutes
htmlTemplate: "<h1>Your code: {code}</h1>",
},
});
// Send SMS code
const smsResult = await auth.sendSMSCode(userId, "+1234567890");
// Send Email code
const emailResult = await auth.sendEmailCode(userId, "[email protected]");
// Verify code
const mfaManager = auth.getSMSEmailMFA();
const verifyResult = await mfaManager.verifyCode(smsResult.codeId, "123456");
if (verifyResult.verified) {
// Continue with authentication
}Custom Providers
// Custom SMS Provider
const customSMSProvider: SMSProvider = {
async sendSMS(to: string, message: string) {
// Your SMS logic
return { success: true, messageId: "xxx" };
},
validateNumber(phoneNumber: string) {
return /^\+[1-9]\d{1,14}$/.test(phoneNumber);
},
};
// Custom Email Provider
const customEmailProvider: EmailProvider = {
async sendEmail(options: EmailOptions) {
// Your email logic
return { success: true, messageId: "yyy" };
},
validateAddress(email: string) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
},
};
// Use custom providers
const auth = new AuthManager({
smsMFA: {
provider: "custom",
customProvider: customSMSProvider,
},
emailMFA: {
provider: "custom",
customProvider: customEmailProvider,
},
});Rate Limiting & Resend
// Configure rate limits
const mfaConfig = {
rateLimits: {
maxCodesPerHour: 5,
maxCodesPerDay: 20,
maxVerificationAttemptsPerCode: 3,
},
};
// Resend code (with delay enforcement)
const resendResult = await mfaManager.resendCode(codeId);
// Get MFA statistics
const stats = await mfaManager.getStatistics(userId, "day");
console.log(`SMS sent: ${stats.sms.sent}, verified: ${stats.sms.verified}`);Account Recovery
Self-service password reset with multiple verification methods:
import { AccountRecoveryManager } from "@iota-big3/sdk-auth";
// Initialize recovery manager
const recoveryManager = new AccountRecoveryManager(
{
methods: ["email", "sms", "security_questions", "backup_codes"],
tokenExpiry: 60, // minutes
maxAttempts: 3,
lockoutDuration: 60, // minutes
recoveryUrl: "https://app.example.com/reset-password",
emailTemplate: {
subject: "Reset Your Password",
htmlTemplate: '<a href="{link}">Reset Password</a>',
},
},
userStore, // Your user database interface
notificationService, // Email/SMS service
featureFlags
);
// Initiate recovery via email
const result = await recoveryManager.initiateRecovery(
"[email protected]",
"email"
);
// Verify token from email link
const verifyResult = await recoveryManager.verifyToken(token);
if (verifyResult.success) {
// Reset password
const resetResult = await recoveryManager.resetPassword(
verifyResult.sessionId,
"NewSecurePassword123!"
);
}Security Questions
// Set up security questions
const questions: SecurityQuestion[] = [
{
id: "q1",
question: "What was your first pet's name?",
category: "Personal",
},
{ id: "q2", question: "In what city were you born?", category: "Personal" },
{
id: "q3",
question: "What is your mother's maiden name?",
category: "Personal",
},
];
recoveryManager.setSecurityQuestions(questions);
// User sets their answers
await recoveryManager.setUserSecurityQuestions(userId, [
{ questionId: "q1", answer: "fluffy" },
{ questionId: "q2", answer: "new york" },
]);
// During recovery
const initResult = await recoveryManager.initiateRecovery(
"[email protected]",
"security_questions"
);
// Get questions
const challenges = await recoveryManager.getSecurityQuestions(
initResult.requestId
);
// Verify answers
const verifyResult = await recoveryManager.verifySecurityAnswers(
initResult.requestId,
[
{ questionId: "q1", answer: "fluffy" },
{ questionId: "q2", answer: "new york" },
]
);Backup Codes
// Generate backup codes for user
const backupCodes = await recoveryManager.generateBackupCodes(userId);
// Returns: ['ABCD1234-5678', 'EFGH9012-3456', ...]
// During recovery
const initResult = await recoveryManager.initiateRecovery(
"[email protected]",
"backup_codes"
);
// Verify backup code
const verifyResult = await recoveryManager.verifyBackupCode(
initResult.requestId,
"ABCD1234-5678"
);Multi-Method Recovery
// Require both email and SMS verification
const recoveryManager = new AccountRecoveryManager({
methods: ["email", "sms"],
requireEmailVerification: true,
requireSMSVerification: true,
});
// Start with email
const emailResult = await recoveryManager.initiateRecovery(
"[email protected]",
"email"
);
// Verify email token
const emailVerify = await recoveryManager.verifyToken(emailToken);
// Continue with SMS
const smsResult = await recoveryManager.continueRecovery(
emailVerify.sessionId,
"sms"
);
// Verify SMS and reset password
const smsVerify = await recoveryManager.verifyToken(smsToken);
await recoveryManager.resetPassword(smsVerify.sessionId, newPassword);Recovery Events & Statistics
// Listen for recovery events
recoveryManager.on("recovery:event", (event) => {
if (event.type === "recovery_locked") {
// Send security alert
sendSecurityAlert({
userId: event.userId,
reason: "Account locked due to failed recovery attempts",
});
}
});
// Get recovery statistics
const stats = await recoveryManager.getStatistics("day");
console.log(`Recovery attempts: ${stats.initiated}`);
console.log(`Successful: ${stats.completed}`);
console.log(`Failed: ${stats.failed}`);
console.log(`Locked accounts: ${stats.locked}`);Session Anomaly Detection
Real-time behavioral analysis to detect suspicious session activities:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
sessionAnomaly: {
velocityThreshold: 100, // Actions per minute
dataAccessThreshold: 1000, // MB per hour
privilegedActionThreshold: 50, // Per hour
enablePatternAnalysis: true,
enableVelocityDetection: true,
enableResourceAnalysis: true,
autoBlockOnCritical: true,
},
});
// Track session activities
auth.trackActivity({
id: crypto.randomUUID(),
sessionId: "session123",
userId: "user123",
timestamp: new Date(),
action: "data_export",
resource: "/api/sensitive-data",
method: "GET",
dataSize: 50 * 1024 * 1024, // 50MB
ipAddress: "1.2.3.4",
});
// Check for anomalies
const anomalyDetector = auth.getSessionAnomaly();
const result = await anomalyDetector.checkForAnomalies("session123");
if (result.anomalyDetected) {
console.log("Anomalies detected:", result.anomalies);
console.log("Risk score:", result.overallRiskScore);
console.log("Suggested actions:", result.suggestedActions);
}Behavioral Profiles
// Update user behavioral profile
await anomalyDetector.updateBehavioralProfile("user123", {
userId: "user123",
averageActionsPerMinute: 10,
typicalActions: ["view_dashboard", "view_reports", "export_data"],
typicalResources: ["/api/reports", "/api/dashboard"],
typicalTimeRanges: [
{ dayOfWeek: 1, startHour: 9, endHour: 17, frequency: 90 },
],
commonIpAddresses: ["192.168.1.100"],
commonUserAgents: ["Chrome/120.0"],
commonLocations: ["US"],
averageDataAccess: 100, // MB/hour
typicalResponseTimes: { "/api/data": 200 },
commonActionSequences: [
{
actions: ["login", "view_dashboard", "view_reports"],
frequency: 80,
averageTimeBetween: 5000,
},
],
lastUpdated: new Date(),
sampleSize: 1000,
});Custom Anomaly Rules
// Add custom detection rule
await anomalyDetector.addRule({
id: "high-data-export",
name: "Excessive Data Export",
description: "Detect large data exports",
enabled: true,
priority: 1,
conditions: [
{ metric: "dataAccess", operator: "gt", value: 500, timeWindow: 5 },
],
actions: [AnomalyAction.ALERT, AnomalyAction.LIMIT_ACCESS],
severity: "high",
cooldown: 30, // minutes
});
// Monitor sessions in real-time
const monitor = anomalyDetector.startMonitoring("session123", "user123");
console.log("Current risk score:", monitor.currentRiskScore);Anomaly Types Detected
- Velocity Anomalies: Excessive API calls or actions
- Pattern Anomalies: Unusual action sequences
- Resource Anomalies: Access to sensitive resources
- Time Anomalies: Activity outside normal hours
- Privilege Escalation: Rapid privileged actions
- Data Exfiltration: Large data transfers
Geo-Location Access Control
IP-based restrictions and location-aware security:
import { AuthManager } from "@iota-big3/sdk-auth";
const auth = new AuthManager({
jwtSecret: "your-secret",
geoLocation: {
provider: "ipapi", // or 'maxmind', 'ipinfo', 'custom'
apiKey: process.env.GEO_API_KEY,
enableCache: true,
cacheExpiry: 60, // minutes
treatVPNAsHighRisk: true,
autoBlockOnViolation: true,
},
});
// Check IP access
const decision = await auth.checkIPAccess("1.2.3.4", {
userId: "user123",
resource: "/api/sensitive",
});
if (!decision.allowed) {
console.log("Access denied:", decision.reason);
if (decision.action === "challenge") {
// Present challenges (MFA, CAPTCHA, etc.)
console.log("Challenges required:", decision.challenges);
}
}Access Rules
const geoManager = auth.getGeoLocation();
// Block specific countries
await geoManager.addRule({
id: "block-countries",
name: "Block High-Risk Countries",
enabled: true,
priority: 1,
conditions: [{ field: "country", operator: "in", value: ["XX", "YY"] }],
action: "block",
});
// Challenge VPN connections
await geoManager.addRule({
id: "challenge-vpn",
name: "Challenge VPN Users",
enabled: true,
priority: 2,
conditions: [{ field: "isVPN", operator: "eq", value: true }],
action: "challenge",
});
// Allow specific IP ranges
await geoManager.addRule({
id: "office-ips",
name: "Allow Office IPs",
enabled: true,
priority: 0, // Highest priority
conditions: [{ field: "ip", operator: "in", value: ["10.0.0.0/8"] }],
action: "allow",
});Location Restrictions
// User-specific whitelist
await geoManager.addLocationRestriction({
id: "user-whitelist",
type: "whitelist",
scope: "user",
scopeId: "user123",
locations: [
{ type: "country", value: "US" },
{ type: "country", value: "CA" },
{ type: "city", value: "San Francisco" },
],
enabled: true,
createdAt: new Date(),
updatedAt: new Date(),
});
// Global blacklist
await geoManager.addLocationRestriction({
id: "global-blacklist",
type: "blacklist",
scope: "global",
locations: [
{ type: "country", value: "Sanctioned Country" },
{
type: "ip_range",
value: { start: "192.0.2.0", end: "192.0.2.255" },
},
],
enabled: true,
createdAt: new Date(),
updatedAt: new Date(),
});Geo-Fencing
// Create office geo-fence
await geoManager.addGeoFence({
id: "hq-fence",
name: "Headquarters",
type: "circle",
coordinates: {
type: "circle",
center: { latitude: 37.7749, longitude: -122.4194 },
radiusKm: 5,
},
rules: [
{
action: "allow",
userScope: "role",
roles: ["employee", "admin"],
},
],
enabled: true,
schedule: {
timezone: "America/Los_Angeles",
active: [
{
dayOfWeek: [1, 2, 3, 4, 5], // Mon-Fri
startTime: "08:00",
endTime: "18:00",
},
],
},
});Travel Analysis
// Analyze user travel patterns
const travelAnalysis = await geoManager.analyzeTravelPattern(
"user123",
"5.6.7.8", // Current IP
new Date()
);
if (travelAnalysis.suspicious) {
console.log("Suspicious travel detected:", travelAnalysis.patterns);
// Check for impossible travel
const impossibleTravel = travelAnalysis.patterns.find(
(p) => p.type === "impossible_travel"
);
if (impossibleTravel) {
// Require additional verification
console.log("Impossible travel:", impossibleTravel.description);
}
}
// Get user travel history
const travelPattern = await geoManager.getUserTravelPattern("user123");
console.log("Typical countries:", travelPattern.typicalCountries);
console.log("Suspicious patterns:", travelPattern.suspiciousPatterns);IP Intelligence
// Get IP reputation
const intelligence = await geoManager.getIPIntelligence("1.2.3.4");
console.log("IP Reputation:", intelligence.reputation); // good, neutral, suspicious, bad
console.log("Trust Score:", intelligence.score); // 0-100
console.log("Risk Factors:", intelligence.factors);
// Get geo-location statistics
const stats = await geoManager.getStatistics("day");
console.log("Blocked attempts:", stats.blockedAttempts);
console.log("Top blocked countries:", stats.topBlockedCountries);
console.log("VPN attempts:", stats.vpnAttempts);Express Middleware Integration
// Session anomaly middleware
app.use((req, res, next) => {
if (req.session && req.user) {
auth.trackActivity({
id: crypto.randomUUID(),
sessionId: req.session.id,
userId: req.user.id,
timestamp: new Date(),
action: `${req.method} ${req.path}`,
resource: req.path,
method: req.method,
ipAddress: req.ip,
userAgent: req.get("user-agent"),
});
}
next();
});
// Geo-location middleware
app.use(async (req, res, next) => {
try {
const decision = await auth.checkIPAccess(req.ip, {
userId: req.user?.id,
resource: req.path,
});
if (!decision.allowed) {
if (decision.action === "block") {
return res.status(403).json({
error: "Access denied",
reason: decision.reason,
});
}
if (decision.action === "challenge") {
req.geoChallenge = decision.challenges;
}
}
req.geoLocation = decision.location;
next();
} catch (error) {
next(error);
}
});Phase 3 & 4: Enterprise Integration
High Availability (Phase 3)
The SDK integrates with other IOTA Big3 SDKs for high availability features:
import { createHAAuthManager } from "@iota-big3/sdk-auth";
const haAuth = createHAAuthManager(
{
secretKey: process.env.JWT_SECRET,
accessTokenExpiry: 3600,
},
{
enableReadReplicas: true, // Uses sdk-database
enableDistributedCache: true, // Uses sdk-performance
enableMultiRegion: true, // Uses sdk-cloud
enableFailover: true, // Uses sdk-database
sessionReplication: {
strategy: "async",
regions: ["us-east-1", "eu-west-1"],
},
}
);Compliance Integration (Phase 4)
Compliance is handled by sdk-compliance, not duplicated in auth:
import { ComplianceIntegratedAuthManager } from "@iota-big3/sdk-auth";
const complianceAuth = new ComplianceIntegratedAuthManager(authConfig, {
enableGDPR: true, // GDPR export/deletion via sdk-compliance
enableSOC2: true, // SOC2 audit logging via sdk-compliance
enablePCIDSS: true, // PCI compliance via sdk-compliance
dataRetentionDays: 365,
auditLogRetentionDays: 2555, // 7 years
});
// GDPR data export
const userData = await complianceAuth.exportUserData(userId);
// GDPR right to be forgotten
await complianceAuth.deleteUserData(userId, "user_request");
// Compliance status
const status = await complianceAuth.getComplianceStatus();Architecture Philosophy
This SDK follows the IOTA Big3 architecture principles:
❌ NOT: Implementing all features within sdk-auth ✅ INSTEAD: Delegating to specialized SDKs
| Feature | Wrong Approach | Right Approach |
| --------------- | --------------------------- | --------------------- |
| Session Storage | Build Redis cluster in auth | Use sdk-performance |
| Read Replicas | Add DB logic to auth | Use sdk-database |
| GDPR Export | Create export in auth | Use sdk-compliance |
| Audit Logs | Add audit tables | Use sdk-compliance |
| Multi-region | Handle regions in auth | Use sdk-cloud |
This prevents duplication and ensures each SDK focuses on its specialty.
