Inkdown
Start writing

Merlin Backend

12 files·0 subfolders

Shared Workspace

Merlin Backend
01-Orchestration.md

11-SecurityAndAuth

Shared from "Merlin Backend" on Inkdown

Security & Authentication Architecture

Overview

The security layer provides authentication, authorization, and request validation. It uses Firebase Auth for user identity and implements multiple authentication patterns for different contexts.


Architecture

Plain text
02-DeepResearch.md
03-Search.md
04-Scraping.md
05-Streaming.md
06-MultiProviderLLM.md
07-MemoryAndContext.md
08-ErrorHandling.md
09-RateLimiting.md
10-TaskQueue.md
11-SecurityAndAuth.md
Orchestration-2nd-draft

Main Auth Middleware

File: src/server/middlewares/auth/auth.ts

TypeScript

User Model

File: src/server/models/user.ts

TypeScript

Task Execution Auth

File: src/server/middlewares/auth/auth.ts:81

For background task execution (different auth pattern):

TypeScript

Why Different:

  • Tasks execute without user present
  • Secret-based auth (internal only)
  • Lightweight user loading (skip heavy checks)
  • Marked as executionContext: TASK

Request Context

File: src/server/repositories/context/requestContext.ts

TypeScript

Why AsyncLocalStorage:

  • Maintains context across async operations
  • No need to pass context through every function
  • Automatically cleaned up after request
  • Thread-safe (per-request isolation)

Internal API Secret

File: src/server/middlewares/auth/secret.ts

TypeScript

Security Headers

File: src/index.ts (Express app setup)

TypeScript

Token Validation

Firebase Token Structure:

TypeScript

Validation Checks:

  1. Token present
  2. Valid format (3 parts: header.payload.signature)
  3. Not expired (exp > now)
  4. Valid issuer (Firebase)
  5. Valid audience (our project)
  6. Signature valid (Firebase verifies)

Error Handling

File: src/server/models/error/error.ts

TypeScript

Middleware Chain

File: src/config/routing.ts

TypeScript

Security Best Practices

1. No Secrets in Code
TypeScript
2. Input Validation
TypeScript
3. Rate Limiting
TypeScript
4. Error Sanitization
TypeScript
5. Token Expiration
TypeScript

Summary

The security architecture:

  1. Firebase Auth: Industry-standard JWT tokens
  2. Bearer Pattern: Authorization: Bearer <token>
  3. AsyncLocalStorage: Context maintained across async ops
  4. User Model: Lazy loading with cleanup checks
  5. Task Auth: Secret-based for background jobs
  6. Helmet + CORS: Security headers and origin validation
  7. Secret Management: Environment variables only
  8. Input Validation: Zod schemas for all inputs
  9. Error Sanitization: No sensitive data in errors
  10. Rate Limiting: Multi-layer protection

Key Principle: Defense in depth. Multiple layers of protection, clear error messages for users, detailed logs for developers.