Files
CatoandClaude Opus 5.5 05d1b2da83 feat(auth): every way in, on @bitbaum/accountkit, keeping every account (#342)
* feat(auth): every way in, on @bitbaum/accountkit, keeping every account

Sign-in offered email and password and Continue with OrangeCat, on
next-auth. It now runs on AccountKit's runtime and screens: email and
password, the emailed sign-in link, passkeys, two-step codes, recovery,
OrangeCat and the shared sign-in (Google, Apple, GitHub, X, Facebook), each
shown once configured. /account holds passkeys, two-step codes, the
password, sign-in methods and deletion. next-auth, the hand-rolled
OrangeCat resolver and the unused /api/v1/auth/{login,register} are gone.

Every account is kept. The Prisma migration 20261101120000 adds
AccountKit's tables (auth_ prefix, modelled in schema.prisma so Prisma
never proposes dropping them) and imports each person under the same id:
the bcrypt / $bs1$ hash (legacyBcrypt) and the OrangeCat link keyed on the
sub, with AccountKit's own placeholder for a person without an address.
A trigger mirrors anyone the old server creates during the cutover. It is
re-runnable and refuses addresses that collide once lower-cased.

/api/v1/* takes the session cookie or the API token /api/account mints in
the format the Express backend verifies. The session key is
BETTER_AUTH_SECRET, or derived from the secret the box already holds.

CI: a new browser-smoke job rehearses the import twice (counts, no Prisma
drift) and drives Chromium through an imported account signing in with
its old password, sign-up, sign-out, a refused wrong password, sign-in,
recovery through the reset link, both API auth paths and every way in at
320, 390 and 1280px.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* test(browser): give the first article visit on next dev a compile-sized wait

The shared-article suite runs on next dev, which compiles a route on its
first visit. The account route (better-auth, pg) now compiles beside the
article for the header, so the first click can outlast the default 5s.
A production server answers at once; the account journey checks that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

* ci: re-run checks on the latest head

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmuJhiHPASaR5k8raL9

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 23:21:15 +01:00

7.1 KiB

Formular Backend Architecture

Overview

This document outlines the production-ready backend architecture for Formular, featuring form sharing, user management, and LLM-powered response analysis.

Tech Stack

Core Technologies

  • Node.js - Runtime environment
  • Express.js - Web application framework
  • Prisma - Database ORM with full TypeScript support
  • PostgreSQL - Primary database
  • tRPC - End-to-end type-safe API layer
  • Zod - Runtime type validation
  • Redis - Background job queues and caching
  • Bull - Robust job queue system

Authentication & Security

  • JWT - Stateless authentication
  • bcryptjs - Password hashing
  • CORS - Cross-origin resource sharing
  • Express rate limiting - API protection

AI/LLM Integration

  • OpenAI GPT-4 - Primary LLM for analysis
  • Custom Analysis Pipeline - Extensible analysis framework

Database Schema

Core Models

User Management

  • User - Core user entity with roles and organizations
  • Organization - Multi-tenant organization support
  • Account/Session - NextAuth-era tables, kept; sign-in now runs on @bitbaum/accountkit (auth_* tables, frontend)

Form System

  • Form - Dynamic form definitions with versioning
  • ShareSettings - Form sharing configuration
  • SharedLink - Public/private form sharing links
  • FormCollaborator - Team collaboration on forms
  • FormVersion - Form schema versioning and history

Data Collection

  • Submission - Form response data with metadata
  • LLMAnalysis - AI analysis results and insights
  • BackgroundJob - Async job processing tracking

API Architecture

tRPC Routers

User Router (/api/trpc/users)

  • User registration and authentication
  • Profile management
  • Admin user management

Forms Router (/api/trpc/forms)

  • Form CRUD operations
  • Form sharing and collaboration
  • Template management
  • Public form access via shared links

Submissions Router (/api/trpc/submissions)

  • Submission collection and management
  • Data export (JSON/CSV)
  • Submission statistics

LLM Analysis Router (/api/trpc/llmAnalysis)

  • AI-powered response analysis
  • Bulk analysis operations
  • Analysis insights and reporting
  • Queue management

REST API (Legacy Support)

  • Backward compatible REST endpoints at /api/v1/
  • Automatic redirects for deprecated endpoints

Form Sharing System

Access Control Levels

  • Private - Owner and collaborators only
  • Restricted - Specific users or domains
  • Public - Anyone with the link

Sharing Features

  • Unique shareable links with custom slugs
  • Expiration dates and submission limits
  • Password protection
  • Domain restrictions
  • Anonymous submissions support

Collaboration Features

  • Multi-user form editing
  • Role-based permissions (Viewer, Editor, Admin)
  • Real-time collaboration tracking

LLM Analysis System

Analysis Types

  1. Sentiment Analysis - Emotional tone and satisfaction
  2. Classification - Automatic categorization
  3. Key Information Extraction - Important data points
  4. Summary Generation - Concise response summaries
  5. Custom Analysis - User-defined analysis prompts

Background Processing

  • Asynchronous analysis using Bull queues
  • Retry mechanisms for failed analyses
  • Progress tracking and status updates
  • Cost estimation and monitoring

Analysis Pipeline

Submission Created → Queue Analysis Job → LLM Processing → Results Stored → Insights Generated

Background Job System

Job Types

  • LLM Analysis - AI-powered response analysis
  • Email Notifications - User alerts and updates
  • Data Export - CSV/JSON export generation
  • Form Backup - Automated form backups

Queue Management

  • Priority-based job processing
  • Automatic retry with exponential backoff
  • Job monitoring and statistics
  • Queue health monitoring

Security Features

Authentication

  • JWT-based stateless authentication
  • Secure password hashing with bcrypt
  • Role-based access control (RBAC)
  • Session management

Data Protection

  • Input validation with Zod schemas
  • SQL injection prevention via Prisma
  • XSS protection
  • CORS configuration
  • Rate limiting

Privacy

  • Anonymous submission support
  • Data encryption at rest
  • Audit logging
  • GDPR-compliant data handling

Performance Optimizations

Database

  • Optimized Prisma queries with proper includes
  • Database indexes on frequently queried fields
  • Connection pooling
  • Query result caching

API

  • Efficient pagination
  • Field selection optimization
  • Response compression
  • Request deduplication

Background Processing

  • Distributed job processing
  • Queue prioritization
  • Resource-aware job scheduling
  • Automatic scaling capabilities

Deployment Architecture

Environment Configuration

  • Development, staging, and production environments
  • Environment-specific configurations
  • Secret management
  • Feature flags

Scaling Strategy

  • Horizontal scaling support
  • Stateless application design
  • Database connection pooling
  • Redis cluster support

Monitoring

  • Application performance monitoring
  • Queue health monitoring
  • Error tracking and alerting
  • Usage analytics

Development Workflow

Setup Commands

# Install dependencies
pnpm install

# Set up database
pnpm run migrate

# Generate Prisma client
pnpm run generate

# Start development server with workers
pnpm run dev

# Run server only
pnpm start

# Run workers only  
pnpm run workers

Environment Variables

See .env.example for all required environment variables including:

  • Database connection
  • JWT secrets
  • OpenAI API keys
  • Redis configuration
  • Email service settings

API Usage Examples

Form Creation

const form = await trpc.forms.create.mutate({
  title: "Employee Onboarding",
  description: "New hire information collection",
  schema: {
    fields: [
      { id: "name", type: "text", label: "Full Name", required: true },
      { id: "email", type: "email", label: "Email", required: true }
    ]
  }
});

Form Sharing

const sharedLink = await trpc.forms.createSharedLink.mutate({
  formId: "form-id",
  settings: {
    accessType: "PUBLIC",
    expiresAt: new Date("2024-12-31"),
    maxSubmissions: 100
  }
});

Submission Analysis

const analysis = await trpc.llmAnalysis.analyzeSubmission.mutate({
  submissionId: "submission-id",
  analysisTypes: ["SENTIMENT", "CLASSIFICATION"]
});

Future Enhancements

Planned Features

  • Real-time collaboration via WebSockets
  • Advanced analytics dashboard
  • Custom analysis model integration
  • Multi-language support
  • Enhanced export formats

Scalability Improvements

  • Microservices architecture
  • GraphQL federation
  • Advanced caching strategies
  • Container orchestration

Support and Documentation

  • API documentation available via tRPC introspection
  • Development setup guide in README.md
  • Troubleshooting guide for common issues
  • Performance tuning recommendations

This architecture provides a solid foundation for a scalable, secure, and feature-rich form management system with advanced AI capabilities.