Skip to content

refactor: extract shared auth preHandler to eliminate scattered inline checks #210

Description

@martincarapia

Problem

Auth validation is currently implemented in two inconsistent patterns:

  1. agents.ts — Uses a proper Fastify preHandler hook (apiKeyAuth) that does format check + DB lookup. This is the correct idiomatic approach.
  2. chat.ts, audio.ts, models.ts, embeddings.ts, responses.ts, files.ts — Inline validateAuth() (shape-only) ± agentStore.validateKey() inside handler bodies.

The inline pattern is error-prone — it caused #149 (comment) where the audio endpoint accepted unregistered keys because the DB check was missing.

Proposed Solution

  1. Extract apiKeyAuth from agents.ts into a shared module (e.g. src/middleware/auth.ts)
  2. Apply it as a preHandler on all authenticated routes
  3. Remove inline validateAuth() + agentStore.validateKey() calls from handler bodies
  4. Single source of truth for auth logic — new routes automatically get proper validation

Benefits

  • Prevents entire class of "forgot to add DB check" bugs
  • Follows Fastify idioms (preHandler hooks)
  • Reduces code duplication across 6+ route files
  • Makes auth policy changes atomic (one place to update)

Files to Update

  • src/routes/chat.ts
  • src/routes/audio.ts
  • src/routes/models.ts
  • src/routes/embeddings.ts
  • src/routes/responses.ts
  • src/routes/files.ts
  • src/routes/agents.ts (extract, keep using)
  • New: src/middleware/auth.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions