Skip to content

Security: 4cecoder/bytestack

Security

SECURITY.md

Security & Architecture Guide

πŸ” Security Overview

Authentication Security

BetterAuth Implementation:

  • βœ… Password Hashing: BetterAuth uses bcrypt for password hashing with salt rounds
  • βœ… Session Management: 7-day expiration with 1-day update cycle (prevents token staleness)
  • βœ… Email Verification: Required before account activation
  • βœ… OAuth 2.0: Google and GitHub OAuth with proper PKCE flow
  • βœ… CSRF Protection: Built into Next.js 15 and BetterAuth
  • βœ… HTTP-only Cookies: Sessions stored in HTTP-only cookies (not accessible to JavaScript)

Database Security

Turso/LibSQL Security:

  • βœ… End-to-End Encrypted: Transport security with TLS 1.3
  • βœ… Authentication Tokens: Per-database tokens with granular permissions
  • βœ… Row-Level Security: Can be implemented via application layer
  • βœ… Encrypted at Rest: Turso provides encryption for all stored data
  • βœ… Edge Distribution: Global replication with regional encryption

ConvexDB Security:

  • βœ… Automatic Authentication: Built-in user context in queries
  • βœ… Permission System: Server functions validate user permissions
  • βœ… Real-time Security: Subscriptions respect user permissions
  • βœ… API Keys: Secure API key generation for service-to-service auth

Infrastructure Security

Next.js 15 Security Headers (configured in next.config.ts):

X-Frame-Options: DENY                 # Prevent clickjacking
X-Content-Type-Options: nosniff       # Prevent MIME sniffing
Referrer-Policy: origin-when-cross-origin  # Control referrer

Deployment (Vercel):

  • βœ… DDoS Protection: Vercel's global network includes DDoS mitigation
  • βœ… SSL/TLS: Automatic HTTPS for all deployments
  • βœ… WAF: Web Application Firewall protection
  • βœ… Rate Limiting: Built-in rate limiting on API routes
  • βœ… Environment Variables: Encrypted secrets management

API Security

BetterAuth API Routes (/api/auth/[...all]):

  • βœ… Rate Limiting: Configure in production
  • βœ… Input Validation: Zod schema validation
  • βœ… CORS: Properly configured for your domain
  • βœ… Method Validation: POST/GET validation per endpoint

Data Validation

Drizzle ORM:

  • βœ… Type-Safe Queries: TypeScript prevents SQL injection
  • βœ… Parameterized Queries: All queries use prepared statements
  • βœ… Schema Validation: Zod integration for runtime validation

Zod Schemas (setup ready):

// Example for additional validation
import { z } from "zod";

export const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(100),
  password: z.string().min(8),
});

⚠️ Security Recommendations

Before Production

  1. Generate Strong Secrets

    openssl rand -base64 32  # BETTER_AUTH_SECRET
  2. Enable Email Verification

    • Currently enabled in auth.ts
    • Configure SMTP for production
  3. Rate Limiting

    // Add to API routes
    import { Ratelimit } from "@upstash/ratelimit";
  4. API Key Security

    • Hash API keys before storage
    • Rotate keys regularly
    • Monitor key usage
  5. Audit Logging

    • All admin actions logged to adminAuditLogs
    • Review logs regularly
    • Archive old logs
  6. Environment Variables

    • Never commit .env.local
    • Use Vercel's environment variable management
    • Rotate secrets quarterly
  7. CORS Configuration Update next.config.ts:

    async headers() {
      return [{
        source: '/api/(.*)',
        headers: [
          { key: 'Access-Control-Allow-Origin', value: process.env.ALLOWED_ORIGIN },
          { key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE' },
        ],
      }];
    }

πŸ“‹ PayloadCMS Integration

Why PayloadCMS Works Well With This Setup

βœ… Headless CMS: Provides content API without coupled frontend βœ… Type-Safe: Full TypeScript support matches your backend βœ… Database Agnostic: Works with Turso/SQLite without issues βœ… Access Control: Built-in role-based access control βœ… REST & GraphQL: Multiple API options βœ… Webhook Support: Integrates with ConvexDB for sync

PayloadCMS Authentication Integration

Option 1: Unified Authentication (Recommended)

// In payload.config.ts
import { auth } from "@/lib/auth";

export default buildConfig({
  // ...
  middleware: [
    async (req, res, next) => {
      // Check BetterAuth session
      const session = await auth.api.getSession({
        headers: req.headers,
      });

      if (session?.user?.isSuperAdmin) {
        // Allow admin access to PayloadCMS
        req.user = session.user;
      }
      next();
    },
  ],
});

Option 2: Separate PayloadCMS Auth

// PayloadCMS has its own built-in authentication
// Use email/password credentials separate from main app
// Can sync users between systems

PayloadCMS Security with Turso

  1. Create Separate Database for PayloadCMS

    turso db create bytestack-cms
    turso db tokens create bytestack-cms
  2. Environment Variables

    PAYLOAD_TURSO_URL=libsql://your-cms-db.turso.io
    PAYLOAD_TURSO_TOKEN=your_cms_token
    PAYLOAD_SECRET=your_payload_secret  # For encryption
  3. Access Control in PayloadCMS

    // In collections/Posts.ts
    access: {
      read: ({ req }) => {
        if (req.user?.role === 'admin') return true;
        return { author: { equals: req.user?.id } };
      },
      update: ({ req }) => req.user?.role === 'admin',
      delete: ({ req }) => req.user?.role === 'superadmin',
    }

Data Synchronization

ConvexDB β†’ Turso Sync (via DataSyncService):

1. User creates content in app
2. ConvexDB updates real-time
3. Sync service periodically syncs to Turso
4. PayloadCMS reads from Turso

PayloadCMS β†’ ConvexDB Sync (webhook):

1. Admin updates content in PayloadCMS
2. Webhook notifies app
3. App updates ConvexDB
4. Real-time updates propagate

Implementation Example

// src/lib/payload-integration.ts
import payload from "payload";

export async function syncContentToConvex() {
  // Get all posts from PayloadCMS
  const posts = await payload.find({
    collection: "posts",
  });

  // Update ConvexDB via mutation
  for (const post of posts.docs) {
    // Your ConvexDB sync logic
  }
}

🚨 Common Vulnerabilities & Mitigations

Vulnerability Status Mitigation
SQL Injection βœ… Protected Drizzle ORM + parameterized queries
XSS βœ… Protected React escaping + Next.js CSP headers
CSRF βœ… Protected BetterAuth + Next.js middleware
Session Hijacking βœ… Protected HTTP-only cookies + 7-day expiry
Password Exposure βœ… Protected Bcrypt hashing + email verification
API Key Leaks ⚠️ Needs Config Hash keys, rotate regularly, monitor usage
SSRF βœ… Protected Server-side validation in API routes
Rate Limiting ⚠️ Configure Add Upstash/Redis rate limiting
DDoS βœ… Protected Vercel's global network protection

πŸ” Security Checklist

Before going to production:

  • Enable email verification in production SMTP
  • Generate new BETTER_AUTH_SECRET for production
  • Configure rate limiting for API routes
  • Set up monitoring and alerting
  • Enable audit logging for admin actions
  • Configure CORS properly for your domain
  • Set up regular security updates for dependencies
  • Enable 2FA for superadmin accounts
  • Configure backup strategy for Turso databases
  • Set up penetration testing
  • Review and test PayloadCMS access controls
  • Document security procedures for team

πŸ“š Additional Resources

There aren't any published security advisories