Middleware Pipeline
11 middleware files in src/middleware/. Applied globally in order. Each layer is independently testable.
Execution Order
Request
│
├── 1. securityHeaders() ← CSP nonce, HSTS, X-Frame-Options
├── 2. outputSanitization() ← Auto-strip PII from responses
├── 3. auditLogger() ← Hash-chain audit trail
├── 4. requestLogger() ← Request ID, timing, correlation
├── 5. Multi-Tenant Isolation ← X-Tenant-ID extraction
│
├── [Per-route group:]
│ ├── 6. authMiddleware() ← JWT verify, user load, RBAC
│ ├── 7. abacMiddleware() ← Attribute-based access control
│ │
│ ├── [Per-endpoint:]
│ │ ├── 8. enhancedRateLimit() ← Per-user + per-IP dual limiting
│ │ ├── 9. requireFeature() ← Feature flag gate
│ │ └── 10. requestSigning() ← HMAC-SHA256 verification
│
├── 11. errorHandler() ← Global catch-all
│
└── Response
1. Security Headers
File: src/middleware/securityHeaders.ts
| Header | Value | Purpose |
|---|---|---|
| Content-Security-Policy | Nonce-based CSP | Prevent XSS, inline script injection |
| Strict-Transport-Security | max-age=31536000 | Force HTTPS for 1 year |
| X-Frame-Options | DENY | Prevent clickjacking |
| X-Content-Type-Options | nosniff | Prevent MIME sniffing |
| Permissions-Policy | camera=(), microphone=() | Disable unused browser APIs |
| X-XSS-Protection | 0 | Disable legacy XSS filter (CSP replaces it) |
2. Output Sanitization
File: src/middleware/outputSanitization.ts
Auto-strips PII (emails, phone numbers, Aadhaar numbers, PAN numbers) from all JSON responses before they reach the client. Prevents accidental data leakage in logs and error messages.
3. Audit Logger
File: src/middleware/auditLogger.ts
Logs every mutation (POST/PUT/DELETE) to the audit_logs table with tamper-evident hash chain: each record includes prev_hash and record_hash. Covers: CREATE, UPDATE, DELETE, LOGIN, LOGOUT, EXPORT, APPROVE, DENY, MFA_ENROLL, PASSWORD_CHANGE, ROLE_CHANGE, CONSENT_GRANT, CONSENT_REVOKE.
4. Request Logger
File: src/middleware/requestLogger.ts
Generates unique request ID, records timing, logs method + path + status + duration. Enables request correlation across services.
5. Multi-Tenant Isolation
Extracts society_id from X-Tenant-ID or X-Society-ID header. Sets c.set('tenantId', societyId) for downstream middleware and handlers. Every D1 query in the codebase uses this value.
6. JWT Authentication
File: src/middleware/auth.ts
Verifies JWT access token from Authorization: Bearer header. Loads user from D1, populates: user object, RBAC roles, permissions list, active persona context, available contexts. Falls back to OpenAuth JWKS verification when OPENAUTH_ISSUER env var is set.
7. ABAC Middleware
File: src/middleware/auth.ts (exported as abacMiddleware)
Attribute-Based Access Control. Evaluates conditions based on user attributes (role, persona, flat_id, time of day) against resource attributes. More flexible than RBAC alone.
8. Enhanced Rate Limiting
File: src/middleware/enhancedRateLimit.ts
Dual limiting: per-user AND per-IP. Uses KV for distributed state. Signature: enhancedRateLimit(tier) where tier is one of: 'AUTH' (10/min), 'READ' (120/min), 'WRITE' (30/min), 'EXPORT' (5/min), 'AI_QUERY' (10/min).
9. Feature Flags
File: src/middleware/featureFlags.ts
requireFeature('feature.key') checks society_features table. KV-cached with 5-minute TTL. Returns 403 if feature is disabled for the society. 101 feature keys across 12 modules.
10. Request Signing
File: src/middleware/requestSigning.ts
HMAC-SHA256 verification for mutating requests. Uses nonce + timestamp to prevent replay attacks. Nonces are stored in nonce_store table and validated for single-use within expiry window.
11. Error Handler
File: src/middleware/errorHandler.ts
Global catch-all. Catches unhandled errors, sanitizes stack traces, returns structured error response. Prevents internal implementation details from leaking.
Anomaly Detection
File: src/middleware/anomalyDetection.ts
6-signal behavioral analysis: unusual request rate, off-hours activity, new IP/device, session hijacking indicators, rapid endpoint traversal, privilege escalation attempts. Flags anomalies and can auto-trigger MFA challenge.