Security Model

12-layer security fortress designed to be "AI-resistant". Every query encrypted, every mutation audited, every session fingerprinted. DPDP Act compliant.

Security Layers

#LayerImplementationFile
1Field-Level EncryptionAES-256-GCM + HKDF per-society keyscrypto.ts
2Session Management15min JWT + 7d httpOnly refresh cookie + device fingerprintingsessionManager.ts
3RBAC Permission Matrix15 roles, 67 permissions, KV-cachedrbac.ts
4Rate LimitingPer-user + per-IP + per-endpoint, 5 tiersenhancedRateLimit.ts
5Request SigningHMAC-SHA256 nonce + timestamprequestSigning.ts
6Anomaly Detection6-signal behavioral analysis, auto MFA challengeanomalyDetection.ts
7Security HeadersNonce-based CSP, HSTS, X-Frame-Options DENYsecurityHeaders.ts
8DPDP Act Compliance14 consent purposes, 6 data subject rightsdpdp.ts
9Audit LogImmutable hash-chain (prev_hash → record_hash)auditLogger.ts
10Output SanitizationAuto-strip PII from responsesoutputSanitization.ts
11MFA (TOTP)Secret + QR + backup codes + lockoutmfa.ts
12Secure StoragehttpOnly refresh cookie, sessionStorage (not localStorage)sessionManager.ts

Encryption

// Field-level encryption: every PII field encrypted per-society
// Key derivation: HKDF from master ENCRYPTION_MASTER_KEY + society_id
// Algorithm: AES-256-GCM (authenticated encryption)

// Encrypted fields include:
// - users.phone, users.email (at rest)
// - mfa_secrets.totp_secret
// - encryption_keys.key_material
// - whatsapp_config.access_token
// - api_keys.key_hash

JWT Structure

{
  "sub": "user-id",
  "iat": 1720000000,
  "exp": 1720000900,        // 15 minutes
  "active_context": {
    "persona_id": "persona-uuid",
    "tenant_id": "society-uuid",
    "role": "SOCIETY_ADMIN",
    "unit_id": "flat-uuid",
    "permissions": ["billing.view", "billing.create", ...]
  },
  "available_contexts": [
    { "persona_id": "...", "role": "SOCIETY_ADMIN", "tenant_id": "..." },
    { "persona_id": "...", "role": "RESIDENT", "tenant_id": "..." }
  ]
}

MFA (Multi-Factor Authentication)

StepFlow
1. SetupPOST /auth/mfa/setup → generates TOTP secret + QR data URL
2. VerifyPOST /auth/mfa/verify → user enters 6-digit code → secret saved
3. LoginPOST /auth/mfa/login → tempToken + TOTP code → full JWT pair
4. DisablePOST /auth/mfa/disable → password recheck required

Anomaly Detection Signals

SignalDetection MethodResponse
Unusual request rateRequests/min exceeds 2x user baselineRate limit + flag
Off-hours activityRequests outside user's typical hoursLog + alert
New IP/deviceIP or user-agent not in recent historyMFA challenge
Session hijackingConcurrent sessions from different IPsRevoke older session
Rapid endpoint traversalSequential access to unrelated endpointsFlag + monitor
Privilege escalationAccessing endpoints above user's roleBlock + audit log

DPDP Act Compliance

RightImplementation
Right to AccessGET /auth/dpdp/consent + data export
Right to CorrectionPATCH /auth/profile
Right to ErasurePOST data_requests (ERASURE type)
Right to PortabilityCSV/JSON data export
Right to ObjectWithdraw consent via user_consents table
Right to RestrictAccount suspension (TEMPORARY/PERMANENT)
Breach Notification72-hour notification requirement (dpdp.ts)

Audit Trail

// Immutable hash-chain audit log
// Each record includes prev_hash → record_hash
// Tamper-evident: modifying any record breaks the chain

CREATE TABLE audit_logs (
  id TEXT PRIMARY KEY,
  society_id TEXT NOT NULL,
  user_id TEXT NOT NULL,
  action TEXT NOT NULL,     -- CREATE, UPDATE, DELETE, LOGIN, LOGOUT, etc.
  entity_type TEXT,
  entity_id TEXT,
  old_value_json TEXT,
  new_value_json TEXT,
  ip_address TEXT,
  user_agent TEXT,
  prev_hash TEXT,           -- hash of previous record
  record_hash TEXT NOT NULL -- SHA-256(prev_hash + action + entity + timestamp)
);