All files / apps / api/src / server / docs openapi.ts

100% Statements 25/25
100% Branches 14/14
100% Functions 11/11
100% Lines 20/20

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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253                                        29x     9x           29x 24x   29x                 247x 113x   112x     245x               6x         14x                 29x                           29x                                 16x 16x   16x                                             2x 16x   2x       2x                                                                                                                                                                                                                                              
import {
  ApiErrorSchema,
  AUTH_ERROR_CODE,
  CHANNEL_API,
  CHANNEL_ERROR_CODE,
  ERROR_CODE,
  HTTP_STATUS,
  SESSION_API,
  SYSTEM_API,
  type Endpoint,
} from '@chattra/shared'
import { z, type ZodType } from 'zod'
import { ERROR_STATUS, type ApiErrorCode } from '../http'
 
// The OpenAPI document behind /api/docs. Paths, bodies and parameters come from the shared
// endpoint contracts, and error statuses from ERROR_STATUS, so they cannot drift from what the
// routes register, validate and throw; tags, summaries and which codes a route answers with are
// written beside them here.
 
/** Swagger UI is served on these environments only (owner's decision, 2026-11-13). */
const DOCS_ENVIRONMENTS = new Set(['local', 'dev'])
 
export function isDocsEnabled(env: Env): boolean {
  return DOCS_ENVIRONMENTS.has(env.ENVIRONMENT)
}
 
type JsonSchema = Record<string, unknown>
type ErrorEntry = [status: string, response: JsonSchema]
 
const schema = (zod: ZodType, io: 'input' | 'output' = 'output'): JsonSchema =>
  z.toJSONSchema(zod, { io, unrepresentable: 'any' })
 
const json = (zod: ZodType, io?: 'input' | 'output'): JsonSchema => ({
  'application/json': { schema: schema(zod, io) },
})
 
