All files / apps / api/src / server http.ts

100% Statements 31/31
100% Branches 14/14
100% Functions 9/9
100% Lines 29/29

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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129                                            29x 134x 134x 134x 134x         29x                                             29x 203x             106x 106x         29x 50x   50x               50x   49x   49x   49x 1x     49x     1x 1x   1x       1x           1x                   156x 97x   21x 20x     20x            
import {
  AUTH_ERROR_CODE,
  CHANNEL_ERROR_CODE,
  ERROR_CODE,
  HTTP_STATUS,
  REQUEST_ID_HEADER,
  type ApiError,
} from '@chattra/shared'
import { zValidator } from '@hono/zod-validator'
import type { ErrorHandler, MiddlewareHandler, ValidationTargets } from 'hono'
import { HTTPException } from 'hono/http-exception'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import type { ZodType } from 'zod'
import { log } from '../lib/log'
import type { Actor } from './permission/service'
 
export interface AppEnv {
  Bindings: Env
  // actor: set by requireActor on every /api/* route that is not public (design 4.2).
  Variables: { requestId: string; actor?: Actor }
}
 
export const requestId: MiddlewareHandler<AppEnv> = async (c, next) => {
  const id = crypto.randomUUID()
  c.set('requestId', id)
  c.header(REQUEST_ID_HEADER, id)
  await next()
}
 
// Each code the API answers with has one status (design G19): a throw names the code, this says
// the status. The web switches on the code only, so the table stays in the API.
export const ERROR_STATUS = {
  [ERROR_CODE.invalidRequest]: HTTP_STATUS.badRequest,
  [ERROR_CODE.unauthenticated]: HTTP_STATUS.unauthorized,
  [ERROR_CODE.forbidden]: HTTP_STATUS.forbidden,
  [ERROR_CODE.notFound]: HTTP_STATUS.notFound,
  [ERROR_CODE.conflict]: HTTP_STATUS.conflict,
  [ERROR_CODE.rateLimited]: HTTP_STATUS.tooManyRequests,
  [ERROR_CODE.internal]: HTTP_STATUS.internalServerError,
  [AUTH_ERROR_CODE.invalidToken]: HTTP_STATUS.unauthorized,
  [AUTH_ERROR_CODE.sessionEnded]: HTTP_STATUS.unauthorized,
  [AUTH_ERROR_CODE.domainNotAllowed]: HTTP_STATUS.forbidden,
  [AUTH_ERROR_CODE.emailNotVerified]: HTTP_STATUS.forbidden,
  [AUTH_ERROR_CODE.notRegistered]: HTTP_STATUS.forbidden,
  [AUTH_ERROR_CODE.accountDeactivated]: HTTP_STATUS.forbidden,
  [AUTH_ERROR_CODE.originRefused]: HTTP_STATUS.forbidden,
  [AUTH_ERROR_CODE.emailInUse]: HTTP_STATUS.conflict,
  [CHANNEL_ERROR_CODE.nameTaken]: HTTP_STATUS.conflict,
} as const satisfies Record<string, ContentfulStatusCode>
 
export type ApiErrorCode = keyof typeof ERROR_STATUS
 
// A plain HTTPException (Hono's own, a status alone) gets the generic code of its status.
// A status without one keeps http_<status>.
const CODE_BY_STATUS: Partial<Record<number, string>> = Object.fromEntries(
  Object.values(ERROR_CODE).map((code) => [ERROR_STATUS[code], code]),
)
 
export class ApiHttpError extends HTTPException {
  readonly code: ApiErrorCode
 
  constructor(code: ApiErrorCode, message: string) {
    super(ERROR_STATUS[code], { message })
    this.code = code
  }
}
 
// Every error leaves as { code, message, requestId } (design G19); internals never reach the client.
export const onError: ErrorHandler<AppEnv> = (err, c) => {
  const id = c.get('requestId')
  // Hono catches the throw, so the runtime never records it: this line is the only trace of a 5xx.
  const trace = {
    requestId: id,
    method: c.req.method,
    path: c.req.path,
    message: String(err),
    stack: err.stack,
  }
 
  if (err instanceof HTTPException) {
    const code =
      err instanceof ApiHttpError ? err.code : (CODE_BY_STATUS[err.status] ?? `http_${err.status}`)
 
    const body: ApiError = { code, message: err.message || code, requestId: id }
 
    if (err.status >= HTTP_STATUS.internalServerError) {
      log('error', { ...trace, status: err.status })
    }
 
    return c.json(body, err.status)
  }
 
  log('error', { ...trace, status: HTTP_STATUS.internalServerError })
  const body: ApiError = { code: ERROR_CODE.internal, message: 'Internal error', requestId: id }
 
  return c.json(body, HTTP_STATUS.internalServerError)
}
 
export function notFound(c: Parameters<ErrorHandler<AppEnv>>[1]): Response {
  const body: ApiError = {
    code: ERROR_CODE.notFound,
    message: 'Not found',
    requestId: c.get('requestId'),
  }
 
  return c.json(body, HTTP_STATUS.notFound)
}
 
// zValidator answers a bad input with its own body; this keeps the shared one (design G19).
// The message names the fields, never their values. The return type is left inferred:
// it is what carries the parsed type into `c.req.valid(target)`.
export function validate<TTarget extends keyof ValidationTargets, TSchema extends ZodType>(
  target: TTarget,
  schema: TSchema,
) {
  return zValidator(target, schema, (result) => {
    if (result.success) return
 
    const fields = [...new Set(result.error.issues.map((issue) => issue.path.join('.')))]
      .filter((field) => field !== '')
      .join(', ')
 
    throw new ApiHttpError(
      ERROR_CODE.invalidRequest,
      fields ? `Invalid ${target}: ${fields}` : `Invalid ${target}`,
    )
  })
}