Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/docs/api.md
T

10 KiB

Production API Runbook

This runbook is the production entrypoint for the dedicated Hono API application served from apps/api. It documents the currently supported /v1 surface, authentication behavior, request correlation, CORS boundaries, safe diagnostics, and local static verification commands for operators and integrators.

API base surface

The dedicated API is designed to run independently from the React Router web runtime at an API origin such as https://api.example-origin. The versioned API surface is rooted at /v1; examples below intentionally use generic origins and token names rather than environment-specific values.

The API server listens on API_PORT when set, falls back to PORT, and otherwise defaults to 3001. Keep apps/api/src/app.ts as the importable Hono app boundary so tests, adapters, and deployment targets can exercise the app without starting a listener.

/v1 endpoint inventory

Method Path Auth Purpose
GET /healthz, /readyz, /v1/health, /v1/openapi.json, /v1/docs None Health/readiness and public API contract discovery.
POST /v1/auth/login, /v1/auth/refresh-token, /v1/auth/logout Credentials or API session JWT API session lifecycle.
GET /v1/session/current-user, /v1/accounts, /v1/accounts/:id Service token Service principal and account metadata.
GET /v1/usage Tenant API key Usage metadata for the credential-scoped tenant.
POST /v1/api-keys/validate Optional presented API key or service token Redacted API-key/service-token validation helper.
POST /v1/maintenance/export-retention/enqueue Service token Operator maintenance enqueue action.
POST /v1/support/inbound-email Webhook signature Signed inbound support email ingress that creates tenant support tickets.
GET /v1/analytics/public Public-setting gate Tenantless global aggregates; unavailable unless AnalyticsSettings.public is enabled.
GET /v1/analytics/admin Service token plus verified operator user Global tenantless aggregates or an exact tenantId + portalId scope.
POST /v1/analytics/events, /v1/analytics/page-views Analytics ingest token Anonymous tenantless analytics ingress; user and portal identity fields are rejected.
GET /v1/notifications/stream Service token Notification diagnostics stream.
GET /v1/entities/:entity Service token Entity metadata lookup.
GET/POST/PATCH/DELETE /v1/entities/:entity/rows* Service token or tenant API key Tenant-scoped entity row operations.
GET/POST/DELETE /v1/relationships/* Service token or tenant API key Tenant-scoped relationship operations.
GET /v1/exports/* Service token or tenant API key Tenant-scoped export download operations.
GET/POST /v1/workspaces/* Service token Workspace auth/invite boundaries.
POST /v1/events/webhooks/attempts/:id, /v1/support/inbound-email, /v1/billing/legacyProvider/webhooks Webhook signature Signed webhook ingress.

Treat /v1/openapi.json and apps/api/src/route-access-inventory.ts as the detailed source of truth. If apps/api/README.md changes, update this runbook in the same change set so the documentation does not drift from the implementation contract.

Tenant-scoped row, relationship, and export requests resolve tenant scope from the stored tenant API key when one is used. Service-token callers must provide an explicit documented tenant scope, such as tenantId query parameters or supported tenant-scope headers where the OpenAPI operation lists them.

Authentication and token behavior

Set API_ACCESS_TOKEN in the API runtime environment to enable the service-token endpoints. Authenticated calls use Authorization: Bearer <service-token>; key validation may also read the candidate key from the x-api-key header or from the JSON apiKey request body when using POST /v1/api-keys/validate.

ANALYTICS_TOKEN is browser-readable by design and is therefore only a bounded ingest capability, not a read credential. It permits anonymous event/page-view submissions after rate limiting. Public aggregate reads rely solely on the operator-controlled public setting, while admin aggregate reads require the service credential and an x-hivegrid-operator-user-id that resolves to an RLS-visible AdminUser row.

Authentication failures return JSON error envelopes without echoing token values, API keys, bearer fragments, headers, request bodies, tenant identifiers, customer identifiers, or environment values. Support notes should record only the generic endpoint, response status, stable error code, and request ID. Never paste real authorization headers, raw API key inputs, or token-shaped values into tickets, chat, logs, screenshots, or documentation examples.

OpenAPI contract

The API contract is available at:

GET /v1/openapi.json

Use the OpenAPI document as the integration contract for supported paths, methods, request shapes, response shapes, and error schema expectations. Static documentation and examples should refer to /v1/openapi.json rather than copying large schema fragments into support notes, because copied schema snippets become stale quickly.

Health and readiness expectations

GET /v1/health is the lightweight health endpoint for the dedicated API application. It should be usable by uptime checks and deployment health probes that need to confirm the API process can serve a request without requiring credentials.

Readiness triage should pair the health response with process-level deployment status and logs that are already redacted. Do not convert health checks into authenticated user, tenant, customer, queue, database, or browser-flow checks. If deeper readiness is needed for an incident, run the focused local checks listed below and correlate production observations by request ID instead of collecting raw request payloads.

Request ID correlation

The API request-id middleware emits x-request-id on responses. Clients may supply x-request-id; the API echoes the supplied value in the response header and includes it in JSON error bodies. If the client does not provide a request ID, the API generates one.

Use x-request-id as the primary correlation key for support, incident response, and production diagnostics. Support records may include the request ID, endpoint path, method, response status, and stable error code. They must not include raw request bodies, authorization headers, API keys, bearer tokens, cookies, tenant names, customer names, full environment dumps, or customer-specific domains.

CORS origin rules

CORS is the source of truth for browser-origin access to the API. Allowed browser origins come from canonical routing-derived app and admin origins, plus explicit WEB_ORIGIN and ADMIN_ORIGIN values when a deployment needs them. Treat WEB_ORIGIN and ADMIN_ORIGIN as complete origin strings including scheme and host, not host-only aliases.

Allowed CORS responses include access-control-allow-origin matching the allowed browser origin and still include x-request-id and the API security headers. Denied or malformed origins must not emit access-control-allow-origin, but should still emit x-request-id so incidents can be correlated safely. Positive and negative CORS checks are both required during triage because positive-only checks can miss over-broad allowlist regressions.

JSON error envelope

API errors use a stable JSON envelope:

{
  "error": {
    "code": "example_error_code",
    "message": "Safe operator-readable message",
    "requestId": "request-id-for-correlation"
  }
}

error.code is the stable programmatic classification, error.message is safe to show to an operator, and error.requestId links the response to server-side diagnostics. Error envelopes must not echo tokens, API keys, authorization headers, request bodies, raw environment values, tenant identifiers, customer identifiers, or secret-shaped substrings.

Redaction constraints

Apply these redaction rules to all API diagnostics, examples, incidents, and support notes:

  • Redact bearer tokens, API keys, cookies, service-token values, and token-shaped substrings in full.
  • Redact or generalize tenant identifiers, customer identifiers, customer domains, account names, and user-specific values.
  • Do not paste raw request bodies, raw response bodies containing customer data, full headers, authorization headers, or environment dumps.
  • Record generic labels such as example-api-origin, example-web-origin, service-token, and request-id-for-correlation instead of real deployment values.
  • Prefer stable error.code, response status, endpoint path, method, and x-request-id for debugging context.

Safe local and static verification

Run these deterministic checks from the repository root when editing this runbook or the API contract. They do not launch browsers, E2E flows, Docker services, registries, or production traffic.

test -s docs/api.md
python - <<'PY'
from pathlib import Path
text = Path('docs/api.md').read_text()
for marker in ('TO' + 'DO', 'T' + 'BD', 'FIX' + 'ME'):
    assert marker not in text
PY
pnpm exec eslint apps/api/src/app.ts apps/api/src/cors.ts --max-warnings=0
pnpm exec vitest run apps/api/src/app.test.ts apps/api/src/cors.test.ts
pnpm run verify:docs-links

Browser automation, Playwright, Cypress, live Docker, live registry, and E2E execution are manual-only unless a human explicitly approves the exact focused run in the current session.

Troubleshooting checklist

  1. Confirm the path is under the supported /v1 surface and compare it with /v1/openapi.json.
  2. For auth failures, check whether API_ACCESS_TOKEN is configured and whether the request used the expected bearer or API-key input channel without copying the secret value.
  3. For CORS failures, compare the request Origin with the full allowed origin string and test a denied origin to detect over-broad allowlists.
  4. For missing diagnostics, confirm the response includes x-request-id and capture that request ID in the incident record.
  5. For JSON errors, record only error.code, safe error.message, error.requestId, status, method, and endpoint.
  6. If production behavior differs from this runbook, update the implementation and documentation together or record the verified contract change in the same review.