# Flowfull - Complete Technical Context **Full developer context for LLMs and AI assistants** This document provides comprehensive technical information about Flowfull, the Pubflow architecture, and all implementation details. --- ## Table of Contents 1. [Overview](#overview) 2. [Pubflow Architecture](#pubflow-architecture) 3. [7 Core Concepts](#7-core-concepts) 4. [Official Starter Kits](#official-starter-kits) 5. [Technology Stack](#technology-stack) 6. [Environment Configuration](#environment-configuration) 7. [API Reference](#api-reference) 8. [Database Schema](#database-schema) 9. [Code Examples](#code-examples) 10. [Deployment](#deployment) 11. [Best Practices](#best-practices) 12. [Community](#community) --- ## Overview **Flowfull** is a backend framework for building production-ready APIs with: - Distributed authentication via Bridge Validation - 3-tier caching system (HybridCache) - PASETO-based Trust Tokens - Multi-database support - Type-safe environment configuration **Key Features:** - ✅ Stateless and horizontally scalable - ✅ Production-ready with battle-tested patterns - ✅ TypeScript-first with full type safety - ✅ Zero-trust security architecture - ✅ 95%+ cache hit rates - ✅ <5ms p50 latency --- ## Pubflow Architecture Pubflow consists of 3 layers: ### 1. Flowless (Core Authentication Backend) **Hosted ONLY at pubflow.com** (NOT self-hostable) **Responsibilities:** - User authentication (email/password, OAuth, magic links) - Session management - User data storage - Bridge Validation API **Key Point:** Flowless is a managed service. You create an instance at pubflow.com and connect your Flowfull backend to it. ### 2. Flowfull (Custom Backend) **Your backend** (this framework) **Responsibilities:** - Business logic and custom APIs - Database and cache management - Trust Tokens (email verification, password reset) - Resource authorization **Key Point:** Flowfull is stateless and can be horizontally scaled behind Pubflow Load Balancer. ### 3. Flowfull-Client (Frontend) **Your frontend** (React, Next.js, React Native, etc.) **Responsibilities:** - User interface - API calls to Flowfull - Session management (stores session_id) **Key Point:** Client authenticates with Flowless, receives session_id, then uses it to call Flowfull APIs. --- ## 7 Core Concepts These concepts are portable across all language implementations. ### 1. Bridge Validation **Distributed authentication** that validates sessions from Flowless to Flowfull. **How it works:** 1. Client sends request with `X-Session-Id` header 2. Flowfull checks cache (LRU or Redis) for session 3. If not cached, validates with Flowless API 4. Caches result for future requests 5. Returns user data to route handler **Implementation:** ```typescript import { BridgeValidator } from './lib/auth/bridge-validator'; const validator = new BridgeValidator({ flowlessApiUrl: process.env.FLOWLESS_URL, validationSecret: process.env.BRIDGE_SECRET, timeout: 5000, retryAttempts: 3 }); const result = await validator.validateSession(sessionId); if (result.success) { console.log('User:', result.session.user_id); } ``` **Environment Variables:** ```env FLOWLESS_URL=https://your-instance.pubflow.com BRIDGE_SECRET=your-bridge-secret SESSION_VALIDATION_CACHE_TTL=300 ``` ### 2. Validation Modes **4 security levels** for session validation: | Mode | IP Check | User-Agent | Device ID | Use Case | |------|----------|------------|-----------|----------| | DISABLED | ❌ | ❌ | ❌ | Development only | | STANDARD | ✅ | ❌ | ❌ | Basic security | | ADVANCED | ✅ | ✅ | ❌ | Recommended | | STRICT | ✅ | ✅ | ✅ | Maximum security | **Environment Variable:** ```env VALIDATION_MODE=ADVANCED ``` ### 3. HybridCache **3-tier caching system** with automatic fallback: **Tiers:** 1. **LRU (In-Memory)** - <1ms, local to instance 2. **Redis (Distributed)** - 2-5ms, shared across instances 3. **Database** - 10-50ms, source of truth **Implementation:** ```typescript import { HybridCache } from './lib/cache/hybrid-cache'; const userCache = new HybridCache({ cacheType: 'userContext', ttl: 300, // 5 minutes maxSize: 10000, // 10k items in LRU keyPrefix: 'user' }); // Get from cache (LRU → Redis → Database) const user = await userCache.get(userId); // Set in cache await userCache.set(userId, userData); // Invalidate cache await userCache.delete(userId); ``` **Environment Variables:** ```env CACHE_ENABLED=true REDIS_URL=redis://localhost:6379 ``` ### 4. Trust Tokens (PASETO) **Secure, single-use tokens** for: - Email verification - Password reset - Invitations - API tokens **Implementation:** ```typescript import { V4 } from 'paseto'; // Generate token const token = await V4.sign({ userId, email, type: 'email_verification', exp: new Date(Date.now() + 86400000).toISOString() }, process.env.PASETO_PRIVATE_KEY); // Verify token const payload = await V4.verify(token, process.env.PASETO_PUBLIC_KEY); ``` **Environment Variables:** ```env PASETO_PRIVATE_KEY=k4.secret.xxx PASETO_PUBLIC_KEY=k4.public.xxx EMAIL_VERIFICATION_TTL=86400 PASSWORD_RESET_TTL=3600 ``` ### 5. Auth Middleware **Route protection patterns** for Hono framework: **Functions:** - `requireAuth()` - Require authenticated user (throws 401) - `optionalAuth()` - Optional authentication (allows guests) - `requireUserType(types)` - Require specific user type (throws 403) - `requirePermission(perm)` - Require specific permission (throws 403) **Implementation:** ```typescript import { Hono } from 'hono'; import { requireAuth, optionalAuth, requireUserType } from './lib/auth/middleware'; const app = new Hono(); // Protected route app.get('/api/profile', requireAuth(), async (c) => { const userId = c.get('user_id'); return c.json({ userId }); }); // Optional auth app.get('/api/posts', optionalAuth(), async (c) => { const userId = c.get('user_id'); // undefined if guest const isGuest = c.get('is_guest'); return c.json({ posts: await getPosts(userId, isGuest) }); }); // Admin only app.get('/api/admin/users', requireUserType('admin'), async (c) => { return c.json({ users: await getAllUsers() }); }); ``` ### 6. Multi-Database Support **Kysely ORM** supporting multiple databases: **Supported Databases:** - PostgreSQL - MySQL - LibSQL / Turso - Neon (Serverless Postgres) - PlanetScale (Serverless MySQL) **Implementation:** ```typescript import { Kysely, PostgresDialect } from 'kysely'; import { Pool } from 'pg'; const db = new Kysely({ dialect: new PostgresDialect({ pool: new Pool({ connectionString: process.env.DATABASE_URL }) }) }); // Type-safe queries const users = await db.selectFrom('users') .selectAll() .where('email', '=', 'user@example.com') .execute(); ``` **Environment Variables:** ```env DATABASE_TYPE=postgresql DATABASE_URL=postgresql://user:password@localhost:5432/mydb ``` ### 7. Environment Configuration **Zod-validated** environment variables with fail-fast validation: **Implementation:** ```typescript import { z } from 'zod'; const envSchema = z.object({ // Flowless FLOWLESS_URL: z.string().url(), BRIDGE_SECRET: z.string().min(32), // Database DATABASE_TYPE: z.enum(['postgresql', 'mysql', 'libsql']), DATABASE_URL: z.string().url(), // Server PORT: z.coerce.number().default(3000), NODE_ENV: z.enum(['development', 'production', 'test']).default('development'), // Security VALIDATION_MODE: z.enum(['DISABLED', 'STANDARD', 'ADVANCED', 'STRICT']).default('STANDARD'), // Cache CACHE_ENABLED: z.coerce.boolean().default(true), REDIS_URL: z.string().url().optional(), }); export const config = envSchema.parse(process.env); ``` --- ## Official Starter Kits ### flowfull-node (Node.js/TypeScript) **Status:** ✅ Official, Production-Ready **Repository:** https://github.com/pubflow/flowfull-node **Features:** - TypeScript-first with full type safety - Bun runtime (Node.js 18+ also supported) - Hono web framework - Kysely ORM - All 7 core concepts implemented - Production-ready patterns **Quick Start:** ```bash git clone https://github.com/pubflow/flowfull-node.git my-backend cd my-backend bun install cp .env.example .env # Edit .env with your configuration bun run migrate bun run dev ``` ### Official SDKs and Libraries - **flowfull-go** - Go SDK/client used from Go projects and the Go starter: https://github.com/pubflow/flowfull-go - **flowfull-python** - Python SDK/client: https://github.com/pubflow/flowfull-python - **flowfull-rust** - Rust SDK crate published as `flowfull`: https://github.com/pubflow/flowfull-rust - **flowfull-elixir** - Elixir package: https://github.com/pubflow/flowfull-elixir ### Official Backend Starters - **flowfull-node** - Node.js/TypeScript reference stack: https://github.com/pubflow/flowfull-node - **flowfull-go-starter** - Go backend starter: https://github.com/pubflow/flowfull-go-starter - **flowfull-python-starter** - Python backend starter: https://github.com/pubflow/flowfull-python-starter - **flowfull-rust-starter** - Rust backend starter: https://github.com/pubflow/flowfull-rust-starter - **flowfull-elixir-starter** - Elixir backend starter: https://github.com/pubflow/flowfull-elixir-starter ### Official Frontend Starters - **next-flowfull-client** - Next.js frontend starter: https://github.com/pubflow/next-flowfull-client - **react-flowfull-client** - React frontend starter with TanStack Start: https://github.com/pubflow/react-flowfull-client --- ## Technology Stack ### flowfull-node Stack | Technology | Purpose | Version | |------------|---------|---------| | **Bun** | Runtime | 1.0+ | | **TypeScript** | Language | 5.0+ | | **Hono** | Web Framework | 4.0+ | | **Kysely** | ORM | 0.27+ | | **Zod** | Validation | 3.22+ | | **PASETO** | Trust Tokens | 3.1+ | | **Redis** | Cache | 7.0+ | | **LRU Cache** | In-Memory Cache | 10.0+ | --- ## Environment Configuration ### Complete .env Example ```env # ============================================ # Flowless Configuration # ============================================ FLOWLESS_URL=https://your-instance.pubflow.com BRIDGE_SECRET=your-bridge-secret-min-32-chars # ============================================ # Database Configuration # ============================================ DATABASE_TYPE=postgresql DATABASE_URL=postgresql://user:password@localhost:5432/mydb # ============================================ # Server Configuration # ============================================ PORT=3000 NODE_ENV=development # ============================================ # Security Configuration # ============================================ VALIDATION_MODE=ADVANCED SESSION_VALIDATION_CACHE_TTL=300 # ============================================ # Cache Configuration # ============================================ CACHE_ENABLED=true REDIS_URL=redis://localhost:6379 REDIS_PASSWORD=your-redis-password # ============================================ # Trust Tokens (PASETO) # ============================================ PASETO_PRIVATE_KEY=k4.secret.your-private-key PASETO_PUBLIC_KEY=k4.public.your-public-key EMAIL_VERIFICATION_TTL=86400 PASSWORD_RESET_TTL=3600 INVITATION_TTL=604800 # ============================================ # Email Configuration # ============================================ EMAIL_PROVIDER=zeptomail ZEPTOMAIL_API_KEY=your-api-key ZEPTOMAIL_FROM_EMAIL=noreply@yourdomain.com ZEPTOMAIL_FROM_NAME=Your App Name # ============================================ # Application URLs # ============================================ FRONTEND_URL=https://yourdomain.com BACKEND_URL=https://api.yourdomain.com ``` --- ## API Reference ### BridgeValidator Class **Constructor:** ```typescript new BridgeValidator(config?: { flowlessApiUrl?: string; validationSecret?: string; timeout?: number; retryAttempts?: number; }) ``` **Methods:** **validateSession(sessionId: string): Promise** - Validates session with Flowless - Returns: `{ success, session?, error?, cached? }` - Caches valid sessions automatically **healthCheck(): Promise** - Checks Flowless connection health - Returns: `{ success, latency?, error? }` ### HybridCache Class **Constructor:** ```typescript new HybridCache(config: { cacheType: string; ttl: number; maxSize: number; keyPrefix: string; }) ``` **Methods:** **get(key: string): Promise** - Get from cache (Redis → LRU → null) **set(key: string, value: T, customTtl?: number): Promise** - Set in cache (both Redis and LRU) **delete(key: string): Promise** - Delete from cache (both Redis and LRU) **deletePattern(pattern: string): Promise** - Delete keys matching regex pattern **clear(): Promise** - Clear all cache **getMetrics(): CacheMetrics** - Get performance metrics ### Auth Middleware **requireAuth(): MiddlewareHandler** - Requires authenticated user - Throws 401 if not authenticated - Sets: `user_id`, `session`, `is_guest` **optionalAuth(): MiddlewareHandler** - Optional authentication - Allows guest access - Sets: `user_id?`, `session?`, `is_guest` **requireUserType(types: string | string[]): MiddlewareHandler** - Requires specific user type(s) - Throws 403 if type doesn't match **requirePermission(permission: string): MiddlewareHandler** - Requires specific permission - Throws 403 if permission not granted --- ## Database Schema ### Core Tables **users** (managed by Flowless, cached in Flowfull) ```sql CREATE TABLE users ( id VARCHAR(255) PRIMARY KEY, email VARCHAR(255) UNIQUE NOT NULL, name VARCHAR(255) NOT NULL, email_verified BOOLEAN DEFAULT FALSE, email_verified_at TIMESTAMP, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL ); ``` **trust_tokens** (managed by Flowfull) ```sql CREATE TABLE trust_tokens ( id VARCHAR(255) PRIMARY KEY, user_id VARCHAR(255) NOT NULL, type VARCHAR(50) NOT NULL, -- email_verification, password_reset, invitation status VARCHAR(50) NOT NULL, -- pending, used, expired expires_at TIMESTAMP NOT NULL, used_at TIMESTAMP, created_at TIMESTAMP NOT NULL, INDEX idx_user_id (user_id), INDEX idx_type_status (type, status) ); ``` **sessions** (managed by Flowless, validated by Flowfull) ```sql CREATE TABLE sessions ( id VARCHAR(255) PRIMARY KEY, user_id VARCHAR(255) NOT NULL, ip_address VARCHAR(45), user_agent TEXT, device_id VARCHAR(255), expires_at TIMESTAMP NOT NULL, created_at TIMESTAMP NOT NULL, last_used_at TIMESTAMP NOT NULL ); ``` --- ## Code Examples ### Complete Protected Route Example ```typescript // src/routes/users/profile.ts import { Hono } from 'hono'; import { requireAuth } from '../../lib/auth/middleware'; import { hybridCache } from '../../lib/cache/hybrid-cache'; import { db } from '../../lib/database'; const app = new Hono(); app.get('/profile', requireAuth(), async (c) => { const userId = c.get('user_id'); // Get from cache (LRU → Redis → Database) const user = await hybridCache.get('user', userId, async () => { return await db.selectFrom('users') .where('id', '=', userId) .selectAll() .executeTakeFirst(); }); if (!user) { return c.json({ error: 'User not found' }, 404); } return c.json({ user }); }); app.put('/profile', requireAuth(), async (c) => { const userId = c.get('user_id'); const data = await c.req.json(); // Update database await db.updateTable('users') .set({ name: data.name, updated_at: new Date().toISOString() }) .where('id', '=', userId) .execute(); // Invalidate cache await hybridCache.delete('user', userId); return c.json({ success: true }); }); export default app; ``` ### Email Verification Flow ```typescript // Generate verification token import { V4 } from 'paseto'; import { redis } from './lib/cache/redis'; import { db } from './lib/database'; async function generateEmailVerificationToken(userId: string, email: string) { const payload = { userId, email, type: 'email_verification', exp: new Date(Date.now() + 86400000).toISOString() // 24 hours }; const token = await V4.sign(payload, process.env.PASETO_PRIVATE_KEY); // Store in Redis for tracking await redis.set(`email_verify:${userId}`, JSON.stringify({ status: 'pending', email, createdAt: new Date().toISOString() }), 'EX', 86400); // Store in database for audit await db.insertInto('trust_tokens') .values({ id: `token_${Date.now()}`, user_id: userId, type: 'email_verification', status: 'pending', expires_at: new Date(Date.now() + 86400000).toISOString(), created_at: new Date().toISOString() }) .execute(); return token; } // Verify token app.post('/verify-email', async (c) => { const { token } = await c.req.json(); try { // Verify PASETO signature const payload = await V4.verify(token, process.env.PASETO_PUBLIC_KEY); // Check expiration if (new Date(payload.exp) < new Date()) { return c.json({ error: 'Token expired' }, 400); } // Check Redis status const status = await redis.get(`email_verify:${payload.userId}`); if (!status) { return c.json({ error: 'Token already used or invalid' }, 400); } // Update user await db.updateTable('users') .set({ email_verified: true, email_verified_at: new Date().toISOString() }) .where('id', '=', payload.userId) .execute(); // Mark token as used await db.updateTable('trust_tokens') .set({ status: 'used', used_at: new Date().toISOString() }) .where('user_id', '=', payload.userId) .where('type', '=', 'email_verification') .execute(); // Invalidate token await redis.del(`email_verify:${payload.userId}`); return c.json({ success: true }); } catch (error) { return c.json({ error: 'Invalid token' }, 400); } }); ``` --- ## Deployment ### Railway **1. Install Railway CLI:** ```bash npm install -g @railway/cli railway login ``` **2. Create project:** ```bash railway init railway link ``` **3. Add PostgreSQL:** ```bash railway add postgresql ``` **4. Set environment variables:** ```bash railway variables set FLOWLESS_URL=https://your-instance.pubflow.com railway variables set BRIDGE_SECRET=your-bridge-secret railway variables set VALIDATION_MODE=ADVANCED ``` **5. Deploy:** ```bash railway up ``` ### Fly.io **1. Install Fly CLI:** ```bash curl -L https://fly.io/install.sh | sh fly auth login ``` **2. Create app:** ```bash fly launch ``` **3. Set secrets:** ```bash fly secrets set FLOWLESS_URL=https://your-instance.pubflow.com fly secrets set BRIDGE_SECRET=your-bridge-secret fly secrets set DATABASE_URL=postgresql://... ``` **4. Deploy:** ```bash fly deploy ``` ### Docker **Dockerfile:** ```dockerfile FROM oven/bun:1 AS base WORKDIR /app # Install dependencies COPY package.json bun.lockb ./ RUN bun install --frozen-lockfile # Copy source COPY . . # Build (if needed) RUN bun run build # Expose port EXPOSE 3000 # Start server CMD ["bun", "run", "start"] ``` **docker-compose.yml:** ```yaml version: '3.8' services: app: build: . ports: - "3000:3000" environment: - FLOWLESS_URL=${FLOWLESS_URL} - BRIDGE_SECRET=${BRIDGE_SECRET} - DATABASE_URL=${DATABASE_URL} - REDIS_URL=redis://redis:6379 depends_on: - postgres - redis postgres: image: postgres:16 environment: POSTGRES_DB: mydb POSTGRES_USER: user POSTGRES_PASSWORD: password volumes: - postgres_data:/var/lib/postgresql/data redis: image: redis:7-alpine volumes: - redis_data:/data volumes: postgres_data: redis_data: ``` **Deploy:** ```bash docker-compose up -d ``` ### Vercel (Serverless) **vercel.json:** ```json { "version": 2, "builds": [ { "src": "src/index.ts", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "src/index.ts" } ], "env": { "FLOWLESS_URL": "@flowless-url", "BRIDGE_SECRET": "@bridge-secret", "DATABASE_URL": "@database-url" } } ``` **Deploy:** ```bash vercel --prod ``` --- ## Best Practices ### Security 1. ✅ **Use VALIDATION_MODE=STRICT in production** - Validates IP, User-Agent, and Device ID - Prevents session hijacking 2. ✅ **Rotate BRIDGE_SECRET regularly** - Update in both Flowless and Flowfull - Use strong, random secrets (min 32 chars) 3. ✅ **Use HTTPS everywhere** - Flowless requires HTTPS - Use SSL/TLS for database connections 4. ✅ **Validate all inputs** - Use Zod for request validation - Sanitize user inputs 5. ✅ **Rate limit sensitive endpoints** - Login, password reset, email verification - Use Redis for distributed rate limiting ### Performance 1. ✅ **Enable caching** - Use HybridCache for frequently accessed data - Set appropriate TTLs (balance freshness vs performance) 2. ✅ **Use Redis in production** - Shared cache across instances - Persistent cache across restarts 3. ✅ **Optimize database queries** - Add indexes for frequently queried columns - Use connection pooling 4. ✅ **Monitor cache hit rates** - Target 80%+ hit rate - Adjust TTLs and cache sizes 5. ✅ **Use CDN for static assets** - Reduce server load - Improve global latency ### Scalability 1. ✅ **Keep Flowfull stateless** - No local state (use Redis/Database) - Enables horizontal scaling 2. ✅ **Use Pubflow Load Balancer** - Automatic load balancing - Health checks and failover 3. ✅ **Separate read/write databases** - Read replicas for queries - Primary for writes 4. ✅ **Use background jobs** - Email sending, data processing - Use queues (BullMQ, Celery, etc.) 5. ✅ **Monitor and alert** - Track latency, error rates, cache hit rates - Set up alerts for anomalies ### Development 1. ✅ **Use TypeScript** - Full type safety - Better IDE support 2. ✅ **Write tests** - Unit tests for business logic - Integration tests for APIs 3. ✅ **Use environment validation** - Fail-fast on missing/invalid config - Use Zod schemas 4. ✅ **Log appropriately** - Use structured logging - Log errors, not sensitive data 5. ✅ **Version your APIs** - Use `/v1/`, `/v2/` prefixes - Maintain backward compatibility --- ## Community ### Support **Community Support (Free):** - Discord: [discord.gg/pubflow](https://discord.gg/pubflow) - Email: support@pubflow.com - GitHub Issues: [github.com/pubflow/flowfull-node](https://github.com/pubflow/flowfull-node) **Professional Support (Paid):** - **Notside.com** - Technology firm specializing in Pubflow - Services: Custom backend development, consulting, enterprise support - Contact: contact@notside.com - Website: [notside.com](https://notside.com) ### Contributing **Official Starter Kits:** Pubflow maintains official backend starters for Node.js, Go, Python, Rust, and Elixir, plus frontend starters for Next.js and React with TanStack Start. **Need another language or framework?** 1. Start from the closest official starter 2. Implement the same 7 core concepts 3. Follow naming convention (`flowfull-{language}-starter`) 4. Add comprehensive documentation 5. Include examples and tests 6. Request an integration or submit a community showcase entry **Recommended structure:** ``` flowfull-{language}-starter/ |-- src/ | |-- lib/ | | |-- auth/ | | | |-- bridge-validator.{ext} | | | +-- middleware.{ext} | | |-- cache/ | | | +-- hybrid-cache.{ext} | | +-- tokens/ | | +-- trust-tokens.{ext} | +-- routes/ |-- tests/ |-- docs/ |-- .env.example +-- README.md ``` ### Links - **Pubflow Website**: [pubflow.com](https://pubflow.com) - **Documentation**: [docs.pubflow.com](https://docs.pubflow.com) - **Official SDKs/Libraries**: - Go: [github.com/pubflow/flowfull-go](https://github.com/pubflow/flowfull-go) - Python: [github.com/pubflow/flowfull-python](https://github.com/pubflow/flowfull-python) - Rust: [github.com/pubflow/flowfull-rust](https://github.com/pubflow/flowfull-rust) - Elixir: [github.com/pubflow/flowfull-elixir](https://github.com/pubflow/flowfull-elixir) - **Official Backend Starters**: - Node.js: [github.com/pubflow/flowfull-node](https://github.com/pubflow/flowfull-node) - Go: [github.com/pubflow/flowfull-go-starter](https://github.com/pubflow/flowfull-go-starter) - Python: [github.com/pubflow/flowfull-python-starter](https://github.com/pubflow/flowfull-python-starter) - Rust: [github.com/pubflow/flowfull-rust-starter](https://github.com/pubflow/flowfull-rust-starter) - Elixir: [github.com/pubflow/flowfull-elixir-starter](https://github.com/pubflow/flowfull-elixir-starter) - **Official Frontend Starters**: - Next.js: [github.com/pubflow/next-flowfull-client](https://github.com/pubflow/next-flowfull-client) - TanStack Start (React): [github.com/pubflow/react-flowfull-client](https://github.com/pubflow/react-flowfull-client) - **Community Discord**: [discord.gg/pubflow](https://discord.gg/pubflow) - **Professional Support**: [notside.com](https://notside.com) --- **Last Updated:** 2025-12-06 **Version:** 1.0.0 **License:** MIT (for flowfull-node starter kit)