openapi
Create and update tereo's multi-file OpenAPI 3.1.0 spec — one spec for the whole service, split by API area (auth, files, webhooks, audit). Use when adding endpoints, modifying request/response shapes
SKILL.md.claude/skills/openapi/SKILL.md
GitHubOpenAPI Specification Management
See examples.md for real excerpts from the spec.
Directory Structure
tereo is one service with one database, and its API is documented as one spec. The
files are split by area — auth, files, webhooks, audit — but there is one root, one bundle and one
Redocly config (packages/tereo/redocly.yaml):
packages/tereo/
├── redocly.yaml # Rules, root openapi/openapi.yaml → output openapi/bundled-openapi.yaml
├── .redocly.lint-ignore.yaml # Lint problems skipped on purpose (redirect-only operations)
└── openapi/
├── openapi.yaml # The root — info, servers, security, tags, x-tagGroups, path $refs, components, webhooks
├── bundled-openapi.yaml # Generated by `npm run openapi:build` — don't hand-edit
├── README.md
├── components/
│ ├── headers.yaml # Retry-After, X-RateLimit-*
│ ├── parameters.yaml # CursorParam, SortDirParam, LimitParam, SortParam, FilterValueParam,
│ │ # FilterOperatorParam, IncludeArchivedParam, Webhook*Header
│ ├── responses.yaml # Unauthorized/Forbidden/NotFound/BadRequest/Conflict/RateLimit/ServerError/NoContent
│ ├── security.yaml # BearerAuth, ClientCredentials
│ ├── webhook-schemas.yaml # WebhookEvent envelope, OrganizationWebhookEvent, WebhookHeaders
│ ├── auth/ # parameters (*IdParam, IncludeRetiredParam), responses (OAuth2ErrorResponse,
│ │ # ArchivedResponse, …), schemas
│ ├── files/ # headers (ETag, Content-*), parameters (bucket/object/signed-URL params),
│ │ # responses (413, 507, idempotency, signature rejected), schemas
│ ├── webhooks/ # parameters, responses, schemas
│ └── audit/ # parameters, responses, schemas
└── paths/
├── auth/ # /oauth, /.well-known, /health at the root; /v1/account, /v1/admin, /v1/setup
│ ├── health.yaml, well-known.yaml, oauth.yaml, oauth-org-select.yaml, account.yaml
│ ├── setup.yaml
│ └── admin/ # clients, organizations, permissions, roles, services, settings, users
├── files/ # /v1/files — buckets, objects, multipart, archives, lifecycle, permissions,
│ # shares, signed, webhook-events
├── webhooks/ # /v1/webhooks — webhooks (+ the webhook.test event), event-types, events
└── audit/ # /v1/audit — entries
There is no index.html.
Shared and area components
A component every area uses the same way is defined once in components/*.yaml. Where an area's
version differs — a different limit range, a different error-code enum, an extra note — it is a
separate component in components/<area>/, named with the area as a prefix: FilesLimitParam,
FilesSortParam, FilesUserIdParam, FilesFilterOperatorParam, FilesUnauthorizedResponse,
FilesRateLimitResponse, FilesConflictResponse, WebhooksLimitParam, WebhooksIdParam,
WebhooksIncludeArchivedParam, WebhooksFilterOperatorParam, WebhooksUnauthorizedResponse,
WebhooksConflictResponse, AuditIdParam, AuditSortParam, AuditFilterValueParam,
AuditFilterOperatorParam, AuditUnauthorizedResponse, AuditForbiddenResponse,
AuditBadRequestResponse, AuditConflictResponse, AuditIdempotencyKeyConflictResponse. Use the area's variant when one exists. Never
widen a shared component (e.g. add an error code to ConflictResponse) unless it is true of every
route that references it — add or extend the area's variant instead. Component names and
operationIds must be unique across the whole spec: Redocly's bundler hoists every component by its
name, so two files defining the same name would collide.
Paths carry the full mount prefix
Express mounts each area under a prefix in src/app.ts; the spec keys every path by its full
URL on core, so there is one server, http://localhost:4001:
| Area | Mount | Spec path |
|---|---|---|
| auth | /oauth, /.well-known, /v1 |
/v1/admin/roles/{id} |
| files | /v1/files |
/v1/files/buckets/{name} |
| webhooks | /v1/webhooks |
/v1/webhooks/webhooks |
| audit | /v1/audit |
/v1/audit/entries |
Descriptions that mention another route use the full path too (POST /v1/files/buckets/{name}/archives,
GET /v1/audit/entries). Health is only GET /health at the root.
Routes that aren't strictly auth — /v1/setup,
/v1/admin/services — live with auth (paths/auth/setup.yaml,
paths/auth/admin/services.yaml); /v1/files/signed and /v1/files/shared are in
paths/files/signed.yaml and shares.yaml.
Tags
Every operation has a tag, and every tag belongs to one x-tagGroups entry — Auth, Files,
Webhooks or Audit — which Redoc shows as sections (a tag in no group is hidden). Tag names
are unique across areas; the files tags carry a prefix (Files - Buckets, Files - Permissions,
…) so they don't read as auth's (Admin - Permissions).
Spec Version and Conventions
- OpenAPI 3.1.0,
info.version: 0.1.0. - All
$refs are relative:'../../components/<area>/schemas.yaml#/SchemaName'or'../../components/responses.yaml#/NotFoundResponse'frompaths/<area>/, one more../frompaths/auth/admin/,'#/SchemaName'inside a component file,'../headers.yaml#/…'fromcomponents/<area>/. - Path refs in the root use JSON-pointer escaping:
'./paths/webhooks/webhooks.yaml#/~1webhooks~1v1~1webhooks~1{id}'(/→~1). The keys inpaths/files are anchors left from before/v1(/webhooks/v1/…,/files/…,/admin/…); the published path is the key inopenapi.yaml, which carries/v1. A new path file may key by its/v1path. - Examples:
examples:(array). A few olderexample:remain, mostly in descriptions of headers — don't add more. - Nullable fields — one style everywhere:
type: [string, 'null']for a scalar (keepformat,maxLengthetc. alongside),oneOf: [{ $ref: '#/X' }, { type: 'null' }]for a ref. Nevernullable: true(a 3.0 keyword that 3.1 tooling ignores). - Pagination is cursor-based everywhere: a limit param (
LimitParamor the area's variant) +CursorParam+ a sort param +SortDirParam, and list responses are{ data, hasMore, limit, nextCursor }(nextCursoris an opaque HMAC-signed string, null whenhasMoreis false). There is noOffsetParam. - Filtering:
filter[field]=value+filter[field_op]=operator(FilterValueParam,FilterOperatorParam, or the area's variants), documented per operation in the description.
Security
The root sets security: [BearerAuth: []], and redocly.yaml makes security-defined an error.
An operation without a security: block inherits BearerAuth, so every public operation must
say security: [] — health, OAuth flows, .well-known, setup, /v1/files/signed/**,
/v1/files/shared/**, and every webhook definition (auth.*, core.service.*, file-service.*,
webhook.test) — they describe outbound deliveries, which carry no bearer token.
Operations that serve anonymous callers on a public bucket but need a token otherwise (the object
reads in paths/files/objects.yaml) make auth optional: security: [ {}, { BearerAuth: [] } ].
| Area | How an operation states its permission |
|---|---|
| auth | In the scope list: security: [{ BearerAuth: [roles.archive] }] |
| files | Scope list and a **Required permissions:** block in the description |
| webhooks | BearerAuth: [] + **Required permissions:** block |
| audit | BearerAuth: [] + **Required permission:** line |
Permission names must match src/definitions/permissions.ts (roles.archive, webhooks.read,
file-service.objects.read, audit-logs.write, …) — permissions are hierarchical (write ⊃
read, delete ⊃ write, admin ⊃ all).
Archive lifecycle conventions
Archivable resources (organizations, custom roles, webhook endpoints) follow a fixed shape:
archivedAtis a nullable date-time.- List operations take
IncludeArchivedParam(includeArchived, boolean, default false). - Document
POST /{id}/archiveandPOST /{id}/restore(and hardDELETE /{id}where it exists), each with its permission (roles.archive,organizations.archive,webhooks.archive) and the 409/404 cases:409 already_archivedon archive,409 not_archivedon restore (NotArchivedResponse),409 resource_archivedfor any other change to an archived row, and404only for a missing or hidden one. Responses differ by area — role and organization archive return 204, webhook endpoint archive/restore return 200 with the resource; match the controller.
Root openapi.yaml Pattern
There is one root, openapi/openapi.yaml. Its info.description is the guide for the whole API:
an overview of the areas and their mounts, Features (per area), the Authentication Guide,
Permissions (per area), Rate Limiting (one shared limiter, with the auth-failure and per-bucket
limits), Pagination / Filtering / Sorting, Error Handling (common codes, then each area's), and
sections for what only one area has (files access control and limits, receiving webhook
deliveries, audit organization scoping). Put a new cross-cutting fact there once, not per area.
openapi: 3.1.0
info:
title: Tereo API
version: 0.1.0
description: |
{Long Markdown description — see above}
license:
name: Apache-2.0
url: https://www.apache.org/licenses/LICENSE-2.0
servers:
- url: http://localhost:4001
description: Local development server (each app deploys its own core; substitute its host)
security:
- BearerAuth: []
tags:
# Auth / Files / Webhooks / Audit
- name: {Tag}
description: {Description}
x-tagGroups:
- name: Auth # then Files, Webhooks, Audit
tags: [...]
paths:
# Auth / Files / Webhooks / Audit
/v1/webhooks/{resource}:
$ref: './paths/webhooks/{resource}.yaml#/~1webhooks~1v1~1{resource}'
components:
securitySchemes:
BearerAuth:
$ref: './components/security.yaml#/BearerAuth'
parameters:
CursorParam:
$ref: './components/parameters.yaml#/CursorParam'
WebhooksLimitParam:
$ref: './components/webhooks/parameters.yaml#/WebhooksLimitParam'
headers:
Retry-After:
$ref: './components/headers.yaml#/Retry-After'
responses:
UnauthorizedResponse:
$ref: './components/responses.yaml#/UnauthorizedResponse'
schemas:
{Resource}:
$ref: './components/{area}/schemas.yaml#/{Resource}'
webhooks: # every event of every area
{prefix}.{resource}.{action}:
$ref: './paths/{area}/{resource}.yaml#/{prefix}.{resource}.{action}'
Path File Pattern
paths/webhooks/webhooks.yaml (trimmed):
/v1/webhooks/webhooks:
get:
tags:
- Webhook Endpoints
summary: List webhook endpoints
description: |
Returns a paginated list of webhook endpoints for the current client.
**Required permissions:**
- `webhooks.read`
**Filter fields and operators:**
- `status`: `equals`, `in`
- `url`: `contains`
**Sort fields:** `createdAt`, `updatedAt`
operationId: listWebhookEndpoints
security:
- BearerAuth: []
parameters:
- $ref: '../../components/webhooks/parameters.yaml#/WebhooksLimitParam'
- $ref: '../../components/parameters.yaml#/CursorParam'
- $ref: '../../components/parameters.yaml#/SortParam'
- $ref: '../../components/parameters.yaml#/SortDirParam'
- $ref: '../../components/parameters.yaml#/FilterValueParam'
- $ref: '../../components/webhooks/parameters.yaml#/WebhooksFilterOperatorParam'
- $ref: '../../components/webhooks/parameters.yaml#/WebhooksIncludeArchivedParam'
responses:
'200':
description: Paginated list of webhook endpoints
headers:
X-RateLimit-Limit:
$ref: '../../components/headers.yaml#/X-RateLimit-Limit'
X-RateLimit-Remaining:
$ref: '../../components/headers.yaml#/X-RateLimit-Remaining'
X-RateLimit-Reset:
$ref: '../../components/headers.yaml#/X-RateLimit-Reset'
content:
application/json:
schema:
$ref: '../../components/webhooks/schemas.yaml#/ListWebhookEndpointsResponse'
'400':
$ref: '../../components/responses.yaml#/BadRequestResponse'
'401':
$ref: '../../components/webhooks/responses.yaml#/WebhooksUnauthorizedResponse'
'403':
$ref: '../../components/responses.yaml#/ForbiddenResponse'
'429':
$ref: '../../components/responses.yaml#/RateLimitResponse'
'500':
$ref: '../../components/responses.yaml#/ServerErrorResponse'
post:
tags:
- Webhook Endpoints
summary: Create a webhook endpoint
description: |
Creates a new webhook endpoint for the current client.
**Required permissions:**
- `webhooks.write`
An audit log entry is created for this action.
operationId: createWebhookEndpoint
security:
- BearerAuth: []
requestBody:
required: true
content:
application/json:
schema:
$ref: '../../components/webhooks/schemas.yaml#/CreateWebhookEndpointRequest'
responses:
'201':
description: Webhook endpoint created successfully
headers: { rate limit headers }
content:
application/json:
schema:
$ref: '../../components/webhooks/schemas.yaml#/WebhookEndpoint'
'400': { BadRequestResponse }
'401': { WebhooksUnauthorizedResponse }
'403': { ForbiddenResponse }
'429': { RateLimitResponse }
'500': { ServerErrorResponse }
Say in the description when an operation writes an audit entry ("An audit log entry is created for
this action.") and which webhook event it emits ("An auth.role.archived webhook event is emitted.").
Schema Pattern
WebhookEndpoint:
type: object
description: A webhook endpoint configuration for receiving event notifications
properties:
id:
type: string
format: uuid
description: Unique identifier
examples:
- "550e8400-e29b-41d4-a716-446655440000"
description:
type: [string, 'null']
description: Optional description of the webhook endpoint
maxLength: 500
archivedAt:
type: [string, 'null']
format: date-time
description: Archive (retirement) timestamp; null for active endpoints.
corsConfig: # from files' Bucket — a nullable ref
oneOf:
- $ref: '#/CorsConfig'
- type: 'null'
createdAt:
type: string
format: date-time
description: Creation timestamp
ListWebhookEndpointsResponse:
type: object
description: Cursor-paginated list of webhook endpoints
properties:
data:
type: array
items:
$ref: '#/WebhookEndpoint'
hasMore:
type: boolean
limit:
type: integer
nextCursor:
type: [string, 'null']
Ids are UUIDs (format: uuid; core generates UUIDv7).
Webhook Definition Pattern (in path files)
Each area documents the events it emits: auth.* and core.service.* at the end of the auth path
file for the resource, file-service.* in paths/files/webhook-events.yaml, webhook.test in
paths/webhooks/webhooks.yaml. A definition is keyed by the event type and referenced from the
root's one webhooks: section, which lists every area's events. Delivery headers are the shared
parameters in components/parameters.yaml (WebhookIdHeader, …). The body extends
OrganizationWebhookEvent (the WebhookEvent envelope with organizationId required) for every
emitted event; only webhook.test, which has no organizationId, uses WebhookEvent itself.
From paths/auth/admin/roles.yaml:
auth.role.archived:
post:
tags: [Admin - Roles]
summary: Role archived
description: Fired when a role is archived.
operationId: webhookRoleArchived
parameters:
- $ref: '../../../components/parameters.yaml#/WebhookIdHeader'
- $ref: '../../../components/parameters.yaml#/WebhookEventHeader'
- $ref: '../../../components/parameters.yaml#/WebhookTimestampHeader'
- $ref: '../../../components/parameters.yaml#/WebhookSignatureHeader'
requestBody:
required: true
content:
application/json:
schema:
allOf:
- $ref: '../../../components/webhook-schemas.yaml#/OrganizationWebhookEvent'
- type: object
properties:
eventType:
const: auth.role.archived
entityType:
const: Role
data:
type: object
required: [id, name]
properties:
id: { type: string, format: uuid }
name: { type: string }
responses:
'2XX':
description: Any 2xx response acknowledges the delivery; anything else is retried.
The headers as core sends them (jobs/webhookDelivery.ts): X-Webhook-Id is the delivery id,
stable across retries and not the body's id; X-Webhook-Timestamp is Unix seconds;
X-Webhook-Signature is sha256= + the hex HMAC-SHA256 of "${timestamp}.${rawBody}".
The event type must exist in src/definitions/eventTypes.ts — that list, not the spec, is what core
accepts (see the outbox skill). A declared event type that nothing emits yet still gets a
definition, saying so and leaving data unspecified.
Common Response Patterns
| Status | Use | Component |
|---|---|---|
| 200 | GET single, PATCH, POST actions | Resource schema |
| 201 | POST create | Resource schema |
| 204 | DELETE, auth archive/restore actions | NoContentResponse (or inline) |
| 400 | Validation errors | BadRequestResponse |
| 401 | Missing/invalid token | UnauthorizedResponse |
| 403 | Insufficient permissions | ForbiddenResponse |
| 404 | Resource not found | NotFoundResponse |
| 409 | Conflict / constraint violation | ConflictResponse |
| 429 | Rate limit exceeded | RateLimitResponse |
| 500 | Server error | ServerErrorResponse |
These are the shared ones, in components/responses.yaml. Use the area's variant where it has one
(see Shared and area components): files uses FilesUnauthorizedResponse,
FilesConflictResponse and FilesRateLimitResponse (which also covers the per-bucket limiter); webhooks WebhooksUnauthorizedResponse and WebhooksConflictResponse;
audit AuditUnauthorizedResponse, AuditForbiddenResponse, AuditBadRequestResponse,
AuditConflictResponse and AuditIdempotencyKeyConflictResponse.
Files adds PayloadTooLargeResponse (413), InsufficientStorageResponse (507) and the idempotency
responses (IdempotencyInProgressResponse, IdempotencyKeyConflictResponse) with the
IdempotencyKeyHeader parameter. Auth's OAuth endpoints use OAuth2ErrorResponse.
Successful JSON responses carry the X-RateLimit-* headers.
Linting & Bundling
From packages/tereo (@redocly/cli is a dev dependency; both read redocly.yaml):
npm run openapi:lint # lint the spec — CI runs this
npm run openapi:build # lint, then regenerate openapi/bundled-openapi.yaml
The bundle is committed: run openapi:build after editing the spec and commit the result. Keep its
path, openapi/bundled-openapi.yaml — consumers such as the admin UI read it from there. The
service itself does not serve the spec.
redocly.yaml extends recommended, turns no-server-example.com and info-license-strict off,
and makes security-defined an error. .redocly.lint-ignore.yaml skips operation-2xx-response
for the operations that only redirect (GET /oauth/authorize, GET /v1/files/shared/{token} and its
/{filename} form). The one remaining warning is GET /health, which has no 4xx response.
When to Update
- New endpoint added → path file + root
openapi.yamlpaths:entry - Request/response schema changed →
components/<area>/schemas.yaml(+ rootcomponents.schemasref) - New model → schema + Create/Update request +
List…Response - Permission changed → the operation's security scope / Required permissions, and
components/security.yamlif it lists the domain's permissions - New webhook event → definition in the area's path file (
paths/<area>/) + rootwebhooks:entry, anddefinitions/eventTypes.ts - New resource group → new path file under
paths/<area>/, referenced from the root, with a tag in the area'sx-tagGroupsentry - Route removed → remove it from the path file and the root
Then npm run openapi:build.
Source of Truth
- Zod schemas —
src/routes/**/schemas.ts— define request validation - Transformers —
src/utils/transformers.ts(formatRole, …) and the controllers define response shapes; the Prisma schema (prisma/schema.prisma) defines what is stored - Route files —
src/routes/**/index.ts— define which paths, methods andrequirePermissions exist - Definitions —
src/definitions/— permission names and event types - The OpenAPI spec must match all of the above — keep them in sync