@iota-big3/sdk-middleware
v2.0.0
Published
Express and Fastify middleware for School OS SDK - TypeScript Edition
Downloads
5
Maintainers
Readme
@iota-big3/sdk-middleware
Industry-aware middleware collection for Express and Fastify applications using the iota-big3 SDK.
Installation
npm install @iota-big3/sdk-middleware @iota-big3/sdk-coreFeatures
- 🔒 Authentication - JWT, API key, and session support
- 📊 Philosophy Tracking - Monitor teacher time saved and student empowerment
- 📝 Logging - Request/response logging with telemetry integration
- ❌ Error Handling - Beautiful error formatting with helpful suggestions
- 🌐 CORS - Industry-specific CORS policies
- ⏱️ Rate Limiting - Adaptive rate limiting based on industry
- ✅ Compliance - FERPA, HIPAA, PCI, GDPR enforcement
- 🛡️ Policy - OPA integration for fine-grained access control
Quick Start
import { SDK } from '@iota-big3/sdk-core';
import {
createAuthMiddleware,
createPhilosophyMiddleware,
createLoggingMiddleware,
createErrorMiddleware
} from '@iota-big3/sdk-middleware';
import express from 'express';
// Initialize SDK
const sdk = new SDK({
serviceName: 'my-service',
industry: 'education'
});
// Create Express app
const app = express();
// Apply middleware
app.use(createLoggingMiddleware(sdk));
app.use(createAuthMiddleware(
{ serviceName: 'my-service', industry: 'education', sdk },
{ enableJWT: true, enableApiKey: true }
));
app.use(createPhilosophyMiddleware(sdk));
app.use(createErrorMiddleware({ serviceName: 'my-service', sdk }));
// Your routes
app.post('/api/grades', (req, res) => {
// Track teacher time saved
res.trackTeacherTimeSaved(300, 'automated-grading');
res.json({ success: true });
});
app.listen(3000);Middleware Components
Authentication Middleware
Supports multiple authentication methods with industry-aware defaults:
const authMiddleware = createAuthMiddleware(
{
serviceName: 'my-service',
industry: 'healthcare', // Strict security for healthcare
sdk
},
{
enableJWT: true,
enableApiKey: true,
enableSession: false,
publicPaths: ['/health', '/api/public/*'],
secret: process.env.JWT_SECRET,
apiKeys: new Map([
['key-1', { id: '1', name: 'Mobile App', hash: 'sha256-hash' }]
])
}
);Philosophy Middleware
Track and celebrate educational philosophy metrics:
const philosophyMiddleware = createPhilosophyMiddleware(sdk, {
trackingEnabled: true,
milestones: {
firstTeacherLiberation: 60, // 1 minute saved
significantLiberation: 3600, // 1 hour saved
transformativeLiberation: 86400 // 1 day saved
}
});
// In your routes
app.post('/api/lesson', (req, res) => {
// Track time saved
res.trackTeacherTimeSaved(1800, 'lesson-planning-ai');
// Track student empowerment
res.trackStudentEmpowerment(30, 'self-paced-learning');
res.json({ success: true });
});Error Middleware
Beautiful error handling with suggestions:
const errorMiddleware = createErrorMiddleware(
{ serviceName: 'my-service', industry: 'education', sdk },
{
enableStackTrace: process.env.NODE_ENV !== 'production',
customFormatter: (error, req) => ({
error: {
code: error.code,
message: error.message,
suggestions: error.suggestions,
path: req.path
}
})
}
);
// Must be last middleware
app.use(errorMiddleware);CORS Middleware
Industry-specific CORS policies:
const corsMiddleware = createCorsMiddleware(
{ serviceName: 'my-service', industry: 'finance' }, // Strict for finance
{
allowedOrigins: ['https://app.example.com'],
credentials: true,
maxAge: 1800 // 30 minutes for finance
}
);Rate Limiting
Adaptive rate limiting by industry:
const rateLimitMiddleware = createRateLimitMiddleware(
{ serviceName: 'my-service', industry: 'retail' },
{
windowMs: 10 * 60 * 1000, // 10 minutes
max: 200, // Retail allows more requests
skipSuccessfulRequests: true
}
);Compliance Middleware
Enforce compliance frameworks:
const complianceMiddleware = createComplianceMiddleware(
{ serviceName: 'my-service', industry: 'healthcare' },
{
frameworks: ['HIPAA', 'HITECH'],
enforceEncryption: true,
requireAuth: true,
auditLog: true,
sensitiveFields: ['ssn', 'patientId', 'diagnosis']
}
);Policy Middleware
OPA integration for policy-based access:
const policyMiddleware = createPolicyMiddleware(
{ serviceName: 'my-service', industry: 'education' },
{
opaUrl: 'http://opa:8181',
enforcementMode: 'enforce',
philosophyEnforcement: true,
philosophyMinScore: 70
}
);Industry Defaults
Each industry has tailored defaults:
| Industry | Auth | CORS | Rate Limit | Compliance | Philosophy | |----------|------|------|------------|------------|------------| | Education | All methods | Permissive | 100/15min | FERPA, COPPA | Enforced | | Healthcare | Strict | Strict | 50/5min | HIPAA, HITECH | Optional | | Finance | Strict | Strict | 30/1min | PCI-DSS, SOX | Optional | | Retail | Flexible | Permissive | 200/10min | PCI | Optional | | Government | Strict | Strict | 40/5min | FISMA, FedRAMP | Optional |
Migration from v1
Before (v1 - JavaScript)
const middleware = createMiddleware({
tribe: 'education', // Old terminology
// Limited options
});After (v2 - TypeScript)
const middleware = createMiddleware(
{
serviceName: 'my-service',
industry: 'education', // New terminology
sdk // SDK integration
},
{
// Full type safety
// Many more options
// Industry-aware defaults
}
);Legacy Support
All middleware supports legacy patterns:
// Old pattern still works
const middleware = createLegacyMiddleware({
tribe: 'education'
});
// Console warning: ⚠️ Using legacy pattern. Please migrate.Fastify Support
All middleware supports both Express and Fastify:
import Fastify from 'fastify';
const fastify = Fastify();
// Register middleware
await fastify.register(authMiddleware.fastify);
await fastify.register(loggingMiddleware.fastify);
fastify.listen({ port: 3000 });TypeScript Support
Full TypeScript support with enhanced types:
import type {
AuthMiddleware,
AuthConfig,
PhilosophyRequest,
PhilosophyResponse
} from '@iota-big3/sdk-middleware';
// Type-safe configuration
const config: AuthConfig = {
enableJWT: true,
secret: process.env.JWT_SECRET!
};
// Enhanced request/response types
app.post('/api/lesson', (req: PhilosophyRequest, res: PhilosophyResponse) => {
res.trackTeacherTimeSaved(300, 'ai-assistance');
});Testing
import { createAuthMiddleware } from '@iota-big3/sdk-middleware';
describe('Auth Middleware', () => {
it('should authenticate JWT', () => {
const middleware = createAuthMiddleware(
{ serviceName: 'test', industry: 'education' },
{ enableJWT: true }
);
// Test implementation
});
});Best Practices
Order Matters: Apply middleware in this order:
app.use(loggingMiddleware); // First - log all requests app.use(corsMiddleware); // Early - handle preflight app.use(rateLimitMiddleware); // Before auth - prevent abuse app.use(authMiddleware); // Authenticate users app.use(complianceMiddleware); // Check compliance app.use(policyMiddleware); // Fine-grained access app.use(philosophyMiddleware); // Track metrics // ... your routes ... app.use(errorMiddleware); // Last - catch all errorsIndustry Selection: Choose the right industry for appropriate defaults
Environment Variables: Use env vars for sensitive configuration
Error Handling: Always include error middleware as the last middleware
Testing: Test middleware with your specific industry requirements
Contributing
See CONTRIBUTING.md for details.
License
MIT
