# Vibe44 - Aggregated Full Documentation for AI Agents & LLMs
> Vibe44 is the 100% agent-native Next.js SaaS Boilerplate.
> This document aggregates the entire developer documentation to enable immediate RAG ingestion, code generation, and setup synthesis.
## Public MCP Server (Live)
Vibe44 provides a **live Model Context Protocol (MCP) server** that AI agents can connect to for real-time, programmatic access to the entire developer documentation.
- **Endpoint**: `https://vibe44.com/mcp`
- **Transport**: Streamable HTTP (stateless, no session tracking)
- **Rate Limit**: 60 requests per minute per IP
### Available MCP Tools
| Tool | Description |
|------|-------------|
| `search_docs` | Search documentation for a specific term or pattern. Returns ranked hits with paths and snippets. |
| `list_categories` | Get the full structured navigation hierarchy of all documentation pages. |
| `read_doc_page` | Read any documentation page as clean markdown by its relative path (e.g. `architecture/payments`). |
### Quick Configuration
To connect your MCP client, add the following to your configuration:
```json
{
"mcpServers": {
"vibe44": {
"url": "https://vibe44.com/mcp"
}
}
}
```
Supported clients include: Cursor, Claude Code, VS Code, Antigravity, Gemini CLI, Windsurf, TRAE, Cline, Claude Desktop, Zed, JetBrains IDEs, and Codex.
For full setup instructions per client, see: https://vibe44.com/docs/mcp
---
# Index
Welcome to the **Vibe44** documentation. This is the complete production-grade infrastructure layer your product runs on.
## Browse by Topic
## Support
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
---
# Mcp
Vibe44 provides a public [Model Context Protocol](https://modelcontextprotocol.io/) server for its documentation and blog. It lets AI assistants search docs, read pages, and browse blog posts as markdown, so answers can stay grounded in the latest official content.
The server is exposed through a Streamable HTTP endpoint:
```txt
https://vibe44.com/mcp
```
> [!NOTE]
>
You do not need to install or run anything locally. Point your MCP client to
the hosted Vibe44 docs endpoint: `https://vibe44.com/mcp`.
## What it provides?
The MCP server gives AI clients direct access to Vibe44 documentation and blog posts.
## Quick start
### Add Vibe44 to your MCP client
Configure your AI assistant to connect to the Streamable HTTP endpoint. Most MCP clients support either a project-level config file or a settings UI.
Create or update `.cursor/mcp.json` in your project root:
```json title=".cursor/mcp.json"
{
"mcpServers": {
"vibe44": {
"url": "https://vibe44.com/mcp"
}
}
}
```
Then enable the server in **Cursor Settings > MCP**. Once connected, Cursor will show the available Vibe44 docs tools.
Create or update `.mcp.json` in your project root:
```json title=".mcp.json"
{
"mcpServers": {
"vibe44": {
"type": "http",
"url": "https://vibe44.com/mcp"
}
}
}
```
Restart Claude Code and run `/mcp` to confirm the server is connected.
Create or update `.vscode/mcp.json` in your project root:
```json title=".vscode/mcp.json"
{
"servers": {
"vibe44": {
"type": "http",
"url": "https://vibe44.com/mcp"
}
}
}
```
Start the server from the **MCP controls** in the VS Code chat panel.
Open **Manage MCP Servers > View raw config** and add to `mcp_config.json`:
```json title="~/.gemini/config/mcp_config.json"
{
"mcpServers": {
"vibe44": {
"serverUrl": "https://vibe44.com/mcp"
}
}
}
```
Save and refresh the MCP Servers panel. You can also use the **MCP Store** to browse and install servers directly.
Add to your Gemini CLI settings file:
```json title="~/.gemini/settings.json"
{
"mcpServers": {
"vibe44": {
"httpUrl": "https://vibe44.com/mcp"
}
}
}
```
Restart the CLI and run `/mcp` to verify the server is connected.
Open **Windsurf Settings > Cascade > MCP Servers > View raw config** and update `mcp_config.json`:
```json title="~/.codeium/windsurf/mcp_config.json"
{
"mcpServers": {
"vibe44": {
"serverUrl": "https://vibe44.com/mcp"
}
}
}
```
Save and restart Windsurf to pick up the new server.
Go to **Settings > MCP > Add > Edit Configuration** and add:
```json title="MCP Configuration"
{
"mcpServers": [
{
"name": "vibe44",
"url": "https://vibe44.com/mcp",
"type": "streamableHttp"
}
]
}
```
Toggle the server on from the MCP settings panel.
Open the **MCP Servers** panel in Cline, go to **Configure**, and update `cline_mcp_settings.json`:
```json title="cline_mcp_settings.json"
{
"mcpServers": {
"vibe44": {
"url": "https://vibe44.com/mcp",
"disabled": false,
"autoApprove": []
}
}
}
```
Restart the Cline extension to initialize the connection.
Add to `claude_desktop_config.json` using the `mcp-remote` bridge:
```json title="claude_desktop_config.json"
{
"mcpServers": {
"vibe44": {
"command": "npx",
"args": [
"-y",
"mcp-remote",
"https://vibe44.com/mcp"
]
}
}
}
```
Requires Node.js v18+. Restart Claude Desktop after saving.
Open **Zed Settings** (`Cmd+,` / `Ctrl+,`) and add to `settings.json`:
```json title="settings.json"
{
"context_servers": {
"vibe44": {
"url": "https://vibe44.com/mcp"
}
}
}
```
Restart Zed to activate the server. Check the Agent Panel for a green indicator.
Go to **Settings > Tools > AI Assistant > Model Context Protocol (MCP)**, click **+**, and select **HTTP**:
```json title="MCP Server Configuration"
{
"type": "http",
"url": "https://vibe44.com/mcp"
}
```
Works with IntelliJ IDEA, WebStorm, PyCharm, and all JetBrains IDEs (2025.2+).
Add the server to `~/.codex/config.toml`:
```toml title="~/.codex/config.toml"
[mcp_servers.vibe44]
type = "http"
url = "https://vibe44.com/mcp"
```
Restart Codex so it picks up the new server.
### Let your AI agent set it up
If your AI assistant (such as Cursor, Claude Code, Cline, or Antigravity) has URL reading or web search capabilities, you can have it configure the Vibe44 MCP server automatically.
### Ask Vibe44-specific questions
Try prompts that need documentation or blog context:
* Search the Vibe44 docs for billing webhooks.
* Read the Vibe44 authentication overview and summarize the setup.
* Find where Vibe44 documents AI-assisted development.
* List all Vibe44 blog posts about security.
* Read the blog post about SSRF hardening in Next.js.
* Search Vibe44 blog for Drizzle vs Prisma comparison.
## Available tools
Your MCP client will see six tools โ three for documentation and three for blog posts.
### Documentation tools
#### `search_docs`
Searches Vibe44 documentation for a specific term or pattern.
```json title="Input"
{
"query": "billing webhooks"
}
```
#### `list_categories`
Gets the structured navigation hierarchy of the documentation pages.
#### `read_doc_page`
Reads a documentation page as clean markdown.
```json title="Input"
{
"pagePath": "architecture/payments"
}
```
The `pagePath` can be any relative page path returned by `list_categories` or `search_docs` (e.g. `introduction/why-vibe44`, `index`, or `architecture/payments`).
### Blog tools
#### `list_blog_posts`
Lists all published blog posts with title, date, author, tags, and excerpt. Returns posts sorted by date (newest first).
#### `search_blog_posts`
Searches blog posts by keyword across title, content, description, and tags.
```json title="Input"
{
"query": "SSRF"
}
```
#### `read_blog_post`
Reads the full markdown content of a blog post by its slug (filename without the `.mdx` extension).
```json title="Input"
{
"slug": "ssrf-hardening-nextjs"
}
```
The `slug` can be any slug returned by `list_blog_posts` or `search_blog_posts` (e.g. `drizzle-vs-prisma`, `owasp-top-10-2025-nextjs`, or `public-mcp-server-docs`).
## Troubleshooting
Make sure the URL is exactly `https://vibe44.com/mcp` and that your MCP client supports Streamable HTTP servers.
Restart the MCP client after editing its configuration. Some clients also
require enabling the server in settings before tools appear.
Check that your network can reach `https://vibe44.com/mcp` over HTTPS. If your
company uses a proxy or firewall, allow requests to the vibe44.com domain.
Ask it to use the Vibe44 docs MCP server explicitly. For example: "Use the Vibe44 docs MCP server to search for authentication setup, then explain the steps."
---
# SECTION: Introduction
## Introduction > Why Vibe44
Most boilerplates ship a landing page and a Stripe integration. You architect everything else from scratch. **Vibe44 is the complete** **production-grade** **infrastructure layer your product runs on** โ engineered with โค๏ธ by Alap Putatunda (Scale with Alap) to help you build & ship your AI SaaS/Startup or web app in weeks instead of months.
> [!NOTE]
>
Every line of code exists because it solves a real problem between "idea" and
"a ready product." Nothing vanity. Everything velocity.
| Problem | Real-World Cost | Vibe44 Solution |
| :--------------------------- | :---------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| ๐ธ**Payment vendor lock-in** | Migrations cost 50+ engineering hours | **Universal Payment Adapter** โ swap 5 providers with one env var. Zero code changes. |
| ๐**Expensive AI Tokens** | AI burns massive tokens analyzing large codebases | **Graphify Knowledge Graph** โ Built-in AST mapping cuts AI token usage by up to 71.5x. |
| ๐จ**Generic UI** | Users judge in ~50ms (Google research). Generic = "side project." | **Glassmorphism 2.0** โ crystal surfaces, spring physics, tri-font typography, collapsible nested navigation, and fully localized marketing forms. Premium from pixel #1. |
| โ๏ธ**Expensive legal** | $2,000โ5,000+ for Privacy Policy + Terms | **AI Legal Generator** โ Gemini-powered, versioned, consent-tracked. |
| ๐ง **No AI infra** | Chat + RAG + voice = 2โ4 weeks from scratch | **Gemini Chat + RAG + ElevenLabs/Murf Voice** โ multi-turn, pgvector embeddings, 29+ language voice. Day 1. |
| ๐**Security afterthought** | ~47% of cyberattacks target small businesses (Verizon DBIR) | **Enterprise security from Day 1** โ RLS on 32 SQL tables, edge + 56+ route-level rate-limited API route files, circuit breaker, OWASP Top 10 (2025) compliant. |
| ๐ค**AI tools hallucinate** | No architectural context = broken code | **agent-native Architecture** โ `AGENTS.md`, `CLAUDE.md` (for Claude Code), along with the `.agents/` folder (skills, workflows) = zero hallucination. |
## Stack Value Breakdown
Built this yourself? Here's what you'd pay for each module separately:
| Component | Market Value | Why |
| :------------------------------ | :----------- | :------------------------------------------------------------ |
| **Enterprise Auth (RBAC)** | $500+ | Multi-tenancy, roles, invitations, sessions โ pre-configured |
| **Universal Payment Adapter** | $2,000+ | Unified interface for 5 providers. Months saved. |
| **AI Chat + RAG Pipeline** | $1,500+ | Vector embeddings, retrieval, chat UI with optimistic updates |
| **ElevenLabs Voice** | $800+ | Real-time TTS/STT with audio wave visualization |
| **super-admin Dashboard & CMS** | $1,000+ | Full CRUD for users, tickets, content. Not a DB viewer. |
| **OWASP Security Audit** | $3,000+ | Published PDF for enterprise sales closings |
| **Total Value** | **$8,800+** | **You pay: $197** (Starter) โ **96.74% off** |
---
## Who Is This For?
**You get:** Auth, payments, AI chat, super-admin panel, legal docs, deployment โ pre-wired. Add your feature. Ship.
**You get:** AI-readable architecture docs, 18 workflow playbooks, typed
everything, super-admin dashboard your non-technical co-founder uses from Day
1.
**You get:** Unlimited deployed products per license. Rebrand via `lib/config.ts` in 5 minutes. Swap payment providers per client. One-click deploy.
---
## ๏ธ How Vibe44 Compares?
| Feature | Vibe44 | ShipFast | Supastarter | LaunchFast |
| :------------------------------ | :-------------------------------------------------------------- | :---------------- | :----------------------- | :--------- |
| **Multi-Payment Provider** | โ
5 providers, swappable | โ ๏ธ Stripe / LS | โ
5 providers | โ ๏ธ 1 only |
| **Knowledge Graph (AI)** | โ
Graphify (71.5x save) | โ N/A | โ N/A | โ N/A |
| **AI Chat + RAG** | โ
4-provider + pgvector RAG | โ N/A | โ ๏ธ Vercel AI | โ N/A |
| **Voice Chat (TTS/STT)** | โ
ElevenLabs + Murf AI | โ N/A | โ N/A | โ N/A |
| **Glassmorphism Design** | โ
Complete | โ ๏ธ Basic | โ ๏ธ Basic | โ ๏ธ Basic |
| **AI Agent Architecture** | โ
AGENTS.md + CLAUDE.md + 4 SKILL.md + 18 Workflows + Graphify | โ ๏ธ Basic | โ
AGENTS.md | โ ๏ธ CLI AI |
| **RLS (Row Level Security)** | โ
All 32 tables | โ ๏ธ Partial | โ
Built-in | โ N/A |
| **Multi-Tenancy / Orgs** | โ
Full RBAC | โ N/A | โ
Built-in | โ N/A |
| **Affiliate System** | โ
Built-in | โ N/A | โ N/A | โ N/A |
| **Analytics System** | โ
9 analytics providers, swappable | โ N/A | โ ๏ธ Basic | โ N/A |
| **oRPC Type-Safe API** | โ
Built-in | โ N/A | โ
Hono/oRPC | โ N/A |
| **AI Legal Generator** | โ
Gemini-powered | โ N/A | โ N/A | โ N/A |
| **super-admin Dashboard** | โ
17 Modules + Impersonation | โ ๏ธ Basic | โ
Admin + Impersonation | โ N/A |
| **E2E + Unit Tests + CI** | โ
900 tests across 84 files + CI | โ N/A | โ
Playwright | โ N/A |
| **Rate Limiting + Breaker** | โ
Edge Redis + Circuit Breaker | โ N/A | โ N/A | โ N/A |
| **Seat-Based Billing** | โ
Stripe-native + DB | โ N/A | โ
Built-in | โ N/A |
| **Universal Email Adapter** | โ
4 providers + 13 templates | โ ๏ธ Mailgun/Resend | โ
Built-in | โ ๏ธ Basic |
| **i18n (Internationalization)** | โ
3 locales + 14 modules | โ N/A | โ
Built-in | โ N/A |
| **OWASP Top 10 Compliance** | โ
Full (2025 edition) | โ N/A | โ N/A | โ N/A |
| **Newsletter System** | โ
Built-in + source tracking | โ N/A | โ N/A | โ N/A |
| **Background Jobs** | โ
QStash + Trigger.dev | โ N/A | โ
trigger.dev | โ N/A |
| **In-App Notifications** | โ ๏ธ Coming Soon | โ N/A | โ
Built-in | โ N/A |
> [!NOTE]
>
This comparison is based on publicly available information from each product's
official website as of the 1st week of May 2026. We respect ShipFast,
Supastarter, and LaunchFast โ they are all solid products serving different
needs. The key differentiator for Vibe44 is depth: AI infrastructure
(multi-provider RAG, voice, legal gen), a premium Glassmorphism design system,
built-in affiliate engine, 9-provider analytics, OWASP-audited enterprise
security, and the Graphify knowledge graph โ features that go beyond what
typical boilerplates ship. Feature availability may change as competitors
update their products.
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Introduction > Features
### Universal Payment Adapter
Vendor lock-in is dead. Switch providers with **one env var** โ zero code changes.
| Provider | Config | Best For | Tax Handling |
| :---------------- | :-------------- | :----------------------- | :----------------- |
| **Stripe** | `stripe` | Global, full-featured | You handle |
| **Polar** | `polar` | Open-source, EU-friendly | Merchant of Record |
| **Lemon Squeezy** | `lemon-squeezy` | Simple global tax | Merchant of Record |
| **Dodo** | `dodo` | Emerging markets | Merchant of Record |
| **Creem** | `creem` | Global tax compliance | Merchant of Record |
Average SaaS changes payment providers at least once in 3 years. Traditional migration = weeks. Vibe44:
```bash
PAYMENT_PROVIDER=polar # Was "stripe". Done.
```
**Built-in security:**
- โ
Webhook idempotency via `webhook_logs` (success skips, active processing skips, failed/stale processing retries)
- โ
Provider-resource idempotency via unique `(provider, provider_subscription_id)` and `(provider, provider_payment_id)` indexes
- โ
Decoupled Billing Architecture โ `TIER_IDS` central registry eliminating hardcoded tiers
- โ
Dynamic Usage Limits โ Render tier constraints (projects, team members, API requests, storage) directly from central pricing configs
- โ
Upgrade Guard Hardening โ Intelligently hide "Upgrade Plan" buttons for users already on the most expensive plan
- โ
Paid product-name mapping โ config-driven `highIntentAliases` per tier (e.g. `business`, `agency`, `enterprise`) resolve provider product names to the correct tier without hardcoded keyword lists
- โ
Digital Product Fulfillment โ Secure downloads decoupled from tier-granting logic
- โ
HMAC-SHA256 signature verification on every webhook
- โ
Replay protection with timestamp validation
- โ
Same-origin checkout/portal redirects via allowlisted return paths
- โ
Generic billing API errors with provider details retained server-side
- โ
Impersonation-aware REST billing routes via `getEffectiveUserId()` parity with Server Actions
- โ
Provider readiness checks โ selected-provider secrets and active paid-tier product IDs validated from one helper
- โ
Fail-closed paid account deletion โ every active-like provider subscription is canceled by stored provider before storage, waitlist, profile, or Auth deletion proceeds
- โ
Guest Checkout โ public checkout creates provider sessions only; subscription users are provisioned from verified webhook completion, and digital products use email/token fulfillment
- โ
Subscription Cancellation โ AlertDialog with "Canceling" badge + period-end banner
- โ
Lifetime Access Rendering โ Dynamic active subscription state for lifetime purchases
- โ
Atomic credit deduction with PostgreSQL `FOR UPDATE` row locking
- โ
Token-Based Fulfillment โ Secure signed download links for digital products
- โ
Independent billing toggles โ credits and seats independently enabled; seat billing auto-disables when orgs disabled
### Glassmorphism 2.0 โ Crystal UI Design System
Looks like you had a dedicated design team. You didn't.
| Element | Implementation | Why |
| :----------------------------- | :----------------------------------------------------------- | :----------------------------------------------- |
| **Crystal Surfaces** | `bg-white/5 backdrop-blur-2xl border-white/10` | Depth without heaviness โ premium feel |
| **Touch-First UI** | Strict 44px tap targets, iOS safe-zones (`min-h-dvh`) | Native mobile app feel on the web |
| **GlowCard** | Animated shine, mesh gradient, colored glow | Conversion-point attention magnet |
| **Spring Animations** | `stiffness: 50`, staggered fade-ins via `motion/react` | Alive and responsive, not janky |
| **Bento Grids** | 8-column responsive system | High info density, zero overload |
| **Tri-Font Stack** | Space Grotesk + DM Sans + Fragment Mono | Professional hierarchy that guides the eye |
| **Split-Screen Auth** | `AuthBranding` left + form right | Social proof during auth reduces drop-off |
| **OKLCH Colors** | Perceptually uniform tokens | No "muddy" gradients across screens |
| **Emoji Loader** | Spinning `โณ` replaces spinner icons | Distinctive, lightweight, consistent |
| **Pixel-Perfect Mobile** | `px-4 md:px-8 max-w-7xl` standardized + adaptive align | Consistent boundaries, no layout drift |
| **Theme-Aware Logos** | `dark:hidden` / `hidden dark:block` conditional render | Brand integrity across light and dark modes |
| **Collapsible Nav** | Animated dropdown sub-links on Home (hover + tap) | Clean header with deep navigation hierarchy |
| **Localized Forms** | Newsletter inputs use `next-intl` translation keys | End-to-end i18n across all marketing surfaces |
| **Sidebar Hover Isolation** | Scoped `group/name` namespaces (`group/text`, `group/theme`) | CSS-safe child animations without parent leakage |
| **Collapsed Sidebar Branding** | Theme-aware compact icons in `collapsible=icon` mode | Professional brand identity at every density |
| **Bifurcated Errors** | `GlobalError` (Public) vs `DashboardError` (Protected) | Context-aware recovery paths for better UX |
> [!NOTE]
>
Built on Tailwind v4 CSS custom properties. Override any design token in
global CSS โ no component files touched.
### ๏ธ AI Legal Compliance Engine
Traditional cost: $2,000โ5,000+ in legal fees. Vibe44 includes AI-powered generation:
> [!NOTE]
>
AI-generated legal docs are a starting point. Have a lawyer review before
going live with sensitive data (health, finance, children).
### AI-Powered Support & RAG Knowledge Base
Complete AI support infrastructure โ chat to knowledge base:
| Feature | Technology | Description |
| :---------------------- | :-------------------------------------- | :------------------------------------------------------------------ |
| **100+ Language Chat** | Gemini 3.1 Flash-Lite Preview | Detects input language, responds in kind |
| **AI Intent Detection** | Gemini `classifyIntent()` | Escalation, priority classification โ any language |
| **RAG Pipeline** | `gemini-embedding-2` + pgvector | Semantic search over your knowledge base |
| **Multilingual Voice** | ElevenLabs/Murf TTS + ElevenLabs STT | Voice conversations with speech output and ElevenLabs transcription |
| **Voice Boundary** | Adapter factory + SSRF guard | Murf `audioFile` URLs are sanitized before server-side fetches |
| **Real-Time Sync** | Supabase Realtime Broadcasts | Live sync between user widget and super-admin |
| **Lazy Creation** | Server Actions | Conversations created on first message โ zero empty records |
| **Escalation** | Support Tickets | AI escalates complex issues to human queue |
| **Lifecycle** | Archive / Unarchive / Delete | Full management flow with defensive deletion safeguards |
| **UX Polish** | Granular Loading States | Per-ticket UI feedback prevents universal dashboard blocking |
| **Guest Access** | localStorage persistence | Non-auth users chat with history preserved |
| **Ownership Guard** | Drizzle owner lookup | Authenticated conversation IDs are resolved by effective user |
### Affiliate & Referral System
Built-in referral tracking with full attribution:
Approved affiliates use `/api/affiliate/track` links that set 30-day
attribution cookies before redirect.
Payment providers pass referral ID and buyer user ID so self-referrals and
expired referrals are rejected before commission credit.
IP addresses and browser user agents are hashed before referral persistence.
Affiliates select Wise, PayPal, or Payoneer during registration; payout
method and email are stored on `affiliates`.
`affiliate_payouts` uses the stored payout profile,
`config.affiliate.minimumPayoutThresholdInCents`, serializable deduction,
and pending-only completion.
Affiliates view performance metrics without raw tracking identifiers.
### Dashboard Analytics
### ๏ธ super-admin Dashboard (17 Modules / Super-Admin RBAC)
Full-featured super-admin panel at `/super-admin` โ no third-party tools. All 17 modules feature standardized Glassmorphism 2.0 `CardHeader` layouts, client-side filtering, and unified CSV export.
Search, metrics, roles, subscription status, org hierarchy badges, deletion
(via centralized `account-deletion` service), super-admin shielding, and
automatic waitlist-to-profile metadata synchronization.
Unified dashboard for all recurring subscriptions and one-time purchases
with granular statuses, intelligent product-name resolution, and CSV
exports.
Premium Glassmorphism 2.0 interface with status tracking, identity-aware
avatar resolution for registered users, CSV export, defensive deletion
dialogs, and interactive 'Reply to Sender' / 'Copy Message' actions
Cookie-based "view as user" with read/write isolation, UI safeguards, 1-hour
auto-expiry, and instantaneous layout synchronization via reactive CSS
variables to eliminate UI jitter during transitions
### Enterprise Security (Baked In, Not Bolted On)
Security isn't a feature you add later. It's in every layer:
| Layer | Implementation | Protects Against |
| :----------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------- |
| **RLS** | Policies on all 32 tables | Data isolation between users/tenants |
| **API Key Hashing** | SHA-256 with salt + prefix-only storage | Zero plaintext exposure of developer keys |
| **Edge Rate Limiting** | Upstash Redis at middleware; fail-closed in production | DDoS, brute force, credential stuffing |
| **Circuit Breaker** | Auto IP ban after 5 violations | Persistent attackers |
| **CSP Headers** | Nonce-based via `proxy.ts` + `'strict-dynamic'` | XSS, code injection, clickjacking |
| **Webhook Verification** | HMAC-SHA256 signature validation | Forged webhook attacks |
| **Input Validation** | Zod i18n-aware factories for bodies, params, and query strings | SQLi, XSS, malformed data |
| **Error Containment** | Generic translated API/action failures; no Zod `flatten()` payloads or raw provider errors | Schema disclosure, noisy UX, support escalations |
| **Session Management** | Supabase Auth with auto-refresh | Session hijacking, token expiry |
| **QStash Security** | Triple-guard bypass constraints (`QSTASH_ALLOW_DEV_BYPASS`) | Unauthorized background job execution |
| **Step-Up Auth** | Server-side password re-verification via `FormData` for high-risk actions (MFA disablement) to prevent log leakage | Account takeover, log-exposure of secrets |
| **AAL Enforcement** | Middleware blocks `/dashboard` until TOTP done; administrative bypassing restricted to secure server actions | MFA bypass |
| **WebAuthn Auditing** | Challenge lifecycle persistence (`status`) creates immutable audit trails for passkey events | Repudiation of authentication events |
| **CSRF Protection** | HMAC-bound double-submit cookie with root-level client context, authenticated page-route token seeding,`csrfFetch()` for browser mutations, and same-origin oRPC CSRF headers; guest chat remains public only without a session | Cross-site request forgery |
| **Impersonation State** | HMAC-signed `impersonation-context` cookie with read-time super-admin/target revalidation | Local cookie tampering and stale target privilege drift |
| **SSRF Protection** | `lib/security/ssrf.ts` blocks private IPs, metadata, and provider-returned Murf audio URLs | Server-Side Request Forgery |
| **XSS Protection** | `lib/security/xss.ts` input sanitization + CSP nonces | Cross-site scripting (XSS) |
| **Crypto Security** | `lib/security/crypto.ts` โ zero `Math.random()` in server code | Predictable token generation |
| **Credit Guard** | `p_amount > 0` check in `deduct_credits()` | Credit inflation via negatives |
| **Profiles Lock** | RLS blocks 6 billing fields from user UPDATEs | Privilege escalation |
| **Cursor Pagination** | All super-admin queries cursor-based | Memory exhaustion |
| **Invoice Lockdown** | INSERT restricted to `service_role` + `amount > 0` CHECK | User-fabricated or negative invoices |
| **Storage Scoping** | `post-images` INSERT scoped to user folder; upload object extensions derive from validated MIME type | Cross-user file uploads and active-content confusion |
| **CI Build Gating** | `build: needs: [quality]` โ lint + type-check first | Deploying broken code |
| **Deletion Safety** | Mandatory `AlertDialog` confirmation guards + fail-closed paid account deletion | Prevents accidental data loss and paid entitlement drift |
| **Resource Gating** | Tier-based limits enforced in UI + server-side | Prevents resource exhaustion |
> [!NOTE]
>
**Zero critical vulnerabilities.** Full OWASP Top 10 (2025) compliance. See
[SECURITY_AUDIT.md](/docs/security/security-audit) ยท
[THREAT_MODEL.md](/docs/security/threat-model)
#### ๏ธ OWASP Top 10 (2025) โ Full Compliance
SSRF validator (`lib/security/ssrf.ts`) โ blocks private IPs, cloud
metadata, non-HTTP schemes; 25+ unit tests
Build-time env validation (`scripts/validate-config.ts`); 9 HTTP header
tests
`npm run security:audit` in CI; CycloneDX SBOM via `npm run sbom`;
Dependabot; `.npmrc` audit config
`lib/security/crypto.ts` replaces all `Math.random()` in server code;
12-secret key rotation
LLM prompt injection audit; SSRF defense-in-depth via `ssrf.ts`
STRIDE threat model with 6 abuse case scenarios
Password strength meter; universal MFA; server-side step-up auth via
`FormData`
SRI hashes on CDN scripts; 11 `JSON.parse()` calls verified safe
`auth_events` append-only table; `logAuthEvent()` + brute-force detection;
Security Dashboard
Fail-closed MFA and production rate limiting, payment timeout handling,
graceful shutdown
### Pricing (One-Time Payment โ No Subscriptions, Ever)
One-time purchase. No monthly fees. No per-seat SaaS tax. Pay once, own forever, deploy unlimited projects.
๐ Check our **[Pricing page](https://vibe44.com/pricing "https://vibe44.com/pricing")** for detailed tier breakdowns (Starter, Growth, Agency), ROI calculations, and latest infrastructure cost-benefit analysis in `PRICING.md`.
### agent-native Architecture (100/100 Machine Readability)
Designed from the ground up for AI-assisted development. Your AI coding agent (Cursor, Trae, Copilot, Windsurf, Gemini CLI, Claude Code, Antigravity, Codex, Jules) reads `.agents/` and immediately understands your entire architecture:
```
AGENTS.md # Root agent instruction contract
CLAUDE.md # Persistent instruction manual for Claude Code
.agents/
โโโ rules/
โ โโโ system-prompt.md # Always-on system prompt (role, anti-hallucination, verification)
โโโ skills/
โ โโโ backend/SKILL.md # Backend architecture bible
โ โโโ frontend/SKILL.md # Frontend design system bible
โ โโโ i18n/SKILL.md # i18n namespace routing & locale architecture
โโโ workflows/
โโโ add-feature.md # End-to-end feature building
โโโ add-api-route.md # API route with auth + validation + rate limiting
โโโ add-ui-component.md # Glassmorphism 2.0 component creation
โโโ add-payment-provider.md # Payment provider integration (strategy pattern)
โโโ add-ai-provider.md # AI provider integration (AIProvider interface)
โโโ add-email-provider.md # Email provider integration (EmailProvider interface)
โโโ add-email-template.md # React Email + i18n + provider adapter
โโโ add-locale.md # Language addition across 14 sub-modules
โโโ add-oauth-provider.md # Social auth provider setup
โโโ database-migration.md # Schema change + migration + RLS
โโโ debugging.md # Systematic debugging with Sentry + logs
โโโ security-audit.md # OWASP-aligned security review
โโโ testing.md # Vitest unit + Playwright E2E
โโโ deploy.md # Vercel / Railway deployment (auto-invocation disabled)
โโโ remove-org-feature.md # Safe org feature removal (auto-invocation disabled)
โโโ remove-mock-data.md # Production data cleanup (auto-invocation disabled)
```
- ๐ฏ **Zero hallucination** โ AI reads your actual schema, not guessed table names; `` XML tags enforce read-before-answering
- ๐ฏ **Knowledge Graph Navigation** โ Built-in Graphify MCP integration maps your entire AST, allowing AI to query codebase relationships directly.
- ๐ฏ **Pattern consistency** โ Every new feature follows established conventions
- ๐ฏ **Token efficiency** โ Modular files + progressive disclosure = AI reads only what's relevant
- ๐ฏ **Workflow automation** โ `"/add-feature"` triggers a proven playbook; all 18 workflows include standardized frontmatter (`name`, `description`, `argument-hint`)
- ๐ฏ **Safety-first** โ Destructive workflows (deploy, migration, removal) include `disable-model-invocation: true` to prevent accidental agent execution
- ๐ฏ **Verification mandate** โ System prompt requires `tsc --noEmit`, test suite run, and build confirmation before marking work complete
### Newsletter System
Independent newsletter subscription infrastructure โ decoupled from waitlist and auth:
### Multi-Tenancy & Organizations
Built-in team/org system with role-based access:
### ๏ธ Developer Tools
---
## ๏ธ The Stack
Every technology choice is strategic:
| Layer | Technology | Why |
| :-------------- | :---------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Framework** | Next.js 16 (App Router) | Server Actions eliminate API boilerplate. RSC reduces client bundle. Edge middleware for CDN-level security. |
| **Styling** | Tailwind v4 + shadcn/ui | Native CSS approach. Component ownership (no npm dependency). |
| **Language** | TypeScript 6 (Strict) + Zod | Strict = compile-time safety. Zod = runtime boundaries. Zero-gap type coverage. |
| **Database** | Supabase (PostgreSQL 15) | RLS. Realtime. pgvector. Auth. One provider. |
| **ORM** | Drizzle ORM | Type-safe. SQL-like syntax.ย `drizzle-kit push` for instant updates. |
| **Payments** | Universal Adapter | Strategy Pattern โ 5 providers. Swap via env var. |
| **Email** | Universal Adapter (SendGrid, Resend, Postmark, Brevo) | Validated provider keys, SDK-backed adapters, configured-key fallback, and 13 i18n-ready React Email templates. |
| **AI** | Universal Adapter (Gemini, OpenAI, Anthropic, DeepSeek) | Validated `AI_PROVIDER` / `EMBEDDING_PROVIDER` factories. Streaming, intent, structured output, and provider-scoped key gates. |
| **Embeddings** | `gemini-embedding-2` | 3072-dim vectors in PostgreSQL. No separate vector DB. Cosine similarity. |
| **Voice** | ElevenLabs + Murf AI + Web Audio API | High-quality TTS via both providers; STT requires ElevenLabs. |
| **Queue** | Upstash QStash + Trigger.dev | QStash verifies signed ingress at `/api/qstash`; Trigger.dev handles configured scheduled jobs and retries. |
| **Analytics** | Universal Adapter (9 providers) | DataFast, GA4, Mixpanel, PostHog, Plausible, Pirsch, Umami, Vercel Analytics, and Vemetric run only after analytics consent and CSP allowlisting. |
| **Rate Limit** | Upstash Redis | Edge-compatible. Sub-ms latency. Sliding window. Circuit breaker. |
| **i18n** | next-intl (EN/ES/FR) | Cookie-based locale switcher. 14 sub-modules. Global translation values via `i18n.ts`. Automated discrepancy detection. |
| **Performance** | RSC boundaries + explicit projections + lazy client bundles | Stable Next.js config, parallel Promise.all() reads, bounded list queries, LazyMotion, hydration-stable ChartContainer, fixed image ratios. |
---
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Introduction > Architecture
RSC + Server Actions architecture. Minimal client JavaScript. Server does the heavy lifting. Database enforces security at the row level.
### Request Lifecycle
**Browser** โ Next.js route
**Middleware** (`proxy.ts`) โ IP ban โ rate limit (fail-closed in
production) โ HMAC-bound CSRF (1-hour TTL, authenticated page-route seeding)
โ session refresh โ MFA enforcement (fail-closed) โ feature flag redirect โ
route auth
**Server Component** โ renders with Supabase data (RLS-enforced isolation)
**Server Actions** โ auth check โ Zod validation โ Drizzle query โ
`revalidatePath()` + `revalidateTag(..., "max")`
**Webhooks** โ HMAC-SHA256 verified โ durable event ID required โ retry-safe
`webhook_logs` claim โ provider-resource upsert/dedup โ synced to DB
> [!NOTE]
>
Production config avoids unstable Next.js flags; independent reads parallelize
via `Promise.all()`; Drizzle reads use explicit projections; webhook
super-admin lists clamp to 100 rows; hydration-stable ChartContainer;
fixed-aspect `next/image` assets preserve intrinsic ratios with explicit auto
sizing.
---
## Project Structure
---
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
---
# SECTION: Getting Started
## Getting Started > Getting Started
> Zero to running in under 10 minutes. Prerequisites, install, env setup, database, first run.
## Prerequisites
| Requirement | Version | Verify |
| :---------- | :------ | :----------------------------------- |
| Node.js | 20+ | `node -v` |
| npm | 10+ | `npm -v` |
| Git | Latest | `git --version` |
| Supabase | โ | [supabase.com](https://supabase.com) |
---
## 1. Clone & Install
```bash
git clone https://github.com/scalewithalap/vibe44.git my-saas-app
cd my-saas-app
npm run setup-wizard # Run the interactive CLI wizard.
```
The wizard runs a preflight-first prompt flow powered by [@clack/prompts](https://github.com/bombshell-dev/clack):
1. **Preflight** - verify project writability, Node.js `>=20`, package-manager detection, `.env.local` conflict status, and Supabase config presence.
2. **Project Identity** - project slug, display name, and support email.
3. **Infrastructure** - payment provider (5), AI provider (4), voice toggle, voice provider (2), email provider (4), analytics provider (9), background jobs provider (2 - QStash/Trigger.dev), and Sentry toggle.
4. **API Keys** - only the Supabase, provider, voice, background jobs provider, analytics, Sentry, and Upstash Redis keys required by your previous choices. Keys are validated locally against provider-specific patterns.
5. **Generated Secrets** - inject `CSRF_SECRET` and `NEXT_AUTH_SECRET` when they are absent. Impersonation cookie signing can use those secrets unless `IMPERSONATION_COOKIE_SECRET` is configured separately.
6. **Write Plan** - preview or write `.env.local`.
The wizard generates:
- `.env.local` โ your fully configured environment (with auto-generated `CSRF_SECRET` & `NEXT_AUTH_SECRET`)
> [!NOTE]
>
The package includes a `.env.example` pre-configured for customer reference.
The setup wizard does not overwrite or regenerate `.env.example`.
> [!NOTE]
>
The wizard runs in-place โ no `cd` navigation is required.
## 3. Database Schema Setup
To ensure 100% build stability and eliminate complex CLI database dependencies, database schema application is a user-driven process:
1. **Option A: Supabase Web Dashboard SQL Editor (Recommended)**
- Open your project on the [Supabase Dashboard](https://supabase.com/dashboard).
- Go to the **SQL Editor** section.
- Open a new query, paste the contents of `supabase/schema.sql`, and click **Run**. This bootstraps all 32 tables, indexes, custom functions, and Row-Level Security (RLS) policies.
2. **Option B: Supabase MCP (AI Agent Native)**
- Leverage AI agents to apply and manage database state seamlessly using the Supabase Model Context Protocol (MCP) server.
- Refer to the official guide: [Supabase MCP Integration](https://supabase.com/docs/guides/ai-tools/mcp).
3. **Option C: Drizzle Kit (For subsequent schema changes)**
- To push schema changes from your local Drizzle schema files, run:
```bash
npm run db:push
```
See [DATABASE.md](/docs/architecture/database) for more details.
## 4. Supabase Email Configuration
Before testing signups, you **must** update the email verification template to use the secure, anti-scanner verification flow.
1. Go to **Authentication > Email Templates** in your Supabase Dashboard.
2. Edit the **Confirm signup** template.
3. Replace `{{ .ConfirmationURL }}` in the link with:
`{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=signup`
## 5. Super-Admin Account
1. `npm run dev`
2. Navigate to `http://localhost:3000/signup`, create account
3. Verify email (check Supabase Auth dashboard if needed)
4. Promote to super-admin:
```sql
-- Supabase SQL Editor
UPDATE profiles SET role = 'super-admin' WHERE email = 'your@email.com';
```
> [!NOTE]
>
Role value is `'super-admin'` (hyphenated). `'admin'` and `'super_admin'` do
NOT work.
## 6. Run
```bash
npm run dev
```
`http://localhost:3000`
### Key URLs
| URL | Purpose |
| :------------------- | :--------------------- |
| `/` | Landing page |
| `/login` | Sign in |
| `/signup` | Create account |
| `/dashboard` | Dashboard |
| `/dashboard/billing` | Subscriptions |
| `/super-admin` | Admin panel |
| `/system` | System status |
| `/docs` | Docs (Fumadocs) |
| `/api-references` | API reference (Scalar) |
## 7. Commands
```bash
# Dev
npm run dev # Dev server
npm run build # Production build
npm run start # Production server
npm run type-check # Application + setup-wizard TypeScript validation
# Database
npm run db:push # Push schema
npm run db:generate # Migration SQL
npm run db:studio # Drizzle Studio
# AI Agents
python -m graphify update . # Refresh Graphify AST
# Testing
npm run test # Unit (Vitest)
npm run test:e2e # E2E (Playwright)
# i18n
npx tsx scripts/find-missing-locale-keys.ts # Missing keys
npx tsx scripts/find-missing-translations.ts # Parity check
```
## 8. Remove Mock Data
Demo data populates the dashboard out of the box. When ready:
**Quick:** Keep `NEXT_PUBLIC_USE_MOCK_DATA=false` in `.env.local` and production environment variables.
**Full:** Follow `/remove-mock-data` workflow.
> Mock data only appears when tables are empty. Real data auto-replaces it.
---
## ๏ธ What's Next?
| Goal | Read |
| :----------------- | :--------------------------------------------------------- |
| AI Agent Setup | `AGENTS.md`, `CLAUDE.md`, [GRAPHIFY.md](/docs/ai/graphify) |
| Architecture | [ARCHITECTURE.md](/docs/architecture/architecture) |
| Branding & theming | [CUSTOMIZATION.md](/docs/getting-started/customization) |
| Payments | [PAYMENTS.md](/docs/architecture/payments) |
| Email | [EMAIL.md](/docs/architecture/email) |
| Deploy | [DEPLOYMENT.md](/docs/operations/deployment) |
| Add features | [WORKFLOWS.md](/docs/operations/workflows) |
| Security audit | [SECURITY_AUDIT.md](/docs/security/security-audit) |
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Setup Wizard
> Production-grade interactive CLI for configuring a Vibe44 checkout in minutes.
The Setup Wizard is a powerful, interactive terminal utility designed to configure your entire Vibe44 project stack in under 10 minutes. It automates collecting project metadata, selecting infrastructure providers, validating API keys, generating application secrets, setting up `.env.local`, and managing initial database deployments with a resumable, stateful flow.
---
## Quick Start
From the root of your downloaded Vibe44 repository, run the following command:
```bash
npm run setup-wizard
```
The root script invokes the launcher (`packages/setup-wizard/launcher.mjs`), which manages dependency checks, package compilation, and child process execution safely across multiple shells (including Bash, zsh, Windows PowerShell, and cmd.exe).
### Import Existing Environment Keys
To seed the wizard with credentials from an existing production or staging environment file, pass the `--from-env` flag:
```bash
npm run setup-wizard -- --from-env .env.production
```
### Non-Interactive Setup (CI/CD / Rapid Dev)
To skip prompts entirely, accept all defaults, and force merge or overwrite configuration:
```bash
npm run setup-wizard -- --yes --overwrite --skip-install
```
---
## CLI Flags
Customize your setup run using standard command-line flags. Note that when running via npm scripts, pass options after the `--` separator.
| Flag | Description |
| :--- | :--- |
| `--from-env ` | Import API keys from an existing `.env` file to seed credentials. |
| `--dry-run` | Preview all file writes and generated variables without writing to disk. |
| `--show-secrets` | Display actual secret values in dry-run logs (redacted by default). |
| `--resume` | Resume from the last saved project checkpoint. |
| `--reset` | Clear the existing project checkpoint before running. |
| `--overwrite` | Overwrite `.env.local` if it exists, bypassing the backup warning prompt. |
| `--skip-install` | Skip automatic dependency installation after configuring. |
| `--skip-db` | Skip pushing the Supabase database migrations. |
| `--skip-validation` | Skip local API key structure and format verification. |
| `--yes` | Accept all defaults and run non-interactively. Merges keys into `.env.local` by default. |
| `--debug` | Enable verbose command output and diagnostics. |
| `-v, --version` | Print CLI version. |
| `-h, --help` | Print usage details. |
---
## Execution Flow
When you launch `npm run setup-wizard`, the CLI entrypoint (`src/index.ts`) executes the setup sequence in a robust, structured order:
```mermaid
graph TD
A[Launch CLI] --> B[Run Preflight Checks]
B --> C{Check for Resume State?}
C -- Yes --> D[Load Checkpoint]
C -- No --> E[Interactive Prompts Clack]
D --> F[Merge Env Key Imports]
E --> F
F --> G[Generate CSRF & Auth Secrets]
G --> H{Dry Run?}
H -- Yes --> I[Print Plan & Exit]
H -- No --> J[Resolve .env.local Conflicts]
J --> K[Write .env.local]
K --> L[Post-Setup: npm install & Supabase db push]
L --> M[Clear Checkpoint & Complete]
```
### 1. Preflight Checks
Verifies that:
- The project directory exists and has active read/write permissions.
- The Node.js version is `>= 20`.
- The package manager (npm, pnpm, yarn, bun) is successfully detected.
- Any potential `.env.local` conflict is flagged.
### 2. State & Resume Resolution
- Reads the unique workspace hash to look for any existing checkpoint file under `~/.vibe44/setup-wizard/{projectHash}.json` (or your custom `SETUP_WIZARD_STATE_DIR`).
- Prompts to resume where you left off if a step failed previously or if you exited early.
### 3. Collection (Interactive / Automatic)
- **Interactive Mode**: Starts a custom `@clack/prompts` run split into logical groups:
1. **Project Identity** (Name, display name, support email).
2. **Infrastructure** (Payment, AI, Voice, Email, Analytics, Jobs, Sentry).
3. **API Keys** (Dynamic inputs based on your chosen providers).
- **Non-Interactive Mode (`--yes`)**: Bypasses prompts and uses smart system defaults.
### 4. Code & Secret Generation
- Generates high-entropy cryptographic strings for `CSRF_SECRET` and `NEXT_AUTH_SECRET` if they are not already set.
- Automatically handles validation checks on provider keys (e.g., verifying that Stripe secret keys start with `sk_`).
### 5. File Resolution & Write Plan
- Evaluates existing configuration files.
- If `.env.local` is present, it prompts to **Merge**, **Backup & Overwrite**, **Overwrite**, or **Abort** to keep your historical variables safe.
### 6. Post-Setup Actions
- Installs dependencies using your detected package manager.
- Installs the Supabase CLI, verifies database status, and pushes Drizzle schema changes automatically unless explicitly skipped.
---
## Security & Invariants
To keep your credentials secure, the wizard enforces strict operational standards:
- **No Sensitive Checkpoints**: API keys are **never** persisted to local checkpoint files. Checkpoints only save project identity and infrastructure choices. If you resume a checkpoint, you will only be asked to provide your keys.
- **Dry-Run Redaction**: `--dry-run` automatically masks all secret values in terminal logs unless you explicitly pass `--show-secrets`.
- **Safe Database Mutators**: Supabase db pushes run a dry-run check first (`supabase db push --dry-run`) to guarantee schema validity before performing mutations.
---
## ๏ธ Recovery & Troubleshooting
If a post-setup step (such as `npm install` or database migration) fails, the wizard saves a recovery checkpoint. You do not need to re-enter your answers:
1. Resolve the reported issue (e.g., check network connectivity or database keys).
2. Run the wizard with the resume flag:
```bash
npm run setup-wizard -- --resume
```
3. To discard a broken session and start completely fresh:
```bash
npm run setup-wizard -- --reset
```
---
## Source Directory Map
For core developers looking to customize or maintain the wizard code, the package structure is organized as follows:
```text
packages/setup-wizard/src/
โโโ index.ts # CLI orchestration & Commander CLI definition
โโโ prompts.ts # Clack interactive prompt layouts and group flows
โโโ preflight.ts # Environment, Node version, and directory readiness checks
โโโ state-machine.ts # Phase state-machine and dynamic result recording
โโโ state.ts # Project-scoped local checkpoint persistence
โโโ secrets.ts # Entropy generators and log-redaction helpers
โโโ generator.ts # Environment file planning, merging, and writing
โโโ installer.ts # Async child process runner for npm install and Supabase CLI
โโโ exec.ts # Execa-wrapped async command executors
โโโ package-manager.ts # Auto-detecting and mapping package manager commands
```
---
_Copyright ยฉ 2026 Scale with Alap. All rights reserved._
_Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Customization
> Branding, theming, feature flags, i18n, analytics, SEO, pricing โ all configurable from centralized files. Zero architectural changes.
## Branding (White-Label)
All brand identity in `lib/config.ts`. Change once โ propagates to 50+ files:
```typescript
export const config = {
app: {
name: "Your SaaS Name",
shortName: "YSN",
description: "Your tagline",
url: process.env.NEXT_PUBLIC_APP_URL,
author: { name: "Your Company", url: "https://yourcompany.com" },
legal: { companyName: "Your Company LLC", email: "legal@yourdomain.com" },
links: { twitter: "...", github: "..." },
},
};
```
Propagates to: header, footer, emails, SEO, legal, AI chat prompt, OpenAPI docs.
### Checklist
| Item | File | Change |
| :------------- | :----------------------------- | :------------------------------------------------ |
| Name + tagline | `lib/config.ts` | `config.app.name`, `config.app.description` |
| Logo | `public/` | Replace `logo.svg`, `favicon.ico`, `og-image.png` |
| Fonts | `app/layout.tsx` | Import via `next/font/google` |
| Colors | `app/globals.css` | OKLCH tokens (`:root` + `.dark`) |
| Email sender | `.env.local` | `EMAIL_FROM`, `EMAIL_FROM_NAME` |
| Social links | `components/global/footer.tsx` | Footer URLs |
| Legal | `/super-admin/legal` | AI Legal Generator |
| OG image | `public/og-image.png` | Social sharing preview |
> Never hardcode app names. Always `config.app.name`.
---
## Theming (Colors & Dark Mode)
OKLCH tokens in `app/globals.css`:
```css
:root {
--background: oklch(0.985 0.005 260);
--foreground: oklch(0.2 0.02 260);
--primary: oklch(46.5% 0.24 302);
}
.dark {
--background: oklch(0.18 0.04 260);
--foreground: oklch(0.98 0.01 260);
--primary: oklch(56% 0.29 301);
}
```
1. Edit OKLCH values
2. Keep `:root` + `.dark` in sync
3. Semantic tokens only (`bg-primary`, `text-foreground`) โ never raw colors
Dark mode via `next-themes` + `ThemeProvider`.
---
## Feature Flags
`lib/config.ts`:
```typescript
features: {
organizations: true, // Multi-tenancy
projects: true, // Project management
i18n: true, // Internationalization
waitlist: false, // Pre-launch mode
affiliate: true, // Affiliate program
aiChat: true, // AI widget
blog: true, // Blog system
}
```
Gates both UI + server-side:
```typescript
// UI
{isOrganizationsEnabled() && }
// Server
if (!isOrganizationsEnabled()) return { success: false, error: t("disabled") };
```
### Helpers
Import feature gates from `@/lib/config/app`; do not read `config.features.*` directly in application code.
`isProjectsEnabled()` ยท `isOrganizationsEnabled()` ยท `isCreditsEnabled()` ยท `isSeatsEnabled()` ยท `isSubscriptionsEnabled()` ยท `isLifetimePurchasesEnabled()` ยท `isDigitalProductsEnabled()` ยท `isTrialEnabled()` ยท `isBlogEnabled()` ยท `isAiChatEnabled()` ยท `isVoiceEnabled()` ยท `isSTTEnabled()` ยท `isWaitlistEnabled()` ยท `isI18nEnabled()` ยท `isAnalyticsEnabled()` ยท `isStorageEnabled()` ยท `isEmailEnabled()` ยท `isAffiliatesEnabled()` ยท `isSupportTicketsEnabled()` ยท `isDocsEnabled()` ยท `isApiReferenceEnabled()`
### Dependencies
- Organizations and Projects are fully decoupled
- Seat billing requires orgs. `isSeatsEnabled()` auto-returns `false` when orgs disabled
---
## Internationalization (i18n)
| Property | Value |
| :---------- | :---------------------------------- |
| Library | `next-intl` |
| Locales | `en`, `es`, `fr` |
| Gate | `isI18nEnabled()` |
| Strategy | Cookie-based (no URL prefix) |
| Sub-modules | 14 domains, 40+ namespaces |
| Globals | `company`, `app_name` via `i18n.ts` |
Full ref: `.agents/skills/i18n/SKILL.md`.
```typescript
// Client
import { useTranslations } from "next-intl";
const t = useTranslations("dashboard");
// Server
import { getTranslations } from "next-intl/server";
const t = await getTranslations("dashboard");
```
### Global Translation Values
Global variables like `company` and `app_name` are injected via `i18n.ts` using `getRequestConfig()`. Available in all components without prop drilling:
```typescript
// In translation files:
{ "welcome": "Welcome to {app_name}" }
// Automatically resolved โ no extra props needed
```
> Do NOT pass `defaultTranslationValues` as a prop to `NextIntlClientProvider`. That prop was removed in next-intl v4. Use `i18n.ts` instead.
### Validation
| Script | Command | Detects |
| :------------------- | :--------------------------------------------- | :---------------------- |
| Missing keys | `npx tsx scripts/find-missing-locale-keys.ts` | Used-but-undefined keys |
| Missing translations | `npx tsx scripts/find-missing-translations.ts` | Cross-locale gaps |
> Run both after modifying keys.
---
## Analytics (Universal Adapter)
One env var:
```bash
NEXT_EXTERNAL_ANALYTICS_PROVIDER=datafast
```
| Provider | Env Var(s) | Integration |
| :-------- | :---------------------------------------------------------------- | :---------- |
| DataFast | `NEXT_PUBLIC_DATAFAST_WEBSITE_ID` + `NEXT_PUBLIC_DATAFAST_DOMAIN` | CDN |
| GA4 | `NEXT_PUBLIC_GA_MEASUREMENT_ID` | CDN |
| Mixpanel | `NEXT_PUBLIC_MIXPANEL_TOKEN` | NPM |
| PostHog | `NEXT_PUBLIC_POSTHOG_KEY` + `HOST` | NPM |
| Plausible | `NEXT_PUBLIC_PLAUSIBLE_DOMAIN` | CDN |
| Pirsch | `NEXT_PUBLIC_PIRSCH_CODE` | CDN |
| Umami | `NEXT_PUBLIC_UMAMI_WEBSITE_ID` + `HOST` | CDN |
| Vercel | โ (auto) | NPM |
| Vemetric | `NEXT_PUBLIC_VEMETRIC_TOKEN` | NPM |
`` in `app/layout.tsx` handles injection. It does not mount third-party scripts or emit page events until `lib/analytics/consent.ts` records explicit analytics consent. DataFast also requires `NEXT_PUBLIC_DATAFAST_DOMAIN`; Sentry Session Replay remains disabled unless `NEXT_PUBLIC_SENTRY_REPLAY_ENABLED=true`.
---
## SEO
| Function | Use Case |
| :----------------------------- | :-------------- |
| `generatePageMetadata()` | Standard pages |
| `generateArticleMetadata()` | Blog posts |
| `generateOrganizationSchema()` | Landing JSON-LD |
| `generateProductSchema()` | Pricing JSON-LD |
```typescript
import { generatePageMetadata } from "@/lib/seo";
export const metadata = generatePageMetadata({
title: "Dashboard","
description: "Your performance overview.",
path: "/dashboard",
noIndex: true,
});
```
---
## Pricing Tiers
Single source of truth: `lib/config/pricing.ts`:
| Tier | Price | Key Limits |
| :--------- | :----- | :------------------------------------------------- |
| ๐ฅ Free | $0/mo | 3 projects, 50 AI credits, 100MB |
| โญ Starter | $29/mo | Unlimited projects, advanced AI, orgs |
| ๐ Pro | $49/mo | Everything + voice, priority support, unlimited AI |
### Customizing
| Operation | Steps |
| :------------ | :------------------------------------------------------------------------- |
| Add tier | Add key to `PRICING_TIERS`, set prices (cents), limits, provider env vars |
| Change prices | Update cents + create new entries in provider dashboard + update env vars |
| Rename | Change `name` only. Never the key โ stored in `profiles.subscription_tier` |
| Remove | `isAvailable: false` to grandfather subs |
| Change limits | Edit `limits`/`credits`/`rateLimit` โ server-side automatic |
**Rules:** One `isDefault: true`. `id` matches key. Prices in cents. Provider IDs from env vars.
> See [PAYMENTS.md](/docs/architecture/payments) for full adapter + webhook reference.
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Environment Variables
> Fully detailed reference for every configuration key used to control Vibe44 integrations, security, analytics, and provider adapters.
> [!NOTE]
>
Never commit your `.env.local` file to version control. The `.env.example`
file serves as the template for required variables. You can automatically
scaffold a new `.env.local` file with the correct keys by running the `npm run
setup-wizard` command.
---
## 1. Application
Base URLs and fundamental Next.js application variables.
- **`NEXT_PUBLIC_APP_URL`**: The base URL of your application. Set this to `http://localhost:3000` for local development, and your production domain for deployment.
- **`NEXT_PUBLIC_APP_NAME`**: The name of your application, displayed in emails, headers, and UI elements.
*(Note: Description, tagline, version, and default support email are configured directly in `lib/config.ts`, not environment variables).*
## 2. Security
Cryptographic secrets required for secure operation.
- **`CSRF_SECRET`**: Random string used to generate CSRF nonces for authenticated mutations. Generate a strong secret using `openssl rand -base64 32`.
- **`NEXT_AUTH_SECRET`**: Random string used to hash tokens and sign cookies for Supabase Auth.
- **`TRUST_PROXY_HEADERS`**: Set to `true` to trust `x-forwarded-for` and real IP headers. Required when deployed behind a reverse proxy (e.g., Vercel, AWS ALB, Nginx). Set to `false` for raw local testing.
## 3. Environment
- **`NODE_ENV`**: Automatically set by Next.js (`development` or `production`). Use `process.env.NODE_ENV === 'development'` in code for dev-only branches.
- **`NEXT_PUBLIC_USE_MOCK_DATA`**: Enables dashboard/demo mock fallbacks when explicitly set to `true`. Keep `false` for production launches.
## 4. Supabase
Database and Authentication configuration. Obtain these from the Supabase Dashboard.
- **`NEXT_PUBLIC_SUPABASE_URL`**: Your project's API URL.
- **`NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY`**: The public anon key (safe for browser).
- **`SUPABASE_SECRET_KEY`**: The service role key used for server-side admin operations. Keep this completely secret.
- **`DATABASE_URL`**: Your Postgres connection string. Use the "Transaction" pooler mode URL (usually port `6543`).
## 5. Payment Providers
Vibe44 supports a Universal Payment Adapter. Set the active provider via `PAYMENT_PROVIDER`.
- **`PAYMENT_PROVIDER`**: Options are `stripe`, `polar`, `lemon-squeezy`, `dodo`, or `creem`.
_Depending on your selected provider, you must configure its respective keys and product IDs:_
### Stripe
- **`STRIPE_PUBLISHABLE_KEY`**: Public Stripe key (starts with `pk_test_` or `pk_live_`).
- **`STRIPE_SECRET_KEY`**: Secret Stripe key (starts with `sk_test_` or `sk_live_`).
- **`STRIPE_WEBHOOK_SECRET`**: Webhook signing secret (starts with `whsec_`).
- **`STRIPE_TIER_*_PRICE_ID`**: Your recurring and lifetime price IDs configured in the Stripe Dashboard.
### Polar
- **`POLAR_ENVIRONMENT`**: Either `sandbox` or `production`.
- **`POLAR_API_KEY`**: Your Polar personal access token.
- **`POLAR_ORGANIZATION_ID`**: Your Polar organization UUID.
- **`POLAR_WEBHOOK_SECRET`**: Webhook signing secret.
- **`POLAR_TIER_*_PRODUCT_ID`**: Product UUIDs from the Polar dashboard.
### Lemon Squeezy
- **`LEMONSQUEEZY_TEST_MODE`**: Set to `true` or `false`.
- **`LEMONSQUEEZY_API_KEY`**: API token.
- **`LEMONSQUEEZY_STORE_ID`**: Your store ID number.
- **`LEMONSQUEEZY_WEBHOOK_SECRET`**: Webhook signing secret.
- **`LEMONSQUEEZY_TIER_*_VARIANT_ID`**: Subscription variant IDs.
### Dodo Payments
- **`DODO_ENVIRONMENT`**: Either `test_mode` or `live_mode`.
- **`DODO_API_KEY`**: API key from Dodo.
- **`DODO_WEBHOOK_SECRET`**: Webhook signing secret.
- **`DODO_TIER_*_PRODUCT_ID`**: Product IDs from Dodo dashboard.
### Creem
- **`CREEM_TEST_MODE`**: Set to `true` or `false`.
- **`CREEM_API_KEY`**: Creem API key.
- **`CREEM_WEBHOOK_SECRET`**: Webhook signing secret.
- **`CREEM_TIER_*_PRODUCT_ID`**: Product IDs from Creem dashboard.
## 6. Digital Products (One-time purchases)
Price and product IDs for one-time digital products, mapped to your active payment provider.
- **`{PROVIDER}_FIRST_DIGI_PRODUCT_ID`** / **`{PROVIDER}_FIRST_DIGI_PRODUCT_PRICE_ID`**: Map to your specific digital products for the provider you selected in `PAYMENT_PROVIDER`.
## 7. Email Providers
Vibe44 uses a Universal Email Adapter. All providers work independently. If your primary provider fails or has its key removed, the system will fall back to the next available provider.
- **`EMAIL_PROVIDER`**: The default provider (`sendgrid`, `postmark`, `resend`, or `brevo`).
- **`SENDGRID_API_KEY`**: SendGrid API key.
- **`POSTMARK_API_KEY`**: Postmark Server API Token.
- **`RESEND_API_KEY`**: Resend API key.
- **`BREVO_API_KEY`**: Brevo API key.
- **`EMAIL_FROM`**: The default outbound address (e.g., `noreply@yourdomain.com`).
- **`EMAIL_FROM_NAME`**: Sender name (e.g., `Your App`).
- **`EMAIL_REPLY_TO`**: Default reply-to address.
- **`PUBLIC_SUPPORT_EMAIL`**: User-facing support address.
- **`SECURITY_ALERT_EMAIL`**: Internal recipient for brute force, IP ban, and role change alerts.
## 8. AI Services
Universal AI Provider Adapter for text generation and embeddings.
- **`AI_PROVIDER`**: Active provider (`gemini`, `openai`, `anthropic`, or `deepseek`).
- **`EMBEDDING_PROVIDER`**: Provider for vector embeddings (`gemini` or `openai`). Required if your `AI_PROVIDER` does not support embeddings (e.g., Anthropic, DeepSeek).
- **`GEMINI_API_KEY`**: Google AI Studio key.
- **`OPENAI_API_KEY`**: OpenAI platform key.
- **`ANTHROPIC_API_KEY`**: Anthropic Console key.
- **`DEEPSEEK_API_KEY`**: DeepSeek platform key.
- **`*_MODEL`**: Optional override for specific AI models to use per provider.
## 9. Voice Provider
Universal Voice Adapter for Text-to-Speech (TTS) and Speech-to-Text (STT).
- **`VOICE_PROVIDER`**: The active provider (`elevenlabs` or `murf`).
- **`ELEVENLABS_API_KEY`**: API key from ElevenLabs (supports TTS & STT).
- **`MURFAI_API_KEY`**: API key from Murf AI (supports high-quality TTS only).
## 10. Analytics Providers
Universal Analytics Adapter handling events seamlessly across 9 supported providers.
- **`NEXT_EXTERNAL_ANALYTICS_PROVIDER`**: Active analytics provider. Supported values are:
- `mixpanel` (Product analytics, default)
- `google` (Google Analytics 4)
- `datafast` (Privacy-first)
- `posthog` (Product OS)
- `plausible` (Privacy-first)
- `pirsch` (Cookieless)
- `umami` (Self-hosted or cloud)
- `vercel` (Vercel built-in analytics)
- `vemetric` (Privacy-friendly analytics)
_Depending on your selection, configure the corresponding variables:_
- **`NEXT_PUBLIC_GA_MEASUREMENT_ID`**: GA4 Measurement ID (`G-...`).
- **`NEXT_PUBLIC_DATAFAST_WEBSITE_ID` / `NEXT_PUBLIC_DATAFAST_DOMAIN`**: DataFast credentials.
- **`NEXT_PUBLIC_MIXPANEL_TOKEN`**: Mixpanel project token.
- **`NEXT_PUBLIC_POSTHOG_KEY` / `NEXT_PUBLIC_POSTHOG_HOST`**: PostHog credentials and ingest host.
- **`NEXT_PUBLIC_PLAUSIBLE_DOMAIN`**: Plausible tracked domain.
- **`NEXT_PUBLIC_PIRSCH_CODE`**: Pirsch tracking code.
- **`NEXT_PUBLIC_UMAMI_WEBSITE_ID` / `NEXT_PUBLIC_UMAMI_HOST`**: Umami tracking target.
- **`NEXT_PUBLIC_VEMETRIC_TOKEN`**: Vemetric token.
## 11. Background Jobs Provider (Universal Adapter)
Only one provider is active at a time (default: QStash).
- **`BACKGROUND_JOBS_PROVIDER`**: `qstash` (default) or `trigger`. Determines which engine processes scheduled background tasks (session cleanup, email digests, usage resets, subscription reminders, etc.).
### QStash (Upstash)
- **`QSTASH_TOKEN`**: Token for scheduling tasks via Upstash QStash.
- **`QSTASH_CURRENT_SIGNING_KEY` / `QSTASH_NEXT_SIGNING_KEY`**: Required to verify incoming webhooks from QStash.
- **`QSTASH_ALLOW_DEV_BYPASS`**: Developer convenience flag to bypass QStash signatures locally. **Never set this in production**.
### Trigger.dev
- **`TRIGGER_PROJECT_ID`**: Project identifier from the Trigger.dev dashboard.
- **`TRIGGER_SECRET_KEY`**: Secret key used to securely enqueue tasks and authenticate the runtime.
## 12. Upstash Redis (Rate Limiting)
Required for production rate-limiting. Independent of background jobs provider choice.
- **`UPSTASH_REDIS_REST_URL`**: Your Redis REST API URL.
- **`UPSTASH_REDIS_REST_TOKEN`**: Your Redis REST API token.
## 13. Sentry (Error Monitoring & Performance)
Optional but highly recommended application monitoring.
- **`SENTRY_DSN` / `NEXT_PUBLIC_SENTRY_DSN`**: Client keys pointing to your Sentry project.
- **`SENTRY_AUTH_TOKEN`**: Token used by CI/CD systems to upload sourcemaps.
- **`SENTRY_ORG` / `SENTRY_PROJECT`**: Your Sentry organization and project slugs.
- **`SENTRY_SEND_PII` / `NEXT_PUBLIC_SENTRY_SEND_PII`**: Opt-in to send PII (IPs, emails) to Sentry. Ensure GDPR compliance if set to `true`.
- **`NEXT_PUBLIC_SENTRY_REPLAY_ENABLED`**: Opt-in to record user sessions natively via Sentry Session Replay.
## 14. End-to-End Testing (Playwright)
Used exclusively for test environments.
- **`TEST_USER_EMAIL`**: Pre-seeded email used to log in during automated test suites.
- **`TEST_USER_PASSWORD`**: Pre-seeded password for the test user.
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Troubleshooting Guide
> Searchable reference for common issues. `Ctrl+F` your error message.
**Quick triage:** `npm run type-check`. If it passes, the issue is environmental (env vars, service connectivity), not code.
## Quick Reference
| Issue | Fix |
| :------------------ | :------------------------------------------------------------------- |
| Port in use | Run `npx kill-port 3000`, then `npm run dev` |
| TypeScript errors | `npm run type-check` |
| DB out of sync | `npm run db:push` |
| Build fails | Check `.env.local`, `npm run build` locally |
| Auth broken | Verify Supabase env vars |
| Setup wizard fails | Re-run with `--dry-run`, then resume or reset the project checkpoint |
| Payments failing | Check webhook secret env var |
| AI silent | `GEMINI_API_KEY` missing or invalid |
| Dark mode broken | Semantic tokens (`bg-background`), not `bg-white` |
| Motion too large | `m` from `motion/react`, not `framer-motion` |
| Translation missing | `npx tsx scripts/find-missing-locale-keys.ts` |
---
## ๏ธ Development
### Setup Wizard
The setup wizard checkpoints each project under `~/.vibe44/setup-wizard/{projectHash}.json`. It never persists `apiKeys`.
| Problem | Fix |
| :------------------------------------------------------- | :--------------------------------------------------------------------------------------------- |
| Interrupted prompt flow | `npm run setup-wizard -- --resume` |
| Bad saved answers | `npm run setup-wizard -- --reset` |
| Need to preview generated env files | `npm run setup-wizard --dry-run` or `npm run setup-wizard -- --dry-run` |
| Dry-run prints redacted secrets | Add `--show-secrets` only in a private terminal |
| Existing `.env.local` conflict | Use merge, backup-and-overwrite, overwrite, or abort; `--yes` defaults to merge |
| Database schema not applied | Paste the contents of `supabase/schema.sql` into the Supabase SQL Editor, or use Supabase MCP. |
| Vitest or build tools fail with `spawn EPERM` on Windows | Re-run outside the sandbox or with worker spawning permitted |
### Port in Use
```
Error: listen EADDRINUSE: address already in use :::3000
```
```powershell
npx kill-port 3000
npm run dev
```
### Node Version
Requires 20+. `node -v`. Use `nvm use 20` if needed.
### Dependencies
```bash
rm -rf node_modules package-lock.json
npm install
```
---
## Authentication
| Problem | Fix |
| :------------------------------ | :------------------------------------------------------------ |
| "Invalid login credentials" | Verify email confirmed in Supabase Auth |
| Magic link not arriving | Check spam, Supabase โ Auth โ Logs |
| Session not persisting | Verify `NEXT_PUBLIC_SUPABASE_URL`, test incognito |
| OAuth redirect fails | Add `{NEXT_PUBLIC_APP_URL}/auth/callback` to provider console |
| OAuth cancel redirects to localhost | Update **Site URL** in Supabase Dashboard (Auth -> URL Configuration) to your production domain (e.g. `https://vibe44.com`) |
| Sidebar missing after login | Login must use `window.location.href` (hard nav) |
| "Auth error" after verify | `/verified` calls `signOut()` to clear stale session |
| Duplicate email success | Expected. Check `data.user?.identities` โ empty = exists |
| `/auth/callback` crash | Route parses error params, redirects with toast |
| MFA bypassed via OAuth | `proxy.ts` checks AAL2, redirects if not met |
| Passkey MFA flash | `handlePasskeyLogin()` mounts `MfaChallenge` inline |
| Feature page still accessible | Server-side `is[Feature]Enabled()` guards |
| Sidebar hydration crash | Stable IDs in Radix tooltips/collapsibles |
| Email verified page shows twice | Server-side OTP action redirects immediately to `/verified` |
| `useTranslations` crash | Needs `NextIntlClientProvider` wrapper |
### Password Reset: 401 / PKCE
1. `/auth/callback` calls `exchangeCodeForSession(code)`
2. `redirectTo`: `{NEXT_PUBLIC_APP_URL}/auth/callback?next=/reset-password`
3. `/reset-password` NOT in `AUTH_ROUTES`
4. After reset: `signOut()` to invalidate
---
## ๏ธ Database & Supabase
| Problem | Fix |
| :------------------------ | :---------------------------------------------- |
| "relation does not exist" | `npm run db:push` |
| RLS blocking queries | Check policies, verify role |
| Drizzle migration errors | `npm run db:generate` then `db:push` |
| Standalone index crash | Inside `pgTable()` third arg (Drizzle #5064) |
| Pool exhausted | Pooled connection (port 6543) |
| Supabase 429 | Client-side caching |
| Avatar upload RLS error | Uses service role client; see `api/user/avatar` |
---
## Payments
| Problem | Fix |
| :------------------------------ | :-------------------------------------------------------------- |
| Webhook not processing | Verify `{PROVIDER}_WEBHOOK_SECRET` |
| "Customer not found" | Check `stripe_customer_id` in profiles |
| Subscription not updating | Enable webhook events in provider dashboard |
| Duplicate subscription/purchase | Confirm the latest provider-resource unique indexes are applied |
| Test โ live fails | Switch to live keys, update endpoint URL |
| Creem 401 | Verify `CREEM_WEBHOOK_SECRET` |
| Creem duplicate retries | Confirm sandbox payloads include durable `event.id` |
| Dodo orphaned records | `syncSubscriptionToDb` requires valid `userId` |
| Sentry not capturing | Verify `@sentry/nextjs`, providers use `captureError()` |
| Health false-positive | Check provider-specific env vars |
### Local Webhooks
```bash
stripe listen --forward-to localhost:3000/api/webhooks/stripe
ngrok http 3000 # All others
```
---
## AI & Voice
| Problem | Fix |
| :------------------ | :-------------------------------------------------------------------------- |
| "API key not valid" | Verify `GEMINI_API_KEY`, enable API |
| Embeddings failing | Ensure `@google/genai` SDK is up to date |
| Widget not loading | `isAiChatEnabled()` returns `true` |
| RAG empty | Re-embed after model change, enable pgvector |
| Mic denied | HTTPS (or localhost), check permissions |
| Audio silent | Check `ELEVENLABS_API_KEY`, user must interact first |
| Murf audio rejected | Confirm the provider `audioFile` URL is public HTTPS and passes SSRF checks |
---
## Frontend & Styling
| Problem | Fix |
| :------------------ | :----------------------------------------------------------------------------- |
| Hydration mismatch | `useEffect` for dynamic values, `suppressHydrationWarning` |
| Dark mode broken | `bg-background` / `text-foreground`, never hardcoded |
| Card inconsistent | Use `GlowCard`, not inline glassmorphism |
| Chart colors wrong | `CHART_COLORS` from `@/lib/constants/chart-colors` |
| Motion too large | `import { m } from "motion/react"` |
| Empty `src` warning | `AvatarImage` normalizes `""` to `undefined`; uses `object-cover` for 1:1 crop |
| React Compiler loop | `useCallback` with explicit deps |
---
## Analytics
| Problem | Fix |
| :-------------------- | :----------------------------------------------------------------------------------------- |
| Not loading | Verify `NEXT_EXTERNAL_ANALYTICS_PROVIDER`, provider env vars, and stored analytics consent |
| Mixpanel not tracking | Ensure `NEXT_PUBLIC_MIXPANEL_TOKEN` is set correctly and consent is granted |
| PostHog not tracking | Host URL must start with `https:` |
| GA4 ID rejected | Only `G-` prefix (not `UA-`) |
| DataFast not loading | Set both `NEXT_PUBLIC_DATAFAST_WEBSITE_ID` and `NEXT_PUBLIC_DATAFAST_DOMAIN` |
| Duplicate pageviews | Verify manual page tracking is not duplicated outside `AnalyticsProvider` |
| SSR hydration | `"use client"` on analytics components |
| PII leak | `trackSignup()` excludes email; scripts stay disabled until explicit analytics consent |
---
## Build & Deploy
| Problem | Fix |
| :------------------ | :----------------------------------------------- |
| Build failing | `npm run type-check`, verify env vars |
| Vercel env missing | Project Settings โ correct environment, redeploy |
| Railway env missing | Variables tab,`railway variables` CLI |
| CSP errors | `proxy.ts` nonce-based CSP + `strict-dynamic` |
| 500 in production | Runtime logs, verify `DATABASE_URL` + API keys |
---
## Passkeys & MFA
| Problem | Fix |
| :----------------- | :------------------------------------------- |
| Registration fails | Chrome 67+, Firefox 60+, Safari 14+, HTTPS |
| Challenge expired | Complete within 60 seconds |
| "Invalid TOTP" | Sync authenticator clock (30s windows) |
| AAL2 not reached | `getAuthenticatorAssuranceLevel()` to verify |
---
## i18n
| Problem | Fix |
| :----------------------- | :------------------------------------------------------ |
| Switcher not visible | `isI18nEnabled()` returns `true` in `lib/config/app.ts` |
| Translations not loading | Check `locales/frontend/{locale}.ts` |
| Wrong namespace | `useTranslations('namespace')` matches top-level key |
| Cache stale | Remove `.next`, then run `npm run dev` |
---
## Background Jobs
| Problem | Fix |
| :--------------- | :---------------------------------------------------------------------------------------------------------------- |
| Not executing | Ensure `BACKGROUND_JOBS_PROVIDER` is set (`qstash` or `trigger`) and correct keys are provided in `.env.local`. |
| QStash failures | Verify `QSTASH_TOKEN`, current/next signing keys, and ensure webhook signature verification passes in production. |
| Trigger.dev fail | Verify `TRIGGER_SECRET_KEY` and `TRIGGER_PROJECT_ID` are set. |
| Dev disconnected | For Trigger.dev: run `npx trigger.dev dev` alongside `npm run dev`. For QStash: use a local tunnel (e.g., ngrok). |
| Failing silently | Check your active provider's dashboard (Upstash QStash schedule history or Trigger.dev Run logs). |
---
## oRPC API
| Problem | Fix |
| :--------------- | :------------------------------------------------ |
| `/api/rpc/*` 404 | Verify `app/api/rpc/[...path]/route.ts` exists |
| Validation fails | Zod schema matches payload |
| Generic 500 | Use `ORPCError("NOT_FOUND")` with i18n |
| Wrong base URL | `lib/rpc/client.ts` derives from `config.app.url` |
| Namespace miss | `Common.serverErrors` (not bare `serverErrors`) |
---
## Unit Testing (Vitest)
| Problem | Fix |
| :------------------------- | :----------------------------------------------------- |
| `redirect` throws | Mock with `vi.fn()` wrapper |
| Class mock fails | Use `function()` not arrow |
| Module mock broken | `@/lib/...` paths match `vitest.config.ts` aliases |
| Stale mock ref | Wrapper functions, not `vi.resetModules()` |
| `db.update()` chain | Mock full chain:`.set().where()` |
| `getTranslations` mismatch | `vi.fn().mockImplementation(async () => (key) => key)` |
| MFA `enrollMfa` fails | Mock `mfa.listFactors()` โ `{ totp: [] }` |
```bash
npm test # All
npm test -- tests/unit/actions/billing.test.ts # Single
npm test -- --reporter=verbose # Verbose
```
---
## Super-Admin
| Problem | Fix |
| :---------------------------- | :------------------------------------------------ |
| Can't access `/super-admin/*` | `role = 'super-admin'` in profiles |
| Redirects to dashboard | `SUPABASE_SECRET_KEY` set |
| Actions not logging | RLS allows super-admin inserts to `activity_logs` |
| Role change no effect | User must re-login |
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Pricing
**One-Time Payment โ No Subscriptions, Ever.**
One-time purchase. No monthly fees. No per-seat SaaS tax. Pay once, own forever, deploy unlimited projects.
| | ๐ฅ**Starter** | โญ**Growth** _(BEST SELLER)_ | ๐ธ**Agency** _(Best Value)_ |
| :---------------------------- | :---------------- | :--------------------------- | :-------------------------- |
| **Price** | **$197** ~~$329~~ | **$497** ~~$929~~ | **$997** ~~$2,035~~ |
| | Save 40%+ | Save 46.5%+ | Save 51%+ |
| **Developer Seats** | 1 | 6 | 12 |
| **Deployed Projects** | **UNLIMITED** | **UNLIMITED** | **UNLIMITED** |
| **Full Source Code** | โ
| โ
| โ
|
| **Lifetime Updates** | โ
| โ
| โ
|
| **Commercial Rights** | โ
| โ
| โ
|
| **Payment Providers (5)** | โ
| โ
| โ
|
| **AI Chat + RAG + Voice** | โ
| โ
| โ
|
| **Super-admin Panel + CMS** | โ
| โ
| โ
|
| **Built-in Tiering** | โ
(Ready-to-use) | โ
(Ready-to-use) | โ
(Ready-to-use) |
| **Multi-Tenancy (RBAC)** | โ
| โ
| โ
|
| **Affiliate System** | โ
| โ
| โ
|
| **OWASP Security Audit** | โ
| โ
| โ
|
| **Playwright E2E Tests** | โ
| โ
| โ
|
| **Support** | Standard (6mo) | **Priority (9mo)** | **Priority (12mo)** |
| **Private Discord Community** | โ
| โ
| โ
|
| **Consultation Call** | โ | **30-min** | **30-min** |
| **White-Label Rights** | โ | โ | โ
|
| **Cost per Developer** | $197 | **~$83** _(60% off)_ | **~$83** _(65% off)_ |
| **Cost per Hour Saved** | $0.60 | **$0.24** | **$0.21** |
| **Ideal For** | Solo Founders | Small Dev Teams | Agencies |
> [!NOTE]
>
**Built-in Resource Management:** This boilerplate ships with a
production-ready, tiered project management system. You can enforce resource
limits (e.g., max 3 projects for Free tier) out-of-the-box, with UI-disabled
states and automated redirection to your pricing page.
## Why Growth Is the Best-Seller
> **~$83/developer.** 6 developers ร 480 hours saved = **2,880 hours recovered** โ that's **$0.24/hour**. No boilerplate on the market comes close.
## The Agency Arbitrage
> Sell **one** client project for $5,000. License cost covered **4x over.** 12 seats ร $8,000 avg monthly output ร 3 weeks saved = **$288,000/year in recovered capacity.**
> ๐ก **Seat = developer accessing source code.** End users of deployed apps don't require seats.
## Stack Value Breakdown
Built this yourself? Here's what you'd pay for each module separately:
| Component | Market Value | Why |
| :------------------------------ | :----------- | :------------------------------------------------------------ |
| **Enterprise Auth (RBAC)** | $500+ | Multi-tenancy, roles, invitations, sessions โ pre-configured |
| **Universal Payment Adapter** | $2,000+ | Unified interface for 5 providers. Months saved. |
| **AI Chat + RAG Pipeline** | $1,500+ | Vector embeddings, retrieval, chat UI with optimistic updates |
| **ElevenLabs Voice** | $800+ | Real-time TTS/STT with audio wave visualization |
| **super-admin Dashboard & CMS** | $1,000+ | Full CRUD for users, tickets, content. Not a DB viewer. |
| **OWASP Security Audit** | $3,000+ | Published PDF for enterprise sales closings |
| **Total Value** | **$8,800+** | **You pay: $197** (Starter) โ **96.74% off** |
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > Changelog
> All notable changes documented here. Format: [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). Versioning: [SemVer](https://semver.org/spec/v2.0.0.html).
---
## [1.0.0] - 22nd May, 2026
### Core Architecture & Developer Experience
- **Agent-Native Architecture** โ Integrates Graphify AST-level codebase mapping to eliminate AI agent hallucination and reduce AI token usage by up to 71.5x.
- **AI Developer Tooling** โ Includes dedicated `.agents/` skills and workflows alongside `AGENTS.md` and `CLAUDE.md` for zero-hallucination AI-assisted development.
- **Strict Tech Stack** โ Utilizes Next.js 16 App Router, TypeScript 6 (Strict), Drizzle ORM, and Zod validation. Guarantees testing parity with 900 unit tests and comprehensive E2E Playwright coverage.
- **Interactive Setup Wizard** โ Provides a robust CLI with interactive prompts, automatic environment variable generation, and manual database bootstrapping instructions. Generates exclusively `.env.local` to avoid clutter, wraps special-character values in double quotes, and guarantees clean builds.
- **Universal Background Jobs** โ Decouples transport logic into swappable Upstash QStash and Trigger.dev adapters with unified dependency health checks.
- **Modular Background Jobs** โ Decoupled configuration validation (`lib/jobs/config.ts`) from dynamic Database/handler pathways to safeguard system health endpoints without side effects.
- **Performance Optimization** โ Employs `Promise.all` for parallel database queries, cursor-based pagination, request-level React `cache()`, and dynamic imports to ensure high performance.
- **Avatar Storage RLS Bypass** โ Uses service role client for avatar upload URL generation and deletion to bypass `storage.objects` RLS, with session identity validated first.
- **Middleware Profile Fallback** โ Profile resolution queries the user-authenticated client first, falling back to service role only when the profile is not found and a valid `SUPABASE_SECRET_KEY` is present.
- **Locale Scoping & Type Integrity** โ Hardened AI legal page publishing and configuration transitions to isolate workflows completely by locale and type, preventing accidental cross-locale state conflicts.
### Design System & UI
- **Glassmorphism 2.0** โ Delivers premium crystal surfaces (`bg-white/50 backdrop-blur-2xl`), tri-font typography (Space Grotesk, DM Sans, Fragment Mono), and OKLCH color tokens.
- **Touch-First Ergonomics** โ Enforces strict 44px minimum tap targets, fluid Bento Grid layouts, and iOS safe-area integration for mobile perfection.
- **Dynamic Interactions** โ Features animated GlowCards, emoji loaders, spring-physics collapsible navigation, and smart sticky headers using `motion/react`.
- **Super-Admin Dashboard** โ Supplies 17 modular management tools for users, billing, support tickets, waitlists, and AI-powered legal document generation, all featuring standardized UI and centralized CSV exports.
- **Internationalization (i18n)** โ Maintains 100% key parity across EN, ES, and FR locales with localized marketing forms and transactional emails.
- **Avatar Aspect Ratio** โ Global `AvatarImage` uses `object-cover object-center` for automatic 1:1 cropping and normalizes empty `src` to `undefined` to prevent browser warnings.
- **Testimonials Network Optimization** โ Eliminated remote dependencies on external random avatar providers, adopting dynamic high-fidelity CSS-native glassmorphic gradients and initials, alongside an explicitly hardened Next.js `allowedPatterns` image configuration.
- **Core Web Vitals Tuning** โ Dynamic progressive loading separates marketing page components into Server and Client lazy wrappers (`BelowFoldSections.tsx`) to drastically cut main-thread blocking time.
### Security & Authentication
- **Enterprise Authentication** โ Supports passkeys, magic links, OAuth (Google/GitHub), and TOTP MFA with step-up verification, secure email verification, PKCE-style server-side verification, and fail-closed middleware enforcement.
- **Email Verification Redirect** โ Server-side OTP confirmation immediately redirects to `/verified`, eliminating duplicate page renders and client-side flash.
- **OWASP Compliance** โ Enforces Row-Level Security (RLS) on all 32 tables, strict CSP nonce policies, SSRF URL sanitization, and cryptographic safety (zero `Math.random()` in server code).
- **Edge Rate Limiting** โ Integrates Upstash Redis to provide route-level rate limiting, brute-force bans, and circuit breakers across 56+ public and authenticated API routes.
- **Impersonation Safety** โ Enables super-admin user impersonation backed by HMAC-signed cookies, auto-expiry, and instantaneous UI layout synchronization.
- **Defensive Deletion** โ Implements fail-closed account deletion to securely cancel all active payment provider subscriptions before wiping user profiles and storage.
### Payments & Billing
- **Universal Payment Adapter** โ Integrates Stripe, Polar, Lemon Squeezy, Dodo, and Creem via a single environment variable with retry-safe webhook idempotency.
- **Complex Billing Models** โ Manages subscriptions, usage-based credits, one-time/lifetime purchases, and team seat entitlements natively.
- **Checkout Security** โ Creates guest-safe checkout sessions, prevents external return targets via same-origin validation, and safely fulfills digital products via signed tokens.
- **Billing Transparency** โ Features a high-fidelity billing dashboard to render tiered resource limits dynamically and manage lifetime access serialization.
### AI & Intelligence
- **Universal AI Adapter** โ Supports Gemini, OpenAI, Anthropic, and DeepSeek for high-quality chat, intent detection, and structured JSON outputs.
- **Google GenAI 2.5.0 Upgrade** โ Integrated `@google/genai` v2.5.0 SDK, designating `gemini-3.5-flash` as primary chat model with robust custom schema mappings for legal page creation.
- **RAG & Knowledge Base** โ Deploys a pgvector embedding pipeline (3072-dim) with cosine similarity and a super-admin managed document repository.
- **Embeddings Dimension Protection** โ Standardized embedding processes on `gemini-embedding-2` yielding a stable 3072-dimensional vector footprint with explicit runtime boundaries and zero pgvector dimension pollution.
- **Universal AI Voice Adapter** โ Supports swappable text-to-speech (TTS) and speech-to-text (STT) services via ElevenLabs and Murf AI with request-time key resolution and integrated SSRF guards for immersive voice conversations in over 29 languages.
- **Autonomous Support** โ Includes an AI chat widget with 100+ language support, lazy conversation creation, and seamless escalation to human support queues via Supabase Realtime.
### Platform Features
- **Organizations & Multi-Tenancy** โ Provides full organization RBAC with owner, admin, and member roles alongside tier-based project management limits and invite systems.
- **Universal Email Adapter** โ Wraps SendGrid, Resend, Postmark, and Brevo into zero-code adapters featuring 13 localized transactional React Email templates.
- **Universal Analytics Adapter** โ Supports 9 analytics providers (including Mixpanel, PostHog, Plausible) in a consent-gated, CSP-compliant architecture.
- **Affiliate System** โ Drives growth via built-in referral tracking with IP hashing, cookie-based attribution, and atomic payout management.
### ๏ธ OWASP Top 10 (2025) โ Full Compliance
- โ
**A01 โ Broken Access Control** โ Block SSRF via `lib/security/ssrf.ts` with 25+ unit tests
- โ
**A02 โ Security Misconfiguration** โ Validate env at build-time; run 9 HTTP header tests
- โ
**A03 โ Supply Chain** โ Run `npm run security:audit` in CI; maintain CycloneDX SBOM and Dependabot
- โ
**A04 โ Cryptographic Failures** โ `lib/security/crypto.ts` replaces all `Math.random()` in server code
- โ
**A05 โ SSRF** โ Audit LLM prompt injection; defense-in-depth via `ssrf.ts`
- โ
**A06 โ Insecure Design** โ Maintain STRIDE threat model with 6 abuse case scenarios
- โ
**A07 โ Auth Failures** โ Provide password strength meter and universal MFA across all vectors
- โ
**A08 โ Data Integrity** โ Use SRI hashes on CDN scripts and verify all `JSON.parse()` calls
- โ
**A09 โ Logging & Alerting** โ Maintain append-only `auth_events` with `logAuthEvent()` and brute-force detection
- โ
**A10 โ Exceptional Conditions** โ Enforce fail-closed MFA, production fail-closed rate limiting, payment timeout handling, and graceful shutdown
---
## ๏ธ Technical Stack
| Category | Technology | Version |
| :-------------- | :------------------------------------------------------ | :------ |
| Framework | Next.js (App Router, RSC) | 16+ |
| Language | TypeScript (Strict Mode) | 6+ |
| Styling | Tailwind CSS | 4+ |
| Components | shadcn/ui | Latest |
| Animation | motion/react (LazyMotion) | Latest |
| Database | PostgreSQL (Supabase) | Latest |
| ORM | Drizzle ORM | Latest |
| Auth | Supabase Auth | Latest |
| Payments | Stripe / Polar / LS / Dodo / Creem | Latest |
| Analytics | Universal Adapter (9 providers) | Latest |
| AI | Universal Adapter (Gemini, OpenAI, Anthropic, DeepSeek) | Latest |
| Voice | Universal Adapter (ElevenLabs, Murf AI) | Latest |
| Vector Search | pgvector | 0.7.x |
| Embeddings | `gemini-embedding-2` | Latest |
| Docs | Fumadocs | Latest |
| Validation | Zod | Latest |
| Forms | React Hook Form | Latest |
| Rate Limiting | Upstash Redis | Latest |
| Background Jobs | Upstash QStash + Trigger.dev | Latest |
| Testing | Vitest (Unit) + Playwright (E2E) | Latest |
| API Docs | OpenAPI 3.0.3 + Scalar | Latest |
---
## Role Terminology
| Role | Scope | DB Value | Description |
| :------------ | :----------- | :-------------- | :------------------------------------- |
| `super-admin` | Platform | `'super-admin'` | Global owner โ distinct from org roles |
| `super-admin` | Organization | Org membership | Org-level super-admin |
| `member` | Organization | Org membership | Standard org member |
| `owner` | Organization | Org membership | Org creator, full ownership |
| `user` | Platform | Default | Standard authenticated user |
> โ ๏ธ Platform `super-admin` uses hyphenated format (`super-admin`, not `super_admin`). All RLS, code, and docs use this consistently.
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Getting Started > License
**Last Updated โ May, 2026**
**Copyright ยฉ 2026 Scale with Alap โ Creator of "Vibe44". All rights reserved.**
---
> โ ๏ธ **IMPORTANT โ READ CAREFULLY:** This Commercial Source Code License Agreement ("Agreement") is a legal contract between You ("Licensee" or "You") and Alap Putatunda d/b/a Scale with Alap ("Licensor" or "Author").
>
> BY PURCHASING, DOWNLOADING, INSTALLING, OR USING THE SOFTWARE, YOU ACKNOWLEDGE THAT YOU HAVE READ THIS AGREEMENT, UNDERSTAND IT, AND AGREE TO BE BOUND BY ITS TERMS. IF YOU DO NOT AGREE, YOU MUST NOT USE THE SOFTWARE.
---
## Quick Reference: What You Can & Can't Do
Before diving into the full legal text, here's a plain-English summary of your rights and restrictions:
| โ
You CAN | โ You CANNOT |
| :------------------------------------------------------- | :------------------------------------------------------- |
| Build **unlimited** production apps for yourself/clients | Resell or redistribute the source code itself |
| Modify code to fit your or your client's needs | Create a competing template, boilerplate, or starter kit |
| Deploy unlimited projects (limited by Developer Seats) | Open-source the code or publish it publicly |
| Charge your users and generate revenue | Share your license with other developers |
| Use it for client projects (freelance/agency) | Claim ownership of the original Software |
| Keep all revenue you generate โ no royalties | Upload uncompiled source to public repositories |
> ๐ก **The core principle:** You're buying the right to **build with** this code, not to **sell** this code. Your End Products are yours. The source code remains ours.
---
## Table of Contents
1. [Definitions](#1-definitions)
2. [Grant of License](#2-grant-of-license)
3. [Multi-License & Enterprise Licensing](#3-multi-license--enterprise-licensing)
4. [Compliance and Ethical Use Protection](#4-compliance-and-ethical-use-protection)
5. [Updates and Support](#5-updates-and-support)
6. [Intellectual Property Rights](#6-intellectual-property-rights)
7. [Warranty Disclaimer](#7-warranty-disclaimer-as-is)
8. [Limitation of Liability](#8-limitation-of-liability-cap)
9. [Termination](#9-termination)
10. [Governing Law and Dispute Resolution](#10-governing-law-and-dispute-resolution)
11. [Entire Agreement](#11-entire-agreement)
12. [Contact Information](#12-contact-information)
---
## 1. Definitions
| Term | Definition |
| :----------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **"Software"** | The "Vibe44" source code, scripts, assets, documentation, configuration files, skill files, workflow files, and all associated files provided by Licensor, regardless of delivery method (download, Git access, or other). |
| **"Deployed Project"** | A single production application, website, or digital product built using the Software and made accessible to end users via a public or private URL. |
| **"End Product"** | The final customized work created by Licensee using the Software for a specific business purpose. The End Product must be substantially different from the original Software and must add significant value beyond the original code. |
| **"License Fee"** | The one-time payment made by Licensee to Licensor in exchange for the rights granted under this Agreement, as specified at the time of purchase. |
| **"Licensee" / "You"** | The individual or legal entity that purchased the License Fee and is bound by this Agreement. |
| **"Licensor" / "Author"** | Alap Putatunda, operating as Scale with Alap, the creator and copyright holder of the Software. |
| **"Derivative Work"** | Any work based upon the Software, including modifications, enhancements, translations, adaptations, or any other form in which the Software may be recast, transformed, or adapted. |
| **"Unethical or Illegal Use"** | Any use of the Software to facilitate, promote, or execute activities that are illegal in the Licensee's jurisdiction, the Licensor's jurisdiction, or under generally recognized international law โ including but not limited to fraud, scams, hate speech, violence, harassment, unauthorized surveillance, data theft, or child exploitation. |
---
## 2. Grant of License
Subject to your full payment of the applicable License Fee and compliance with this Agreement, Licensor grants You a limited, non-exclusive, non-transferable, revocable, worldwide license to use the Software as described below.
### 2.1 Permitted Uses
| Permission | Details | Example |
| :--------------------------- | :---------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------- |
| โ
**Development** | Use the Software to code, test, and build Deployed Projects in development environments | Running locally via `npm run dev`, deploying to staging |
| โ
**Modification** | Modify, alter, and adapt the source code for your specific business needs | Changing branding, adding features, modifying the UI |
| โ
**Production Deployment** | Deploy **UNLIMITED** End Products to production | `my-saas.com`, `client-project.com`, `app-3.com` |
| โ
**Commercial Use** | Generate revenue from your End Products by charging your users | Subscriptions, one-time purchases, freemium models |
| โ
**Client Work** | Build End Products for clients, provided the client does not receive the original source code | Freelance/agency work where you deliver a deployed product |
| โ
**Private Repository** | Store the Software in a private version control repository accessible only to available **Developer Seats** | Private GitHub/GitLab repo for your team |
> ๐ก **Unlimited Deployments:** You may build and deploy an unlimited number of projects. The limiting factor is the number of **Developer Seats** (individuals accessing the source code), which is determined by your license tier.
### 2.2 Strict Prohibitions (Zero Tolerance)
The following actions are **expressly prohibited** and constitute grounds for immediate license termination:
| โ Prohibition | What This Means | Why This Exists |
| :-------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------------------- |
| **No Resale of Source** | You may NOT sell, rent, lease, sublicense, distribute, or otherwise transfer the Software source code itself, in whole or in part, to any third party. | Protects the commercial viability of the Software |
| **No Competing Products** | You may NOT use the Software to create a competing product, such as a SaaS boilerplate, starter kit, theme, template, or code generator where the primary value is the code itself. | Prevents direct competition with the original product |
| **No Open Source** | You may NOT release the Software or any Derivative Works under an Open Source license (e.g., GPL, MIT, Apache, BSD) that would require or permit disclosure of the source code. | Prevents circumvention of commercial licensing |
| **No Public Exposure** | You may NOT upload the uncompiled source code to public repositories, public file shares, public Gists, or any publicly accessible location. | Prevents unauthorized distribution |
| **No License Sharing** | You may NOT share, transfer, or allow use of your license by individuals or entities that are not part of your immediate development team. | Maintains per-license accountability |
| **No Code Extraction for Resale** | You may NOT extract components, utilities, functions, or design systems from the Software and sell, distribute, or package them as standalone products. | Prevents piecemeal redistribution |
> โ ๏ธ **Gray area guidance:** If you're unsure whether your intended use is permitted, contact `legal@scalewithalap.com` before proceeding. When in doubt, the test is: _"Am I selling what I built, or am I selling the code I used to build it?"_ The former is permitted; the latter is not.
---
## 3. Multi-License & Enterprise Licensing
### 3.1 Developer Seats (The Constraint)
This license is sold under a **Seat-Based Model**. You may build unlimited projects, but the number of developers who can access, edit, or view the source code is limited by your tier:
| Tier | Developer Seats | Deployed Projects |
| :---------- | :-------------- | :---------------- |
| **Starter** | **1 Seat** | Unlimited |
| **Growth** | **6 Seats** | Unlimited |
| **Agency** | **12 Seats** | Unlimited |
**Definition of a Seat:** Any individual who downloads, views, modifies, or accesses the uncompiled Source Code.
**Example violations:**
- Buying a "Starter" license (1 seat) and sharing the git repo with 2 co-founders. (Requires Growth license).
- An agency with 10 developers buying a "Growth" license (6 seats). (Requires Agency license).
### 3.2 Enterprise & Volume Licensing
For organizations requiring:
- **5+ simultaneous Deployed Projects**
- **Custom licensing terms** (e.g., white-label rights, unlimited deployments)
- **Source code escrow** or other enterprise requirements
Contact `legal@scalewithalap.com` for custom enterprise licensing arrangements.
---
## 4. Compliance and Ethical Use Protection
### 4.1 Non-Liability for Licensee's Actions
**THE LICENSOR SHALL HAVE ABSOLUTELY NO LIABILITY FOR WHAT YOU BUILD.**
You acknowledge that the Software is a tool โ a starting point for building your own application. How you use this tool is solely and exclusively your responsibility. Licensor expressly disclaims any and all liability, responsibility, or obligation for End Products that are:
- **Illegal, fraudulent, or deceptive** in any jurisdiction
- **Used for spamming**, harassment, threats, or any form of unauthorized communication
- **Used for unethical activities**, including but not limited to predatory lending, dark patterns, gambling (where prohibited), or deceptive marketing
- **In violation of any third-party rights**, including privacy rights (GDPR, CCPA, etc.), intellectual property, trade secrets, or contractual obligations
- **Non-compliant with industry regulations**, including but not limited to HIPAA, PCI-DSS, FERPA, SOX, or similar regulatory frameworks applicable to the Licensee's industry
- **Used for unauthorized surveillance**, data harvesting, or tracking without proper consent
> ๐ **Your compliance responsibility:** While the Software includes security features (RLS, fail-closed production rate limiting, Zod input validation, HMAC-bound CSRF protection, same-origin payment redirects, webhook and provider-resource idempotency, fail-closed paid account deletion, retained deletion audit events, and all the automated test definitions across all the unit test files), achieving regulatory compliance (GDPR, HIPAA, PCI-DSS, etc.) for your specific End Product is **YOUR RESPONSIBILITY**. The Software provides a strong foundation, but compliance depends on how you use it, what data you collect, and what industry you operate in.
### 4.2 Right to Verify Compliance
Licensor reserves the right, **no more than once per calendar year**, to request written certification of compliance with the Developer Seat limits. Upon request, Licensee must provide:
1. A written statement confirming the current number of developers with access to the Source Code.
2. A list of version control usernames (e.g., GitHub, GitLab) or email addresses for all individuals with Source Code access.
If verification reveals that you have exceeded your seat limit, you must purchase the necessary additional licenses or upgrade your tier within 14 days.
### 4.3 Indemnification by Licensee
You agree to **indemnify, defend, and hold harmless** Licensor, its affiliates, officers, agents, successors, and assigns from and against any and all claims, damages, losses, liabilities, costs, and expenses (including reasonable attorneys' fees and legal costs) arising out of or related to:
1. Your use, modification, or deployment of the Software.
2. Your End Product or any services, content, or data you provide through it.
3. Your violation of this Agreement or any term herein.
4. Your violation of any applicable law, regulation, or third-party right.
5. Any claim by a third party relating to your End Product.
**This indemnification obligation survives the termination or expiration of this Agreement** indefinitely.
---
## 5. Updates and Support
### 5.1 Software Updates
| Aspect | Policy |
| :---------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- |
| **Availability** | Licensor may provide updates, patches, or new versions at its sole discretion. There is no obligation to provide updates. |
| **Access** | This License entitles you to access updates released during your update access period (as specified at purchase). |
| **Breaking Changes** | Licensor will make reasonable efforts to document breaking changes in the CHANGELOG, but is not liable for any disruption caused by updates. |
| **Update Installation** | You are responsible for applying updates to your Deployed Projects. Updates are not automatically applied. |
### 5.2 Technical Support
| Aspect | Policy |
| :---------------- | :------------------------------------------------------------------------------------------------------ |
| **Duration** | Technical support is provided for the period specified at the time of purchase (default: **6 months**). |
| **Scope** | Support covers technical issues with the **original Software** as delivered. |
| **Response Time** | Best-effort basis. No guaranteed SLA unless explicitly agreed in writing. |
| **Channels** | Email (`alap@vibe44.com`) and any support channels specified at purchase. |
**Support does NOT include:**
- โ Debugging your custom modifications or business logic
- โ Adding custom features or integrating third-party services
- โ Refactoring your codebase or code reviews
- โ Server/infrastructure configuration or deployment troubleshooting
- โ Performance optimization of your End Product
- โ Training on technologies used in the Software (Next.js, Supabase, etc.)
---
## 6. Intellectual Property Rights
### 6.1 Licensor's Ownership
All rights, title, and interest in and to the Software โ including but not limited to all source code, object code, architecture, database schema designs, documentation, trade secrets, trademarks, service marks, logos, and all other intellectual property rights โ remain the **sole and exclusive property of Licensor**.
This Agreement does **not** grant you any ownership rights in the Software. You are granted only the limited usage rights described in Section 2.
### 6.2 Licensee's Ownership
You retain full ownership of:
- **Your custom code** โ modifications, features, and business logic you add to the Software
- **Your brand identity** โ logos, copy, images, and other brand assets
- **Your data** โ all user data, business data, and content in your End Product
- **Your End Product** โ the final deployed application as a whole (but not the underlying Software code)
### 6.3 Attribution
Attribution to "Scale with Alap" or "Vibe44" in your End Product is **not required** but is appreciated. You may remove all references to Scale with Alap, Vibe44, and associated branding from your Deployed Project.
---
## 7. Warranty Disclaimer ("AS IS")
**THE SOFTWARE IS PROVIDED "AS IS" AND "AS AVAILABLE," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.**
TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, LICENSOR EXPRESSLY DISCLAIMS ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO:
- **WARRANTIES OF MERCHANTABILITY** โ that the Software is suitable for commercial purposes.
- **WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE** โ that the Software is suitable for your specific use case.
- **WARRANTIES OF NON-INFRINGEMENT** โ that the Software does not infringe upon any third-party rights.
- **WARRANTIES OF ACCURACY** โ that the Software, its documentation, or its outputs are accurate, complete, or current.
- **WARRANTIES OF SECURITY** โ that the Software is free from vulnerabilities, even though security measures are included.
- **WARRANTIES OF CONTINUOUS OPERATION** โ that the Software will be error-free, secure, or uninterrupted.
**YOU ASSUME THE ENTIRE RISK** as to the quality, safety, performance, security, and suitability of the Software for your intended purpose.
> ๐ก **What this means in practice:** While Vibe44 includes enterprise-grade security features (RLS, fail-closed production rate limiting, HMAC-bound CSRF protection, strict request validation, same-origin payment redirects, payment webhook and provider-resource deduplication, SSRF-safe provider media fetching, payment tier mapping safeguards, and documented verification workflows), no software is perfectly secure. You are responsible for security testing, penetration testing, payment-provider configuration, and ongoing security maintenance of your Deployed Project.
---
## 8. Limitation of Liability (Cap)
### 8.1 Exclusion of Consequential Damages
**UNDER NO CIRCUMSTANCES SHALL LICENSOR BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL, EXEMPLARY, OR PUNITIVE DAMAGES** โ including but not limited to:
- Loss of revenue, profits, or anticipated savings
- Loss of data or data breach costs
- Business interruption or business opportunity loss
- Cost of procurement of substitute goods or services
- Damage to reputation or goodwill
This exclusion applies REGARDLESS of:
- Whether Licensor has been advised of the possibility of such damages
- The legal theory under which liability is asserted (contract, tort, strict liability, or otherwise)
- Whether the damages were foreseeable
### 8.2 Total Liability Cap
**IN NO EVENT SHALL LICENSOR'S TOTAL CUMULATIVE LIABILITY** for all claims arising out of or relating to this Agreement **EXCEED THE ACTUAL AMOUNT PAID BY YOU FOR THE LICENSE FEE.**
This limitation applies:
- Regardless of the number of claims asserted
- Regardless of the legal theory (contract, tort, or otherwise)
- To all causes of action in the aggregate
---
## 9. Termination
### 9.1 Termination by Licensor
Licensor may terminate this Agreement **immediately and without notice** if You:
- Breach any term of this Agreement (including the prohibitions in Section 2.2)
- Fail to cure a breach within 15 calendar days of written notice
- File for bankruptcy or become insolvent
- Engage in Unethical or Illegal Use of the Software
### 9.2 Effect of Termination
Upon termination of this Agreement:
1. **All usage rights** granted herein immediately and irrevocably cease.
2. You must **delete all copies** of the Software from all systems, devices, and backups within 30 days.
3. You must **take down** any Deployed Projects operating in violation of this Agreement.
4. Upon Licensor's request, you must provide **written certification** of destruction of all copies.
5. Sections 3, 4, 6, 7, 8, and 10 **survive termination** indefinitely.
### 9.3 Termination by Licensee
You may terminate this Agreement at any time by:
1. Deleting all copies of the Software from all systems
2. Taking down all Deployed Projects built using the Software
3. Notifying Licensor in writing at `legal@scalewithalap.com`
> โ ๏ธ **No refunds upon termination.** The License Fee is non-refundable after purchase, regardless of the reason for termination.
---
## 10. Governing Law and Dispute Resolution
### 10.1 Jurisdiction
This Agreement shall be governed by and construed in accordance with the **laws of the jurisdiction where the Licensor is domiciled at the time the dispute arises**, without regard to conflict of law provisions or principles.
> ๐ก **Why Licensor's domicile?** This ensures consistent legal treatment regardless of where the Licensee is located, and prevents forum shopping.
### 10.2 Binding Arbitration
Any dispute, controversy, or claim arising out of or relating to this Agreement โ including its existence, validity, interpretation, performance, breach, or termination โ shall be settled by **binding arbitration** under the following conditions:
| Aspect | Requirement |
| :-------------- | :--------------------------------------------------------------------------- |
| **Language** | English |
| **Proceedings** | Conducted remotely (video conference) unless both parties agree to in-person |
| **Decision** | The arbitrator's decision shall be final and binding on both parties |
| **Enforcement** | Judgment on the award may be entered in any court having jurisdiction |
| **Costs** | Each party bears its own legal costs unless the arbitrator awards otherwise |
### 10.3 Class Action Waiver
**You agree to resolve disputes only on an individual basis** and hereby waive any right to participate in a class action, collective action, or representative proceeding against Licensor. This waiver applies to the fullest extent permitted by applicable law.
### 10.4 Injunctive Relief
Notwithstanding the arbitration provisions above, Licensor may seek **injunctive or equitable relief** in any court of competent jurisdiction to protect its intellectual property rights or enforce the prohibitions in Section 2.2, without the requirement of posting a bond or proving actual damages.
---
## 11. Entire Agreement
This Agreement constitutes the **entire understanding** between the parties with respect to the subject matter hereof and supersedes all prior agreements, negotiations, representations, warranties, and understandings โ whether written or oral โ concerning the same subject matter.
**Severability:** If any provision of this Agreement is held to be invalid, illegal, or unenforceable by a court of competent jurisdiction, such provision shall be modified to the minimum extent necessary to make it valid and enforceable, and the remaining provisions shall continue in full force and effect.
**Waiver:** The failure of Licensor to enforce any provision of this Agreement shall not constitute a waiver of that provision or the right to enforce it at a later time.
**Assignment:** You may not assign or transfer this Agreement or any rights hereunder without the prior written consent of Licensor. Licensor may assign this Agreement freely.
---
## 12. Contact Information
For licensing inquiries, enterprise licensing, or legal questions:
| Channel | Contact |
| :------------------ | :--------------------------------------------- |
| **Email** | legal@scalewithalap.com |
| **General Support** | alap@vibe44.com |
| **Website** | [scalewithalap.com](https://scalewithalap.com) |
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
---
# SECTION: Architecture
## Architecture > Architecture
> System design, data flows, component boundaries, and integration topology for this codebase.
## ๏ธ Technology Stack
| Layer | Technology | Purpose |
| :-------------- | :--------------------------------------- | :------------------------------------------------------ |
| Framework | Next.js 16 (App Router) | RSC, Server Actions, edge middleware |
| Language | TypeScript 6 (Strict) | Zero `any`, compile-time safety |
| Database | PostgreSQL 15 (Supabase) | 32 tables, RLS on every table |
| ORM | Drizzle ORM | Type-safe SQL, schema-driven |
| Auth | Supabase Auth | PKCE, OAuth, MFA, passkeys |
| Payments | Universal Adapter (5 providers) | Strategy pattern, env var swap |
| AI | Universal Adapter (4 providers) | Validated Gemini, OpenAI, Anthropic, DeepSeek factories |
| Embeddings | `gemini-embedding-2` + pgvector | 3072-dim, cosine similarity RAG |
| Voice | Universal Adapter (2 providers) | ElevenLabs/Murf TTS; STT requires ElevenLabs |
| Email | Universal Adapter (4 providers) | Validated SendGrid, Resend, Postmark, Brevo adapters |
| Analytics | Universal Adapter (9 providers) | Consent-gated scripts/events with CSP allowlisting |
| Rate Limiting | Upstash Redis | Edge middleware, circuit breaker |
| Background | Universal Adapter (QStash / Trigger.dev) | Strategy pattern, swappable background jobs |
| Knowledge Graph | Graphify | AST parsed, 71.5x token reduction for AI Agents |
| Styling | Tailwind CSS v4 + shadcn/ui (57) | OKLCH, Glassmorphism 2.0 |
| Motion | `motion/react` (LazyMotion) | Spring physics, ~15KB vs ~100KB |
| i18n | next-intl | 3 languages, 14 sub-modules |
| Testing | Vitest + Playwright | 900 tests across 84 unit test files + E2E coverage |
| API | oRPC + OpenAPI 3.0.3 + Scalar | Type-safe RPC, interactive docs |
| Error Tracking | Sentry | PII and replay opt-in, GDPR-safe default |
---
## Request Lifecycle
Every request passes through this pipeline:
```
Browser Request
โ
proxy.ts (Edge Middleware)
โโโ Route classification (public / auth / protected / super-admin / API)
โโโ Rate limiting (Upstash Redis, per-tier from lib/config/pricing.ts)
โโโ Circuit breaker (auto IP ban after 5 violations)
โโโ CSP nonce generation (per-request, strict-dynamic)
โโโ CSRF validation (HMAC-bound double-submit cookie + user binding)
โโโ Auth session refresh (Supabase token rotation)
โโโ MFA enforcement (AAL2 check via getAuthenticatorAssuranceLevel(), fail-closed)
โโโ Feature flag redirects (disabled modules โ /dashboard)
โโโ Header injection (x-pathname, x-org-id, x-nonce, x-impersonating-*)
โโโ Signed impersonation context propagation (1hr auto-expiry + read-time profile revalidation)
โโโ Waitlist Gating: unapproved users deleted via super-admin client
โโโ Waitlist Metadata Sync: fullName โ profile (first login)
โโโ CSRF cookie seeding/refresh for authenticated page requests
โ
Next.js App Router
โโโ Root layout (fonts, ThemeProvider, MotionProvider, NextIntlClientProvider, CSRFProvider)
โโโ Server Component (data fetching via Server Actions)
โโโ Client Component (interactive UI, motion animations)
โ
Server Actions (app/actions/)
โโโ 1. Auth check โ requireUser() / verifyAdmin()
โโโ 2. Zod validation โ schema.safeParse(input)
โโโ 3. Drizzle operation โ db.select/insert/update/delete
โโโ 4. Cache invalidation โ revalidatePath() + revalidateTag(..., "max")
โ
PostgreSQL (Supabase)
โโโ RLS policies enforce data isolation at query level
โโโ Drizzle ORM parameterizes all queries (SQL injection prevention)
โโโ Indexes optimized for RLS super-admin checks + common patterns
```
---
## Performance Contracts
The current performance hardening uses stable production primitives, not experimental framework flags:
- Next.js config strips unstable keys after plugin composition; production builds must not depend on `experimental`.
- Pricing auth/billing reads execute in parallel and commit one derived billing-context state update.
- Drizzle reads use explicit projections to reduce payload size and avoid accidental over-fetching.
- Super-Admin webhook log reads clamp requested limits to 100 rows and project only fields needed by retry/list/detail views.
- Fixed-aspect `next/image` assets include `style={{ width: "auto", height: "auto" }}` to prevent ratio warnings and layout shifts.
- Heavy client libraries remain behind dynamic import or provider-level lazy loading: Recharts via chart wrappers, support chat widget via `next/dynamic`, and motion via `LazyMotion` + `domAnimation`.
---
## Directory Structure
```
app/
โโโ (marketing)/ # Public: landing, pricing, blog, contact, system, docs, API ref
โโโ (auth)/ # Login, signup, forgot/reset password, invite, verified
โโโ (protected)/ # Dashboard, billing, settings, super-admin, onboarding
โ โโโ dashboard/
โ โ โโโ analytics/ # Usage analytics (Recharts)
โ โ โโโ billing/ # Subscriptions, invoices
โ โ โโโ organizations/# Multi-tenant teams
โ โ โโโ projects/ # Project CRUD
โ โ โโโ settings/ # Profile, security (MFA/passkeys), notifications, activity
โ โโโ super-admin/ # 17 super-admin module routes
โโโ api/
โโโ auth/callback/ # OAuth, magic link, password-reset code exchange
โโโ health/ # Minimal public liveness endpoint
โโโ rpc/[...path]/ # oRPC handler (type-safe API)
โโโ webhooks/ # Payment webhooks (stripe, polar, lemon-squeezy, dodo, creem)
components/
โโโ auth/ # Split-screen auth, MFA challenge, passkeys
โโโ dashboard/ # Sidebar, nav, charts, settings, org switcher
โโโ global/ # Header, footer, chat widget, theme toggle
โโโ marketing/ # Hero, features, pricing, testimonials
โโโ super-admin/ # 17 super-admin modules (Glassmorphism 2.0 logic)
โโโ support/ # Tickets, chat widget
โโโ ui/ # 57 shadcn/ui primitives (you own the code)
lib/
โโโ ai/ # Universal AI Adapter, providers/, RAG, intent, embeddings
โโโ rpc/ # oRPC routers, procedures, middleware
โโโ auth/ # Supabase client factory (server, client, super-admin), RBAC
โโโ config/ # App config, pricing, feature flags (single source of truth)
โโโ db/ # Drizzle client + schema/ (14 domain files)
โโโ email/ # Universal Email Adapter, templates, i18n content
โโโ invoices/ # PDF Invoice generation service
โโโ payments/ # Universal Payment Adapter (5 providers), types, utils
โโโ jobs/ # Universal Background Jobs (shared business logic)
โโโ qstash/ # QStash transport adapter for background jobs
โโโ trigger/ # Trigger.dev transport adapter for background jobs
โโโ realtime/ # Supabase Realtime broadcasting utilities
โโโ security/ # SSRF (ssrf.ts), crypto (crypto.ts), security alerts
โโโ seo/ # Metadata generators, JSON-LD schemas
โโโ validations/ # Shared Zod schemas
โโโ voice/ # Universal Voice Adapter (ElevenLabs, Murf AI)
locales/
โโโ frontend/ # UI: en.ts, es.ts, fr.ts (14 sub-modules each)
โโโ emails/ # Email content: en.ts, es.ts, fr.ts
.agents/
โโโ skills/ # 4 SKILL.md (backend, frontend, graphify, i18n)
โโโ workflows/ # 18 step-by-step playbooks
graphify-out/ # ๐ง Auto-generated AST knowledge graph for AI
```
---
## Integration Architecture
### Universal Payment Adapter
```
lib/payments/
โโโ types.ts # PaymentProvider interface contract
โโโ index.ts # Factory: getPaymentProvider() reads PAYMENT_PROVIDER env var
โโโ readiness.ts # Selected-provider env and paid-tier product readiness
โโโ utils.ts # mapProductNameToTier(), shared helpers
โโโ providers/
โโโ stripe.ts
โโโ polar.ts
โโโ lemon-squeezy.ts
โโโ dodo.ts
โโโ creem.ts
```
**Pattern:** Strategy. All providers implement `PaymentProvider`. App code calls `getPaymentProvider()` โ never a specific provider. Switching = one env var change, zero code mods. `getPaymentProviderReadiness()` validates the selected provider's API key/access token, webhook secret, and active paid-tier price/product IDs for super-admin health without exposing secret values.
**Paid product-name fallback:** Providers that cannot resolve a tier from metadata or price/product IDs call `mapProductNameToTier()` in `lib/payments/utils.ts`. The helper matches configured paid tier IDs and display names first, maps config-driven `highIntentAliases` (e.g., `business`, `agency`, `enterprise`) to the correct paid tier, and falls back to the lowest paid tier for unknown paid provider names so completed one-time purchases are never downgraded to the default free tier. Each call emits a `[mapProductNameToTier]` warning so teams can replace string-based matching with metadata or configured IDs.
**Webhook flow:**
```
Provider sends webhook
โ
app/api/webhooks/[provider]/route.ts
โ
Read raw body + signature header(s)
โ
provider.handleWebhook(payload, signature) โ HMAC-SHA256
โ
webhook_logs claim(provider, event_id) โ success skip, active-processing skip, failed/stale retry
โ
syncSubscriptionToDb() / savePurchase() โ provider-resource upsert/dedup + profiles.subscription_tier + subscriptions/purchases
```
**Features:**
- **Token-Based Fulfillment:** Secure, signed, short-lived download links for digital products.
- **Same-Origin Redirects:** Checkout success/cancel and portal return URLs are built with `lib/security/redirects.ts` from `config.app.url` plus allowlisted paths. External redirect targets are rejected before provider session creation.
- **Provider Resource Idempotency:** `subscriptions(provider, provider_subscription_id)` and `purchases(provider, provider_payment_id)` are unique when provider IDs are present, preventing duplicate entitlements after webhook retries or concurrent deliveries.
- **Billing Identity Parity:** REST checkout, portal, cancel, and subscription routes use `getEffectiveUserId()` so impersonated super-admin flows target the same account as Server Actions.
- **Fail-Closed Paid Deletion:** Account deletion stops before local profile/auth/storage removal if immediate provider subscription cancellation, configured-bucket storage cleanup, or Auth deletion fails.
- **Dynamic Usage Limits:** Renders tier constraints (projects, team members, API requests, storage) directly from central pricing configs without hardcoded fallbacks.
- **Upgrade Guard Hardening:** Intelligently hides "Upgrade Plan" buttons exclusively for users already on the most expensive plan.
### AI & RAG Pipeline
```
User message (text or voice)
โ
Language detection (getAIProvider().classifyIntent() โ 100+ languages)
โ
Generate embedding (getEmbeddingProvider().generateEmbedding(), 3072 dims)
โ
pgvector cosine similarity โ knowledge_base
โ
Top-K context injected into AI provider prompt
โ
getAIProvider().streamChat() responds (in detected language)
โ
[Optional] Voice Provider (ElevenLabs / Murf) TTS โ speech; STT only when ElevenLabs is configured
โ
Response โ chat widget (Web Audio API)
```
**Key properties:**
- Lazy conversation creation โ DB record on first message, not widget open
- Guest access โ no auth required
- Message dedup โ client-side + event IDs
- Provider gates โ invalid `AI_PROVIDER` / `EMBEDDING_PROVIDER` values fail closed before SDK construction
### Email Adapter
```
lib/email/
โโโ index.ts # sendEmail() โ validates EMAIL_PROVIDER and configured-key fallback
โโโ types.ts # EmailTemplateType (13 template names)
โโโ providers/
โ โโโ sendgrid.ts # Native batch up to 1000
โ โโโ resend.ts # Auto-chunks at 100
โ โโโ postmark.ts # Official postmark SDK, auto-chunks at 500
โ โโโ brevo.ts # Sequential Promise.allSettled
โโโ templates/ # 13 i18n-ready templates
```
### Analytics Adapter
```
lib/analytics/
โโโ consent.ts # localStorage/cookie consent contract + app-local change event
โโโ index.ts # getAnalyticsAdapter() โ SSR/feature/consent guard
โโโ types.ts # AnalyticsProvider (10 event helpers)
โโโ providers/ # 9 implementations
```
PII protection: `trackSignup()` excludes email. Client scripts mount through `components/providers/analytics-provider.tsx` only after explicit analytics consent. `proxy.ts` allowlists analytics `connect-src` endpoints for the configured providers; DataFast requires both `NEXT_PUBLIC_DATAFAST_WEBSITE_ID` and `NEXT_PUBLIC_DATAFAST_DOMAIN`.
---
## ๏ธ Data Model
### Entity Relationships
```
auth.users (Supabase-managed)
โโโ profiles (1:1)
โโโ subscriptions (1:many)
โโโ purchases (1:many)
โโโ invoices (1:many)
โโโ projects (1:many)
โโโ activity_logs (1:many)
โโโ ai_conversations (1:many)
โ โโโ ai_messages (1:many)
โโโ support_tickets (1:many)
โ โโโ ticket_replies (1:many)
โโโ api_keys (1:many)
โ โโโ api_usage_logs (1:many)
โโโ passkeys (1:many)
โโโ notification_preferences (1:1)
โโโ organizations (owner, 1:many)
โโโ org_members (many:many with profiles)
โโโ org_invitations (1:many)
Standalone:
โโโ posts โ blog_categories (many:1)
โโโ knowledge_base (RAG vectors)
โโโ generated_legal_docs
โโโ contact_submissions
โโโ waitlist
โโโ newsletter_subscribers
โโโ webhook_logs
โโโ webauthn_challenges
โโโ auth_events (append-only)
โโโ affiliates โ referrals โ affiliate_payouts
โโโ user_legal_consents
```
### Key Design Decisions
| Decision | Rationale |
| :----------------------- | :------------------------------------------------------------- |
| UUID primary keys | Globally unique, no sequential enumeration |
| `timestamptz` everywhere | Timezone-aware, no UTC bugs |
| `text` not `varchar` | PostgreSQL treats identically; avoids arbitrary limits |
| Hard deletes + CASCADE | Simpler cleanup; retained deletion facts live in `auth_events` |
| JSONB for metadata | Flexible extension (goals, product_usage, line_items) |
| Barrel re-exports | Single import point; domain files keep schema organized |
---
## Security Architecture
```
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Edge Layer โ
โ Rate Limiting (Upstash Redis) โ
โ Circuit Breaker (auto IP ban) โ
โ CSP Nonce (per-request) โ
โ CSRF (HMAC-bound double-submit) โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโ
โ Application Layer โ
โ Auth Check (supabase.auth.getUser) โ
โ MFA Enforcement (AAL2 check) โ
โ Zod Input Validation โ
โ Ownership Verification โ
โโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโ
โ Database Layer โ
โ RLS on all 32 tables โ
โ Drizzle parameterized queries โ
โ FOR UPDATE row locks (credits) โ
โ API Key SHA-256 hashing โ
โ Composite indexes (20+) โ
โ auth_events append-only logging โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
```
> Full OWASP Top 10 (2025) compliance. See [SECURITY_AUDIT.md](/docs/security/security-audit) ยท [THREAT_MODEL.md](/docs/security/threat-model) ยท [SUPPLY_CHAIN_SECURITY.md](/docs/security/supply-chain-security).
---
## ๏ธ Configuration Architecture
Single source of truth:
```
lib/config.ts (barrel export)
โโโ lib/config/app.ts # App name, URL, feature flags, legal
โโโ lib/config/pricing.ts # PRICING_TIERS: prices, limits, credits, rate limits, provider IDs
โโโ lib/config/billing.ts # Billing model toggles (subs, lifetime, credits, seats, trials)
```
Feature flags gate UI + server-side logic:
```typescript
// UI
{isOrganizationsEnabled() && }
// Server
if (!isOrganizationsEnabled()) return { success: false, error: t("disabled") };
```
21 helpers: `isProjectsEnabled()`, `isOrganizationsEnabled()`, `isCreditsEnabled()`, `isSeatsEnabled()`, `isSubscriptionsEnabled()`, `isLifetimePurchasesEnabled()`, `isDigitalProductsEnabled()`, `isTrialEnabled()`, `isBlogEnabled()`, `isAiChatEnabled()`, `isVoiceEnabled()`, `isSTTEnabled()`, `isWaitlistEnabled()`, `isI18nEnabled()`, `isAnalyticsEnabled()`, `isStorageEnabled()`, `isEmailEnabled()`, `isAffiliatesEnabled()`, `isSupportTicketsEnabled()`, `isDocsEnabled()`, `isApiReferenceEnabled()`.
---
_Copyright ยฉ {YYYY} Vibe44. Built with โค๏ธ by [Scale with Alap](https://scalewithalap.com)._
## Architecture > Frontend
> Design system, component architecture, motion physics, SSR/RSC patterns, forms, and accessibility.
## Design System: Glassmorphism 2.0
### Surface System
Every elevated surface uses the Crystal Card โ translucent glass with iridescent overlay:
```tsx
```
### Glass Tokens
| Layer | Class | Use Case |
| :------------ | :------------------------------------------------------------------------ | :----------------- |
| Crystal Card | `bg-white/5 backdrop-blur-2xl border-white/10` | Primary containers |
| Crystal Hover | `hover:bg-white/10 transition-all duration-500` | Interactive cards |
| Depth Layer | `bg-white/[0.02] backdrop-blur-xl border-white/[0.06]` | Nested panels |
| Elevated | `bg-white/10 backdrop-blur-3xl border-white/15` | Modals, dropdowns |
| Iridescent | `bg-linear-to-br from-white/40 via-transparent to-transparent opacity-20` | Light refraction |
### GlowCard
Animate gradient glow on hover:
```tsx
import { GlowCard } from "@/components/ui/glow-card";
Feature
Description
;
```
---
## Typography
### Tri-Font System
| Font | CSS Variable | Class | Usage |
| :------------ | :--------------- | :------------- | :------------------- |
| Space Grotesk | `--font-heading` | `font-heading` | Headlines, CTAs, nav |
| DM Sans | `--font-body` | `font-body` | Body, descriptions |
| Fragment Mono | `--font-heading` | `font-heading` | Code, data, metrics |
### Scale
| Element | Classes |
| :------ | :--------------------------------------------------------------- |
| h1 | `font-heading text-4xl md:text-5xl font-bold tracking-tight` |
| h2 | `font-heading text-2xl md:text-3xl font-semibold tracking-tight` |
| h3 | `font-heading text-lg font-semibold` |
| Body | `font-body text-base leading-relaxed` |
| Caption | `font-body text-sm text-muted-foreground` |
| Metric | `font-heading text-xs uppercase tracking-wider` |
---
## Color Palette
### OKLCH Tokens
Defined in `app/globals.css` with `:root` (light) and `.dark` variants.
- โ
Use: `text-foreground`, `bg-background`, `text-muted-foreground`, `bg-primary`
- โ Never: `text-white`, `bg-black`, `text-gray-500` (breaks dark mode)
| Token | Light | Dark |
| :-------------- | :------------------------------- | :------------------------------------ |
| `--background` | Near-white | Deep blue-black |
| `--foreground` | Near-black | Near-white |
| `--primary` | Purple (`oklch(46.5% 0.24 302)`) | Bright purple (`oklch(56% 0.29 301)`) |
| `--muted` | Light gray | Dark gray |
| `--destructive` | Red | Red (dark-adjusted) |
Dark mode via `next-themes` + `ThemeProvider`.
### Dark Mode Enforcement Policy
Every component that uses hardcoded light-mode Tailwind classes **must** include a corresponding `dark:` override. This is a non-negotiable standard enforced through deep audits.
| Light-Mode Class | Required Dark Override | Context |
| :------------------ | :-------------------------------------------- | :------------------------- |
| `bg-white` | `dark:bg-slate-950` | Card backgrounds, surfaces |
| `bg-slate-50` | `dark:bg-slate-950` | Muted/alternating surfaces |
| `bg-white/50` | `dark:bg-white/5` | Glass translucent layers |
| `border-slate-200` | `dark:border-white/5` | Container borders |
| `border-white` | `dark:border-slate-800` | Decorative borders |
| `bg-emerald-50` | `dark:bg-emerald-950/30` | Accent-colored surfaces |
| `hover:bg-white/40` | `dark:hover:bg-white/5` | Interactive row/card hover |
| `bg-slate-100/80` | `dark:bg-slate-800/80` | Badge/pill backgrounds |
| `bg-slate-900/80` | `dark:bg-white/5` with `dark:border-white/10` | Floating navigation pills |
> **Rule:** If a Tailwind class contains a color or opacity value tied to a light background, it needs a `dark:` sibling. No exceptions.
### Branding & Logos (Dynamic Theme)
Whenever the primary brand logo is displayed (Header, Footer, Sidebar, Auth), you **must** use dynamic logo states to conditionally render the correct logo variant depending on the active theme:
```tsx
{
/* Light Mode Logo */
}
;
{
/* Dark Mode Logo */
}
;
```
> **Rule (Non-Logo Assets):** Any visual asset (illustration, icon, decorative graphic) that is designed for a light background MUST have a dark-mode counterpart or use CSS `filter`/`invert` โ never display a light-only graphic on a dark background unchecked.
### Image Compliance (Aspect Ratio Safety)
To prevent Next.js hydration layout shifts and aspect ratio console warnings, **every** `next/image` instance for logos and fixed-aspect assets MUST include the `style={{ width: "auto", height: "auto" }}` attribute.
```tsx
```
> **Rule:** If you use CSS (like Flexbox or grid) that might constrain the image layout, you must use `style={{ width: "auto", height: "auto" }}`. Ensure the `width` and `height` props precisely match the intrinsic ratio of the source asset (e.g., `1364x256` scales to `135x25`).
### Pricing Render Contract
`components/marketing/common/pricing-section.tsx` is intentionally a Client Component because it owns billing interval controls, authenticated checkout state, and provider-backed plan actions. Its authenticated billing reads are parallelized with `Promise.all()` and committed through one `PricingBillingContext` state update. This avoids a profile -> purchase -> subscription waterfall and prevents three independent render commits during pricing-page hydration.
Required invariants:
1. Keep profile, lifetime purchase, and active subscription reads independent unless a future data dependency is proven in code.
2. Keep Supabase reads projected to the exact fields consumed by the pricing UI.
3. Commit derived billing state once per auth refresh.
4. Preserve the empty billing context fallback for signed-out and failed-read states.
### Layout Synchronization (CSS Variables)
For decoupled components that affect global layout (e.g., the Impersonation Banner), the application uses reactive CSS variables to ensure zero-jitter transitions.
1. **Variable**: `--topbar-height` (defaults to `0px`).
2. **Management**: Handled via `useLayoutEffect` in the banner component to update the DOM _before_ the paint cycle.
3. **Consumption**: Components like `AppSidebar` and `AdminPageShell` use `var(--topbar-height, 0px)` for their top offset.
4. **SSR Safety**: The banner injects a `