SaaS Boilerplate - Project Documentation¶
Brownfield Documentation for AI-Assisted Development Generated: 2026-02-12 | Last Full Rescan: 2026-03-26 | Scan Level: Exhaustive | Workflow: document-project v1.2.0
Project Overview¶
A production-ready SaaS boilerplate consisting of a Node.js/TypeScript backend and a Next.js 15 frontend, designed for rapid development of subscription-based web applications.
| Aspect | Details |
|---|---|
| Project Type | Multi-Part SaaS Application |
| Backend | Express.js 4.18 + TypeScript 5.4 + PostgreSQL |
| Frontend | Next.js 15 + React 19 + TailwindCSS 4 |
| Deployment | Vercel (API) + Netlify (Frontend) |
Quick Navigation¶
Architecture Documentation¶
- Architecture Overview — High-level system design
- Backend Architecture — Express.js API: 30 modules, 212 endpoints, 14 middleware, 10 policies, event system
- Frontend Architecture — Next.js app: 74 pages, 239 components, 139 API hooks across 20 domains
- Database Schema — 29 entities, ~233 columns, 30 relations, 11 enums, 52 indexes
- API Reference — 212 REST endpoints across 30 modules with request/response examples
- Integration Guide — Frontend-backend communication, auth flow, cache revalidation, payments
Quick Start¶
Backend Setup¶
cd saas-boilerplate
yarn install
cp .env.example .env
# Configure database and secrets in .env
yarn dev # Starts on port 5500
yarn seed # Seed database
Frontend Setup¶
cd Sass-boilerplate-frontend-v1
npm install
# Set NEXT_PUBLIC_API_URL=http://localhost:5500/api/v1 in .env.local
npm run dev # Starts on port 3000
Key Features Summary¶
Authentication & Security¶
- Email/Password with email verification
- OAuth (Google) integration
- OTP-based passwordless login
- Two-factor authentication (Email OTP, Google Authenticator)
- JWT with refresh token rotation
- Role-Based Access Control (RBAC) with route-level permissions
- Login attempt tracking with account lockout
Subscription & Payments¶
- Stripe integration (subscriptions + one-time payments)
- LemonSqueezy alternative provider
- Package/Plan management with categories
- Coupon/discount codes
- Webhook handling for payment events
Content Management¶
- Blog system (posts, categories, tags, view tracking)
- Generic CMS pages with rich text
- Dynamic menu builder with nested items
- Product catalog with categories
- Email template management
- Rich text editor (BlockNote)
Admin Dashboard¶
- User management with invite-only mode
- Role/permission management UI
- Site settings configuration
- Analytics dashboard
- Contact form submissions
Technology Stack¶
Backend¶
| Category | Technology |
|---|---|
| Runtime | Node.js |
| Language | TypeScript 5.4 |
| Framework | Express.js 4.18 |
| Database | PostgreSQL |
| ORM | TypeORM 0.3 |
| Validation | Zod 3.22 |
| Auth | JWT + Passport |
| Payments | Stripe + LemonSqueezy |
| Storage | Cloudinary + AWS S3 (factory pattern) |
| Nodemailer + Resend + Brevo (factory pattern) | |
| Logging | Winston + PostgreSQL transport |
| Cron | node-cron |
Frontend¶
| Category | Technology |
|---|---|
| Framework | Next.js 15 (App Router + Turbopack) |
| UI Library | React 19 |
| Styling | TailwindCSS 4 |
| State | Redux Toolkit 2.8 (auth + settings) |
| Data Fetching | TanStack React Query 5 |
| UI Components | Radix UI (shadcn pattern) |
| Forms | React Hook Form 7 |
| Rich Text | BlockNote 0.35 |
| Charts | ApexCharts + Recharts |
| Animations | Framer Motion 12 |
| Drag & Drop | @dnd-kit |
| Icons | Lucide React |
Repository Structure¶
SaaS/ # Project root (documentation)
├── docs/ # This documentation
│ ├── index.md # You are here
│ └── architecture/ # Architecture docs (6 files)
├── saas-boilerplate/ # Backend
│ ├── src/
│ │ ├── app/modules/v1/ # 30 API modules (212 endpoints)
│ │ ├── entity/ # 29 database entities (~233 columns)
│ │ ├── lib/ # Service factories (email, payment, storage, cache)
│ │ ├── shared/ # 15 shared utility files
│ │ ├── helper/ # 23 helper files (auth, upload, encryption)
│ │ ├── app/middlewares/ # 14 middleware files (auth, RBAC, validation, security)
│ │ ├── app/policy/ # 10 auth validation policies
│ │ ├── app/events/ # Event-driven side effects (7 handlers)
│ │ └── app/cron/ # Scheduled tasks (2 jobs)
│ ├── package.json # 47 prod + 20 dev dependencies
│ └── .env.example
└── Sass-boilerplate-frontend-v1/ # Frontend
├── src/
│ ├── app/ # Next.js pages (74 routes, 4 layouts)
│ ├── components/ # 239 component files (42 UI + 33 custom + 128 page + 15 editor + 9 layout + 5 providers + 7 theme)
│ ├── api/ # React Query hooks (31 files, 139 hooks across 20 domains)
│ ├── hooks/ # 10 custom hooks
│ ├── store/ # Redux store (auth + settings slices)
│ ├── actions/ # Server actions (revalidation)
│ └── interceptors/ # Axios config + auth interceptors
└── package.json # 26 prod + 7 dev dependencies
Environment Requirements¶
Prerequisites¶
- Node.js 18.17+ (required by both backend and frontend; Next.js 15 enforces this minimum)
- PostgreSQL 14+
Package Managers¶
- Backend: Has both
yarn.lockandpackage-lock.json. Docs useyarncommands butnpmalso works. - Frontend: Uses
npmexclusively (package-lock.jsononly).
Note: Neither
package.jsonspecifies anenginesfield. Consider adding"engines": { "node": ">=18.17.0" }to both to enforce the minimum version.
External Services¶
- Stripe account (payments)
- Cloudinary account (file uploads)
- SMTP server or Resend/Brevo API (email)
- Google Cloud Console (OAuth — optional)
Testing¶
Current State¶
Neither the backend nor frontend currently includes a test suite. No test files (*.test.ts, *.spec.ts, *.test.js), test scripts, or testing framework dependencies exist in either package.json.
Recommended Setup¶
Backend (suggested):
yarn add -D jest ts-jest @types/jest supertest @types/supertest
# Configure jest.config.ts with ts-jest preset
# Add "test": "jest" to scripts
Frontend (suggested):
npm install -D vitest @testing-library/react @testing-library/jest-dom
# Add "test": "vitest" to scripts
Common Development Tasks¶
Adding a New API Module (Backend)¶
- Create module directory:
src/app/modules/v1/NewModule/ - Create files: controller, service, routes, validation
- Register routes in
src/app/routes/v1/index.ts - Create entity if needed in
src/entity/ - Add permissions via seed or API
Adding a New Page (Frontend)¶
- Create page in
src/app/(dashboard-layout)/dashboard/new-page/ - Create component in
src/components/pages/new-page/ - Create API hooks in
src/api/new-module/ - Add navigation item via Menu Builder or API
Adding a New Permission¶
- POST to
/permissionswith route pattern - Assign to roles via
/roles/:idupdate - Frontend: Use
useCheckPermissionhook for UI gating
Changes Since Last Scan (2026-03-12 → 2026-03-26)¶
Backend (8 commits)¶
- Security: OTP generation switched to
crypto.randomInt(CSPRNG, replacing Math.random) - Security: Password hashing now async (
bcrypt.hashnon-blocking) - Security: JWT
decodeTokenvalidates signature before decoding - Config:
AppConfig.tssingleton with required env variable validation at startup - Docs: 6 solution documentation files added
Frontend (39 commits)¶
- Cache revalidation system: New
/dashboard/settings/revalidatepage, 3 revalidation hooks, server actions for tag-based cache busting (7 tags) - Blog tags CRUD: New
/dashboard/blogs/tagspage with full CRUD operations - DOMPurify sanitization: Applied to all 9
dangerouslySetInnerHTMLinstances, newSanitizedHTMLPreviewcomponent - Menu Builder v2: Drag-and-drop reordering with @dnd-kit, WordPress-style hierarchy
- Pricing refactor: Split into
PricingContent(monthly/yearly toggle) andPricingSection - Security fixes: Axios interceptor operator precedence bug,
target="_blank"rel attributes - Cleanup: BlogTagsPage component removed and re-added via PR
Cumulative Changes (2026-02-25 → 2026-03-12)¶
- Auth controller typo fixed, helpers deleted (1,837 LOC), middleware simplified (227 LOC dead code removed)
validateRequestnow replacesreq.bodywith validated data- Registration endpoint renamed, email verification rewritten with JWT
- WebP auto-conversion, routes middleware streamlined
- KC1 GenericPage XSS fixed (DOMPurify), KC5 IframeEmbed fixed (URL allowlist + sandbox)
- AI Integration, BasicEditor, theme/font customization, FooterCredit added
- Dead code removed: email-templates-v1, permissions sandbox, roles-badge-group (~2,440 LOC)
Deep-Dive Documentation¶
Detailed exhaustive analysis of specific areas — View all options & tracker
- Authentication System Deep-Dive — Comprehensive full-stack analysis of the authentication system: multi-provider login, 2FA, JWT lifecycle, RBAC, progressive lockout, and frontend auth state (70+ files, 5,500+ LOC) — Generated 2026-02-13
- Auth Review Findings — Adversarial review of the auth deep-dive (21 findings, all resolved)
- Auth Review Meta-Findings — Adversarial meta-review of the review findings document itself (14 findings)
- Subscription & Payments Deep-Dive — Exhaustive analysis of the payment system: Stripe integration, subscription lifecycle, webhook handling, coupon system, payment factory pattern, and package management (48 files, 4,200+ LOC, 47 issues) — Generated 2026-02-13
- Middleware & API Infrastructure Deep-Dive — Exhaustive analysis of the request processing pipeline: 13 middleware files, security headers, auth guards, RBAC, validation, rate limiting, logging, Swagger docs, public API (19 files, 2,184 LOC, 26 issues) — Generated 2026-02-16
- User Management & RBAC Deep-Dive — Exhaustive full-stack analysis of user CRUD, role/permission management, invite system, 2FA settings, RBAC architecture, and permission checking infrastructure (80+ files, 15,600+ LOC, 70 issues) — Generated 2026-02-25
- Menu Builder System Deep-Dive — Exhaustive full-stack analysis of dynamic navigation management: Menu/MenuItem CRUD, WordPress-style tree editor, drag-and-drop reordering, multi-content linking, dual old/v2 implementations, 3,300+ LOC dead code identified (38+ files, 8,900+ LOC, 42 issues) — Generated 2026-02-25
- RBAC Attack Scenarios — Red Team privilege escalation analysis: zero-permission user to super_admin in 1 API call, 6 attack vectors, pre-mortem analysis (7 failure scenarios), 5 ADRs with migration plan, root cause analysis — Generated 2026-02-25
- RBAC Sprint Plan — Cross-functional war room output: 70 issues triaged into Ship Blockers (~1hr), Sprint 1 (~7hrs), Sprint 2 (~12hrs), Backlog. Total ~23hrs over 3 weeks. — Generated 2026-02-25
- API Documentation Review Findings — Adversarial code-level audit of api.md: 94 total findings across 3 rounds (70 + 14 + 10), all resolved — includes privilege escalation in PATCH /users/profile, blog hybrid permission model, fabricated analytics param — 2026-02-25
- Email Template System Deep-Dive — Exhaustive full-stack analysis of the email template builder, CRUD module, email sending infrastructure (3 providers), and visual DnD editor: disconnected DB templates, dual email architecture, SQL injection, stored XSS (44 files, 10,600+ LOC, 60 issues) — Generated 2026-02-25
- Email Template Attack Scenarios — Red Team analysis: 5 attack chains including SQL injection → DB compromise and stored XSS → admin takeover (2 CRITICAL, P0 fix in 45 min) — 2026-02-25
- Email Template ADRs — 3 Architecture Decision Records: unify email infra (~4h), connect DB templates to sending (~6h), delete legacy v1 (~5min) — 2026-02-25
- Email Template Pre-mortem — 7 failure scenarios: SQL injection breach, silent email failure, permission lockout, wasted sprint, config nightmare, XSS escalation, runtime crash — 2026-02-25
- Email Template Root Cause Analysis — 5 Whys analysis: 3 systemic root causes (zero test coverage, super_admin-only dev, no integration tracking) driving all architectural issues — 2026-02-25
- UI Component Library Deep-Dive — Exhaustive analysis of the full frontend component system: 40 ui/ primitives (shadcn/Radix), 34 custom/ composed components, 15 editor/ files (BlockNote), 9 layout/ shells. 18 dead code files, gold color tokens undefined, 3 competing modal systems, 5 user flows traced (98 files, ~13,700 LOC, ~405 issues incl. 9 Critical) — Generated 2026-02-25
- UI Component Attack Scenarios — Red Team vs Blue Team analysis: 5 kill chains (GenericPage stored XSS → account takeover, social login token forgery, clickjacking, blog preview XSS, iframe phishing), 4 CRITICAL defense gaps (no CSP, no sanitization, no httpOnly, no iframe sandbox), P0 fix in 1.25 hours — 2026-02-25
- Settings & Configuration Deep-Dive — Exhaustive full-stack analysis of 3 configuration subsystems: Setting (global site config, 19 seeded keys), AppConfig (encrypted secrets vault), UserSetting (per-user 2FA/prefs). Public GET endpoints, 3 frontend access patterns (React Query + Redux + SSR cache), dual source of truth, unseeded permissions, 2FA secret leakage (40+ files, ~5,800+ LOC, 85 issues incl. 18 Critical) — Generated 2026-02-25
- Settings & AppConfig Deep-Dive — Focused analysis of the AppConfig encrypted secrets vault and its integration with the Setting entity system (45 issues incl. 14 Critical) — Generated 2026-02-25
- Landing Page & Public Site Deep-Dive — Exhaustive full-stack analysis of the public-facing site: landing page (7 sections), blog system (listing/detail/author/category), contact form, dynamic pages, navigation. ALL 5
unstable_cachewrappers broken, 2 stored XSS vectors, 7 dead CTA buttons, GenericPage data leak, zero test coverage (81 files, ~8,200+ LOC, 70 issues incl. 7 Critical) — Generated 2026-02-25 - Attack Scenarios — Red Team: 7 attack chains, full platform takeover chain, 16-fix hardening roadmap (~4h 40m)
- ADRs — 5 architecture decisions: caching migration, HTML sanitization, CTA wiring, SEO infrastructure, CI pipeline (23-31h total)
- Pre-mortem — 9 failure scenarios, ship-blocker list, ~3h fix estimate
- Root Cause Analysis — 5 Whys: 6 patterns, 4 systemic root causes
- Blog/CMS System Deep-Dive — Exhaustive full-stack analysis of the Blog/CMS system: Blog CRUD with ownership-based permissions (9/10 checkPermissionAndThrow commented out), BlogCategory (hierarchical), BlogTag (ManyToOne — not shared), GenericPage (CMS pages), Slug generator, Public SSR pages with ISR. SQL injection via orderBy, Rules of Hooks crash, hero image field mismatch, author pages broken, category links broken. Adversarial reviewed 2026-03-27 (79 files, ~14,978 LOC, 236 issues incl. 26 Critical) — Generated 2026-03-26, Reviewed 2026-03-27
- Frontend Infrastructure Deep-Dive — Exhaustive analysis of cross-cutting frontend wiring: Redux store (auth + settings), Axios interceptor, 10 custom hooks, 5 providers, theme context, 10 lib utilities, services, server actions, HOCs, constants, middleware, 4 layouts. No token refresh mechanism, permission split-brain after refresh, 403→logout bug, theme desync, uploadFile zero validation, full Lucide import, 727 LOC dead code, 4 coexisting state systems, 5 user flows traced (45 files, ~2,100 LOC, ~179 issues incl. 16 Critical) — Generated 2026-03-26
- Shared Utilities Deep-Dive — Exhaustive analysis of the cross-cutting utility layer: DB repository factory (53 consumers), async error wrapper (32 consumers), response standardizer (29 consumers), permission caching/normalization, request context (AsyncLocalStorage), CORS config, slug generation, image processing, caching.
pick.tsdead code, mutable permission Set (privilege escalation), unbounded slug loop (DoS), ACTION_MAPPING ignored, zero test coverage (15 files, ~926 LOC, 108 issues incl. 17 Critical) — Generated 2026-03-29 - Service Factories Deep-Dive — Exhaustive analysis of 4 factory subsystems: Email (3 providers: NodeMailer, Resend, Brevo), Payment (Stripe + LemonSqueezy), Storage (AWS S3, Cloudinary, Local), Cache (node-cache). Factories ~11% adopted — 89% of consumers use legacy helpers. Storage and Cache factories 100% dead code. Email factory broken by default (EMAIL_SERVICE missing), BrevoService silently swallows errors, Stripe cancelUrl broken, LemonSqueezy webhook secret hardcoded, ~434 LOC dead code, 13 competing implementations, 0% test coverage (45+ files, ~2,200+ LOC, ~147 issues incl. 28 Critical) — Generated 2026-03-29
- Helper Functions, Config & DB Deep-Dive — Exhaustive analysis of the foundational utility layer: 24 helper files (auth, file upload, email, encryption, pagination), 8 config files (env loading, Stripe/LemonSqueezy/Cloudinary/Passport init), 1 DB connection. Leaked Cloudinary credentials in dead code, 3x path traversal, zero file type validation, MASTER_KEY not validated, AppConfig.ts 150 LOC duplicate, dual Stripe init, hardcoded localhost in LemonSqueezy, triple permission implementation, dual email pipeline, ~350 LOC dead code, 0% test coverage (33 files, ~1,328 LOC, 88 issues incl. 20 Critical) — Generated 2026-03-30
- Logging & Analytics Deep-Dive — Exhaustive full-stack analysis of HTTP logging pipeline (Winston + PostgresTransport + Logger entity) and dashboard analytics module. HTTP logging pipeline entirely disabled (httpLogger never registered). Analytics endpoint has no permission check and no caching (~20 DB queries per call). 3 critical frontend-backend mismatches (totalGames/upvotes/blogWithAuthor "today" key). ~2,345 LOC dead code (V1/V2 dashboards + disabled logging pipeline). Two chart libraries bundled. 0% test coverage (34 files, ~5,800 LOC, 64 issues incl. 9 Critical) — Generated 2026-04-11
- Product Catalog Deep-Dive — Exhaustive full-stack analysis of the Product Catalog system: Product CRUD (multi-image upload, pricing, categories), ProductCategory (copied from BlogCategory with 5+ copy-paste bugs), Image upload module (unauthenticated). Entire frontend is mocked — every API call commented out, 15 hardcoded products, mock delays. Backend functional but permission checks missing/commented-out,
originalPricefield mismatch causes data loss, zero permissions seeded, hard delete on categories despite @DeleteDateColumn. 5 user flows traced end-to-end (23 files, ~2,786 LOC, 75 issues incl. 18 Critical, ~577 LOC dead code) — Generated 2026-04-11
Documentation Metadata¶
| Field | Value |
|---|---|
| Last Updated | 2026-04-11 |
| Last Full Rescan | 2026-03-26 |
| Initial Scan Date | 2026-02-12 |
| Scan Level | Exhaustive |
| Deep-Dives | 16 (Auth, Payments, Middleware, RBAC, Menu Builder, Email Templates, UI Components, Settings & Config, Settings AppConfig, Landing Page, SEO, Blog/CMS, Frontend Infrastructure, Shared Utilities, Service Factories, Helper Functions/Config/DB, Product Catalog, Logging & Analytics) |
| Workflow | document-project v1.2.0 |
| Backend .ts Files | 289 |
| Backend Entities | 29 (~233 columns, 30 relations, 11 enums) |
| Backend API Modules | 30 |
| Backend Endpoints | 212 (verified) |
| Backend Middleware Files | 14 |
| Backend Policy Files | 10 |
| Backend Dependencies | 47 prod + 20 dev |
| Frontend .js/.jsx Files | 413 |
| Frontend Pages | 74 (4 layouts) |
| Frontend Components | 239 (42 UI + 33 custom + 128 page + 15 editor + 9 layout + 5 providers + 7 theme) |
| Frontend API Hook Files | 31 (20 domains) |
| Frontend API Hooks Total | 139 (verified) |
| Frontend Custom Hooks | 10 |
| Frontend Dependencies | 26 prod + 7 dev |
Generated by BMAD Document Project workflow v1.2.0 — Exhaustive scan, 2026-02-12 | Full rescan: 2026-03-26 | 608 source files read, 127 issues documented across 6 parallel deep-dive agents