Hono API Specification — LumiBase
For AI agents: This page is also available as clean Markdown. Append
/index.mdto any LumiBase docs URL.Base URL:
https://api.<your-site>.lumibase.dev(orhttp://localhost:1989in local dev)All endpoints are versioned under
/api/v1. Every request must include:
Authorization: Bearer <token>— logintoken, or an API key (lbk_…)X-Lumi-Site: <siteId>— site identifier (or resolved via subdomain routing)
Response envelope
All responses follow this structure:
{
"data": <T>,
"meta": {
"total": 123,
"page": 1,
"pageSize": 50,
"filter_count": 50
}
}
Error response:
{
"errors": [
{
"code": "PERMISSION_DENIED",
"message": "You don't have permission to read field 'secret'.",
"path": ["fields", "secret"],
"extensions": { "reason": "field_policy" }
}
]
}
Error codes
| Code | HTTP | Description |
|---|---|---|
PERMISSION_DENIED | 403 | Policy check failed |
RECORD_NOT_FOUND | 404 | Item does not exist or not visible to this role |
VALIDATION_FAILED | 400 | Input schema validation error |
CONFLICT | 409 | Unique constraint violated |
RATE_LIMITED | 429 | Rate limit exceeded — honour Retry-After |
RATE_LIMIT_UNAVAILABLE | 503 | Rate limiter's backing cache is unavailable and the deployment runs the throttle in fail-closed mode (LUMIBASE_RATE_LIMIT_FAIL_CLOSED=true). Transient — retry with backoff. Not emitted in the default fail-open configuration |
SITE_NOT_FOUND | 404 | X-Lumi-Site header resolves to unknown tenant |
TOKEN_EXPIRED | 401 | JWT has expired — refresh and retry |
SKILL_DENIED | 403 | AI skill requires a capability the session lacks |
HITL_REQUIRED | 202 | Dangerous operation gated for human approval |
VALIDATION | 400 | Organization payload validation failed |
SCOPE_NOT_ALLOWED | 400 | Organization keys must be minted through the organization API |
ORGANIZATION_FORBIDDEN | 403 | Credential scope or organization role does not allow this action |
ORG_SIGNUP_DISABLED | 403 | Organization signup is disabled for this caller |
SITE_NOT_IN_ORGANIZATION | 403 | Selected site does not belong to the organization key |
ORGANIZATION_NOT_EMPTY | 409 | Organization must have no sites before deletion |
LAST_OWNER | 409 | At least one owner must remain |
REQUESTER_REVOKED | 409 | Requester no longer holds live organization authority |
APPROVAL_ALREADY_DECIDED | 409 | A conflicting approval decision is already committed |
Deprecation signalling. A retiring endpoint returns the IETF
DeprecationandSunsetresponse headers (RFC 8594) plus aLink rel="deprecation"to the changelog. Clients should log these and migrate before theSunsetdate. Seedocs/en/security/owasp-api-top-10-audit.md(API9).
Standard query parameters (list endpoints)
| Parameter | Example | Description |
|---|---|---|
fields | fields=id,title,author.name | Select specific fields + nested relations |
filter | filter[status][_eq]=published or filter={"status":{"_eq":"published"}} | Filter using rule operators — see Filter forms |
sort | sort=-updated_at,title | Comma-separated, - prefix for DESC |
page | page=2 | Page number (1-indexed) |
limit | limit=25 | Items per page (max 200) |
aggregate[count] | aggregate[count]=* | Aggregate functions |
groupBy | groupBy=status | Group aggregation results |
deep | deep[author][fields]=name,avatar | Nested relation query params |
Full-text search is a separate endpoint,
GET /api/v1/search(MeiliSearch), not a list-endpoint parameter. It supports single-collection and cross-collection (omitcollection) queries and is diacritics-insensitive for Vietnamese. See features/search.md.
Filter operators
| Operator | Description |
|---|---|
_eq | Equals |
_neq | Not equals |
_lt, _lte, _gt, _gte | Comparison |
_in, _nin | In / not in array |
_null, _nnull | Is null / not null |
_contains, _icontains | Contains (case-sensitive / insensitive) |
_starts_with, _ends_with | String prefix/suffix |
_between | Range (two-element array) |
_and, _or | Logical grouping |
_json_contains | JSONB @> — value/sub-object/array-membership containment |
_has_key | The JSON object has this key |
_has_any_keys, _has_all_keys | The JSON object has any / all of these keys (string array) |
_near, _within_bbox | geopoint fields: within { lat, lng, radius } metres / inside [minLng, minLat, maxLng, maxLat] — see Geopoint fields |
Searching inside JSON. A filter field key may be a dotted path into a
nested JSON/JSONB field — e.g. filter={"metadata.author.country":{"_eq":"VN"}}
compiles to a data #>> '{metadata,author,country}' lookup. Path segments are
restricted to [A-Za-z0-9_] and bound as parameters (injection-safe); depth is
capped at 8. The _json_contains / _has_* operators run against the JSONB and
use the existing GIN index. Top-level keys and structural fields behave exactly
as before.
Typed comparisons (Cast_Rule). Item values are stored as JSONB, so a naive
comparison is textual ('10' > '9' is false). _eq, _neq, _in, _nin,
_gt, _gte, _lt and _lte therefore cast both sides by type:
| Field / value | Comparison |
|---|---|
Top-level field of type integer, bigInteger, decimal, float | numeric |
Top-level field of type boolean | boolean |
Top-level field of type date, datetime, timestamp | timestamptz |
Nested path, json field or unknown key with a JSON number / boolean value | numeric / boolean, inferred from the value |
Anything else (string, text, uuid, string values on nested paths) | text, as before |
The stored side uses a guarded cast: a row whose value does not look like the
type (for example "n/a" in a decimal field) compares as NULL and drops
out, instead of failing the query. A filter value that cannot be cast (for
example {"price":{"_gt":"cheap"}}) is rejected with 400 INVALID_FILTER.
String operators (_contains, _starts_with, _ends_with) always compare text.
Sorting on a top-level numeric, boolean or date field uses the same cast, so
sort=-price orders numerically. Structural fields (id, status, sort,
created_at, …) keep their native column types.
GET /api/v1/items/products?filter={"price":{"_gt":10}}&sort=-price
GET /api/v1/items/products?filter={"metadata.rating":{"_gte":4.5}}
To make a typed filter on a hot path use an index, ask the index advisor for matching DDL.
Filter forms
List endpoints accept the filter query parameter in two equivalent forms — use
whichever is more convenient. Both produce the same filter object server-side.
1. Bracket form — ergonomic for hand-written URLs and HTML forms:
GET /api/v1/items/articles?filter[status][_eq]=published&filter[views][_gte]=100
- Nesting maps directly:
filter[field][_op]=value. - Values are coerced:
true/false→ boolean,null→ null, clean integers/decimals → number (leading-zero strings like007stay strings), everything else → string. - Array operators (
_in,_nin,_between) accept comma-separated values:filter[status][_in]=published,scheduled. - Logical groups use an index segment:
filter[_and][0][status][_eq]=published.
2. JSON form — better for complex/programmatic filters and the SDK:
GET /api/v1/items/articles?filter={"status":{"_eq":"published"}}
If both are supplied on the same request, the JSON form wins. A malformed JSON
filterreturns400 VALIDATION; a malformed bracket key is ignored rather than failing the whole request.
1. Auth
| Method | Path | Auth | Description |
|---|---|---|---|
POST | /api/v1/auth/login | public | Exchange Logto auth code or username/password for an access JWT + rotating refresh token |
POST | /api/v1/auth/register | public | Self-service subscriber sign-up (generic 202, anti-enumeration, rate-limited) |
POST | /api/v1/auth/verify-email | public | Activate a self-service account from the emailed token |
POST | /api/v1/auth/resend-verification | public | Re-send the activation email (generic 202, rate-limited) |
POST | /api/v1/auth/forgot-password | public | Email a password-reset link (generic 202, rate-limited) |
POST | /api/v1/auth/reset-password | public | Consume a reset token, set new password, revoke refresh tokens |
POST | /api/v1/auth/refresh | public | Rotate the refresh token (cookie or body) → fresh access JWT + new refresh token |
POST | /api/v1/auth/logout | public | Revoke the presented refresh token's family + clear the cookie |
POST | /api/v1/auth/verify-totp | public | Second leg of a two-step Studio login — exchange an MFA challenge token + TOTP (or recovery) code for a session |
GET | /api/v1/auth/me | bearer | Get current user profile |
GET | /api/v1/me/tfa | bearer | TOTP enrollment status ({ enabled, enrolledAt, recoveryCodesRemaining }) |
POST | /api/v1/me/tfa/setup | bearer | Begin enrollment (password step-up) → one-time secret + otpauthUrl |
POST | /api/v1/me/tfa/confirm | bearer | Confirm enrollment with a live code → single-use recovery codes |
POST | /api/v1/me/tfa/recovery-codes | bearer | Regenerate recovery codes (password + TOTP code) |
DELETE | /api/v1/me/tfa | bearer | Disable TOTP (password + either a TOTP code or a recovery code); revokes sessions and bumps tokenVersion |
POST | /api/v1/auth/passkey/options | public | Passkey authentication options: with challengeToken = second factor, without = passwordless staff sign-in → { ceremonyId, options } |
POST | /api/v1/auth/passkey/verify | public | Finish a passkey ceremony → same session payload as login (amr contains webauthn, tfaVerified) |
GET | /api/v1/me/passkeys | bearer | The caller's passkeys + recoveryCodesRemaining, totpEnabled, available |
POST | /api/v1/me/passkeys/registration-options | bearer | Begin passkey registration (password step-up) → { ceremonyId, options } |
POST | /api/v1/me/passkeys | bearer | Finish registration → { passkey, recoveryCodes } (codes only for a first factor) |
PATCH | /api/v1/me/passkeys/:id | bearer | Rename a passkey |
DELETE | /api/v1/me/passkeys/:id | bearer | Remove a passkey (password); the last second factor revokes sessions and bumps tokenVersion |
POST | /api/v1/me/passkeys/recovery-codes | bearer | Regenerate recovery codes (password + a passkey-opened session) |
POST | /api/v1/me/change-password | bearer | Verify current password, set new hash, revoke refresh tokens + bump tokenVersion |
GET | /api/v1/me/sessions | bearer | List the caller's active sessions (live refresh tokens, redacted) |
DELETE | /api/v1/me/sessions/:id | bearer | Revoke one of the caller's sessions |
DELETE | /api/v1/me/sessions | bearer | Revoke all of the caller's sessions; ?scope=others keeps the current session |
GET | /api/v1/me/security-history | bearer | The caller's own security events (sign-ins, new devices, password/MFA changes, revocations), redacted; ?cursor=&limit=&scope=site|account — see Security history |
GET | /api/v1/me/security-history/export | bearer | Download the same history; ?format=json|csv&scope= (max 5,000 rows, 10 exports / 15 min) |
GET | /api/v1/auth/social/providers | public | Social login providers enabled for the site |
POST | /api/v1/auth/social/:provider/start | public | Begin Google / Apple / GitHub sign-in (PKCE) → authorizationUrl |
GET/POST | /api/v1/auth/social/callback/:siteId/:provider | provider | Provider callback (POST = Apple form_post); redirects to the allow-listed URI with a one-time code |
POST | /api/v1/auth/social/exchange | public | Redeem the one-time code with the client codeVerifier → session (aud: frontend) |
GET | /api/v1/me/identities | bearer | Linked login identities + hasPassword |
POST | /api/v1/me/identities/:provider/link | bearer | Begin linking a provider to the signed-in account |
POST | /api/v1/me/identities/complete | bearer | Finish linking (one-time code + codeVerifier) |
DELETE | /api/v1/me/identities/:id | bearer | Unlink a provider (never the last login method) |
GET | /api/v1/admin/social-providers | site-admin | Per-site social provider configuration (secrets write-only) |
PUT/DELETE | /api/v1/admin/social-providers/:provider | site-admin | Configure / remove a provider — see Social login |
POST | /api/v1/users/subscriber-access | site-admin | Grant subscribers read on a collection (Policy DSL) |
GET/DELETE | /api/v1/users/subscriber-access[/:collection] | site-admin | List / revoke subscriber read grants |
GET | /api/v1/me/preferences | bearer | Current user's preferences blob (identity-global) |
PATCH | /api/v1/me/preferences | bearer | Shallow-merge a preferences patch |
GET | /api/v1/me/consents | bearer | List the current user's consent decisions |
PUT | /api/v1/me/consents/:type | bearer | Grant or withdraw a consent (GDPR Art. 7, PDPD) |
GET | /api/v1/me/data-export | bearer | Download the current user's personal data (GDPR Art. 15/20) |
GET | /api/v1/me/restriction | bearer | Current restriction-of-processing state (GDPR Art. 18) |
PUT | /api/v1/me/restriction | bearer | Set restriction of processing ({ restricted, reason? }) |
GET | /api/v1/me/automated-decisions | bearer | Agent-authored revisions on the user's content (GDPR Art. 22) |
GET | /api/v1/retention | admin | Report configured retention horizons |
POST | /api/v1/retention/run | admin | Prune activity + handled notifications past horizons |
Cookie-sourced /auth/refresh + /auth/logout require the
X-LumiBase-Refresh header (CSRF brake). Refresh tokens are delivered both
as an httpOnly cookie and in the response body; see
docs/en/security/user-management.md §4d for per-realm TTLs and the
cross-domain cookie env (REFRESH_COOKIE_SAMESITE/_DOMAIN/_SECURE).
Account erasure (GDPR Art. 17) and Subject Access Requests are served by the regulated-content-readiness feature at
/api/v1/admin/erasureand/api/v1/admin/sar.
Two-factor login (TOTP). Optional and per-user. When a user with TOTP
enrolled logs into the Studio realm, POST /api/v1/auth/login does not
return a session. It returns a challenge instead:
// POST /api/v1/auth/login → 200
{ "data": { "status": "mfa_required",
"challengeToken": "eyJ…", // aud: mfa-challenge, 5 min TTL
"expiresIn": 300 } }
// POST /api/v1/auth/verify-totp → 200 (same shape as a normal login)
{ "challengeToken": "eyJ…", "code": "123456" }
// …or, if the authenticator is lost:
{ "challengeToken": "eyJ…", "recoveryCode": "XXXX-XXXX-XXXX" }
The challenge token carries the mfa-challenge audience, so it cannot be
replayed as a session JWT, and its jti is single-use (tracked in the cache
provider). Verification is rate-limited per user and per IP. A successful
verify issues the access JWT with amr: ["pwd", "totp"]. Policy-driven
step-up (anomalyAction: 'require_mfa') uses the same challenge flow when the
user has TOTP enrolled, and still returns 401 MFA_REQUIRED when they do not.
Enrollment is a two-step, password-stepped-up flow: POST /me/tfa/setup
returns the base32 secret and otpauthUrl once (never re-readable), then
POST /me/tfa/confirm proves possession with a live code and returns eight
single-use recovery codes. The TOTP seed is persisted only as a KeyProvider
AEAD envelope, so enrollment requires ENCRYPTION_KEY in production;
recovery codes are stored as PBKDF2 hashes. Set LUMIBASE_TOTP_ISSUER to
control the label shown in authenticator apps (default LumiBase).
Key availability is reported explicitly rather than as a 500: setup returns
503 ENCRYPTION_NOT_CONFIGURED when the deployment has no active key, and
verify / regenerate return 409 TFA_KEY_UNAVAILABLE when the key that wrapped
that particular seed is no longer configured. In the latter case DELETE /me/tfa accepts a recovery code in place of a TOTP code, so the user can
remove an enrollment whose seed can no longer be decrypted. See
Encryption key operations.
Passkeys (WebAuthn). When the user also (or only) has passkeys, the
mfa_required response adds methods (["totp"], ["webauthn"] or both),
and the challenge can be finished with POST /auth/passkey/options +
POST /auth/passkey/verify instead of verify-totp. The same two endpoints
without a challengeToken give a passwordless staff sign-in. See
Passkeys.
Consent management (:type ∈ marketing · analytics · personalization · functional · sale_share):
// PUT /api/v1/me/consents/marketing
{ "granted": true, "source": "preference_center", "version": "v1" }
// Response
{ "data": { "consentType": "marketing", "granted": true,
"grantedAt": "2026-06-24T10:00:00.000Z", "withdrawnAt": null,
"source": "preference_center", "version": "v1",
"updatedAt": "2026-06-24T10:00:00.000Z" } }
Each change writes a consent_granted / consent_withdrawn audit event. Only user
principals (not API keys) can manage consent. Current state is stored per
(site_id, user_id, consent_type) in user_consents; full history lives in the audit log.
Email unsubscribe & suppression (CAN-SPAM):
| Method | Path | Auth | Description |
|---|---|---|---|
GET | /api/v1/email/unsubscribe?token=… | public | One-click unsubscribe (renders HTML confirmation) |
POST | /api/v1/email/unsubscribe | public | RFC 8058 one-click (token in query or form body) |
GET | /api/v1/email/suppressions | admin | List suppressed addresses |
POST | /api/v1/email/suppressions | admin | Add an address ({ email, reason? }) |
DELETE | /api/v1/email/suppressions/:email | admin | Remove an address (re-subscribe) |
The unsubscribe token is a stateless HS256 JWT ({ siteId, email }, no expiry) signed
with JWT_SECRET. Marketing sends (EmailModuleService.send({ category: 'marketing' }))
filter recipients against email_suppressions before dispatch. Unsubscribe/suppression
changes audit email_unsubscribed / email_suppressed / email_unsuppressed.
Preferences & save action. PATCH /api/v1/me/preferences shallow-merges a
validated patch into users.preferences (other sections like language /
keybindings are preserved). Send { "saveAction": "stay" | "return" | "create_new" } to set the Studio editor's post-save navigation; send
{ "saveAction": null } to fall back to the site default
(sites.default_save_action, set via PATCH /api/v1/site). Invalid enum → 400.
Email identity policy
users is identity-global (one row per human across sites), so the rule that
decides whether two addresses are the same account is set in two tiers. A
site can only be stricter than the instance, never looser.
| Method | Path | Auth | Description |
|---|---|---|---|
GET | /api/v1/admin/email-identity | site-admin | { instanceMode, siteStrict, effective } for the active site |
PUT | /api/v1/admin/email-identity/instance | bootstrap admin | Change the instance mode — body { mode: "exact" | "root", dryRun? } |
PUT | /api/v1/admin/email-identity/site | site-admin | Toggle per-site strict — body { strict: boolean, dryRun? } |
- Instance mode (
exactdefault,root).exactkeeps every distinct address as its own account.rootmakes one root mailbox one account instance-wide:+tagis stripped on every domain, and for Gmail the local part also loses its dots andgooglemail.comfolds togmail.com. Stripping+tagon every domain is a policy choice, not a guarantee that the alias reaches the same mailbox (sub-addressing is a provider convention). It is chosen in the Setup Wizard (emailIdentityModein thePOST /api/v1/setup/completebody; omitted →exact) and changed later only by the bootstrap admin — a user principal, never an API key (403 FORBIDDENotherwise). - Site strict (
falsedefault). Underexact, a strict site allows one membership per root mailbox, enforced by a unique index on(site_id, identity_key)rather than a check-then-insert. Underrootthe site flag is a no-op (effective: "root"). - Tightening (
exact → root,strict: false → true) first checks the existing data and answers409 IDENTITY_COLLISIONwith the colliding accounts — nothing changes. Loosening always succeeds.dryRun: trueruns the same transaction and rolls it back.
// PUT /api/v1/admin/email-identity/instance { "mode": "root" } → 409
{ "errors": [{ "code": "IDENTITY_COLLISION",
"message": "Existing accounts share a root mailbox; resolve them before tightening the policy.",
"collisions": [{ "root": "[email protected]",
"accounts": [{ "userId": "u_1", "email": "[email protected]" },
{ "userId": "u_2", "email": "[email protected]" }] }] }] }
// …after resolving the duplicates → 200
{ "data": { "previous": "exact", "current": "root", "changed": true, "dryRun": false } }
Every applied change writes an audit event (email_identity_mode_changed /
site_email_identity_changed). Effects on the other endpoints:
POST /api/v1/auth/registerkeeps the identical generic202when the address — or, underroot, any alias of it — already exists, or when a strict site already has a member with the same root mailbox. The account and its membership commit in one transaction, so a refused membership never leaves an orphan account.POST /api/v1/auth/login,/forgot-passwordand/resend-verificationresolve the account under the instance mode: underroot, any alias reaches the account. Lockout is tracked on the resolved account row, so rotating aliases does not reset or dodge it.POST /api/v1/users/invitelooks the account up case-insensitively (and by root mailbox underroot) and returns public fields only. Inviting an alias of an existing member of a strict site answers409 EMAIL_IDENTITY_CONFLICT.- SCIM (
/scim/v2/Users) answers409withscimType: "uniqueness"when the address resolves to an existing account or collides on a strict site.
External JWT authentication
A site can trust JWTs issued by an external IdP (Okta, Entra, Auth0, Logto,
Keycloak, Cloudflare Access…). Present the token as Authorization: Bearer <jwt> with X-Lumi-Site. The auth chain verifies it against the issuer's
public JWKS (between the API-key and internal-JWT branches): it matches the
token's iss to a trusted issuer registered for that site, verifies the
signature + aud/exp/nbf with the issuer's allowed (asymmetric-only)
algorithms, maps role claims to LumiBase roles (default-deny — no mapping
means 403, never implicit admin), enforces that any siteId claim equals the
request site, and optionally JIT-provisions the user. A token whose iss isn't
trusted is ignored (falls through to internal auth); once an issuer matches,
verification is fail-closed.
Admin CRUD for trusted issuers (admin-only):
| Method | Path | Description |
|---|---|---|
GET | /api/v1/admin/auth/issuers | List trusted external issuers |
POST | /api/v1/admin/auth/issuers | Register an issuer |
GET | /api/v1/admin/auth/issuers/:id | Get one |
PATCH | /api/v1/admin/auth/issuers/:id | Update |
DELETE | /api/v1/admin/auth/issuers/:id | Remove |
Issuer config: { issuer, jwksUri | discoveryUrl, audience, algorithms (RS*/ES* only), claimMapping: { email, roles, siteId?, externalId? }, roleMapping: { "<claim role>": { roleId | systemKey } }, defaultRoleId?, jitProvisioning, clockSkewSeconds (≤300), enabled }. Errors: VALIDATION_FAILED (422, incl. an
HS*/none algorithm), ISSUER_ALREADY_EXISTS (409), NOT_FOUND (404).
Login request:
{
"email": "[email protected]",
"password": "your-password"
}
Login response: a single bearer token plus the user profile. Send the token as
Authorization: Bearer <token> on subsequent requests.
{
"data": {
"token": "eyJ...",
"user": {
"id": "usr_abc123",
"email": "[email protected]",
"firstName": "Admin",
"lastName": "User",
"avatar": null
}
}
}
For long-lived server-to-server access, create an API key (
POST /api/v1/api-keys, token prefixlbk_) instead of using a login token.
1b. Organizations (ADR-013)
Organization requests use the authenticated identity and the target organization, without X-Lumi-Site. An organization key (lbo_) is bound to one organization and has its fixed admin role, except that it cannot change who holds authority: PATCH /orgs/:orgId, member writes and organization-key writes require a user session and return 403 ORGANIZATION_FORBIDDEN to a key. A key requests those changes through organization MCP, where a human approves them. Staff identities use current organization membership. Site keys (lbk_), publishable keys (lbk_pub_), and frontend sessions cannot enter this plane. Missing membership or a resource outside the selected organization returns 404 NOT_FOUND.
| Method | Endpoint | Authority / payload |
|---|---|---|
GET | /api/v1/orgs | List the caller's organizations; an organization key returns exactly its organization |
POST | /api/v1/orgs | Bootstrap operator, or Studio user with LUMIBASE_ALLOW_ORG_SIGNUP=true; { name, slug }; caller becomes owner |
GET | /api/v1/orgs/:orgId | org:read; includes the caller's role |
PATCH | /api/v1/orgs/:orgId | org:settings:write; { name?, slug?, settings? }; only owner can change slug |
DELETE | /api/v1/orgs/:orgId | Owner; X-Confirm-Delete: <orgId>; organization must have no sites |
GET | /api/v1/orgs/:orgId/sites | org:read |
POST | /api/v1/orgs/:orgId/sites | org:sites:create; { name, id?, slug? }; id and slug must agree if both supplied |
DELETE | /api/v1/orgs/:orgId/sites/:siteId | Owner; X-Confirm-Delete: <siteId> |
POST | /api/v1/orgs/:orgId/sites/:siteId/transfer | The same human must own both organizations; { toOrganizationId } |
GET | /api/v1/orgs/:orgId/members | org:read |
POST | /api/v1/orgs/:orgId/members | org:members:manage; { userId?, email?, role }; exactly one identity field |
PATCH | /api/v1/orgs/:orgId/members/:userId | org:members:manage; { role } |
DELETE | /api/v1/orgs/:orgId/members/:userId | org:members:manage |
GET | /api/v1/orgs/:orgId/keys | org:read; metadata only |
POST | /api/v1/orgs/:orgId/keys | org:keys:manage; { name, description?, expiresAt? }; plaintext returned at creation |
POST | /api/v1/orgs/:orgId/keys/:keyId/rotate | org:keys:manage; old token stops working; plaintext returned at rotation |
DELETE | /api/v1/orgs/:orgId/keys/:keyId | org:keys:manage; revoke the key |
GET | /api/v1/orgs/:orgId/approvals | Human owner/admin only; summaries omit result secrets |
GET | /api/v1/orgs/:orgId/approvals/:approvalId | Human owner/admin only; a minted key is never stored or returned again (tokenRedacted: true) |
POST | /api/v1/orgs/:orgId/approvals/:approvalId/decide | Human owner/admin; { decision: "approved" } / { decision: "rejected" }; operation-specific owner checks still apply; approving org:create_org_key returns the plaintext key in this response only |
Create operations return 201, other successful operations return 200, using the standard data envelope. Organization roles are owner, admin, billing, and member. Admins cannot add/change/remove owners; the final owner cannot be removed or demoted. Owner/admin inherit site administrator authority on owned sites; billing/member do not. Organization keys are always admin and can never execute owner-only operations themselves. A member email that has no identity creates an invited identity; organization membership is separate from the staff account activation flow.
Site creation uses the same provisioning as setup. settings replaces the settings object when supplied, so preserve unrelated fields. Slug default can be renamed by its owner and is then available again. POST /api/v1/api-keys remains site-scoped and rejects scope="organization"; an organization key may mint site keys only for sites in its organization.
Organization MCP approvals
Organization MCP is off until settings.contentOs.mcp.allowOrganizationTools=true; LUMIBASE_MCP_ORG_TOOLS=off overrides it. Every organization mutation creates a pending approval with a real organization parent. confirm=true cannot approve it, and no REST fallback exists for these MCP tools. The agent receives pending_approval, approvalId, organizationId, and a run id; it never receives a newly minted organization key.
Approval rechecks live requester access and the human decider's authority. Execution and the receipt commit atomically. Repeating the same decision returns the existing receipt; a conflicting decision returns 409 APPROVAL_ALREADY_DECIDED. A revoked requester cannot be approved (409 REQUESTER_REVOKED), but can be rejected. Deleting a transfer destination does not prevent rejecting its pending request or replaying an already committed receipt. Pending transfer execution still requires both organizations and their human owner. Disabling MCP blocks approval (403 MCP_DISABLED) without blocking rejection. Discovery with MCP disabled returns 404 MCP_DISABLED. See Organization settings and MCP.
Organization errors additionally include 400 VALIDATION, 400 SCOPE_NOT_ALLOWED, 403 ORGANIZATION_FORBIDDEN, 403 ORG_SIGNUP_DISABLED, 403 SITE_NOT_IN_ORGANIZATION, 404 NOT_FOUND, 409 LAST_OWNER, 409 ORGANIZATION_NOT_EMPTY, and 409 CONFLICT.
2. Schema Admin
Collections
| Method | Path | Description |
|---|---|---|
GET | /api/v1/collections | List all collections |
POST | /api/v1/collections | Create a new collection |
GET | /api/v1/collections/:name | Get collection detail |
PATCH | /api/v1/collections/:name | Update collection meta (display name, icon, note) |
DELETE | /api/v1/collections/:name | Soft-delete collection |
GET | /api/v1/collections/:name/schema | Export collection schema as JSON |
PUT | /api/v1/collections/:name/schema | Apply schema (idempotent, diff-aware) |
POST | /api/v1/collections/diff | Compare bundle schema vs current |
GET | /api/v1/collections/:name/index-advice?path=&cast= | JSON path index advisor (read-only, schema:read) |
GET | /api/v1/collections/:name/form-layout | Item form layout: tabs, groups, dividers, conditions (schema:read); see Form layout |
PUT | /api/v1/collections/:name/form-layout | Replace (or with null remove) the form layout (schema:update) |
Create collection request:
{
"name": "articles",
"displayName": "Articles",
"icon": "article",
"note": "Blog articles",
"singleton": false,
"status_field": "status",
"sort_field": "sort"
}
JSON path index advisor
GET /api/v1/collections/:name/index-advice?path=<dot.path>[&cast=numeric|boolean|timestamp|text]
returns CREATE INDEX DDL whose expression matches exactly what the filter
builder emits for that path and cast, so Postgres can use it for typed
_eq/_in/range filters. The index is partial on the collection
(WHERE collection_id = … AND deleted_at IS NULL). cast defaults to the
declared type of a top-level field; it is required for nested or json paths.
The endpoint never runs the DDL: an operator reviews it and runs it outside a
transaction (CONCURRENTLY). timestamp returns ddl: null, because
timestamptz casts are not IMMUTABLE and Postgres refuses to index them.
{
"data": {
"path": "price",
"cast": "numeric",
"indexName": "items_products_price_numeric_idx",
"expression": "(case when (data ->> 'price') ~ '…' then (data ->> 'price')::numeric end)",
"ddl": "CREATE INDEX CONCURRENTLY IF NOT EXISTS items_products_price_numeric_idx ON lumibase_items ((…)) WHERE collection_id = '…' AND deleted_at IS NULL;",
"notes": ["Run outside a transaction (CONCURRENTLY).", "…"]
}
}
Errors: 400 VALIDATION (missing/invalid path, unknown cast, or no cast
for a nested path), 404 NOT_FOUND (collection or top-level field).
Fields
| Method | Path | Description |
|---|---|---|
GET | /api/v1/fields/:collection | List fields in a collection |
POST | /api/v1/fields/:collection | Add a field |
GET | /api/v1/fields/:collection/:field | Get field detail |
PATCH | /api/v1/fields/:collection/:field | Update field config |
DELETE | /api/v1/fields/:collection/:field | Remove field |
Create field request:
{
"field": "title",
"type": "string",
"interface": "input",
"display": "raw",
"options": { "placeholder": "Article title" },
"required": true,
"sort": 1
}
Relations
| Method | Path | Description |
|---|---|---|
GET | /api/v1/relations | List all relations |
POST | /api/v1/relations | Create relation |
PATCH | /api/v1/relations/:id | Update relation |
DELETE | /api/v1/relations/:id | Remove relation |
Code-First Configuration (Config Manifest)
Export / diff / apply a site's schema configuration — collections, fields,
relations, settings and webhooks — as a single declarative, version-controllable
JSON manifest (lumibase.config@v1). Built for CI/CD and environment sync (à la
Directus schema snapshot/apply). Admin-only. Does not include content
items, secrets, or access control (use /api/v1/access/* for the latter).
| Method | Path | Description |
|---|---|---|
GET | /api/v1/config/export?scope=all|schema|settings|webhooks | Export the config manifest |
POST | /api/v1/config/import?dryRun=true&mode=<mode> | Validate + diff a manifest (no write) |
POST | /api/v1/config/import?mode=<mode>&allowDestructive=true | Apply a manifest in one transaction |
mode ∈ merge (create/update only — never deletes), replace-managed (also
deletes resources within the manifest's managedScopes), replace-all (full
sync — deletes anything absent from the manifest). High-risk destructive changes
(dropping a collection/field with data, changing a field type, widening a
relation's onDelete to cascade) are rejected unless allowDestructive=true.
Export response ({ data: ConfigManifest }):
{
"data": {
"version": "lumibase.config@v1",
"exportedAt": "2026-06-22T00:00:00.000Z",
"collections": [{ "name": "articles", "label": "Articles", "versioning": true }],
"fields": [{ "collection": "articles", "field": "title", "type": "string", "interface": "input" }],
"relations": [],
"webhooks": [],
"settings": [{ "key": "login_security_policy", "value": { } }],
"managedScopes": ["articles"]
}
}
Dry-run / apply response ({ data: { valid, errors, diff, applied? } }): the
diff lists per-resource create | update | unchanged | delete counts and a
top-level risk (low | medium | high). On apply, applied reports
{ created, updated, deleted }. Validation errors use codes
UNSUPPORTED_MANIFEST_VERSION, DANGLING_REFERENCE, DUPLICATE_KEY; a blocked
destructive apply returns HTTP 409 DESTRUCTIVE_BLOCKED.
CLI: pnpm --filter @lumibase/cms config export|diff|apply — see
docs/en/contributing/code-first-config.md.
3a. Pages (Delivery page-builder rows)
Studio-authenticated CRUD over lumibase_pages (consumed by
GET /api/v1/deliver/page/:site_id/:slug). Create and slug rename clear
matching negative-cache tombstones immediately.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/pages | List pages for the active site |
POST | /api/v1/pages | Create { slug, title, layoutConfig? } |
GET | /api/v1/pages/:id | Get one page |
PATCH | /api/v1/pages/:id | Partial update (slug / title / layoutConfig) |
DELETE | /api/v1/pages/:id | Delete page |
Slug shape matches the Delivery guard (^[a-z0-9]+(?:[/_-][a-z0-9]+)*$, ≤200).
Admin cache purge (control-plane): POST /api/v1/utils/cache/purge with
{ tags?: string[], keys?: string[] } — every tag/key must include the
active siteId.
3. Items (Generic CRUD)
| Method | Path | Description |
|---|---|---|
GET | /api/v1/items/:collection | List items (paginated, filterable) |
POST | /api/v1/items/:collection | Create item (or array for bulk) |
GET | /api/v1/items/:collection/export | Stream the collection as CSV or JSON (Data export) |
GET | /api/v1/items/:collection/:id | Get single item |
PATCH | /api/v1/items/:collection/:id | Partial update |
PUT | /api/v1/items/:collection/:id | Full replace |
DELETE | /api/v1/items/:collection/:id | Delete item — 409 if blocked by dependents |
GET | /api/v1/items/:collection/:id/dependents | List records that reference this item |
POST | /api/v1/items/:collection/:id/resolve-dependents | Batch-resolve a relation's dependents |
POST | /api/v1/items/:collection/:id/move | Move an item and its subtree in a tree collection; list with ?tree=children|subtree|ancestors (Hierarchical collections) |
GET | /api/v1/items/:collection/:id/revisions | List revisions |
POST | /api/v1/items/:collection/:id/revert | Revert to revision |
GET | /api/v1/items/:collection/:id/versions | List named draft versions (each has a mainChanged flag) |
POST | /api/v1/items/:collection/:id/versions | Create a version { key, name } (snapshots current main) |
GET | /api/v1/items/:collection/:id/versions/:key | Get a version |
PATCH | /api/v1/items/:collection/:id/versions/:key | Update a version { data?, name? } (does not touch main) |
DELETE | /api/v1/items/:collection/:id/versions/:key | Delete a version |
GET | /api/v1/items/:collection/:id/versions/:key/compare | Field diff vs main → { main, version, changes } |
POST | /api/v1/items/:collection/:id/versions/:key/promote | Apply version to main (writes a revision); meta.mainDiverged |
Dependent records. Because item references live in JSONB (not physical FK
columns), a relation's onDelete is enforced in the application layer. On
DELETE, if a relation declared restrict still has records pointing at the
item, the delete is blocked with 409 DEPENDENT_RECORDS_EXIST and a
dependents array. (set null/cascade are not auto-applied on
soft-delete — that would break soft-delete's recoverability; the editor clears
them explicitly.) GET …/dependents returns
{ data: { blocking, dependents: [{ relation, collection, field, onDelete, count, sample }] } }. POST …/resolve-dependents takes
{ action: "set_null"|"delete"|"reassign", relation, newTargetId?, hard? } and
runs transactionally (delete delegates to the normal item-delete path).
Errors: DEPENDENT_RECORDS_EXIST (409), FIELD_REQUIRED (409, set_null on a
required field), INVALID_TARGET (422, reassign), NOT_FOUND (404).
Export. GET /items/:collection/export?format=csv|json&fields=&locales=&relations=id|slug|embed&filter=&sort=&status=
streams every matching row (keyset-paged, so any size). It uses the caller's
read permission and the list filter/sort syntax, runs the extensions'
items.export.before hook per row, and writes an items_exported audit entry.
CSV writes one field.locale column per locale of a translatable field and
neutralises spreadsheet formulas; JSON is
{ collection, format: "lumibase-export@1", exportedAt, fields, locales, relations, items: [{ id, status, sort, created_at, updated_at, data }] }.
Errors before streaming: 400 VALIDATION / 400 UNKNOWN_FIELD / 400 INVALID_FILTER,
403 FORBIDDEN, 404 NOT_FOUND. See Data export.
Imports. Background jobs that read the export formats back:
| Method | Path | Description |
|---|---|---|
POST | /api/v1/imports?collection=&format=csv|json&mode=create|upsert | Upload a file (multipart file or raw body) → 202 { data: job } |
GET | /api/v1/imports?collection=&status=&limit= | Recent jobs (own; site admins see all) |
GET | /api/v1/imports/:id | Job progress and counters |
GET | /api/v1/imports/:id/errors | Row errors; ?format=csv downloads them |
POST | /api/v1/imports/:id/cancel | Stop a queued or running job |
Bad files fail with 400 VALIDATION / 413 PAYLOAD_TOO_LARGE before a job is
created; missing create (or update for upsert) permission is 403. See
Data import.
List pagination & totals. GET /items/:collection accepts limit
(1–200, default 25), offset, and meta:
meta=total_count(default) — response is{ data, meta: { total, limit, offset } }.meta=none— skips thecount(*)aggregate for a cheaper query; response is{ data, meta: { limit, offset } }(nototal). Use for infinite-scroll / feed views that never render a total page count.
The default is unchanged, so existing clients keep receiving meta.total.
The @lumibase/sdk readItems accepts the same meta option.
Optional headers:
X-Lumi-Draft: true— fetch draft versionX-Lumi-Locale: vi— apply translation server-side
Create item:
{ "title": "Hello World", "status": "draft", "author": "usr_abc123" }
Bulk create (array body):
[
{ "title": "Article 1", "status": "published" },
{ "title": "Article 2", "status": "draft" }
]
3b. Content Releases
A Release collates specific item revisions across collections into a named bundle that publishes all at once — manually or scheduled for a date/time (à la Directus Releases). Publish delegates to the item update path, so the editorial gate, validation, permissions and hooks all apply.
| Method | Path | Description |
|---|---|---|
POST | /api/v1/releases | Create a release (draft, or scheduled if publishAt set) |
GET | /api/v1/releases | List releases (?status=&page=&limit=) |
GET | /api/v1/releases/:id | Release detail + its items |
PATCH | /api/v1/releases/:id | Update meta, addItems/removeItems, set publishAt |
POST | /api/v1/releases/:id/publish | Publish now (manual) |
DELETE | /api/v1/releases/:id | Delete release (items cascade) |
Create / patch body:
{
"name": "Spring launch",
"atomicityMode": "all_or_nothing",
"publishAt": "2026-07-01T09:00:00Z",
"maintenanceWindow": { "windows": [{ "dow": 1, "start": "09:00", "end": "17:00" }] },
"addItems": [
{ "collection": "articles", "itemId": "itm_1", "targetStatus": "published", "revisionId": "rev_3" }
]
}
atomicityMode: all_or_nothing (pre-flight checks every item is publishable —
exists, not deleted, editorial gate satisfiable — and publishes nothing if any
is blocked) or best_effort (publishes each independently, recording a per-item
outcome). revisionId pins a specific revision's snapshot; omit it to publish
the item's live state at publish time.
Publish response ({ data: { release, status, outcomes } }): status is
published | partially_failed | failed; each outcome is
{ collection, itemId, outcome: 'published'|'skipped'|'failed', reason? }. A
partial/failed publish still returns HTTP 200 with the outcomes.
Error codes: EMPTY_RELEASE (422), ALREADY_PUBLISHED (409),
RELEASE_IMMUTABLE (409, editing a published release's items), ITEM_NOT_FOUND
(404), REVISION_STAGED (409, pinning an uncommitted revision),
VALIDATION_FAILED (422, incl. publishAt in the past). Per-item publish
blockers surface as outcome reasons EDITORIAL_GATE_REQUIRED / ITEM_DELETED.
Scheduled releases publish via the shared content-scheduler tick
(sweepDueReleases) — idempotent and maintenanceWindow-aware.
4. Permissions, Roles & Policies
| Method | Path | Description |
|---|---|---|
GET | /api/v1/permissions/me | Effective permission matrix for current user |
POST | /api/v1/permissions/check | Debug: evaluate a policy rule |
GET/POST/PATCH/DELETE | /api/v1/roles | Role CRUD |
GET/POST/PATCH/DELETE | /api/v1/policies | Policy CRUD |
GET/POST/DELETE | /api/v1/policies/:id/permissions | Permission rules in a policy |
POST | /api/v1/policies/:id/attach | Attach policy to a role, user, or team |
Permission rule shape:
{
"collection": "articles",
"action": "read",
"fields": ["id", "title", "status"],
"conditions": { "status": { "_eq": "published" } }
}
5. Users & Teams
| Method | Path | Description |
|---|---|---|
GET/POST | /api/v1/users | List / create users |
GET/PATCH/DELETE | /api/v1/users/:id | Get / update / delete user |
POST | /api/v1/users/invite | Send invitation email |
POST | /api/v1/users/:id/impersonate | Impersonate (admin only) |
GET | /api/v1/users/:id/sessions | List active sessions |
DELETE | /api/v1/sessions/:id | Revoke a session |
GET/POST/PATCH/DELETE | /api/v1/teams | Team CRUD |
6. Files & Assets
| Method | Path | Description |
|---|---|---|
POST | /api/v1/files/presigned-url | Get presigned R2/S3 PUT URL |
POST | /api/v1/files | Register file metadata after upload |
GET | /api/v1/files | List files (filterable) |
GET | /api/v1/files/:id | File metadata |
PATCH | /api/v1/files/:id | Update metadata (title, tags, folder) |
DELETE | /api/v1/files/:id | Delete file |
GET | /api/v1/assets/:id | Serve/transform image (query params below) |
POST | /api/v1/media/:key | Upload raw media bytes (RBAC media:create; upload guard applies) |
GET | /api/v1/media/:key | Download media (served as attachment + nosniff); with transform params → 302 to derivative |
DELETE | /api/v1/media/:key | Delete media object |
GET | /api/v1/transform-presets | List named image-transform presets (RBAC media:read) |
POST | /api/v1/transform-presets | Create a preset { key, name, dsl } (RBAC media:create) |
PATCH | /api/v1/transform-presets/:id | Update a preset (RBAC media:update) |
DELETE | /api/v1/transform-presets/:id | Delete a preset (RBAC media:delete) |
GET | /api/v1/uploads/config | Effective upload policy + type catalogue (any member) |
PUT | /api/v1/uploads/config | Update allowlist / size cap (site admin) |
Image transform DSL (/api/v1/media/:key and /api/v1/assets/:id):
?width=800&height=600&format=webp&quality=80&fit=cover&focal=0.5,0.5
?preset=thumbnail
On /media/:key, transform params are validated against transformDslSchema
(@lumibase/contracts; MAX_DIM=5000) and the request 302-redirects to the runtime
image URL (CF Image Resizing / Imgproxy). No params → the original bytes.
?preset=<key> resolves a saved transform_presets row for the site. See
.kiro/specs/image-transform-dsl.
Upload policy (/api/v1/uploads/config). Enforced by the file-upload-policy
guard on every upload surface (POST /api/v1/files, PUT /api/v1/files/upload/:key,
POST /api/v1/media/:key): a public role cannot upload; the body is size-capped on
its true byte length; the declared MIME must be in the allowlist and match the
filename extension; raw bytes are content-sniffed (magic bytes) and executables /
active-content SVGs are rejected; raster images are scanned for an embedded
script/executable payload (polyglot) and rejected. The allowlist + cap resolve
per-site DB (settings key upload_policy) → env (FILE_UPLOAD_*) → default. See
the feature spec .kiro/specs/upload-file-controls/ and
docs/en/security/runtime-security-guards-plan.md §3 for the full guarantees.
GET /api/v1/uploads/config
→ { data: { maxBytes, allowedMimeTypes[], allowedExtensions[], catalogue[] } }
PUT /api/v1/uploads/config # site admin only
{ "maxBytes": 5242880, "allowedMimeTypes": ["image/png","image/jpeg"] }
6b. View presets (collection views + bookmarks)
| Method | Path | Description |
|---|---|---|
GET | /api/v1/presets/effective?collection= | Effective default view (precedence user > role-chain > global), with sourceScope |
GET | /api/v1/presets/bookmarks?collection= | Named bookmarks visible to the principal, each with sourceScope |
GET | /api/v1/presets | List presets (optional ?collection=) |
POST | /api/v1/presets | Create a preset/bookmark; user-scope self-managed, role/global require admin |
PATCH | /api/v1/presets/:id | Update (authorized against the row's current scope) |
DELETE | /api/v1/presets/:id | Delete (user owns own; role/global require admin) |
Scope is derived from ownership columns: userId set → user, roleId set →
role, neither → global. Role presets inherit down the roles.parentId chain.
See .kiro/specs/presets-inheritance.
6c. Translation memory
| Method | Path | Description |
|---|---|---|
GET | /api/v1/tm?source=&target=&entrySource=&limit=&offset= | List TM entries (paginated; meta { total, limit, offset }) |
POST | /api/v1/tm | Upsert an entry |
PATCH | /api/v1/tm/:id | Edit target/quality/source (siteId-scoped, 404 cross-tenant) |
DELETE | /api/v1/tm/:id | Delete an entry (siteId-scoped) |
POST | /api/v1/tm/lookup | Best fuzzy match { query, sourceLang, targetLang, threshold? } → { match } |
POST | /api/v1/tm/translate | MT pipeline { text, from, to } (TM → glossary → provider) |
TM_DEFAULT_THRESHOLD = 75 (@lumibase/contracts). Learn-TM (Studio) upserts
human translations on save when translations.learnTm is enabled.
See .kiro/specs/translation-memory-ui.
7. Flows / Automation
| Method | Path | Description |
|---|---|---|
GET | /api/v1/flows/operations | Registered operation keys + option hints (editor palette / validateGraph knownKeys) |
GET | /api/v1/flows | List flows (filter by status, trigger) |
POST | /api/v1/flows | Create a new flow (validates graph when active; schedule flows require a valid cron) |
GET | /api/v1/flows/:id | Get flow detail + graph |
PATCH | /api/v1/flows/:id | Update flow (graph, status, options) |
DELETE | /api/v1/flows/:id | Delete flow |
POST | /api/v1/flows/:id/run | Manual trigger with body as input |
POST | /api/v1/flows/:id/trigger | Webhook trigger — no CMS session; authenticate with the per-flow token (x-flow-token header or Bearer), compared constant-time. Input = { body, headers, query } (credential headers stripped). 404 for non-webhook/inactive flows; 401 WEBHOOK_NOT_CONFIGURED/UNAUTHENTICATED |
GET | /api/v1/flows/:id/runs | Execution history |
GET | /api/v1/flows/:id/runs/:runId | Single run detail (steps output) |
Save-time gates: an active flow must pass the shared graph validation — 400 with GRAPH_DANGLING_EDGE / GRAPH_CYCLE / GRAPH_NO_ENTRY / GRAPH_UNKNOWN_OPERATION (+ nodeId) otherwise; drafts may hold invalid work-in-progress. Schedule flows validate triggerOptions.cron (5-field, UTC): 400 CRON_INVALID on a malformed expression, 400 CRON_REQUIRED when activating without one; next_run_at is computed on save and advanced by the scheduler sweep before each enqueued run (idempotent).
Triggers: event flows fire on item create/update/delete via the flow-events queue (triggerOptions.collection / .action filter, string or array, missing = all); schedule flows are swept every scheduler tick; webhook flows use the endpoint above; manual runs inline via /run.
Trigger a flow:
POST /api/v1/flows/flw_abc123/run
Content-Type: application/json
Authorization: Bearer <token>
{ "userId": "usr_xyz", "action": "welcome" }
Response:
{
"data": {
"runId": "run_def456",
"status": "running",
"startedAt": "2026-06-07T00:00:00Z"
}
}
7c. Deployments
Per-site deployment targets (Vercel / Netlify), manual deploy triggers, build
status and logs (spec deployment-integrations), plus environments, promotion and
deploy approvals (#743, see docs/en/features/deployment-environments.md). Every
route except the inbound webhook needs a site admin or a deploy:* capability
(lumibase_deploy:<scope> permission rows): 400 TENANT_REQUIRED without a
resolved site, 403 FORBIDDEN without either. Target create/update/delete,
PUT /environments and GET /:id/logs stay site-admin only (requireSiteAdmin).
Provider tokens are encrypted
on write and never returned. Bodies are validated with
DeploymentTargetCreateSchema / DeploymentTargetUpdateSchema /
DeployTriggerSchema (@lumibase/contracts); a failed parse returns
400 VALIDATION. 400 UNKNOWN_PROVIDER means the stored target names a
provider that is not registered in this deployment (only vercel and netlify
are).
| Method | Path | Description |
|---|---|---|
GET | /api/v1/deployments/targets | List targets for the site (token columns omitted) |
POST | /api/v1/deployments/targets | Create { provider (vercel|netlify), name, projectId, token, defaultBranch?, productionUrl? } → 201. The token is verified against the provider before anything is stored: 400 TOKEN_INVALID |
PATCH | /api/v1/deployments/targets/:id | Update { name?, projectId?, token?, defaultBranch?, productionUrl?, status? (active|inactive) }. A token is re-verified and re-encrypted (rotation). 404 NOT_FOUND, 400 TOKEN_INVALID, 400 UNKNOWN_PROVIDER (only when a token is sent) |
DELETE | /api/v1/deployments/targets/:id | Delete a target (its deployments cascade) → { data: null }. 404 NOT_FOUND |
POST | /api/v1/deployments/targets/:id/deploy | Trigger a build { branch?, reason? } → 201 with the new deployment row (triggerSource: "manual"). Needs deploy:trigger:<targetId>, deploy:trigger:<env> of an environment containing it, or deploy:trigger:*; when one of those environments has requiresApproval the response is 202 { data: { status: "pending_approval", environment, approval } } and nothing is dispatched. 403 FORBIDDEN, 404 NOT_FOUND, 400 TARGET_INACTIVE, 400 UNKNOWN_PROVIDER, 429 RATE_LIMITED, 502 TRIGGER_FAILED (provider call failed; an error row is still recorded) |
GET | /api/v1/deployments | List deployments, newest first (createdAt descending, id descending as tie-breaker). Filter ?targetId=&status=&limit=. limit must be a non-negative integer: it defaults to 50 when absent or empty, 0 returns an empty list, and values above 200 are capped at 200. Any other value (abc, -5, 1.5) returns 400 VALIDATION. No meta |
GET | /api/v1/deployments/:id | Get one deployment. 404 NOT_FOUND |
GET | /api/v1/deployments/:id/logs | Fetch the build log from the provider, secrets masked → { data: { log } }. 404 NOT_FOUND when the deployment does not exist or has no provider id yet, 400 UNKNOWN_PROVIDER when its target or provider is unavailable |
POST | /api/v1/deployments/:id/refresh | Force a status sync from the provider (no-op once the status is terminal). 404 NOT_FOUND when the deployment does not exist. With no provider id yet, or with an unavailable target or provider, the row is returned unchanged (200, never UNKNOWN_PROVIDER) |
GET | /api/v1/deployments/access | The caller's { admin, capabilities, humanDecider, environments: [{ key, canTrigger, canApprove }] } |
GET | /api/v1/deployments/environments | The environment map (settings key deployment.environments, defaults preview / staging → production / production with requiresApproval). 500 ENVIRONMENTS_INVALID when the stored map does not validate |
PUT | /api/v1/deployments/environments | Site admin. Replace the map { environments: [{ key, name, targetIds, requiresApproval, promotesTo }] } (DeploymentEnvironmentsUpdateSchema). 400 VALIDATION (duplicate key, unknown promotesTo), 400 UNKNOWN_TARGET |
POST | /api/v1/deployments/environments/:key/deploy | Deploy every target of the environment { branch?, reason? }. Needs deploy:trigger:<key> (or on every target, or *). 201 { data: { status: "dispatched", environment, results: [{ targetId, ok, deployment, error? }] } }, or 202 { data: { status: "pending_approval", environment, approval } } when requiresApproval. 403 FORBIDDEN, 404 ENVIRONMENT_NOT_FOUND, 409 NO_TARGETS |
POST | /api/v1/deployments/environments/:key/promote | Promote the environment's newest ready deployment (or { deploymentId }) into its promotesTo environment { deploymentId?, reason? }; same build where the provider can promote, else the same commit re-triggered. Needs the trigger grant on the destination. 201 / 202 as above. 404 NOT_FOUND (deployment not in the environment), 409 NO_PROMOTION_TARGET, 409 SOURCE_NOT_READY |
GET | /api/v1/deployments/approvals | Deploy approvals, newest first, default ?status=pending (status=all for every status), each with canDecide for the caller |
POST | /api/v1/deployments/approvals/:id/decide | { decision: "approved" | "rejected", reason? } (DeployApprovalDecisionSchema). Approve needs a signed-in person, not the requester, holding deploy:approve:<env> or deploy:approve:*; the requester may reject (withdraw) their own. 403 HUMAN_APPROVER_REQUIRED / SELF_APPROVAL_FORBIDDEN / FORBIDDEN, 404 NOT_FOUND, 409 APPROVAL_ALREADY_DECIDED / APPROVAL_EXPIRED / REQUESTER_REVOKED / PLAN_STALE |
Public (no session; signature-verified):
| Method | Path | Description |
|---|---|---|
POST | /api/v1/deployments/webhook/:provider/:siteId | Inbound status webhook (vercel | netlify) with path tenant (works on the shared API host without X-Lumi-Site). 404 UNKNOWN_PROVIDER, 400 TENANT_INVALID / TENANT_MISMATCH, 401 INVALID_SIGNATURE; otherwise 200 { data: null }, including when the body matches no deployment |
POST | /api/v1/deployments/webhook/:provider | Inbound status webhook (vercel | netlify). Tenant comes from withTenant (X-Lumi-Site or host mapping). 404 UNKNOWN_PROVIDER, 401 INVALID_SIGNATURE; otherwise 200 { data: null }, including when the body matches no deployment |
Target shape (data of the target routes): { id, provider, name, projectId, defaultBranch, productionUrl, status, createdAt, updatedAt }.
Deployment shape (data of the deployment routes and the trigger): { id, siteId, targetId, provider, providerDeploymentId, status (queued|building|ready|error|canceled), branch, commitSha, commitMessage, url, triggeredBy, triggerSource (manual|auto|agent), errorMessage, logExcerpt, createdAt, updatedAt, completedAt }.
Trigger rate limit: each target has a two-tier budget, 5 triggers per 60 s and 30 per 3600 s, keyed by site and target (apps/cms/src/services/deployment/trigger-rate-limit.ts). It applies to every triggerSource (manual, auto, agent). A coalesced auto trigger reuses a recent build and does not consume budget. When the limiter backend is unreachable the trigger is allowed (fail-open). A rejected trigger creates no row and returns:
{
"errors": [
{
"code": "RATE_LIMITED",
"message": "Too many deploy triggers for this target. Please try again later.",
"retryAfterSeconds": 42
}
]
}
with a matching Retry-After: 42 header.
Webhook signatures: the secret is the per-site setting deployment.webhook.<provider> (value { "secret": "…" }), never a request header. An empty or missing secret rejects every request (fail-closed). Vercel sends x-vercel-signature, the lowercase hex HMAC-SHA1 of the raw body. Netlify sends x-webhook-signature, a compact JWS (HS256) whose sha256 claim must equal the SHA-256 hex digest of the raw body (a JWS whose payload is the raw body itself is also accepted). Both comparisons are constant-time.
Trigger a deploy:
POST /api/v1/deployments/targets/dpt_abc123/deploy
Content-Type: application/json
Authorization: Bearer <token>
X-Lumi-Site: <siteId>
{ "branch": "main", "reason": "Homepage copy update" }
Response (201, abridged):
{
"data": {
"id": "dep_def456",
"targetId": "dpt_abc123",
"provider": "vercel",
"status": "queued",
"branch": "main",
"triggerSource": "manual"
}
}
8. AI Copilot
| Method | Path | Description |
|---|---|---|
POST | /api/v1/ai/chat | Send natural-language instruction to AI Copilot |
GET | /api/v1/ai/approvals | List pending HITL approvals |
POST | /api/v1/ai/approvals/:id/decide | Approve or reject a pending action |
GET | /api/v1/ai/conversations | List conversation history |
GET | /api/v1/ai/conversations/:id/messages | Get messages in a conversation |
DELETE | /api/v1/ai/conversations/:id | Delete a conversation |
POST | /api/v1/ai/decisions | Ask the decision model (TypeSafe Jev or equivalent) typed questions |
GET | /api/v1/ai/review-profiles | List active draft review profiles (?collection=) |
GET | /api/v1/ai/review-profiles/:key | Get a review profile (?version= for an older one) |
POST | /api/v1/ai/review-profiles | Create version 1 of a review profile (admin) |
POST | /api/v1/ai/review-profiles/:key/versions | Publish the next version of a review profile (admin) |
POST | /api/v1/ai/reviews | Review an item or an unsaved draft with a profile (suggest-only) |
GET | /api/v1/ai/reviews?collection=&itemId= | List the review runs of an item |
GET | /api/v1/ai/reviews/:id | Get a review run with its staleness |
POST | /api/v1/ai/reviews/:id/feedback | Record accept / edit / reject on a run's answers |
GET | /api/v1/ai/reviews/rollout?collection= | Draft-review pilot mode of a collection: off, baseline or assisted |
POST | /api/v1/ai/reviews/sessions | Record one editor review session on a pilot collection (timing) |
GET | /api/v1/ai/reviews/metrics?from=&to= | Draft-review pilot metrics (admin) |
GET | /api/v1/ai/automation/templates | Jev automation flow templates (admin) |
POST | /api/v1/ai/automation/templates/:key/build | Build a draft manual flow from a template; writes nothing (admin) |
GET | /api/v1/ai/automation/actions | Automation action history with its audit chain (admin) |
GET | /api/v1/ai/automation/actions/:id | One automation action with its audit chain (admin) |
POST | /api/v1/ai/automation/actions/:id/feedback | Accept / override / reject the decision behind an action (admin) |
POST | /api/v1/ai/automation/actions/:id/revert | Restore the value before an applied action (admin) |
GET | /api/v1/ai/automation/metrics?from=&to= | Shadow precision and coverage in the auto-action zone (admin) |
Chat request:
{ "message": "Create a collection called 'products' with title, price, and status fields" }
Safe skill response:
{
"data": {
"status": "executed",
"data": { "collectionName": "products", "fieldsCreated": 3 }
}
}
HITL required (dangerous skill) response:
{
"data": {
"status": "pending_approval",
"approvalId": "apr_ghi789",
"message": "Creating a collection requires admin approval."
}
}
Decide on an approval:
{ "decision": "approved" }
Decision request (POST /api/v1/ai/decisions) — Experimental in 1.0.0 (along with /api/v1/ai/review-profiles*, /api/v1/ai/reviews*, and /api/v1/ai/automation*; outside the 1.0 semver freeze per contributing/versioning-policy.md until live-data validation #548 completes). 1–32 questions keyed by [A-Za-z0-9_-]{1,64}; noul = yes/no, choice = 2–255 options, score = 2–10 rubric levels (lowest first). state is a string, object or array. The whole request (state, instructions, criteria and nesting) must fit the input budget: ≤ DECISION_MAX_INPUT_BYTES UTF-8 bytes (default 131,072) and ≤ DECISION_MAX_INPUT_TOKENS estimated tokens (default 24,000), checked before the provider is called. Read-only, so no HITL approval:
{
"state": { "title": "Summer sale", "body": "Buy now!!!" },
"questions": {
"spam": {
"type": "noul",
"instructions": "Is this post spam?",
"criteria": { "true": "spam", "false": "legitimate" }
},
"topic": {
"type": "choice",
"instructions": "Pick the topic",
"criteria": { "promo": "Promotion", "news": null }
},
"quality": {
"type": "score",
"instructions": "Rate editorial quality",
"criteria": ["poor", "ok", "great"]
}
}
}
Decision response — calibrated is false when DECISION_PROVIDER=llm, because those probabilities are self-reported by the LLM. usage.inputTokens / usage.outputTokens are null when the provider did not report them (unknown, never a made-up 0):
{
"data": {
"provider": "typesafe",
"model": "jev-1.13",
"calibrated": true,
"answers": {
"spam": { "type": "noul", "noul": 0.12 },
"topic": { "type": "choice", "choice": "promo", "probabilities": { "promo": 0.9, "news": 0.1 }, "confidence": 0.9 },
"quality": { "type": "score", "score": 1.4, "legend": { "0": "poor", "1": "ok", "2": "great" }, "probabilities": { "0": 0, "1": 0.6, "2": 0.4 }, "confidence": 0.6 }
},
"usage": { "inputTokens": 120, "outputTokens": 0 }
}
}
Errors: 403 FORBIDDEN (no ai:decide, or the caller is a publishable API key or a frontend session), 403 DECISION_DISABLED, 422 DECISION_FIELD_NOT_ALLOWED, 429 DECISION_QUOTA_EXCEEDED / DECISION_CONCURRENCY_LIMITED, 503 DECISION_QUOTA_UNAVAILABLE (see Governance below), 400 VALIDATION, 413 DECISION_INPUT_TOO_LARGE (over the byte or token budget; the message gives sizes only), 503 DECISION_NOT_CONFIGURED (no DECISION_PROVIDER), 429 DECISION_RATE_LIMITED, 503 DECISION_UNAVAILABLE (upstream overloaded or unreachable), 504 DECISION_TIMEOUT, 499 DECISION_CANCELLED (the client closed the request), 422 DECISION_VALIDATION, 502 DECISION_AUTH / DECISION_UPSTREAM / DECISION_PARSE_FAILED.
Deadlines and retries: one decision has a total deadline (DECISION_TIMEOUT_MS, default 20 s) that includes every retry and backoff, and each upstream attempt has its own timeout (DECISION_ATTEMPT_TIMEOUT_MS, default 8 s, capped by what remains of the deadline). Only 429/503/529, network errors and attempt timeouts are retried, at most DECISION_MAX_RETRIES times (default 2), with full-jitter exponential backoff that honours Retry-After. A wait that would run past the deadline is not started. Auth, validation and parse failures are never retried. When the client disconnects, the in-flight upstream call is aborted and no retry follows. The llm provider is bounded by the same deadline and budget but makes a single call; the deadline and a client disconnect abort that LLM request.
The token count is an estimate, not the provider's tokenizer: about 4 ASCII characters per token, and every non-ASCII code point (e.g. Vietnamese diacritics) as one token. It over-counts on purpose; the 24,000 default leaves 25% headroom under Jev's 32,000-token context.
The CMS validates upstream answers before returning them: required values must be finite and in range, Choice/Score distributions must include exactly the declared options/levels and sum to 1 within an absolute tolerance of 1e-6, and Score must lie in 0..N-1. Missing or malformed answers return 502 DECISION_PARSE_FAILED; values are never clamped or defaulted into decisions. Confidence is required for Choice/Score and is not inferred from the winning probability. The LLM provider uses the same validation.
DECISION_PROVIDER=llm is an equivalent provider you select by configuration; it is not an automatic failover, and nothing switches to it when Jev fails. It calls LLM_PROVIDER in structured decision mode: a dedicated decision system prompt, no Copilot skills and no tool calling. A Score answer from the LLM is the weighted expected level Σ i·p(i) computed from its validated level probabilities, on the same 0..N-1 scale as Jev and never rounded; the level the model names is ignored, so one distribution yields one score on every adapter. Because the probabilities are uncalibrated, thresholds tuned for Jev must not be reused for llm as-is. Tool-only or non-JSON replies fail with 502 DECISION_PARSE_FAILED. With llm, the estimated size of the complete answer is also checked against DECISION_LLM_MAX_OUTPUT_TOKENS before the call (413 DECISION_INPUT_TOO_LARGE), a 2xx reply that is not JSON or has the wrong envelope is 502 DECISION_PARSE_FAILED (as with Jev), an unreachable provider is 503 DECISION_UNAVAILABLE, upstream HTTP statuses map to the same codes as Jev, and upstream error bodies are never logged or returned.
Governance (#511). Every gate below runs before the provider is called, in this order, and a request that fails one never reaches it:
- Capability
ai:decide. Grant it with a policy permissioncreateon the reserved collectionlumibase_ai_decisions; site admins already satisfy it. That permission grants nothing else (noitems:write). Without it →403 FORBIDDEN. Anonymous callers, members without the capability and principals of another site are all refused here. Publishable API keys (lbk_pub_…) andfrontend-audience sessions are always refused here with403 FORBIDDEN, even when a role or policy grantscreateonlumibase_ai_decisionsor admin access (#562). Those credentials live in browsers and apps, so paid decision calls must come from Studio users or from a server that holds a secret API key. The refusal comes before the body is read. It applies to everyai:decideroute (decisions, review profiles, reviews, feedback, rollout, sessions) and to Flowsai:decisionnodes. Refusals at this step are audited in aggregate, not one event per request (see the audit paragraph below). - Provider configured → otherwise
503 DECISION_NOT_CONFIGURED. - Site opt-in. The site sends content to the provider only after a site admin stores the
aiDecisionssetting withenabled: true(POST /api/v1/settings). It is off by default, and a malformed value reads as off. Setting it back tofalse(or deleting the key) is the per-site kill switch: the next request gets403 DECISION_DISABLED. Only the decision endpoints, draft review and Flowsai:decisionnodes read this setting, so editing, publishing and Copilot chat are unaffected. UnsettingDECISION_PROVIDERis the platform-wide switch. - Field allowlist. With
allowedStateFieldsset,statemust be an object whose top-level keys are all listed; otherwise422 DECISION_FIELD_NOT_ALLOWED. - Input budget →
413 DECISION_INPUT_TOO_LARGE(above). - Site quota, accounted atomically with the runtime counter (Redis
INCRBYon Docker, the per-sitePageviewCounterDurable Object on Cloudflare): admitted decisions per hour, decisions in flight, and estimated tokens per UTC day. The token reservation is the worst case, every attempt the provider can send included: with Jev/OpenRouter, (estimated input + estimated output) × (DECISION_MAX_RETRIES+ 1); withllm, which sends one request and never retries, estimated input + the output cap sent upstream (thinking headroom included). Once the provider answers, the site is charged the reported usage plus an estimate for each earlier failed attempt, and the rest is refunded. An unknown count is charged at the estimate, never as free. A timeout or failure after attempts were sent is charged per attempt; a request that never reached the provider is fully refunded. A limit that would be exceeded →429 DECISION_QUOTA_EXCEEDEDor429 DECISION_CONCURRENCY_LIMITEDwithRetry-After. A request whose worst-case reservation alone exceeds the daily token budget can never be admitted, so its429 DECISION_QUOTA_EXCEEDEDcarries noRetry-After. If the counter backend is down or answers with a non-numeric value, the request fails closed with503 DECISION_QUOTA_UNAVAILABLE.Retry-Afteris listed inAccess-Control-Expose-Headers, so cross-origin callers (Studio on Pages, the desktop shell, browser SDK) can read it.
The site aiDecisions setting can tighten the platform ceilings, never raise them:
{ "key": "aiDecisions", "value": { "enabled": true, "allowedStateFields": ["title", "body"], "requestsPerHour": 100, "maxConcurrent": 2, "budgetPerDay": 200000 } }
Each admitted call, and each call refused after this first step, writes one ai_decision audit event with the request ID, the principal (type and ID), provider, model, a rubric fingerprint (sha256: of the questions, so the same rubric gives the same version), question types, outcome, HTTP status, latency, reported usage, attempts, and reserved and charged tokens. It never records state, instructions, criteria, answers, the actor's email or the client IP. Audit rows follow the audit log retention (LUMIBASE_AUDIT_RETENTION_DAYS, default 90 days). POST /ai/decisions stores no decision content. Draft review runs (below) store the answers, never the reviewed content. What the provider keeps is governed by the provider's own terms.
Refusals are audited in aggregate (#564). A 403 FORBIDDEN from step 1 does not write one event per request, so a flood of refused requests cannot flood the audit log. Refusals are counted per site, refusal reason and subject: the principal (type and ID), or a keyed hash of the client IP when there is no principal. The first refusal in each DECISION_REFUSAL_AUDIT_WINDOW_SECONDS window (default 300 s) writes an event with refusal.count: 1. Later refusals in the same window write again only at counts 10, 100, 1000, and so on. The first event of the next window carries refusal.previousWindowCount, the exact count of the window before. If no refusal follows, the last event's count is a lower bound, and the metric lumibase_ai_decision_refusals_total{reason,principal,audit} has the exact number of every refusal. If the counter store is unavailable, every refusal writes an event (evidence is never dropped). 0 turns aggregation off. Each refusal event has metadata.refusal (reason, count, dedup: first / checkpoint / unbounded, windowStart, windowSeconds) and clientIpHash: HMAC-SHA256 of the site and IP keyed by JWT_SECRET, 16 hex characters, or null when the IP is unknown. The ip column stays empty. Rotating JWT_SECRET changes the hashes. refusal.reason is one of publishable_api_key, frontend_session, unclassified_caller, capability_missing, principal_unresolved, principal_site_mismatch, principal_not_found, principal_inactive, principal_not_member, api_key_revoked, api_key_expired, dev_principal_forbidden, principal_denied, other. A key of another site is reported as principal_not_found.
Abuse bounds for /api/v1/ai/* (#564). Every request under /api/v1/ai counts against a per-client-IP, per-site limit, LUMIBASE_AI_IP_RATE_LIMIT (default 300 per minute, 60-second window, 0 = off). It runs after the site check and before authentication, so a blocked request costs no token or API-key check, no quota reservation, no provider call and no audit event. Over the limit → 429 RATE_LIMITED with Retry-After (listed in Access-Control-Expose-Headers); the counter is lumibase_ai_ip_rate_limited_total. If the limiter store is unavailable, the request passes, or gets 503 RATE_LIMIT_UNAVAILABLE when LUMIBASE_RATE_LIMIT_FAIL_CLOSED=true (the same rule as the other limiters). The limit is skipped when the client IP cannot be resolved. On Docker behind a reverse proxy, the proxy must overwrite CF-Connecting-IP with the real client IP: the CMS trusts that header as sent, so a client-supplied value must never pass through.
As an outer defence, add a Cloudflare WAF rate-limiting rule in front of the Worker or the Docker origin: expression (http.request.uri.path wildcard "/api/v1/ai/*") (optionally and http.request.method eq "POST"), counting by IP, for example 120 requests per 1 minute, action Block for 1 minute (block, not a challenge, because callers are APIs). The CMS limits stay in force behind it.
Draft review (#512). A review profile is a versioned rubric: the top-level fields a review reads and the Decision questions it asks (same shapes as above). A review run applies one profile version to one item, or to an unsaved draft, through the governed path above (so the ai:decide capability, site opt-in, field allowlist, budgets and the ai_decision audit event all apply), and stores the answers with their provenance. Reviews only suggest: no endpoint here changes an item.
- Profiles. Reading needs
ai:decide; creating and versioning need a site admin. Rows are immutable:POST /review-profiles/:key/versionsinserts version + 1 and archives the previous active version in one transaction, so a run always points at the exact questions it was answered against. A profile may be bound to onecollection(others get422 REVIEW_COLLECTION_MISMATCH) and may setminConfidence. - Presets.
taxonomyis achoiceoverpresetOptions.categoriesplusotherandunknown.brand-voicescores tone match and clarity on atomic 5-level rubrics (againstpresetOptions.voice) and adds aneeds_reviewflag.brief-alignmentcompares the content with thesourceField(a brief or source the editor supplies). Without asourceFieldit only checks internal coherence and the profile stores the noteno source — not a fact-check. No preset claims to verify facts. - Reading content. With
itemId, the server reads the profile's fields with the caller's own row and field permissions. Fields the caller cannot read are not sent and are listed inomittedFields. Withsnapshot(an unsaved draft), each key must be one of the profile's fields and one the caller may read and write (create, orupdatewhenitemIdis also given). Otherwise the request fails with422 REVIEW_FIELD_NOT_ALLOWEDbefore any provider call. Content travels only instateand the questions come from the stored profile, so text inside the content cannot change what is asked. - Provenance and staleness. A run records the actual provider, model,
calibrated, the profile key and version, the latest live revision, the principal, latency, usage andcontentHash(sha256:of the canonical JSON of the reviewed fields).GET /reviews/:idrecomputes the hash and revision. When either changed, the run comes backstale: truewithstaleReasoncontent_changed,revision_changedoritem_unavailable. A caller who can no longer read a field the run reviewed gets404. Snapshot runs are visible only to their author and admins. - Abstention.
statusisabstainedwhen everychoiceanswer isother/unknown, or when a confidence is below the profile'sminConfidence. - Idempotency. Keys are scoped to the caller: the same
idempotencyKey(body) orIdempotency-Keyheader from the same principal returns the same run (200) with no second provider call, while another principal using the same key gets its own run. A run that ended inerroris retried in place, so it never becomes a second row. The retry re-reads the item and rebinds the run (content hash, revision, profile version, omitted fields) to what it actually reviewed. A run stillrunningfive minutes after it started (its process died) is reclaimed the same way; until then a replay returns it asrunning. If the original call does finish after that, its answers are discarded: a run is completed only by the attempt that holds the current claim, so the response of the late call is the run as stored. - Feedback.
POST /reviews/:id/feedbacktakesentriesof{ questionKey, verdict: accept | edit | reject, editedValue? }. It stores one row per run, question and principal; a retried submission adds none and returns the stored rows. The first verdict is final: resubmitting a different verdict (oreditedValue) for the same question does not overwrite it, and the response carries the stored verdict, so compare it with what you sent.acceptorediton a stale run returns409 REVIEW_STALEunless the body saysacknowledgeStale: true, so a review is never silently applied to a different revision. For snapshot runs, send the current draft'scontentHashto get the same check.rejectis always accepted. - Retention. The hourly job deletes runs older than
DECISION_REVIEW_RETENTION_DAYS(default 180), and their feedback with them. Profiles are kept. - Pilot rollout (#516). The
aiDecisionssetting has areviewobject:{ enabled, pilotCollections, mode: 'baseline' | 'assisted' }. It is off when absent or malformed.POST /reviewsand new feedback need the collection in the pilot inassistedmode (which also needsaiDecisions.enabled); otherwise they return403 DECISION_DISABLEDbefore any content is read.GET /reviews/rollout?collection=reports the mode (ai:decide). Turning the pilot off deletes nothing: runs, feedback and sessions stay readable. - Flows (#517). A flow node
ai:decisionruns one review with a pinnedprofileVersionon one item and returnsbranch:true/false/unknownfor anoulquestion (noulThreshold), the option key orunknownfor achoicequestion (minConfidence, abstention), orerror. It needs theaiDecisionssetting to have bothenabled: trueandflows: true;flowsis off by default. When the node executes, the server re-resolves the principal that started the run, checksai:decideon that live grant and re-reads both switches, so a revoked grant or a later kill switch stops queued runs too. Only manual runs (POST /flows/:id/run) carry a principal; event, schedule and webhook runs are refused (FORBIDDEN). A failure (forbidden, disabled, quota, timeout, cancel, provider error) takes the node'serrorbranch when one is mapped and otherwise fails the node (onError); it is nevertrue. The review idempotency key isflow:<flowRunId>:<nodeId>, so re-executing a run replays the stored decision with no second provider call. See Flows. - Sessions.
POST /reviews/sessions(ai:decide, signed-in users only: API keys and the dev principal get403 FORBIDDEN) records{ collection, itemId?, mode, runId?, viewedQuestions?, durationMs, locale? }: one editor session from opening the editor to the first save. The mode must match the collection's current mode (409 REVIEW_SESSION_MODE_MISMATCH), the collection must be in the pilot (403 DECISION_DISABLED), and arunIdmust be the caller's own run on the same collection and item, withviewedQuestionsit answered (422 REVIEW_SESSION_RUN_INVALID). No content is stored. The run retention purge setsrun_idto null and keeps the session. - Metrics.
GET /reviews/metrics?from=&to=(site admin, window at most 366 days, default the last 30) returns time per item (baseline vs assisted p50/p95), accept/edit/reject/no-action rates over viewed suggestions only with 95% Wilson intervals, coverage, abstention, error rate, latency p50/p95, tokens per run, splits by locale, provider and profile version, sample counts (with distinct editors and items per mode), and the pre-registered criteria of protocoljev-pilot-v1withinsufficientSampleflags. Only sessions and verdicts ofuserprincipals count. Run counts are operational denominators, never user value. See Draft-review pilot. - Automation (#518). Flow nodes
ai:apply-tagsandeditorial:routeread an upstreamai:decisionand record one row per flow run, node and item inlumibase_ai_automation_actions. They are shadow by default: the proposal is recorded and nothing is written. A proposal is live only whenaiDecisions.automationhasmode: 'live', agate(approvedBy,approvedAt,evidenceRef) and a threshold for the item's locale and the action whoseprovider,model,profileKey,profileVersionandquestionKeymatch the decision (read from the stored review run, which must be about the node's item), and the confidence is at or above itsminConfidence; anything else (including a malformed block) is shadow. A live proposal goes through the governed harness (updateItem, agentjev-automation,autonomyCap: 1), so it becomes an approval or is refused at L0; automation never writes directly. TheupdateItemcall carriesexpect: { <field>: <value the proposal was computed from> }, which the harness re-checks when the approved write runs; a field a human changed in between fails the approval withITEM_PRECONDITION_FAILEDand nothing is written (rowdenied, reasonstale_at_approval).expectis an optionalupdateItemargument for any caller. Only the target field is proposed, neverstatus, deletes or schema; thesubmit_reviewtransition is proposed only. Stale decisions, decisions an editor overrode, pinned or unreadable fields are skipped and recorded./api/v1/ai/automation/*is control plane (site admin).POST /automation/actions/:id/revertrestorespreviousof an applied action through the caller's ItemService, and refuses with409 AUTOMATION_REVERT_CONFLICTwhen the field changed since.GET /automation/metricsreports precision and coverage in the auto-action zone withinsufficientSampleandshadowRequired; it switches nothing on. See Jev automation.
POST /api/v1/ai/reviews
{ "profile": "spam-check", "collection": "posts", "itemId": "itm_1", "idempotencyKey": "review-itm_1-0001" }
Errors: 403 FORBIDDEN, 404 REVIEW_PROFILE_NOT_FOUND / REVIEW_ITEM_NOT_FOUND / REVIEW_RUN_NOT_FOUND, 409 REVIEW_PROFILE_EXISTS / REVIEW_PROFILE_CONFLICT / REVIEW_STALE / REVIEW_NOT_COMPLETE, 422 REVIEW_FIELD_NOT_ALLOWED / REVIEW_COLLECTION_MISMATCH / REVIEW_SESSION_RUN_INVALID, 409 REVIEW_SESSION_MODE_MISMATCH, 400 VALIDATION, plus every decision error above.
Agent API (Content OS)
All routes mount under the authenticated chain; the token's roles are the capability set.
| Method | Path | Description |
|---|---|---|
GET/POST | /api/v1/agent/goals | List / create goals (execution: 'async' enqueues a queued run) |
POST | /api/v1/agent/goals/:id/decompose | Planner: create role-scoped sub-goals inheriting remaining budget |
POST | /api/v1/agent/goals/:id/settle | Settle a parent goal from its children's terminal states |
POST | /api/v1/agent/runs/:id/retry | Re-execute a failed/cancelled run as a new queued run (retryOfRunId → the original), enqueued on agent-runs under the requester's re-resolved rights. Only the goal's latest attempt, only while nothing on the goal is in flight — at most one new execution per request. 201 { goalId, runId, agentName, status, retryOfRunId }; 404 unknown or other-tenant run; 409 not retryable, in flight, effect already recorded (RUN_EFFECT_RECORDED), superseded, goal closed or busy, intent not active, or task unrecoverable; 423 frozen; 400 no queue adapter; 503 enqueue failed. See agent harness |
GET/POST/PATCH/DELETE | /api/v1/agent/roles[/:name] | Agent role library CRUD (admin) — seeded with Planner, Writer, … |
GET | /api/v1/agent/autonomy | Trust ledger: grants + open incidents |
GET/POST | /api/v1/agent/autonomy/promotions[...] | Promotion proposals; POST :id/decide is the only path to a higher level (admin) |
GET/POST | /api/v1/agent/staged[...] | Veto window: pending stagings enriched with approvalId/collection/itemId/patch/agentRole from the staging revision (null fields when the staging is gone); POST :id/veto discards a staging |
GET | /api/v1/agent/approvals | Approval inbox (status filter; defaults to pending) |
POST | /api/v1/agent/approvals/:id/decide | Human decision on a parked action. Body { decision: 'approved' | 'rejected', reason? }; needs approvals:decide (403 otherwise), 404 for an unknown or other-tenant id, 409 when the approval already left pending. On approved the harness owns the state transition, so execution and the status write happen once. Execution re-resolves the requester's current rights and runs with requester ∩ decider: an approval whose requester was since revoked, demoted or removed is denied, and one with no recorded requester (parked before provenance existed) is denied with APPROVAL_PROVENANCE_MISSING. An approval stored with approvalPolicy: human_required (every external-action tool) is released only by a signed-in user: an API key, a connector token or an agent gets 409 EXECUTION_FAILED carrying HUMAN_APPROVAL_REQUIRED, and the approval stays pending |
POST | /api/v1/agent/approvals/:id/reopen | Return a failed approval to pending so it can be decided again. Body { reason } is required and audited; needs approvals:decide. A skill that reached a service and then failed is parked rather than re-offered, because retrying could repeat a non-idempotent write — this is the deliberate way back. A veto approval whose staged patch is already live (a commit that died after applying it) answers 409 VETO_ALREADY_APPLIED instead, since reopening would apply it twice |
POST | /api/v1/agent/approvals/:id/agent-decide | Agent-as-reviewer decision (needs review:<domain>; self-review forbidden) |
GET | /api/v1/agent/questions | askUser clarification questions, newest first. ?status=pending (default) | answered | expired | cancelled | all. Each item: { id, runId, goalId, toolCallId, agentName, question, options, allowFreeText, context, status, expiresAt, createdAt, answer, answeredAt, answeredBy }. Questions are not listed by /approvals, and /approvals/:id/decide and /reopen answer 409 NOT_AN_APPROVAL for a question id. See agent harness |
GET | /api/v1/agent/questions/:id | One question; 404 for an unknown or other-tenant id |
POST | /api/v1/agent/questions/:id/answer | Answer a question and resume its waiting_user run. Body { answer } (1–2000 chars, trimmed; one of options when allowFreeText is false). Only a signed-in user answers: any API key, site- or organization-scoped and whatever its capabilities, gets 403. Allowed for a holder of approvals:decide (or control-plane admin) and for the run's requesting user; today only site administrators reach the route (control-plane guard), so the requester rule takes effect once backlog B207 moves it out of the control plane. The claim and the resume are one transaction. 200 with the answered question (run succeeded); 400 VALIDATION / ANSWER_INVALID / ANSWER_NOT_AN_OPTION; 403; 404; 409 ALREADY_ANSWERED, EXPIRED, QUESTION_CLOSED, RUN_NOT_WAITING, REQUESTER_REVOKED (the requester lost access; the run is failed); 423 FROZEN (the run is cancelled) |
GET/POST | /api/v1/agent/constitution[...] | Versions, draft, /compile (NL→evaluators), :id/dry-run, :id/activate |
* | /api/v1/agent/skills[...] | Site Skills — playbooks injected into matching agent runs: CRUD by id or slug, :id/activate|archive|draft, :id/versions, :id/versions/:version/restore, /import, /export, /match. Every write needs a control-plane admin (403 FORBIDDEN otherwise; there is no delegated author and riskClass is a label only). PATCH takes expectedVersion and status actions take version (409 VERSION_MISMATCH); DELETE refuses a skill that was ever active (409 SKILL_HAS_BEEN_ACTIVE); /import refuses content changes to active skills unless updateActive: true (ACTIVE_SKILL_CHANGE). See features/site-skills.md |
GET/PUT/DELETE | /api/v1/agent/tool-secrets[/:name] | Secrets of external-action tools, per site. GET lists names, key version and timestamps; PUT /:name with { value } (8 to 8192 characters) stores or replaces; DELETE /:name removes. No route returns a value. All need a signed-in site administrator: an API key or connector token gets 403 FORBIDDEN even with administrative rights. 400 for an invalid name or value, 404 deleting an unknown name, 503 KEYS_UNAVAILABLE when no KeyProvider is configured. See features/external-action-tools.md |
GET/POST | /api/v1/agent/kill-switch[/lift] | Four-scope stop (run/intent/role/site); freezes need agents:freeze. Freezing a role or the site, pausing an intent and cancelling a run also cancel runs waiting on an askUser question in that scope (stopReason: frozen) and close their questions |
* | /api/v1/agent/intents[...] | Content intents CRUD, `:id/pause |
POST | /api/v1/intents/:id/scan | One reconciliation cycle: { scan, reconcile, dispatch }. dispatch advances each reconciler goal one step (draft → promote → verify) and reports dispatched/completed/skipped/blocked plus queueUnavailable on runtimes without a queue adapter. See reconciler repair loop. When the intent has semantic rules, scan.semantic reports the separately budgeted semantic pass (status ran/off/unavailable, counts, completed, cursor), and scan.semanticOrphansResolved counts rows of removed semantic rules it resolved. Updating an intent so a stored semantic rule changes profile, question, context or fields without a version bump returns 422 SEMANTIC_RULE_VERSION_REQUIRED; see semantic drift |
POST | /api/v1/mcp | MCP server (Streamable HTTP, JSON-RPC 2.0) — gated by contentOs.mcp flag. Besides tools/*, prompts/list and prompts/get expose the site's active skills to control-plane admins (empty for any other caller). A tools/call of askUser returns a normal tool result with status: "waiting_user", questionId and runId |
POST | /api/v1/mcp/sites/:siteId | Same MCP server, site taken from the path (for hosted OAuth connectors that cannot send X-Lumi-Site) |
GET | /.well-known/oauth-protected-resource/api/v1/mcp[/sites/:siteId] | RFC 9728 Protected Resource Metadata (public; 404 unless MCP is on and a trusted issuer lists the resource URI in audience) — see OAuth connector |
GET/DELETE | /api/v1/items/:collection/:id/pins[/:field] | Law Zero pins: list / release |
GET | /api/v1/deliver/llms.txt/:site_id | Public llms.txt index per site |
9. Realtime (WebSocket)
Endpoint: wss://api.<your-site>.lumibase.dev/api/v1/realtime
Auth (ticket exchange): browsers cannot send Authorization on the WS
handshake, so exchange the session for a short-lived (1 min) ticket first:
POST /api/v1/realtime/ticket (studio) or POST /api/v1/realtime/audience-ticket
(end-user), then connect:
wss://...realtime?ticket=<ticket>
The studio ticket embeds the collections the principal can read; the hub
rejects any other subscribe with { "type": "error", "code": "SUBSCRIBE_FORBIDDEN" }.
Subscribe to collection (optional Directus-style filter, evaluated
server-side over the event envelope collection/action/itemId):
{ "type": "subscribe", "collection": "articles", "filter": { "action": { "_eq": "delete" } } }
Server event — signal-only: no row data on the wire (clients re-fetch via
/items, which enforces RBAC + field masking):
{ "type": "event", "collection": "articles", "action": "update", "itemId": "art_001", "payload": null }
Server notification frame (push-noti feature) — broadcast to every session for the site (not collection-scoped):
{ "type": "notification", "notification": { "id": "…", "kind": "approval", "severity": "info", "title": "…", "body": "…", "deepLink": "/mission-control/inbox?entry=approval:…", "entityId": "…", "ts": "2026-06-23T01:00:00Z" } }
See features/websockets-realtime.md for full protocol reference.
9b. Push notifications
Web Push (VAPID) + in-app realtime for agent events. Tenant-scoped; the VAPID key is a shared deployment resource. See features/push-notifications.md.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/push/vapid-public-key | Application-server public key (404 PUSH_NOT_CONFIGURED when unset). Same key for every tenant. |
GET | /api/v1/push/status | { vapidConfigured, realtimeAvailable, subscriptions } for the active site. |
POST | /api/v1/push/test | Dispatch a one-off test notification to the active site (both transports). |
POST | /api/v1/push/subscriptions | Upsert a browser subscription: { endpoint, keys: { p256dh, auth } }. |
DELETE | /api/v1/push/subscriptions | Remove a subscription by { endpoint }. |
10. Settings
| Method | Path | Description |
|---|---|---|
GET | /api/v1/settings | Get all site settings |
PATCH | /api/v1/settings | Update multiple settings |
GET | /api/v1/settings/:key | Get single setting by key |
PUT | /api/v1/settings/:key | Set single setting |
POST | /api/v1/settings/export | Export settings as JSON bundle |
POST | /api/v1/settings/apply | Apply settings bundle |
Site configuration
The active site's identity, branding and theme defaults live on the sites
row (not the key/value settings table). Scoped to the active tenant via the
X-Lumi-Site header.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/site | Get the active site's configuration |
PATCH | /api/v1/site | Update site identity / branding / theme (partial) |
PATCH /api/v1/site accepts any subset of: name, displayTitle, siteUrl,
descriptor, domain, defaultLanguage, defaultAppearance
(auto|light|dark), defaultSaveAction
(stay|return|create_new — the site-wide default save action a user's
personal preference overrides), branding ({ logoUrl, faviconUrl, brandColor }),
themeOverrides ({ light, dark } maps of whitelisted CSS tokens → H S% L%
values), and customCss. An empty string clears a nullable field. A duplicate
domain returns 409 { errors: [{ code: 'DOMAIN_TAKEN' }] }.
Theme model: the site holds the global defaults; per-user appearance/theme/ language overrides (resolved client-side) take precedence.
10b. Regulated / sensitive content (admin)
Opt-in capability set (spec: regulated-content-readiness). All admin routes
require the admin role; field-level decryption additionally requires the
read_decrypted permission. Sensitive pii/phi field reads are recorded in
field_access_log; decrypt failures fail closed (500 DECRYPTION_FAILED) and
are audited — never a placeholder.
Encryption — keys & envelope mode
Key material lives only in the runtime KeyProvider (Workers Secrets /
env: ENCRYPTION_KEY_<id> + ENCRYPTION_ACTIVE_KEY_ID); these surfaces record
metadata + audit and drive migrations.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/admin/encryption/keys | List configured key metadata (id/status/algo). |
POST | /api/v1/admin/encryption/keys/rotate | Promote a provisioned key to active; retires the previous. Body { keyId }. Audits encryption_key_rotated. 422 KEY_NOT_PROVISIONED if the bytes are absent. |
POST | /api/v1/admin/encryption/keys/rewrap | Re-encrypt retired-key ciphertext (and re-wrap per-record DEKs) onto the active key. Idempotent, resumable, bounded per call. |
GET | /api/v1/admin/encryption/envelope | Current envelope-mode setting + migration progress. |
POST | /api/v1/admin/encryption/envelope | Toggle envelope (per-record DEK) mode. Body { enabled, password } — step-up auth re-verifies the admin password (401 INVALID_CREDENTIALS on mismatch). Records encryption.envelope, audits envelope_mode_changed, enqueues the background migration and drains a bounded inline batch. |
POST | /api/v1/admin/encryption/envelope/migrate | Drain more migration batches (resumable). Poll until { done: true }. |
Editorial review → publish
Mounted at /api/v1/editorial. Per-collection toggle via collection
meta.editorialWorkflow; meta.requireSeparateReviewer enforces a different
reviewer than the author. Transitions audit editorial_transition.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/editorial/reviews | List review requests (filter by status/assignee). |
POST | /api/v1/editorial/:collection/:id/submit-review | Move draft → in_review; assign a reviewer. |
POST | /api/v1/editorial/:collection/:id/approve | in_review → approved (→ publish per workflow). |
POST | /api/v1/editorial/:collection/:id/reject | in_review → rejected. Body { reason }. |
GDPR erasure (dual-control)
Mounted at /api/v1/admin/erasure. Crypto-shreds (drops per-record DEK) or
hard-deletes items + revisions while preserving the tamper-evident
data_erased audit (no cascade). Dual-control via erasureDualControl setting.
| Method | Path | Description |
|---|---|---|
POST | /api/v1/admin/erasure | Create an erasure request. Body { collection, filter } + reason. Stores a subject hash, never plaintext. |
POST | /api/v1/admin/erasure/:id/confirm | Second-admin confirmation (dual-control). |
POST | /api/v1/admin/erasure/:id/execute | Execute the confirmed erasure; audits data_erased with recordCount. |
Field access log & Subject Access Request
| Method | Path | Description |
|---|---|---|
GET | /api/v1/admin/field-access-log | Query decrypted-read audit of pii/phi fields (never values). |
POST | /api/v1/admin/sar/export | Subject Access Request: export one subject's decrypted records + provenance. Forces a field_access_log entry (Req 13.2). |
11. Extensions
| Method | Path | Description |
|---|---|---|
GET | /api/v1/extensions | List installed extensions |
POST | /api/v1/extensions/upload | Upload extension bundle (multipart) |
POST | /api/v1/extensions/:id/enable | Enable extension |
POST | /api/v1/extensions/:id/disable | Disable extension |
POST | /api/v1/extensions/:id/capabilities | Grant capabilities |
GET | /api/v1/extensions/ui/manifest | UI manifest for dynamic Studio import |
Signing & official extensions. Every install/load path (marketplace install,
generic CRUD POST /extensions, the dynamic endpoint mount, and hook dispatch)
routes through a shared verifier. Detached Ed25519 signatures are checked against
publisher keys resolved from MARKETPLACE_PUBLIC_KEYS (env) merged with the
lumibase_publisher_keys table (DB overrides env for official/revoked).
isOfficial is derived server-side (name in the lumibase- namespace and a
signature by an official key) — never from a manifest claim. Official extensions
are fail-closed: an unverifiable bundle never loads. Third-party enforcement
follows LUMIBASE_EXT_SIGNATURE_POLICY (require default, or warn). The
lumibase- namespace is reserved: community /marketplace/submit rejects it, and
official extensions with autoInstall/enabledByDefault are installed during
setup / on site-create by the reconciler. Sign bundles with the
@lumibase/extension-cli (lumibase-ext keygen|sign|verify).
11a. Pageviews (visitor counting)
Public beacon + authenticated read for the built-in pageview module. Per-site
config lives in the pageviews settings key (scope: 'module'): strategy
(db-rollup default | hot-counter | cdc | hll), userTable,
respectConsent, botFilter, hashSalt, flushIntervalS. Authenticated hits
are attributed to a user only with analytics consent; anonymous hits use a
salted hash (never a raw IP). Counters flush to lumibase_pageview_daily every 5
minutes.
| Method | Path | Description |
|---|---|---|
POST | /api/v1/pageviews/:site_id/hit | Public beacon; bot/DNT/GPC-filtered, rate-limited; returns 204 |
GET | /api/v1/pageviews/stats?from=&to=&path= | Authenticated daily views/uniques for a range |
11b. Email (templates, layouts, send)
Site-admin scope (requireSiteAdmin). Backed by the shared EmailService
(SMTP / MailChannels) + a site-scoped template/layout store. Full guide:
docs/en/features/email-service.md.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/email/capabilities | Transport availability + default from |
GET | /api/v1/email/layouts | List layouts |
POST | /api/v1/email/layouts | Create layout (HTML shell with {{content}}) |
PATCH | /api/v1/email/layouts/:id | Update layout |
DELETE | /api/v1/email/layouts/:id | Delete layout |
GET | /api/v1/email/templates | List templates |
POST | /api/v1/email/templates | Create template |
PATCH | /api/v1/email/templates/:id | Update template |
DELETE | /api/v1/email/templates/:id | Delete template |
POST | /api/v1/email/templates/:key/preview | Render without sending |
POST | /api/v1/email/send | Render (if templateKey) + send — extension entry point |
POST | /api/v1/email/test | Send a one-off test mail |
POST /api/v1/email/send body: { to[], cc?, replyTo?, variables?, and
exactly one of templateKey or inline: { subject, html?, text? } }.
Returns 502 DELIVERY_FAILED, 404 NOT_FOUND (template), or
503 EMAIL_NOT_CONFIGURED (degraded mode).
12. Firebase Sync
Sync content (items) to a Firebase target — Cloud Firestore or Realtime Database — in real time. All endpoints require site-scoped admin. Firebase credentials are write-only (supplied on create/update, encrypted at rest with ENCRYPTION_KEY, never returned). See features/firebase-sync.md.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/firebase-sync/pipelines | List sync pipelines for the active site |
POST | /api/v1/firebase-sync/pipelines | Create a pipeline |
GET | /api/v1/firebase-sync/pipelines/:id | Pipeline detail (credentials omitted) |
PATCH | /api/v1/firebase-sync/pipelines/:id | Update config / rotate credentials |
DELETE | /api/v1/firebase-sync/pipelines/:id | Delete pipeline (cascades its log) |
GET | /api/v1/firebase-sync/pipelines/:id/log | Recent sync attempts |
POST | /api/v1/firebase-sync/pipelines/:id/backfill | Push all matching items to Firebase now |
Create a pipeline (Firestore):
POST /api/v1/firebase-sync/pipelines
Content-Type: application/json
Authorization: Bearer <token>
X-Lumi-Site: <siteId>
{
"name": "blog-to-firestore",
"target": "firestore",
"projectId": "my-firebase-project",
"credentials": {
"project_id": "my-firebase-project",
"client_email": "[email protected]",
"private_key": "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
},
"collections": ["articles", "authors"],
"targetPath": "content/{collection}",
"syncOnCreate": true,
"syncOnUpdate": true,
"syncOnDelete": true
}
For target: "rtdb", credentials is { "databaseUrl": "https://<project>.firebaseio.com", "secret": "<rtdb-secret>" }.
Response (201):
{
"data": {
"id": "V1StGXR8_Z5jdHi6B-myT",
"name": "blog-to-firestore",
"target": "firestore",
"status": "active",
"projectId": "my-firebase-project",
"collections": ["articles", "authors"],
"targetPath": "content/{collection}",
"syncOnCreate": true,
"syncOnUpdate": true,
"syncOnDelete": true,
"lastSyncAt": null,
"lastSyncItemCount": null,
"createdAt": "2026-06-17T00:00:00Z",
"updatedAt": "2026-06-17T00:00:00Z"
}
}
Backfill response:
{ "data": { "scanned": 120, "pushed": 118, "failed": 2, "truncated": false } }
Error codes specific to this section: ENCRYPTION_KEY_REQUIRED (400 — ENCRYPTION_KEY not configured, cannot encrypt credentials), VALIDATION_ERROR (400 — body / credential shape does not match the selected target).
12a. Translation Memory
Reusable translations feeding the MT pipeline (TM → glossary → provider).
| Method | Path | Description |
|---|---|---|
GET | /api/v1/tm | List entries; filters ?source=&target=&entrySource=; paginated ?limit=&offset= → { data, meta: { total, limit, offset } } |
POST | /api/v1/tm | Upsert a TM entry |
PATCH | /api/v1/tm/:id | Update targetText/quality/context/source |
DELETE | /api/v1/tm/:id | Delete an entry |
POST | /api/v1/tm/lookup | Fuzzy match (threshold default 75, shared TM_DEFAULT_THRESHOLD) |
POST | /api/v1/tm/translate | Full pipeline (TM → glossary → MT provider) |
12b. Insights (Dashboards)
User-built dashboards of aggregate panels over collections. Panel queries are executed safely: every referenced field must be in the collection's field whitelist and the query is scoped to the active site — no user input reaches SQL identifiers.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/dashboards | List dashboards |
POST | /api/v1/dashboards | Create dashboard { name, icon?, color?, note? } |
GET | /api/v1/dashboards/:id | Get dashboard |
PATCH | /api/v1/dashboards/:id | Update dashboard |
DELETE | /api/v1/dashboards/:id | Delete dashboard |
GET | /api/v1/dashboards/:id/panels | List panels |
POST | /api/v1/dashboards/:id/panels | Create panel { name, type, position, query } |
PATCH | /api/v1/dashboards/:id/panels/:panelId | Update panel (incl. position for layout) |
DELETE | /api/v1/dashboards/:id/panels/:panelId | Delete panel |
POST | /api/v1/dashboards/:id/panels/:panelId/data | Run a panel → { data, meta: { executedAt, rowCount, durationMs } } |
POST | /api/v1/dashboards/:id/panels/preview | Dry-run a PanelQuery (editor preview) |
PanelQuery (shared contract @lumibase/contracts): { collection, aggregate (count|sum|avg|min|max), field?, groupBy?, filter? (condition rule), dateRange?, limit? }. field is required for non-count aggregates. A field outside the
collection whitelist returns 400 { errors: [{ code: 'INVALID_FIELD' }] }.
Activation milestones
| Method | Path | Description |
|---|---|---|
GET | /api/v1/activation | The active site's milestone funnel → { data: { siteId, milestones, reached, total } }. Site admins only (403 FORBIDDEN). |
Each entry of milestones is { key, reachedAt, source, secondsSinceSiteCreated } with key one of site_created, item_published, delivery_request, agent_run. Milestones are write-once and site-scoped. See Activation milestones and usage telemetry.
12c. Git Integration (GitHub / GitLab)
Per-site connections to source repositories: track pull requests + CI, view/store
CI logs, post a content-validation status back, reconcile declarative intents
(GitOps), and run auto preview environments. Authenticated routes require site
admin and ENCRYPTION_KEY (tokens are stored encrypted, never returned).
| Method | Path | Description |
|---|---|---|
GET | /api/v1/integrations/git | List integrations for the site |
POST | /api/v1/integrations/git | Create { provider (github|gitlab), repoFullName, displayName, authMethod (app|pat), token?, installationId? } → 409 on duplicate (provider, repo) |
GET | /api/v1/integrations/git/:id | Get one |
PATCH | /api/v1/integrations/git/:id | Update display name / token / status / sync config |
DELETE | /api/v1/integrations/git/:id | Disconnect (forgets token) |
POST | /api/v1/integrations/git/:id/rotate-secret | Rotate the webhook secret |
GET | /api/v1/integrations/git/:id/oauth/authorize | Returns { authorizeUrl } (single-use cache state) |
GET | /api/v1/integrations/git/:id/pull-requests | List cached PRs |
POST | /api/v1/integrations/git/:id/pull-requests/refresh | Pull PRs live from the provider (upsert cache) |
GET | /api/v1/integrations/git/:id/pull-requests/:number/ci | CI runs for the integration |
POST | /api/v1/integrations/git/:id/pull-requests/:number/validate | Validate config + post lumibase/content-validation commit status |
GET | /api/v1/integrations/git/:id/ci-runs/:runId/logs | Fetch + cache CI log (blob storage) |
POST | /api/v1/integrations/git/:id/gitops/sync | Reconcile lumibase/intents.json into content intents (+ drift scan/reconcile) |
GET | /api/v1/integrations/git/:id/provenance | Provenance ?collection=&itemId= — which commit/PR changed an item |
Public (no session; signature-verified or single-use state):
| Method | Path | Description |
|---|---|---|
GET | /api/v1/integrations/git/oauth/:provider/callback | OAuth code → token exchange (bound to cache state) |
POST | /api/v1/integrations/git/webhook/:provider/:siteId/:integrationId | Webhook receiver — GitHub HMAC-SHA256 (X-Hub-Signature-256) / GitLab token (X-Gitlab-Token); idempotent by delivery id |
Preview environments are opt-in per integration (sync_config.preview = true):
on PR open/sync LumiBase seeds an ephemeral site (${siteId}__pr-${number})
served at /api/v1/deliver/page/${ephemeralSiteId}/...; on close/merge it is
torn down. CI failure records an agent_incident (role git-sync) + a
git_ci_failed audit entry.
13. Delivery (Public)
No Authorization header needed. Permission applied via public role.
| Method | Path | Description |
|---|---|---|
GET | /api/v1/deliver/page/:slug | 1-roundtrip page hydration |
GET | /api/v1/deliver/items/:collection | Public item list |
GET | /api/v1/deliver/menu/:key | Menu config |
HTTP caching (GET /deliver/page/:site_id/:slug): responses without
credentials are shared-cacheable so any CDN/proxy can absorb repeat reads.
| Request | Response headers |
|---|---|
| No credentials (default) | Cache-Control: public, s-maxage=60, stale-while-revalidate=300 · ETag: W/"…" · Vary: X-Lumi-Site |
Authorization header present | Cache-Control: private, no-store (no shared ETag) |
| Page not found | 404 + Cache-Control: no-store |
Identifier shape invalid (site_id / slug) | 404 + Cache-Control: no-store (identical body to a real miss — not 400) |
Client IP over LUMIBASE_DELIVER_RATE_LIMIT | 429 + Retry-After + Cache-Control: no-store |
Conditional requests: send If-None-Match with the last ETag; a match
returns 304 Not Modified with an empty body and skips section hydration
entirely. The ETag is a site-level content fingerprint — any item write (or a
scheduled publish/unpublish taking effect) rotates it, so a stale 304 is never
served at the cost of a lower revalidation hit-rate.
Tunables (env): LUMIBASE_DELIVER_SMAXAGE (seconds, default 60, 0
disables public caching), LUMIBASE_DELIVER_SWR (seconds, default 300),
LUMIBASE_NEGATIVE_CACHE_TTL (seconds, default 30, 0 disables
tombstones), LUMIBASE_DELIVER_RATE_LIMIT (req/min/IP, default 1200,
0 disables). See Caching — penetration.
14. Utility endpoints
| Method | Path | Description |
|---|---|---|
GET | /api/v1/utils/health | Health check (DB, cache, storage, search, queue) |
GET | /api/v1/utils/version | API version info |
POST | /api/v1/utils/render-template | Render a display template server-side |
POST | /api/v1/utils/jsonata/test | Evaluate JSONata expression |
GET | /api/v1/metrics | Prometheus metrics (Docker mode only) |
GET | /api/v1/openapi.json | Live OpenAPI 3.1 document for the caller's site and permissions — 404 until enabled |
GET | /api/v1/openapi/config | Read the live OpenAPI switch (site admin) |
PUT | /api/v1/openapi/config | { enabled, realms } — enable it and choose realms (site admin, audited) |
The live OpenAPI document is described in Live OpenAPI document.
Health response:
{
"data": {
"status": "healthy",
"checks": {
"database": "ok",
"cache": "ok",
"storage": "ok",
"search": "ok",
"queue": "ok"
},
"version": "1.0.0",
"runtime": "cloudflare"
}
}
15. Rate limits
| Scope | Limit |
|---|---|
| Auth endpoints | 30 req/min per IP |
| Items write | 600 req/min per user |
| Items read | 6,000 req/min per user |
| File upload | 100 req/min per user |
| Realtime connections | 50 concurrent per site |
| AI Chat | 60 req/min per user |
AI routes (/api/v1/ai/*), before auth | 300 req/min per client IP per site (LUMIBASE_AI_IP_RATE_LIMIT) |
Rate limit headers:
X-RateLimit-Limit: 600
X-RateLimit-Remaining: 598
X-RateLimit-Reset: 1749254460
16. Versioning
Breaking changes get a new path prefix (/api/v2). The previous version is maintained for at least 12 months.
Send X-Lumi-API-Version: 1 to pin to a specific API version. Default is the latest stable.
Change Feed (/api/v1/cdc — spec cdc-extension-integration)
Mounted on the authenticated api app BEFORE the ClickHouse CDC control-plane router. Frontend-realm tokens are rejected on every route (ADR-011).
| Method | Path | Guard | Description |
|---|---|---|---|
| GET | /cdc/events | capability cdc:subscribe (admin implies) | Keyset-paginated change events. Query: cursor, collections (CSV), operations (CSV), limit (≤500), wait (long-poll seconds ≤25 — holds an empty first read until an event arrives). Returns { data, meta: { nextCursor, hasMore } }. Envelope type is <resource>.<operation> (items.* content, collections.*/fields.* schema). 400 malformed cursor; 410 CURSOR_EXPIRED + earliestCursor past retention. |
| GET/POST | /cdc/subscriptions | site admin | List (with per-subscription lag) / create (max 50 per site → 403; duplicate name → 409; kind=webhook requires a webhook with a secret → 400). |
| GET/PATCH/DELETE | /cdc/subscriptions/:id | site admin | Detail / update filters + pause/resume (invalid transition → 409) / delete (audited). |
| POST | /cdc/subscriptions/:id/ack | capability cdc:subscribe | Commit a pull checkpoint. Forward-only — rewind → 409 ACK_REGRESSION. |
| POST | /cdc/subscriptions/:id/replay | site admin | Rewind inside retention ({cursor} xor {occurred_after}); resets dead/stale → active. Audited. |
| POST | /cdc/subscriptions/:id/dispatch | site admin | On-demand dispatch (no-queue fallback). 202. |
| GET | /cdc/subscriptions/:id/deliveries | site admin | Delivery-attempt history, newest first (limit, page; meta.total). |
Webhook deliveries are signed: X-LumiBase-Signature: t=<unix>,v1=<hmac_sha256_hex> over `${t}.${rawBody}` — see docs/en/features/cdc-change-feed.md for the verify snippet and envelope reference.