/** One response for codes that share a status; the status comes from ERROR_STATUS. */
export function errorResponse(
  description: string,
  codes: [ApiErrorCode, ...ApiErrorCode[]],
): ErrorEntry {
  const statuses = new Set(codes.map((code) => ERROR_STATUS[code]))
  if (statuses.size > 1) throw new Error(`${codes.join(', ')} do not share one status`)
 
  return [
    String(ERROR_STATUS[codes[0]]),
    {
      description: `${description}. \`code\`: ${codes.map((code) => `\`${code}\``).join(', ')}`,
      content: { 'application/json': { schema: { $ref: '#/components/schemas/ApiError' } } },
    },
  ]
}
 
function parameters(zod: ZodType, where: 'query' | 'path'): JsonSchema[] {
  // SAFETY: toJSONSchema of a z.object is always an object schema with `properties`.
  const { properties, required } = schema(zod, 'input') as {
    properties: Record<string, JsonSchema>
    required?: string[]
  }
 
  return Object.entries(properties).map(([name, value]) => ({
    name,
    in: where,
    required: (required ?? []).includes(name),
    schema: value,
  }))
}
 
// Every route behind the token check can answer these.
const TOKEN_ERRORS: ErrorEntry[] = [
  errorResponse('Missing, invalid or ended token', [
    ERROR_CODE.unauthenticated,
    AUTH_ERROR_CODE.invalidToken,
    AUTH_ERROR_CODE.sessionEnded,
  ]),
  errorResponse('Not signed up, deactivated, or a write from another origin', [
    AUTH_ERROR_CODE.notRegistered,
    AUTH_ERROR_CODE.accountDeactivated,
    AUTH_ERROR_CODE.originRefused,
  ]),
  errorResponse('Over the per-IP ceiling', [ERROR_CODE.rateLimited]),
]
 
const BEARER = [{ firebaseIdToken: [] }]
 
type SuccessStatus = (typeof HTTP_STATUS)['ok' | 'created' | 'noContent']
 
interface OperationDoc {
  tags: string[]
  summary: string
  description?: string
  security?: JsonSchema[]
  /** The success status the endpoint answers with; the contract has the body. */
  success: { status: SuccessStatus; description: string }
  /** A later entry with the same status replaces an earlier one. */
  errors?: ErrorEntry[]
}
 
/** One `[path, { method: operation }]` entry of `paths`, with the parts the contract knows filled in. */
function operation(endpoint: Endpoint, doc: OperationDoc): [string, JsonSchema] {
  const { body, query, params, response } = endpoint
  const { success, errors = [], ...text } = doc
 
  return [
    // Hono's `:id` is OpenAPI's `{id}`.
    endpoint.path.replace(/:(\w+)/g, '{$1}'),
    {
      [endpoint.method.toLowerCase()]: {
        ...text,
        ...(query && { parameters: parameters(query, 'query') }),
        ...(params && { parameters: parameters(params, 'path') }),
        ...(body && { requestBody: { required: true, content: json(body, 'input') } }),
        responses: {
          [String(success.status)]: {
            description: success.description,
            ...(response && { content: json(response) }),
          },
          ...Object.fromEntries(errors),
        },
      },
    },
  ]
}
 
// Merged, so two methods on one path (GET and POST /api/x) do not overwrite each other.
function pathsOf(entries: [string, JsonSchema][]): JsonSchema {
  const paths: Record<string, JsonSchema> = {}
  for (const [path, item] of entries) paths[path] = { ...paths[path], ...item }
 
  return paths
}
 
export function buildOpenApi(): JsonSchema {
  return {
    openapi: '3.1.0',
    info: {
      title: 'Chattra API',
      version: '0.1.0',
      description:
        'Every error is `{ code, message, requestId }` (design G19). Writes need an `Origin` header equal to the site or one in `ALLOWED_ORIGINS`.',
    },
    components: {
      securitySchemes: {
        firebaseIdToken: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
          description: 'A Firebase ID token from `user.getIdToken()` (design 4.2).',
        },
      },
      schemas: { ApiError: schema(ApiErrorSchema) },
    },
    paths: pathsOf([
      operation(SYSTEM_API.health, {
        tags: ['system'],
        summary: 'Health: both D1 databases answer and the config is valid',
        success: { status: HTTP_STATUS.ok, description: 'Healthy' },
      }),
      operation(SYSTEM_API.config, {
        tags: ['system'],
        summary: 'Public config the SPA reads at start (environment, Firebase web settings)',
        success: { status: HTTP_STATUS.ok, description: 'Config' },
      }),
      operation(SESSION_API.bootstrap, {
        tags: ['session'],
        summary: 'Sign in: create or open the session for a Firebase + Google sign-in',
        description:
          'Bearer: the Firebase ID token. Body: Google’s own ID token, which carries `hd`. A first sign-in creates the person and their #general membership; a domain no workspace allows deletes the Firebase account.',
        security: BEARER,
        success: { status: HTTP_STATUS.ok, description: 'Signed in' },
        errors: [
          errorResponse('Malformed body', [ERROR_CODE.invalidRequest]),
          errorResponse('Missing or invalid token, or an ended session', [
            ERROR_CODE.unauthenticated,
            AUTH_ERROR_CODE.invalidToken,
            AUTH_ERROR_CODE.sessionEnded,
          ]),
          errorResponse('Refused', [
            AUTH_ERROR_CODE.domainNotAllowed,
            AUTH_ERROR_CODE.emailNotVerified,
            AUTH_ERROR_CODE.accountDeactivated,
            AUTH_ERROR_CODE.originRefused,
          ]),
          errorResponse('The email belongs to another person', [AUTH_ERROR_CODE.emailInUse]),
          errorResponse('Too many sign-ins for this account', [ERROR_CODE.rateLimited]),
        ],
      }),
      operation(SESSION_API.signOutEverywhere, {
        tags: ['session'],
        summary: 'End every session of mine and revoke my Firebase refresh tokens',
        security: BEARER,
        success: { status: HTTP_STATUS.noContent, description: 'Signed out everywhere' },
        errors: TOKEN_ERRORS,
      }),
      operation(SESSION_API.list, {
        tags: ['session'],
        summary: 'My open sessions, newest first',
        security: BEARER,
        success: { status: HTTP_STATUS.ok, description: 'A page of sessions' },
        errors: [
          errorResponse('Bad limit or cursor', [ERROR_CODE.invalidRequest]),
          ...TOKEN_ERRORS,
        ],
      }),
      operation(CHANNEL_API.create, {
        tags: ['channel'],
        summary: 'Create a public or private channel; the creator joins it as its admin',
        description:
          'A Member may create only what the workspace’s `member_create` allows; an Admin or Owner always may. Names are lowercase ASCII letters, digits and hyphens, unique in the workspace (archived channels keep theirs).',
        security: BEARER,
        success: { status: HTTP_STATUS.created, description: 'Created' },
        errors: [
          errorResponse('Malformed body', [ERROR_CODE.invalidRequest]),
          errorResponse('The name is already used', [CHANNEL_ERROR_CODE.nameTaken]),
          ...TOKEN_ERRORS,
          errorResponse(
            'Not allowed to create this kind of channel, not signed up, deactivated, or a write from another origin',
            [
              ERROR_CODE.forbidden,
              AUTH_ERROR_CODE.notRegistered,
              AUTH_ERROR_CODE.accountDeactivated,
              AUTH_ERROR_CODE.originRefused,
            ],
          ),
        ],
      }),
      operation(CHANNEL_API.browse, {
        tags: ['channel'],
        summary: 'Browse the channels I may see, by name',
        description:
          'Public channels and the private ones I am in; never a direct message, never another workspace’s channel. `type=archived` lists archived channels, every other type hides them.',
        security: BEARER,
        success: { status: HTTP_STATUS.ok, description: 'A page of channels' },
        errors: [
          errorResponse('Bad scope, type, limit or cursor', [ERROR_CODE.invalidRequest]),
          ...TOKEN_ERRORS,
        ],
      }),
      operation(SESSION_API.end, {
        tags: ['session'],
        summary: 'End one of my sessions (sign out on that device)',
        security: BEARER,
        success: { status: HTTP_STATUS.noContent, description: 'Ended' },
        errors: [
          errorResponse('Malformed id', [ERROR_CODE.invalidRequest]),
          errorResponse('Not one of my sessions', [ERROR_CODE.notFound]),
          ...TOKEN_ERRORS,
        ],
      }),
    ]),
  }
}