npm package: @iota-big3/sdk-middleware
Description: Express and Fastify middleware for School OS SDK - TypeScript Edition
Author: School OS Team
Latest version: 2.0.0

# @iota-big3/sdk-middleware

Industry-aware middleware collection for Express and Fastify applications using the iota-big3 SDK.

## Installation

```bash
npm install @iota-big3/sdk-middleware @iota-big3/sdk-core
```

## Features

- 🔒 **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

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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:

```typescript
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)
```javascript
const middleware = createMiddleware({
  tribe: 'education', // Old terminology
  // Limited options
});
```

### After (v2 - TypeScript)
```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:

```typescript
// 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:

```typescript
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:

```typescript
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

```typescript
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

1. **Order Matters**: Apply middleware in this order:
   ```typescript
   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 errors
   ```

2. **Industry Selection**: Choose the right industry for appropriate defaults
3. **Environment Variables**: Use env vars for sensitive configuration
4. **Error Handling**: Always include error middleware as the last middleware
5. **Testing**: Test middleware with your specific industry requirements

## Contributing

See [CONTRIBUTING.md](../../CONTRIBUTING.md) for details.

## License

MIT