Skip to main content

Architecture Overview

BT Management is a Multi-Tenant SaaS application designed to serve multiple synagogues from a single installation. The architecture strictly isolates data for each tenant while allowing shared infrastructure.

Multi-Tenancy Implementation​

1. AsyncLocalStorage (ALS)​

We use Node.js AsyncLocalStorage via AlsService (src/common/als/) to store request context (user ID, role) globally throughout the request lifecycle. This prevents the need for "Prop Drilling" of user context through every method in services.

2. TenantInterceptor​

The TenantInterceptor is the gatekeeper for populating context.

  • It extracts the user ID from the JWT Token (via request.user).
  • For Admins, it checks the x-customer-context header. If present, it sets the context to the impersonated user.
  • It initializes the AlsService Store with { userId, isAdmin }.

3. Prisma Middleware (Data Isolation)​

This is the critical security layer. We attach Middleware to the Prisma service that intercepts all database queries.

  • Before each query (findMany, count, etc.), it checks if the model is in the tenantModels list.
  • If it's a tenant-dependent model, it automatically injects the filter where: { userId: currentUserId }.
  • Admin Bypass: If AlsService indicates this is an admin (and not in impersonation mode), this filter is skipped.
Critical Rule

Never manually filter by userId in Controllers or Services for tenant-dependent models. Trust the Middleware to prevent data leakage.

Request Pipeline​

A typical HTTP request goes through the following layers:

  1. Fastify Middleware: helmet, cors, rateLimit.
  2. Global Guards:
    • JwtAuthGuard: Validates the Bearer Token.
    • PermissionsGuard: Checks the @Permissions() decorator against user roles.
    • RateLimitGuard: Enhanced protection.
    • AccountLockoutGuard: Login security.
  3. Interceptors:
    • TenantInterceptor: Sets the ALS context.
    • TransformInterceptor: Wraps the response in { success: true, data: ... } structure.
  4. Validation Pipe: ZodValidationPipe validates data objects (DTOs).
  5. Controller: Handles routing.
  6. Service: Executes business logic (Prisma queries are automatically filtered).

System Layers​

Core Services​

Auth, Users, Devices, Prisma, Redis, ALS (multi-tenancy).

Domain Modules​

Tfila Times, General Messages, Hanzch, Shior, Olie Latora, Screen Timers, Zmanim, Aliya Notifications, Daily Content Preferences, Holiday Times, Synagogue.

Device Management​

Device CRUD, Configuration, Metrics, Monitoring, Settings, Certificates, Remote Control, Remote Installations, Screenshots, Screen Streaming (WebRTC), Software Updates (OTA).

Real-time & Communication​

MQTT (Mosquitto) for IoT, Socket.IO (EventsGateway) for clients, WebSocket room management, WhatsApp integration, Email (Nodemailer), SMS (Twilio/AWS SNS), Webhooks (HMAC-signed).

AI & Analytics Layer​

ML Prediction, Pattern Detection, Advanced Anomaly Detection, Predictive Analytics, AI Scheduler, Behavioral Analytics, Advanced Reports.

Automation & Commands​

Alert Rules (in-memory engine), Smart Alerts (cron-based), Single Commands, Batch Commands (parallel/sequential via MQTT).

System & Operations​

Software Update Management, Telemetry, Health Monitoring, Cleanup Scheduler, Audit Logging, License Management, Performance Monitoring, System Configuration, Backups.

Technology Stack​

  • Backend: NestJS (with Fastify adapter).
  • Database: MongoDB (via Prisma ORM, 71+ models).
  • Caching: Redis.
  • Real-time: MQTT (Mosquitto) for devices, Socket.IO for clients.
  • Frontend: React (Vite) + Material UI.
  • Mobile: React Native (Android TV).
  • AI/ML: TensorFlow.js, statistical models.
  • Monitoring: Prometheus, Grafana.
  • File Storage: Local filesystem + Cloudinary.