All files / apps / api/src / server / auth middleware.ts

100% Statements 31/31
100% Branches 20/20
100% Functions 7/7
100% Lines 27/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79                        29x     29x           29x     97x       2x         29x 114x   68x 68x   68x   68x 3x     65x       29x 113x 113x 1x     112x       29x 111x   65x 65x   60x   57x         41x   41x   40x    
import { API_DOCS, AUTH_ERROR_CODE, ERROR_CODE, SESSION_API, SYSTEM_API } from '@chattra/shared'
import type { Context } from 'hono'
import { createMiddleware } from 'hono/factory'
import { ApiHttpError, type AppEnv } from '../http'
import type { Actor } from '../permission/service'
import { isWithinIpCeiling } from '../ratelimit/client'
import { authenticate, type RequestContext } from './service'
import { readBearer } from './tokens'
 
// The app-wide steps of design 2.2: Origin → rate limit → ID token. Mounted in app/routes.ts on
// /api/*, so no route can skip them.
 
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
// Answer before any data route: public, or the one route that runs before a users row exists (5.1).
// The docs pages are public on local and dev only (owner's decision, 2026-11-13; docs-routes.ts).
const PUBLIC_PATHS = new Set<string>([
  SYSTEM_API.config.path,
  SESSION_API.bootstrap.path,
  API_DOCS.page,
  API_DOCS.openApi,
])
const DEVICE_MAX = 200
 
export function requestContext(c: Context<AppEnv>): RequestContext {
  return {
    requestId: c.get('requestId'),
    device: c.req.header('user-agent')?.slice(0, DEVICE_MAX) ?? null,
    ip: c.req.header('cf-connecting-ip') ?? null,
    waitUntil: (promise) => c.executionCtx.waitUntil(promise),
  }
}
 
/** Exact Origin on every write (design 6.2 V4); the token is not a cookie, this is defence in depth. */
export const requireOrigin = createMiddleware<AppEnv>(async (c, next) => {
  if (SAFE_METHODS.has(c.req.method)) return next()
 
  const origin = c.req.header('origin')
  const allowed = [
    new URL(c.req.url).origin,
    ...c.env.ALLOWED_ORIGINS.split(',').map((value) => value.trim()),
  ].filter(Boolean)
  if (!origin || !allowed.includes(origin)) {
    throw new ApiHttpError(AUTH_ERROR_CODE.originRefused, 'Origin not allowed')
  }
 
  return next()
})
 
/** The high per-IP ceiling (design G7); per-account limits sit on the routes that need them. */
export const ipCeiling = createMiddleware<AppEnv>(async (c, next) => {
  const ip = c.req.header('cf-connecting-ip') ?? 'unknown'
  if (!(await isWithinIpCeiling(c.env, ip))) {
    throw new ApiHttpError(ERROR_CODE.rateLimited, 'Too many requests')
  }
 
  return next()
})
 
/** Verifies the Firebase ID token and loads the caller (design 4.2). */
export const requireActor = createMiddleware<AppEnv>(async (c, next) => {
  if (PUBLIC_PATHS.has(c.req.path)) return next()
 
  const token = readBearer(c.req.header('authorization'))
  if (!token) throw new ApiHttpError(ERROR_CODE.unauthenticated, 'Sign in first')
 
  c.set('actor', await authenticate(c.env, token, requestContext(c)))
 
  return next()
})
 
/** The caller of a route behind requireActor. */
export function getActor(c: Context<AppEnv>): Actor {
  const actor = c.get('actor')
  // Only reachable if a route is mounted outside /api/*, where requireActor does not run.
  if (!actor) throw new ApiHttpError(ERROR_CODE.unauthenticated, 'Sign in first')
 
  return actor
}