Production-ready, multi-tenant REST API with hierarchical RBAC, passwordless authentication, comprehensive event logging, webhooks, and cloud-agnostic service adapters. Designed as a reference implementation demonstrating TDD (Test-Driven Development) and enterprise-grade architecture.
Originally conceived as a configuration drift reduction demonstration, this project evolved into a comprehensive example of AI-assisted software development with meticulous context refinement.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CLIENT APPLICATION β
β (Web / Mobile / Third-Party) β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
β HTTPS/REST
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β API GATEWAY LAYER β
β ββββββββββββββββ βββββββββββββ ββββββββββββ βββββββββββββββββ β
β β Rate Limiter ββ β CORS ββ β Helmet ββ β Compression β β
β ββββββββββββββββ βββββββββββββ ββββββββββββ βββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AUTHENTICATION LAYER β
β ββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββ β
β β JWT Verification β β Device Fingerprinting β β
β β (Access/Refresh) β β (Trust Status Tracking) β β
β ββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Tenant Context Validation (orgId/envId) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AUTHORIZATION LAYER β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Hierarchical RBAC Permission Resolution β β
β β (Group-based β User-based β Environment-scoped) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Impersonation Chain Validation & Audit β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ROUTING LAYER β
β ββββββββββββββββββββ ββββββββββββββββββ ββββββββββββββββββββ β
β β Tenant-Scoped β β Admin Routes β β System Routes β β
β β /orgs/{orgId}/ β β /admin/* β β /health, /docs β β
β β envs/{envId}/* β β β β β β
β ββββββββββββββββββββ ββββββββββββββββββ ββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CONTROLLER LAYER β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β HTTP Request/Response Handling & Validation β β
β β (Extract params β Delegate to services β Format output) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SERVICE LAYER β
β ββββββββββββββββ βββββββββββββββββ ββββββββββββββββββββββββββ β
β β Business β β Transaction β β External Service β β
β β Logic β β Management β β Orchestration β β
β β β β β β (Adapters) β β
β ββββββββββββββββ βββββββββββββββββ ββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββ
β MODEL LAYER β β ADAPTER LAYER β
β ββββββββββββββββββββββββ β β ββββββββββββββββββββββββββββββββ β
β β Sequelize ORM β β β β Email (SendGrid/SMTP) β β
β β (PostgreSQL) β β β β Secrets (GCP/AWS/Vault) β β
β β β β β β Storage (GCS/S3/Local) β β
β β - Entities β β β β Queue (Pub/Sub/SQS/Kafka) β β
β β - Associations β β β ββββββββββββββββββββββββββββββββ β
β β - Validations β β β (Cloud-Agnostic Interfaces) β
β ββββββββββββββββββββββββ β ββββββββββββββββββββββββββββββββββββββ
β β
β ββββββββββββββββββββββββ β
β β Event Publisher β ββββββββββ
β β (CloudEvents 1.0.2) β β β
β ββββββββββββββββββββββββ β β
βββββββββββββββββββββββββββββ β
β
ββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β EVENT PROCESSING LAYER β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Write-Ahead Log (WAL) Manager β β
β β (Batch buffering + PII redaction + Flush) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Webhook Delivery Queue β β
β β (CloudEvents β Retry with Exponential Backoff) β β
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Database β Message Queue
ββββββββββββββββ ββββββββββββββββββββ
β PostgreSQL β β Pub/Sub / SQS β
β (Primary) β β / Kafka / etc β
ββββββββββββββββ ββββββββββββββββββββ
-
Passwordless Authentication
- Magic link delivery via email/SMS
- 8-digit verification codes
- Client-generated device fingerprinting (FingerprintJS/ThumbmarkJS)
- Automatic new device notifications with "This wasn't me" revocation
- Environment-specific token TTLs (15min production, 1 day dev/staging)
-
Advanced Session Management
- JWT access tokens (15min lifespan) + refresh tokens (30 days)
- httpOnly, secure, SameSite=Strict cookies
- Refresh token rotation (one-time use pattern)
- Device-bound sessions (1 active session per device)
- Granular revocation (by session, device, or global logout)
-
Multi-Layer Rate Limiting
- Configurable per endpoint type and environment
- Per-email, per-IP, per-device, per-user tracking
- Exponential backoff with configurable lockout strategies
- Prevents enumeration attacks and abuse
-
Device Trust Management
- Automatic trust status tracking (trusted, pending, revoked)
- User-defined device names (with fallback to parsed User-Agent)
- Configurable device limits (10 default, tiered plans)
- Auto-revocation of oldest unused device when limit exceeded
-
Hierarchical Organization Model
- Organization β Environment β Groups β Users
- Default environments: Live (production) + Test (sandbox)
- Tenant-scoped endpoints:
/orgs/{orgId}/envs/{envId}/*
- JWT-based tenant context validation (prevents cross-tenant access)
-
User Impersonation with Full Audit Trails
- System Impersonation: Admin access to ANY user across ALL orgs/envs
- Organization Impersonation: Managers impersonate subordinates only (hierarchy-based)
- Session Chaining: Multi-level impersonation (Admin β Manager β User)
- Pop Operation: Revert to parent impersonation level
- Full chain tracking in JWT + database + event logs
-
Context Switching
- Users can belong to multiple orgs/environments
- Seamless context switching with new JWT issuance
- Last context stored in
user.last_org_id
/user.last_env_id
-
Granular Permissions
- Pattern:
{resource}:{action}
(e.g.,devices:read
,admin:users:manage
) - Categories: Tenant-scoped, Admin-scoped, System-level
- Environment-scoped role assignments (polymorphic to groups/users)
- Pattern:
-
Group-Based Permission Inheritance
- Hierarchical groups with
hierarchy_level
tracking - Permission resolution: User roles + Group roles (deduplicated)
- Restrict impersonation to subordinate groups (lower hierarchy level)
- Hierarchical groups with
-
System Roles
- Predefined: Admin, Manager, Member, Viewer
- Custom roles with permission bundling
is_system
flag prevents accidental deletion
-
W3C Activity Streams Model
- Actor (who) + Verb (action) + Object (what) + Target (where)
- Denormalized org/env names for <200ms query SLO
- Full impersonation context in event actor metadata
- HTTP audit trail (request/response/headers/IP/user agent)
-
Write-Ahead Log (WAL) with Batch Buffering
- In-memory buffer with configurable flush thresholds
- Batch insert for high-throughput scenarios
- Automatic PII redaction (passwords, tokens, sensitive headers)
- Graceful shutdown ensures buffer flush
-
CloudEvents 1.0.2 Message Queue
- All events published to queue (Pub/Sub / SQS / Kafka / Redis)
- CloudEvents spec compliance (
id
,source
,type
,data
, etc.) - Impersonation metadata included in event payload
-
Webhook Delivery System
- User-configurable webhooks per environment
- Event subscription filtering (subscribe to specific verbs)
- Exponential backoff retry (5 attempts: 1min β 5min β 15min β 1hr β 6hr)
- HMAC signature validation
- Delivery history and manual retry
-
<200ms Response Time SLO
- Denormalized reads (event table stores org/env names)
- Cursor-based pagination for 10M+ record endpoints
- Sequelize eager loading to prevent N+1 queries
- Strategic indexing (foreign keys, frequently filtered/sorted fields)
-
Cloud-Agnostic Adapter Pattern
- Email: SendGrid, SMTP, Mock
- Secrets: GCP Secret Manager, AWS Secrets Manager, Vault, Env Variables, Memory
- Storage: Google Cloud Storage, AWS S3, Local Filesystem
- Queue: Pub/Sub, SQS, Kafka, Redis, In-Memory
- Factory pattern for runtime provider switching
-
Comprehensive Test Coverage
- 36 test suites covering 106+ API endpoints
- 1066 passing tests, 11 skipped (1077 total)
- 1 test suite intentionally skipped (rate limiting - disabled for test performance)
- AAA pattern (Arrange, Act, Assert)
- Test helpers for JWT generation, magic token extraction, permission checks
-
Test Organization
- Phase 1: Middleware (49/49 passing) β
- Phase 2: Endpoints (120/120 passing) β
- Batch 1: Auth (36/36) β
- Batch 2: Users (36/36) β
- Batch 3: Orgs/Envs (48/48) β
- Collocated with source code (
src/__tests__/
)
-
Extensive Documentation
- 23+ markdown files in
api/docs/
- Component STANDARDS.md files (controllers, services, routes, middleware, tests)
- Architecture docs (entity model, JWT structure, auth design, adapter pattern)
- OpenAPI 3.0 specification (106 endpoints across 14 resource groups)
- Interactive Swagger UI at
/api-docs
- 23+ markdown files in
-
Code Quality Tooling
- TypeScript 5.7 with strict mode
- ESLint + Security plugin
- Prettier for formatting
- 196 source files, zero magic strings (centralized constants)
- File size limits enforced (<500 lines recommended, 1000 max)
-
12-Factor Methodology
- Configuration via environment variables
- Stateless services (sessions in DB, not memory)
- Structured logging to stdout (Winston)
- Graceful shutdown with cleanup handlers
- Node.js β₯ 24.0.0
- PostgreSQL β₯ 16.x
- npm β₯ 10.0.0
# Clone the repository
git clone https://github.com/yourusername/enterprise-api-starter-nodejs.git
cd enterprise-api-starter-nodejs/api
# Install dependencies
npm install
# Configure environment variables
cp .env.example .env
# Edit .env with your database credentials and secrets
# Run database migrations
npm run db:migrate
# Start development server
npm run dev
The API will be available at http://localhost:3000
with Swagger UI at http://localhost:3000/api-docs
.
# Run all tests
npm test
# Watch mode (auto-rerun on file changes)
npm run test:watch
# Coverage report
npm run test:coverage
# TypeScript type checking
npm run typecheck
# Lint for errors
npm run lint
# Auto-fix linting issues
npm run lint:fix
# Format with Prettier
npm run format
- I want to save money by enabling local development and remaining host agnostic
- I want efficient cloud operations by patching vulnerabilities that could run up my bill
- I want flexible data integration via API endpoints and configurable webhooks
- I want PII redaction, MFA security, and audit history compliance so I can earn ISO and SOC certification
- I want my own demo environment(s) to allow me to sell my product
- I want early sandbox access to new features to drive more closed-won opportunities
- I want searchable audit logs to quickly diagnose customer issues
- I want to impersonate any user across any organization so that I can provide customer support and resolve issues
- I want to invite users to my organization so that I can grant team members access to our resources
- I want to organize users into hierarchical groups so that I can manage permissions efficiently
- I want to assign roles at the environment level so that users have different permissions in Live vs Test environments
- I want to impersonate users in subordinate groups so that I can troubleshoot issues and provide support to my team
- I want to view audit logs of all user actions so that I can ensure compliance and investigate security incidents
- I want to authenticate without passwords so that I can access my account securely without remembering complex credentials
- I want to receive a magic link via email or SMS so that I can verify my identity and log in quickly
- I want my devices to be automatically recognized so that I don't need to re-verify on trusted devices
- I want to manage my active sessions so that I can revoke access from lost or stolen devices
- I want to switch between organizations and environments so that I can manage multiple tenants from a single account
- I want comprehensive OpenAPI documentation so that I can understand all available endpoints and schemas
- I want webhook notifications for important events so that my application can react to changes in real-time
- I want CloudEvents-compliant event payloads so that I can integrate with standard event processing tools
- I want consistent camelCase field names across all API responses so that my frontend code is predictable
- I want cursor-based pagination for high-volume endpoints so that I can efficiently process large datasets
- I want to impersonate any user across any organization so that I can provide customer support and resolve issues
- I want to track impersonation chains with full audit trails so that I have complete accountability for all actions
- I want to force-revoke user sessions so that I can respond to security incidents immediately
- I want to monitor webhook deliveries and retry failures so that I can ensure event notifications are reliable
- I want to configure rate limits per environment so that I can prevent abuse while allowing testing flexibility
- I want cloud-agnostic service adapters so that I can deploy to GCP, AWS, or on-premises without code changes
- I want environment-specific configuration so that I can tune rate limits and TTLs per deployment stage
- I want structured logs to stdout so that I can integrate with centralized logging platforms (Cloud Logging, CloudWatch, Splunk)
- I want database migrations with rollback support so that I can safely deploy schema changes
- I want graceful shutdown handlers so that in-flight requests complete and buffers flush before termination
- I want complete impersonation audit trails so that I can verify who performed actions on behalf of whom
- I want PII redaction in event logs so that sensitive data is not stored in plaintext
- I want device fingerprinting and trust status tracking so that I can identify suspicious authentication patterns
- I want HMAC-signed webhook payloads so that I can verify event authenticity
- I want rate limiting with exponential backoff so that brute-force attacks are automatically mitigated
enterprise-api-starter-nodejs/
βββ api/ # API application
β βββ src/
β β βββ __tests__/ # Test files (collocated)
β β β βββ helpers/ # Test utilities (auth, constants)
β β β βββ integration/ # API endpoint tests (31 files)
β β β βββ unit/ # Middleware & utility tests
β β βββ config/ # Configuration & database setup
β β βββ constants/ # HTTP status, errors, auth constants
β β βββ controllers/ # HTTP request/response handlers
β β β βββ STANDARDS.md # Controller best practices
β β βββ middleware/ # Auth, RBAC, validation, error handling
β β β βββ STANDARDS.md # Middleware best practices
β β βββ models/ # Sequelize ORM models (14 entities)
β β βββ routes/ # RESTful route definitions
β β β βββ STANDARDS.md # Routing best practices
β β βββ services/ # Business logic & orchestration
β β β βββ STANDARDS.md # Service layer best practices
β β β βββ email/ # SendGrid, SMTP, Mock
β β β βββ queue/ # Pub/Sub, SQS, Kafka, Redis, Memory
β β β βββ secrets/ # GCP, AWS, Vault, Env, Memory, File
β β β βββ storage/ # GCS, S3, Local
β β βββ types/ # TypeScript type definitions
β β βββ utils/ # Helper functions
β β βββ app.ts # Express app configuration
β β βββ server.ts # Server entry point
β βββ api-docs/ # OpenAPI 3.0 specification
β β βββ index.yaml # Main spec file
β β βββ paths/ # Endpoint definitions (factored)
β β βββ components/ # Reusable schemas (factored)
β βββ docs/ # Architecture documentation (23 files)
β β βββ ENTITY_MODEL.md # Complete database schema
β β βββ JWT_TOKEN_STRUCTURE.md # Token format & impersonation
β β βββ AUTHENTICATION_DESIGN.md # Passwordless auth flow
β β βββ ADAPTER_PATTERN.md # Cloud-agnostic design
β β βββ ADAPTER_USAGE.md # Adapter implementation guide
β β βββ QUERY_PARAMETER_STANDARDS.md # API query conventions
β β βββ progress-tracking/ # Implementation status
β β βββ security-analysis/ # Periodic self audits
β βββ migrations/ # Sequelize database migrations
β βββ .env.example # Environment variable template
β βββ package.json # Dependencies & scripts
β βββ tsconfig.json # TypeScript configuration
β βββ jest.config.js # Jest test configuration
β βββ CONTRIBUTING.md # Developer guide
βββ infra/ # Terraform infrastructure (future)
βββ CLAUDE.md # AI assistant context & guidelines
βββ README.md # This file
Metric | Value |
---|---|
Total Endpoints | 106 (across 14 resource groups) |
Source Files | 196 TypeScript files |
Test Suites | 36 passing, 1 skipped (37 total) |
Tests | 1066 passing, 11 skipped (1077 total) |
Documentation Files | 23+ markdown files |
Database Entities | 20 core models |
Supported Cloud Providers | Local, GCP, AWS, Agnostic (via adapters) |
API Response SLO | <200ms (achieved via denormalization) |
Layer | Technology |
---|---|
Runtime | Node.js 24.x |
Language | TypeScript 5.7 |
Framework | Express 5.x |
Database | PostgreSQL 16.x |
ORM | Sequelize 6.x |
Authentication | JWT + Magic Links |
Testing | Jest 30.x + Supertest |
Validation | Joi 18.x |
Logging | Winston 3.x |
Security | Helmet, bcrypt, express-rate-limit |
API Docs | OpenAPI 3.0 + Swagger UI |
This project follows strict code quality standards and TDD practices. See CONTRIBUTING.md
for detailed guidelines.
Key Principles:
- Always reference component STANDARDS.md files before creating new code
- Follow TDD: Write failing test β Implement β Refactor
- Run
npm run typecheck && npm run lint && npm test
before committing - Keep files under 500 lines (max 1000) - refactor if exceeding
- Use centralized constants (no magic strings)
- Maintain camelCase in API layer, snake_case in database layer
This project is licensed under the MIT License - see the LICENSE file for details.
- Inspired by typescript-postgres-auth-example
- Built with Test-Driven Development (TDD) and AI-assisted context refinement
- Demonstrates enterprise-grade architecture patterns for Node.js/TypeScript APIs
For questions, issues, or contributions:
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: See
api/docs/
for comprehensive guides
Built with β€οΈ using TypeScript, Express, and PostgreSQL