# HTTP API

**For AI agents and scripts.** Everything the dashboard does is a route
under `<public URL>/v1`. The machine-readable contract is the OpenAPI 3.1
document at `<public URL>/v1/openapi.json` (no authentication), where each
operation states its scope and minimum role. Authenticate with a personal
access token (`Authorization: Bearer rdns_...`, bound to one organization)
or an OAuth 2.1 access token; see Authentication below. An agent that speaks
MCP should use the MCP server instead (`<public URL>/mcp`): its guide, with
worked workflows and rules for agents, is `docs/mcp.md` (served at
`<public URL>/docs-content/mcp.md`, tool parameters at
`/docs-content/mcp-tools.md`), and `<public URL>/llms.txt` lists all of them.

The dashboard, the MCP tools and third-party clients use one API under
`/v1`. Its OpenAPI 3.1 document is served, without authentication, at
**`/v1/openapi.json`**; `internal/controlplane/openapi_routes.go` declares
it as a table of operations and a test walks the router so every `/v1`
route is documented (and every documented operation exists). A new `/v1`
route fails the build until it is added there.

## Authentication

| Method | How | Notes |
|---|---|---|
| Dashboard session | `rdns_session` cookie from `POST /auth/code` + `POST /auth/verify` | every scope; limited by the user's role |
| Personal access token | `Authorization: Bearer rdns_<org>_<id>_<secret>` (`rdns_sbx_...` in the public sandbox, `docs/sandbox.md`) | bound to one org, scopes, optional IP allowlist and expiry; created in the dashboard |
| OAuth 2.1 access token | `Authorization: Bearer <JWT>` | from the authorization code flow with PKCE; organizations (one or several, one of them the default) and scopes chosen at consent; 1 hour, refreshable |

Login codes are limited (security review 2026-09-28): 5 codes per
address per 15 minutes and 20 sign-in requests per client IP per 15
minutes across `POST /auth/code`, `POST /auth/verify` and the OAuth
fallback login forms answer `429 tooManyRequests` beyond, with a
`Retry-After` header (seconds). Five wrong codes for an address (within
an hour, across codes) lock it for 15 minutes: code requests and guesses
answer `429 loginLocked` with `Retry-After` until then, even with the
right code. A guess within 5 seconds of the code's issue answers `400
invalidCode` without being checked or counted (nobody types an e-mailed
code that fast; this keeps a script from locking an address the moment it
asks for a code), and an operator lifts a lockout at once with
`rdns user unlock --email <e>` (audited `auth.unlock`; security review
2026-10-09, AUTH-L7).
`GET /oauth/authorize` has a per-IP budget of its own, 60 requests per
15 minutes (`429 tooManyRequests` with `Retry-After` beyond), checked
before the pending authorization request is written (security review
2026-10-09, AUTH-L1).
Failed credentials are limited per client IP too (AUTH-L3): 20 failures
per 15 minutes (an unknown, revoked or expired PAT, an OAuth access token
that does not verify, a non-Bearer `Authorization` header, a session
cookie this installation did not sign; an expired or revoked session of
ours is not counted), then every request from that address with an
`Authorization` header, a valid token included, answers `429
tooManyRequests` with `Retry-After` until the window ends, before the
token is looked up (a dashboard session cookie is still accepted: its
signature is checked before anything is read).

Cross-site request protection (CSRF): a state-changing request that
carries the session cookie, and every `POST /auth/*`, OAuth fallback form
and consent decision, must come from the dashboard's own origin: a
`Sec-Fetch-Site` other than `same-origin`/`none`, or an `Origin` other
than the public URL's, answers `403 csrf`. Requests without `Origin` and
`Sec-Fetch-Site` (non-browser clients) pass. A body sent without an
`Authorization: Bearer` header must be `Content-Type: application/json`
(charset allowed; `415 unsupportedMediaType` otherwise) and hold exactly
one JSON value (trailing data: `400 invalidBody`). Bearer callers (PATs,
OAuth, MCP) are exempt from both checks, except on the sign-in and
sign-out routes. A request with an `Authorization` header is
authenticated by that header alone: anything but a Bearer token answers
`401 invalidToken`, and the session cookie is never used in its place
(security review 2026-10-09, AUTH-L4).

Sessions last 12 hours and can be revoked before that (security review
2026-09-28, A-M2). `POST /auth/logout` revokes the current session on the
server (a copied cookie answers `401 notLoggedIn` afterwards), and
`POST /auth/logout {"everywhere": true}` or `POST /v1/me/sessions/revoke-all`
(session only) revokes every session of the account, this one included.
A platform admin can do the same for any user with
`POST /v1/admin/users/{userId}/revoke-sessions`, and removing a user's
platform admin role (`PUT /v1/admin/users/{userId}/platform-admin` or
`rdns user platform-admin --set false`) revokes that user's sessions too.
Each of these also revokes the user's personal access tokens minted
before it, in every organization, and every OAuth grant the user approved
before it (access tokens answer `401 invalidToken`, refresh tokens
`invalid_grant`; security review 2026-10-09, AUTH-3). New tokens and new
approvals afterwards work.
A role change or a removal from an organization needs no revocation: every
organization request reads the role from the organization's manifest.

Two-factor authentication (TOTP, RFC 6238: an authenticator app, 6
digits, 30 seconds; security review 2026-09-28, A-M5) is required for
platform admins and optional for everyone else. Enrolment is
session-only: `POST /v1/me/totp/enrol` returns `{secret, otpauthUrl,
qrCode}` (the QR code as an SVG `data:` URL; the secret waits 30
minutes), `POST /v1/me/totp/confirm {code}` turns it on and returns ten
single-use `backupCodes` (shown once), `POST /v1/me/totp/disable {code}`
turns it off, `GET /v1/me/totp` reads the state (`enabled`, `pending`,
`required`, `backupCodesLeft`, `lockedUntil`, `stepUpUntil`). Once it is
on, `POST /auth/verify` answers `{"mfaRequired": true, "method": "totp"}`
with a five-minute `rdns_mfa` cookie instead of a session, and
`POST /auth/totp {code}` (a current code or a backup code) finishes the
sign-in. Every `/v1/admin` route (and minting a PAT with an operations
scope) needs a platform admin session with the factor on
(`403 totpEnrollmentRequired` otherwise, `details.enrolUrl`) and a code
checked within the last 15 minutes (`403 stepUpRequired`,
`details.stepUpUrl`): a sign-in with the factor, the enrolment
confirmation or `POST /v1/auth/step-up {code}` (session-only; re-signs
the session cookie with `stepUpUntil`). A code is accepted once; five
wrong codes within an hour lock the factor for 15 minutes
(`429 totpLocked`); a wrong one answers `400 invalidTotpCode`. The OAuth
fallback consent page cannot ask for the factor: such an account signs in
on the dashboard first. An operator removes a lost factor with
`rdns user totp reset --email <e>` (which also revokes the user's
sessions).

A platform admin never enrols on a session alone (security review
2026-10-09, AUTH-2): `POST /v1/me/totp/enrol` answers `403
totpEnrolmentOutOfBand` unless the body carries `enrolmentToken`, a
one-time token another platform admin issued with
`POST /v1/admin/users/{userId}/totp-enrolment` (step-up and
`{ticket, reason}` like every admin write; `201 {userId, enrolmentToken,
expiresAt}`, 15 minutes, single use; `400 notPlatformAdmin`, `400
cannotIssueOwnEnrolment`, `409 totpAlreadyEnabled`). A wrong, used or
expired token answers `403 totpEnrolmentTokenInvalid`; a pending secret
started without a token cannot be confirmed by a platform admin (`403
totpEnrolmentOutOfBand`). On a server, `rdns user totp enrol --email <e>`
does the same without a token. Turning a platform admin's factor on or
off (or resetting it) raises the `admin_totp_changed` installation alert
for 24 hours and e-mails every other platform admin.

Every `/v1/admin` write (POST, PUT, PATCH, DELETE) carries the support
request it answers and why, `{ticket, reason}` in the JSON body next to
the route's own fields, like the support actions (A-M6): 1 to 200 and 10
to 2000 characters, `400 invalidTicket` / `400 invalidReason` otherwise.
Both are recorded on every audit entry the request writes (`ticket`,
`reason`). For `PUT /v1/admin/tenants/{orgId}/plan` the reason is also
the billing mode's reason, and for `POST /v1/admin/domains/{name}/cancel`
the cancel's (still at most 500 characters there). Reads of one
organization's data (`GET /v1/admin/tenants/{orgId}`, its invoices and
snapshots, `GET /v1/admin/domains`, `GET /v1/admin/audit?orgId`, the
audit stream export and verification, a license file, the user and
support action lists) are audited as `admin.read.<what>` in the platform
stream with the organization as target. The admin routes are
dashboard-only, so there are no MCP admin tools to change.

Tokens (PAT or OAuth) can never manage tokens, members, create
organizations or use `/v1/admin`: those are dashboard-only.

Sessions pick the organization with the `X-RDNS-Org` header (or `?org=`),
defaulting to their first membership. A PAT is bound to the one
organization it was created for (a header naming another answers `403
forbidden`): a user with several organizations needs one PAT per
organization. An OAuth token acts on its default organization; when the
consent granted several (multi-org grant, since 2026-10-11), the
`X-RDNS-Org` header picks another granted one per request (an id or the
exact name), checked live: `403 orgNotGranted` for an organization of the
user the grant does not cover (or one the user left, or the app was
disconnected from), `404 orgNotFound` for no organization of the user by
that id or name, `409 orgAmbiguous` for a shared name; each carries
`details.grantedOrgs`. A single-org OAuth token (every token issued before
then) refuses another organization as before. `GET /v1/orgs` with a token
lists the organizations it may act on, each with `default` and the
`scopes` granted there. The MCP tools take the same choice as their `org`
argument (`docs/mcp.md`, "Organizations").
The dashboard's organization switcher (header) lists the user's
organizations with their role, remembers the last one per user in the
browser (`localStorage` key `rdns.org.<userId>`) and creates new ones
(`POST /v1/orgs {name}`, session only: the caller becomes the owner and
the dashboard switches to it); switching reloads every page for the new
organization.

### Token lifetime

A new personal access token expires in 90 days unless the request says
otherwise (security review 2026-09-28, A-L4): `POST /v1/tokens` takes
`expiresInDays` or `expiresAt` (not both), at most 366 days away and not
in the past (`400 invalidTokenExpiry`); `noExpiry: true` mints one that
never expires, for platform admins only (`403 noExpiryAdminOnly`). The
Tokens page offers 90 days by default. Tokens created before this rule
keep their expiry (or none). A token that lives longer than 90 days, or
never expires, needs a session with a code from the authenticator app
checked within 15 minutes, platform admins included (security review
2026-10-09, AUTH-3): `403 totpEnrollmentRequired` without a second factor,
`403 stepUpRequired` without a recent code (`POST /v1/auth/step-up`).

### Token clients

A personal access token declares what it is for at creation:
`POST /v1/tokens {..., client}` with `api` (default: scripts and
integrations), `terraform`, `cli` or `mcp`. The token record (and the
manifest) stores it and `GET /v1/tokens` shows it. The plan gates every
request of a `terraform`, `cli` or `mcp` token by that client
(`402 plan_limit_reached`, action `access.terraform`, `access.cli` or
`access.mcp`), whatever its `User-Agent`. Creating a token for a client
the plan (or the license) does not include is refused up front with
`400 plan_limit_reached` (same details, `upgradeTo` names the plan that
unlocks it); a token minted before a downgrade keeps getting the 402 on
every call. An OAuth client declares itself
at registration with the RFC 7591 `software_id`: one starting with
`rdnsctl` is gated as the CLI, one starting with `terraform` as the
Terraform provider (`rdnsctl login` and the Terraform provider register
with them). An `api` token, an older token without a client and an OAuth
client with any other `software_id` fall back to the `User-Agent`
declaration (`rdnsctl/`, `terraform-provider-redundantdns/`), which the
go-client sets. Declarations are not proofs: they keep honest clients
inside their plan.

### Scopes

`zones:read`, `zones:write`, `connections:read`, `connections:write`,
`domains:read`, `domains:write`. A
token request needs the route's scope and the user's minimum role
(viewer < editor < admin < owner); each operation's description in the
OpenAPI document states both.

`domains:transfer` lets a token take a domain out: reveal its EPP auth
code, unlock it and offer a hand-off (A-L5), and change who owns it
(REG-4, security review 2026-10-09): `POST
/v1/domains/{name}/registrant`, replacing an existing registrant profile
(`PUT /v1/domains/registrant-profile`; creating the first one is open)
and editing a contact that owns a domain or is the profile (`PUT
/v1/domains/contacts/{contactId}`: the owner's e-mail receives the
registry's transfer confirmations and, at some registries, the auth
code). These need a dashboard session or a PAT minted with this scope,
which is granted only when asked for explicitly (the answer's `warnings`
and the Tokens page say what it allows) and never through OAuth, so an
MCP connection over OAuth gets `403 transferScopeRequired` there.
Locking a domain, editing a contact that owns nothing and every other
domain route keep `domains:write`. The exit guarantee is
unchanged: the dashboard always reveals the code and unlocks, whatever
the plan or the terms.

`org:export` lets a PAT request the organization export and read its
download link (`POST /v1/orgs/{orgId}/export`, `GET
/v1/orgs/{orgId}/exports/{jobId}`; security review 2026-10-09, AUTH-1):
the bundle opens every provider credential with the passphrase the
caller chooses. Like `domains:transfer` it is PAT-only, granted only
when asked for explicitly (with a warning) and never through OAuth;
without it a token gets `403 exportScopeRequired` and the export is
requested from the dashboard. There is no MCP export tool.

`ops:backup-report` is an operations scope: only platform admins can
create a PAT with it (`403 platformScope` otherwise; the Tokens page
offers it to them only), OAuth clients never get it, and it opens a
single route, `POST /v1/ops/backups/report` ("Offsite backup reports"),
which also checks at every call that the token's owner is still a
platform admin.

### IP allowlists

The org allowlist and the token's (PAT allowlist, or the OAuth token's
snapshot of the org allowlist at issuance) are enforced on every token
request. A multi-org OAuth token carries one snapshot per organization:
the token is accepted when any of them allows the address, and each
request is checked against the live allowlist of the organization it acts
on. The client IP is the TCP peer, or, for requests from a trusted
proxy (`RDNS_TRUSTED_PROXIES`), the `X-Forwarded-For` entry
`RDNS_FORWARDED_COUNT` positions from the right.

### Rate limits

Beyond the sign-in limits above (2026-10-09 review, AUTH-4), every answer
`429 tooManyRequests` with `Retry-After`:

- `/v1` (MCP tool calls included): 600 requests a minute per PAT or
  OAuth token (`RDNS_API_RATE_PER_MINUTE`) and 1200 per signed-in
  dashboard user (`RDNS_API_SESSION_RATE_PER_MINUTE`); the sandbox keeps
  its own per-token limit. In memory per control plane instance.
- `GET /v1/domains/check` (and so the MCP `domain_check` tool and its
  `privacyDefault`): 30 a minute per organization and per client IP. The
  data plane also reuses a registrar answer (availability or price) for 60
  seconds per name, operation and years.
- `POST /v1/zones/{id}/verify`, `POST /v1/zones/{id}/delegation/check`
  and a fresh `POST /v1/zones/{id}/insights/run`: once per zone every 10
  minutes; a second one answers `409 cooldown` with
  `details.retryAfter` (seconds) and `Retry-After`. Scheduled runs are not
  affected. Off with `RDNS_E2E`.
- Zone insights check at most 500 targets over the network per run (the
  rest keep their previous check or wait for a later run) and 5000 per
  organization per UTC day (per data plane process).
- Alert channels (AUTH-5): 5 tests an hour per channel, 3 verification
  e-mails an hour per e-mail channel, both also within the organization's
  mail limit; `POST /v1/orgs` 5 an hour per user and at most 10 owned
  organizations (`409 tooManyOrganizations`). See Alerts, "E-mail
  channels: double opt-in".

## OAuth 2.1 authorization server

Metadata: `GET /.well-known/oauth-authorization-server` (RFC 8414) and
`GET /.well-known/oauth-protected-resource[/mcp|/v1]` (RFC 9728); keys at
`/.well-known/jwks.json`. The issuer is `RDNS_PUBLIC_URL`, never a request
header.

| Endpoint | Purpose |
|---|---|
| `POST /oauth/register` | dynamic client registration (RFC 7591); `software_id` and `software_version` are stored and echoed (a `software_id` of `rdnsctl…` or `terraform…` gates the client as the CLI or the Terraform provider, see Token clients). Public clients (`token_endpoint_auth_method: none`) with the same redirect set and the same metadata (name, URIs, scopes, grant types, `software_id`) get the same `client_id` back, unchanged; different metadata gets a new `client_id` and never rewrites the existing client (registration is unauthenticated); confidential clients get a new id and a secret shown once. Redirect URIs: https, http on loopback only, or a native-app scheme; exact match later. 20 successful registrations per IP per hour per instance |
| `GET /oauth/authorize` | `response_type=code`, `client_id`, `redirect_uri`, `code_challenge` (S256 only), `state`, `scope`, optional `resource`. Redirects to the consent UI (`RDNS_OAUTH_CONSENT_PATH?request=<id>`); a GET never issues a code (security review 2026-09-28, A-M4). When the user approved this client for these scopes within 30 days, the consent UI is a compact "Continue as <email>" screen, still a `POST /oauth/authorize/decision`. Only `prompt=none` from a trusted client (redirect hosts in `RDNS_OAUTH_TRUSTED_DOMAINS`) with such an approval and a `state` of at least 16 characters goes straight back with a code; a `prompt=none` that cannot be answered that way goes back with `error=login_required`, `consent_required` or `invalid_request` (short state), never to a screen |
| `GET /oauth/consent?request=<id>` | the SPA consent page (`RDNS_OAUTH_CONSENT_PATH`): signs the user in and asks for the legal acceptance in place when needed, shows the client, its redirect host and the requested scopes, and posts the decision |
| `GET /oauth/authorize/request?request=<id>` | consent details for the signed-in user (client, requested scopes, the user's orgs, `maxOrgs`, and `rememberedOrgId` / `rememberedOrgIds` (default first) when a recent approval covers these scopes) |
| `POST /oauth/authorize/decision` | JSON `{request, approve, orgId, orgIds, scopes, orgScopes}` from the consent UI; returns `{redirectTo}`. `orgIds` (up to 20) are the organizations granted, `orgId` the default one (must be one of them; the first of `orgIds` when empty); `orgScopes` optionally narrows one organization's scopes (`{"<orgId>": ["zones:read"]}`). `{orgId}` alone is a single-org grant, as before. Every organization must be one of the user's (`403 access_denied` otherwise) |
| `GET /oauth/consent-fallback?request=<id>` | minimal server-rendered consent (sign in with an e-mail code, accept the current Terms and Privacy Policy when needed, check the organizations (the first checked is the default) and the scopes) |
| `POST /oauth/token` | `authorization_code` (with `code_verifier`) and `refresh_token` (optional narrower `scope`) |
| `POST /oauth/revoke` | RFC 7009; revoking a refresh or access token revokes its whole grant |

Rules mirrored from `zodo:auth-mcp-kit`:

- Codes are single use (10 minutes). A replayed code revokes the grant it
  issued.
- Refresh tokens rotate on every use (30 days). Reusing a rotated refresh
  token revokes the whole family (all its refresh and access tokens).
- Scopes granted = requested ∩ catalog ∩ the client's registered scopes;
  consent may narrow them; refresh may narrow them, never widen.
- Access tokens are Ed25519 JWTs (`typ: at+jwt`) with `sub`, `org`,
  `scope`, `client_id`, `gid` (grant id), `ipa` (org IP allowlist
  snapshot), `iat`/`exp` (1 hour). They are verified offline: signature,
  expiry, IP snapshot and the user's revocation list in the bucket. The
  control plane also checks that the user is still a member of the org.
- A multi-org grant: `org`, `scope` and `ipa` are the default
  organization's, and `orgs` lists every granted organization (default
  first) as `{org, scope, ipa}`; a single-org token has no `orgs` claim.
  The default organization is the grant's home: its codes, refresh tokens
  and revocation list live there, and disconnecting the app there (or
  leaving it) ends the grant. Each organization keeps its own approval
  record; acting on another one checks it live (still a member, approval
  present, not cut off by that organization's revocation list), and a
  refresh drops the organizations that fail those checks.

### Connected apps

A signed-in user lists the OAuth clients they approved, per organization,
with `GET /v1/me/oauth/grants` (client, scopes, approval time, live refresh
tokens) and disconnects one with `DELETE /v1/me/oauth/grants/{clientId}`
(optionally `?orgId=`). A multi-org grant is listed in each of its
organizations; disconnecting it in one removes only that organization
from the grant, except the default one, which ends it. Disconnecting writes a per-client cut-off in the
user's revocation list (every access token of that client issued until
then fails verification, offline too), revokes its refresh tokens and
forgets the approval, so the next authorization asks again. The token
endpoint issues nothing for a grant of a disconnected app: a code still
in flight, or a refresh token that escaped the revocation pass by racing
the disconnection, answers `invalid_grant` (the approval must exist and
the grant must postdate the client's cut-off, kept 30 days; security
review 2026-10-09, AUTH-L8). Both routes are dashboard-session only; the SPA shows them under **API tokens →
Connected apps**.

## Members and invitations

An organization's members and their roles live in the sealed manifest
(`members`), the source of truth; each user's record in `users/` mirrors
their memberships so a session knows its orgs. Roles, from most to least
privileged: `owner` (everything, including billing, members and
ownership), `admin` (connections, zones, members, settings), `editor`
(creates zones and edits records; deleting a zone, attaching or detaching
a provider need `admin`), `viewer` (read-only). Every org request checks the
caller's role in the manifest, so a role change or a removal applies to
the next request.

Dashboard session only (tokens get `403 sessionRequired`; no MCP tool):

| Route | Who | What |
|---|---|---|
| `GET /v1/members` | any member | `{members: [{userId, email, role, joinedAt, lastLoginAt}], invites: [...]}`; `invites` (pending invitations with `inviteId, email, role, invitedBy, invitedByEmail, createdAt, expiresAt, expired`) is filled for owners and admins only |
| `POST /v1/invites {email, role}` | owners, admins | creates the invitation (7 days) and e-mails an accept link `<RDNS_PUBLIC_URL>/invite#<token>` (the token in the fragment, never sent to a server); `201 {invite}`. Inviting the same address again replaces its pending invitation (the old link stops working); `409 alreadyMember` for a member; only owners invite owners (`403 ownerOnly`). There is no members limit in the plan catalog today. Sending is limited (with hand-off offers): 10 per recipient and 50 per organization per day, `429 tooManyRequests` with `Retry-After` beyond |
| `DELETE /v1/invites/{inviteId}` | owners, admins | revokes a pending invitation (an owner invitation: owners only) |
| `POST /v1/invites/accept {token}` | the invitee's session | the signed-in e-mail must match the invitation's (case-insensitive, `403 inviteEmailMismatch`); joins with the invited role and consumes the invitation: `200 {orgId, name, role}`. `404 inviteNotFound` (unknown, revoked, replaced or used), `410 inviteExpired`, `409 alreadyMember` (the invitation is consumed, the role kept). Outside the org scope: no `X-RDNS-Org` needed |
| `PATCH /v1/members/{userId} {role, transferOwnership?}` | owners, admins | changes a role. Admins cannot grant the owner role (`403 ownerOnly`) nor change an owner (`403 ownerProtected`); nobody changes their own role (`403 cannotChangeOwnRole`); the last owner is never demoted (`409 lastOwner`; in practice only an owner changes an owner and nobody changes their own role, so a sole owner's own attempt answers `403 cannotChangeOwnRole` and `409 lastOwner` shows on leave or removal). `transferOwnership: true` (owners, `role: owner`): the member becomes owner and the caller admin in one write |
| `DELETE /v1/members/{userId}` | owners, admins | removes a member (an owner: owners only, never the last one; yourself: `400 cannotRemoveSelf`, use leave). Their personal access tokens for the org are revoked in the same write and their OAuth clients for the org disconnected |
| `POST /v1/members/leave` | any member | leaves the org (the last owner cannot, `409 lastOwner`); revokes the caller's tokens for it |

The token is `rinv_<orgId>_<inviteId>_<secret>` (256-bit secret); only its
SHA-256 is stored, in the manifest's `invites`. It travels once, in the
invitation e-mail (security stream), in the link's fragment: browsers
never send it, so no access log records it (A-L2). The dashboard's
`/invite#<token>` page asks for the e-mail code when signed out and for
the legal acceptance when due, then accepts (`POST /v1/invites/accept
{token}`) and opens the organization. Links of older e-mails
(`/invite/<token>`) keep working until 2026-10-28 (the server logs a
deprecation line; the page moves the token to the fragment); from
2026-10-29 00:00 UTC they answer `410 tokenInUrlRetired` (security review
2026-10-09, AUTH-L2). A new user who signs in
there also gets their own first organization, as on any first sign-in.

Audit (and so the audit stream): `org.invite.create`, `org.invite.revoke`,
`org.member.join` (actor: the invitee), `org.member.role` (`from`, `to`,
`transferOwnership`), `org.member.remove` and `org.member.leave` (with the
number of revoked tokens and OAuth clients).

## Legal acceptance

A dashboard session must accept the current Terms of Service and Privacy
Policy (`GET /v1/legal/versions`, `GET /v1/me/legal`,
`POST /v1/me/legal/accept`) before using the rest of `/v1`; until then it
gets `428 legal_acceptance_required`. PAT and OAuth bearers (and MCP tool
calls) are not gated, because no token is issued without it: the OAuth
server never issues a code to a user without a current acceptance
(`POST /oauth/authorize/decision` answers `428 legal_acceptance_required`,
and a `prompt=none` answers `consent_required`), and the fallback consent page
shows a terms step (`POST /oauth/consent-fallback/terms`, recorded exactly
like `POST /v1/me/legal/accept`) before consent. See `docs/dev.md`.
`GET /v1/legal/versions` also returns the current versions of the
per-organization documents: `managedTerms` (the Managed Provider Terms),
`domainTerms` (the Domain Registration Terms) and `nameserversTerms` (the
RedundantDNS Nameservers Terms), all below.

### Managed Provider Terms

Managed connections (platform-owned provider accounts) are governed by the
Managed Provider Terms and Acceptable Use Policy (`/legal/managed-terms`),
accepted once per **organization** by an owner or admin, with a session or
a token:

| Route | Access | What it does |
|---|---|---|
| `GET /v1/legal/managed` | viewer + `connections:read` | `{current, accepted: {version, acceptedAt, userId, ip} \| null, required, url}` |
| `POST /v1/legal/managed/accept` `{version}` | admin + `connections:write` (session or PAT) | records the acceptance in `billing.json` (audit `org.managedTerms.accept`) and returns the same body; a version other than the current one answers `409 legalVersionMismatch` |

Until the org accepts the current version, `POST /v1/connections` with
`mode: managed` and attaching a managed connection answer `428
managed_terms_required` with `details: {version, url}` (after the plan
check). `POST /v1/connections` also takes `acceptManagedTerms: "<version>"`
(Terraform, rdnsctl): the acceptance is recorded the same way before the
connection is created. A new version asks again before the next managed
connection or attachment; existing managed zones keep being served. The
RedundantDNS nameservers (`rdns-ns`) are not covered by these terms: they
have their own, below.

### RedundantDNS Nameservers Terms

The RedundantDNS nameservers (`rdns-ns`, our own nameserver nodes) are
governed by the RedundantDNS Nameservers Terms (`/legal/nameservers-terms`),
accepted once per **organization** by an owner or admin, separately from
the Managed Provider Terms: an org that accepted the Managed Provider Terms
has not accepted these.

| Route | Access | What it does |
|---|---|---|
| `GET /v1/legal/nameservers` | viewer + `connections:read` | `{current, accepted: {version, acceptedAt, userId, ip} \| null, required, url}` |
| `POST /v1/legal/nameservers/accept` `{version}` | admin + `connections:write` (session or PAT) | records the acceptance in `billing.json` (`nameserversTerms`, audit `legal.nameserversTerms.accept`) and returns the same body; a version other than the current one answers `409 legalVersionMismatch` |

Until the org accepts the current version, `POST /v1/connections` with
`provider: "rdns-ns"` and attaching an rdns-ns connection answer `428
nameservers_terms_required` with `details: {version, url}`. Both calls also
take `acceptNameserversTerms: "<version>"`: the acceptance is recorded the
same way first. A new version asks again before the next rdns-ns connection
or attachment; zones already attached keep being served.

## Providers and connections

`GET /v1/providers` lists the providers this installation offers, each
with its credential fields (`credentialFields`, write-only; `secretFields`
render as passwords), optional scope fields (`scopeFields`, returned in
`scopeHints`), the label of its zone id for "manage an existing zone"
attachments (`zoneIdLabel`), its capabilities, whether a managed
account exists and `policies`: the permission block of the provider guide
per access level (`{zone_admin|zone_editor|mirror_source: {format, text}}`,
`format` the fence language, `""` for plain text or `permissions` for a
Cloudflare token table), extracted from the blocks marked `` in `docs/providers/<provider>.md`, the only copy (the
dashboard's "Permissions to grant" panel shows it). `POST /v1/connections`
takes `{provider, label, accessLevel, credentials, sealedFields,
scopeHints}` with those fields; `accessLevel` is `zone_admin`,
`zone_editor` or `mirror_source`. `credentials` and `sealedFields` are
optional (see "Sealed credentials" and "Connections awaiting credentials"
below).

### Sealed credentials

A secret credential field can travel end to end encrypted, so it never
shows in plain text in a client, an AI tool call or its transcript. Each
organization has an age X25519 identity (https://age-encryption.org),
created on first use and stored sealed with the org DEK inside the sealed
manifest (`credentialSealingKeys`).

| Route | Access | Answer |
|---|---|---|
| `GET /v1/connections/sealing-key` | admin + `connections:write` | `{recipient: "age1...", keyId, createdAt}`; the first call creates the identity (audit `connection.sealing_key.create`) |
| `POST /v1/connections/sealing-key/rotate` | admin + `connections:write` | `{recipient, keyId, createdAt, previousKeyId}`: a new current identity; the previous ones are kept, so ciphertext sealed for them still opens (audit `connection.sealing_key.rotate`) |

The client seals each secret field for the recipient, ASCII-armored
(`age -r age1... -a < key.pem`, or a vault that seals for a public key),
and sends it in `sealedFields` (field name to armored ciphertext) on
`POST /v1/connections` or `PATCH /v1/connections/{connectionId}`; the
non-secret fields may stay in `credentials`. The secret fields, by the
providers' credential schemas (`secretFields` of `GET /v1/providers`):
route53 `secretAccessKey`, oci `privateKey`, gcp `serviceAccountJson`,
azure `clientSecret`, cloudflare `apiToken`, selfhost `apiKey`; any
credential field may be sealed. The server opens every sealed field with
the org's identities (current and retired), merges them into the
credentials and validates and tests them as usual.

- `400 sealedFieldConflict` (`details.field`): the same field in
  `credentials` (non-empty) and `sealedFields`.
- `400 sealedFieldUnknown`: not a credential field of the provider.
- `400 sealedFieldInvalid` (`details.field`, `details.reason`): not an
  armored age message, or it does not decrypt with the org's keys (sealed
  for another recipient, damaged), or the value is empty or not text. The
  error names the field only, never a value.
- `400 sealedFieldTooLarge`: more than 8 sealed fields, a field over 32
  KiB armored (16 KiB decrypted) or 96 KiB in total.
- A sealed value is never logged nor audited; the audit entry of the
  create or update lists `sealedFields` (the names). A provider error that
  echoes a submitted value is redacted before it is returned.
- Plain `credentials` stay accepted. Through the MCP server, a secret field
  sent in plain text adds a `warning` to the answer (it passed through the
  AI conversation and should be rotated at the provider) and
  `plaintextSecretFields` (the names) to the audit entry.

### Connections awaiting credentials

A BYO `POST /v1/connections` with neither `credentials` nor `sealedFields`
saves the connection untested with status `awaiting_credentials` and
answers `201 {connection, deferred: false, awaitingCredentials: true,
credentialsUrl}`. `credentialsUrl` (also on the connection in `GET
/v1/connections` while it waits) is the dashboard page,
`<public URL>/providers/<connectionId>`, where an organization admin
signed in with the usual session and step-up rules pastes the credentials;
they go through `PATCH /v1/connections/{connectionId}` (tested first, then
saved), after which the status is `ok` (or `pending` for a zone-scoped
grant). A partial set of credentials is still `400 credentialsIncomplete`.

Until then the connection cannot be attached (`409
connectionAwaitingCredentials`) nor tested (`POST .../test`, same 409); the
data plane refuses it on every path. It has no attachment, so no job uses
it and it raises no alert nor sync error: waiting is not broken. The
dashboard flags one waiting for more than 7 days; nothing is deleted
automatically. Managed connections are unchanged.

Each provider also carries `status`: `available`, or `coming_soon` for a
provider that is listed but not offered yet. Azure DNS is coming soon
(owner decision 2026-09-30): `POST /v1/connections` with `provider:
azure` answers `422 providerComingSoon` (`details: {provider, status}`),
in BYO and managed mode and through MCP. Only creation is gated: an Azure
connection that already exists keeps working (test, replace credentials,
attach, reconcile, delete, org export and import). The operator turns it
on without a release with `rdns config set featureFlags.providerAzure
true` (the provider then lists as `available`).

| Provider id | Credentials | Scope hints | Zone id (`zone_editor`, `mirror_source`) |
|---|---|---|---|
| `route53` | `accessKeyId`, `secretAccessKey` | `region` | hosted zone id |
| `oci` | `tenancyId`, `userId`, `fingerprint`, `privateKey` | `compartmentId`, `region` | zone OCID (or the zone name; the OCID is stored) |
| `gcp` | `serviceAccountJson`, `projectId` | | managed zone name |
| `azure` (coming soon) | `tenantId`, `clientId`, `clientSecret`, `subscriptionId` | `resourceGroup` | zone resource id |
| `cloudflare` | `apiToken` | `accountId` | zone id |
| `selfhost` | `apiUrl` (https, public address), `apiKey`, `nameservers` (comma separated NS names, one at least) | `serverId` (default `localhost`) | zone name (`example.com.`) |
| `rdns-ns` | none: managed only (`mode: managed`) | | zone name (`example.com.`) |
| `fake` | `token` | | zone id (e2e only) |

A `selfhost` connection points at a PowerDNS Authoritative server run by
the customer (`docs/providers/selfhost.md`); its `nameservers` are the
names it contributes to every attached zone's NS plan. The data plane
refuses an `apiUrl` over plain http or resolving to a non-public address,
except the destinations listed in `RDNS_SELFHOST_PRIVATE_ALLOWLIST` (plain
http only for a literal IP in the list) and anything in dev and e2e.

### RedundantDNS nameservers (`rdns-ns`)

`rdns-ns` is the nameservers the platform runs
(`docs/providers/rdns-ns.md`). `GET /v1/providers` lists it only when the
installation has nameserver nodes, with `managed: true` and `managedOnly:
true`. It is created with `POST /v1/connections` `{provider: "rdns-ns",
mode: "managed", label?, acceptNameserversTerms?}` (no credentials; as BYO
`400 managedOnly`; without nodes `400 managedUnavailable`), needs the
RedundantDNS Nameservers Terms (not the Managed Provider Terms; `428
nameservers_terms_required`), and is **included in
every plan, the trial too** (no `connection.managed` check, no
pass-through line). It still counts toward `providersPerZone`, except on a
free zone.

**Free DNS for domains registered here.** A zone is free (`free: true` in
the zone view, `GET /v1/zones` and `GET /v1/zones/{zoneId}`) when its name
equals a live domain of the same organization registered or transferred
through the platform: the registration or the transfer in completed and
was not canceled by an admin, and the registrar does not report the
domain expired or deleted (a domain handed off to another organization
keeps it). Freeness is computed on every request, never stored: a domain
that expires stops making its zone free (the plan gates apply again, the
zone and its records are kept), and a renewal makes it free again. For a free
zone, whatever the plan or the billing state:

- `POST /v1/zones` skips the zone limit and `402 org_read_only`; free zones
  never count toward the zone limit of the other zones (nor toward usage).
- Attaching `rdns-ns` in the active role skips `providersPerZone` and
  `402 org_read_only`, and that attachment is not counted for the other
  providers of the zone. Any other provider, and `role: standby`, follow
  the plan and the read-only gate.
- Records (`PUT`/`DELETE .../records`), `POST .../reconcile`, detach and
  zone delete stay open while the organization is read-only; the data
  plane keeps applying the zone's `rdns-ns` attachment and only verifies
  the others.
- `POST /v1/connections` for `rdns-ns` works while read-only when the
  organization has at least one live domain registered or transferred
  here.
- The billing detach keeps `rdns-ns` on free zones; a detached organization
  loses it on the next billing pass once the zone stops being free.
- The Nameservers Terms still apply, and MCP stays a plan feature.
- **Nameservers applied at the registrar automatically.** When such a zone
  has `rdns-ns` active and its NS plan (two or more names) is new or
  changed, and every active attachment serves the zone, the data plane
  queues the registrar `nameservers` operation of the domain with the plan
  (the same operation as `POST /v1/domains/{name}/nameservers/apply-zone`),
  unless the domain's nameservers already are the plan. Each plan is
  applied at most once per domain: a manual change of the nameservers
  afterwards stays until the plan itself changes. Audited as
  `domain.nameservers.autoApply` (`source: system`, details `zoneId`,
  `nameservers`, `previous`), with a `nameservers.auto` line in the
  domain's activity. A transferred-in domain qualifies only when the
  transfer asked for the zone's NS (`applyZoneNs`); one that kept its
  current nameservers or took the registrar default is never rewritten
  automatically (apply-zone by hand stays open). Never for a domain not
  registered or transferred here (or expired, deleted, canceled), nor for
  a zone without `rdns-ns`.

The zone view also carries `domainRegisteredHere` (the domain named like
the zone is registered or transferred through the platform and live,
whatever the billing: RedundantDNS is the registrar) and `domainNsPlanApplied` (with
it, the domain's nameservers at the registrar, as last read, are the NS
plan). The dashboard's Delegation tab uses them to offer "Apply at the
registrar" (apply-zone, then a delegation check) instead of the manual
instruction, and, when the plan is applied but the delegation check still
reports a mismatch, to say the registry (the parent zone) has not published
it yet.

Attached to a zone it creates the zone on every active node; the
attachment's `nameServers` are every active node's NS name (so the NS plan
lists them all) and its `providerZoneId` is the zone name. Every sync runs
node by node, and the attachment status carries one entry per node:

```json
"nodes": [
  {"name": "altair-na", "region": "na", "nsName": "altair-na.redundantdns.org.", "state": "failed", "lastSyncAt": "...", "error": "selfhost: HTTP 503"},
  {"name": "vega-latam", "region": "latam", "nsName": "vega-latam.redundantdns.org.", "state": "ok", "lastSyncAt": "..."}
]
```

`state` is `ok`, `failed` or `pending`. While some nodes fail and others
are in sync, the attachment stays `in_sync` with the finding
`nodes_partial` (`names`: the failing nodes); it is `error` only when every
node fails. Detaching (or deleting the zone, or a billing detach of a
zone that is not free) deletes the zone on every node, whatever
`deleteRemote` says; each node zone records the org as its PowerDNS
`account`. When the operators drain or activate a
node, every rdns-ns attachment's `nameServers` change: the zone gets a new
serial (journal action `zone.nsnodes.update`), every attachment is
reconciled and the delegation is checked again.

### Replacing credentials (key rotation)

A key rotated or revoked at the provider puts every attachment of its
connection in `error`. `PATCH /v1/connections/{connectionId}` (admin +
`connections:write`) replaces the credentials in place, without detaching
anything:

```json
{"credentials": {"apiUrl": "https://pdns.example.net", "apiKey": "<new key>", "nameservers": "ns1.example.net, ns2.example.net"},
 "scopeHints": {"serverId": "localhost"}, "label": "PowerDNS (rotated)"}
```

- Every field of the provider is required (as on create), in `credentials`
  or sealed in `sealedFields` ("Sealed credentials" above); it is
  write-only and sealed with the org DEK like on create. The same route
  adds the credentials of a connection `awaiting_credentials`.
  `scopeHints` (replaces the stored ones) and `label` are optional; omitted,
  they are kept.
- The new credentials are **tested first**, with the create check, and
  also against the provider zone of every attachment of the connection (a
  key of another account, or one that lost access to an attached zone, is
  refused). On failure nothing is saved: `422 providerRejected` with the
  provider's message, and the stored credentials keep working.
- A refused attempt is audited as `connection.credentials.update.failed`
  (actor, provider, access level, the provider's message and the
  identifier hint, never a secret), so a leaked or stale key being tried
  shows in the audit log.
- On success the connection's status is `ok` (`pending` for a `zone_editor`
  connection with no attachment, as on create), the audit log records
  `connection.credentials.update` (actor, provider, scope hints; never a
  secret) and a reconcile runs at once for every attachment of the
  connection (`jobIds` in the answer), even one waiting out a retry backoff,
  so the `error` state clears without a manual reconcile.
- Provider, mode and access level never change: sending another value
  answers `400 connectionImmutable` (create a new connection instead). A
  managed connection has no credentials to replace: `400
  connectionManaged`.
- The route is not blocked for a read-only (unpaid) organization: replacing
  a leaked key stays possible. A `selfhost` connection's `nameservers` are
  read when a zone is attached: changing them here does not move the NS
  plan of zones already attached (detach and attach again for that).

The dashboard's Providers page offers it as "Replace credentials" on each
BYO connection; the MCP tool is `provider_connection_update`.

Connection status: `ok` once a test or an attach verified the credentials
at their access level, `error` after a failed test, `pending` only
while nothing verified them, and `awaiting_credentials` for a BYO
connection created without credentials. A `zone_editor` (or `mirror_source`) connection can only be
verified against a zone: it is `pending` from its create until its first
attach (or a `PATCH` tested against its attached zones) sets `ok`; `POST
/v1/connections/{connectionId}/test` without a zone answers `{ok: true,
deferred: true}` and keeps an `ok` connection `ok`.

## Record sets: search and paging

`GET /v1/zones/{zoneId}/records` (viewer + `zones:read`) has two forms.

- Without `q`, `type`, `limit` or `cursor` it answers the historical form,
  a bare array of every record set of the zone (existing clients keep
  working).
- With any of them it answers one page:
  `{recordSets, total, matched, limit, nextCursor, types}`. Sets are
  ordered by name, then type. `total` counts every set of the zone,
  `matched` those the filters keep, `types` the zone's sets per type
  (unfiltered, for a type filter). Pass `nextCursor` as `cursor` for the
  next page; it is empty on the last page.

| Parameter | Meaning |
|---|---|
| `q` | case-insensitive substring of the name, the type or one of the values |
| `type` | only this record type (`A`, `MX`...) |
| `limit` | page size: default 100, `0` = every matching set, at most 1000 (`400 invalidLimit`) |
| `cursor` | the previous page's `nextCursor` (`400 invalidCursor` when malformed) |

The cursor holds the (name, type) of the last set of the page, so an edit
between two pages neither repeats nor skips the sets after it. The zone
view (`GET /v1/zones/{zoneId}`) still carries every set; the dashboard's
Records tab reads the paged form. MCP `record_list` takes the same
parameters and asks for 200 sets per page by default.

## Subdomain redundancy (parent delegation)

`POST /v1/zones` takes `parentDelegation` (boolean). When the new zone is a
subdomain of another zone of the organization (`api.example.com` under
`example.com`; the closest parent wins), the platform writes an NS record
set named after the child (`api`) into the parent zone with the child's NS
plan, keeps it equal to the plan whenever the child's attachments change
and removes it when the child is deleted; the data plane's schedule
converges it after a crash and removes delegations whose child is gone.
Omitted means on when such a parent exists; `false` turns it off; `true`
without a parent answers `422 parentZoneNotFound`. The zone view carries
`parentDelegation: {enabled, parentZoneId, parentZoneName, label}`.

Zone names nest only inside one organization once the other
organization's zone is verified (see "Zone names, claims and takeover
protection" below). The RedundantDNS nameservers serve every
organization's zones from one namespace, so `POST /v1/zones` (and every
path that creates a zone: free DNS, org import) refuses a name that is a
strict subdomain of a verified zone another organization manages (`409
zoneNameUnderAnotherOrg`) or a strict parent of one (`409
zoneNameAboveAnotherOrg`). The answer never names the other organization.

### Zone names, claims and takeover protection

A zone name is claimed platform-wide (`zone-names/<name>`) by the
organization that creates it. Since the 2026-10-09 security review (DP-1,
DP-2):

- **Public suffixes** are nobody's zone: a name on the Public Suffix List
  (ICANN or private section: `com.br`, `co.uk`, `github.io`) or above a
  registrable domain answers `422 zoneNamePublicSuffix` ("this name is a
  public suffix; create the zone of a registrable domain"). A registrable
  domain (`example.com.br`) and every name below it are allowed.
- **Domains held here**: a name that another organization holds on the
  platform as a domain (registered, transferred in, or a registration or
  transfer in progress; `domain-names/<name>`), or a name under such a
  domain (`www.victim.com` under `victim.com`), answers `409
  zoneNameTaken` ("this domain is held by another organization on this
  platform"). A registration or transfer a platform admin canceled holds
  nothing.
- **Deleted zones leave a tombstone**: `DELETE /v1/zones/{zoneId}` keeps
  the claim for 30 days with `releasedBy` and `releasedAt`. Only the
  organization that deleted the zone may create the name again in that
  window; another organization gets `409 zoneNameTaken` with
  `details.releasedUntil` (RFC 3339). After the window the name is free.
- **Verified claims**: a zone is verified when its organization registered
  or transferred its domain through the platform (live), or when its last
  delegation check found the parent delegating to its nameservers
  (`complete` or `partial`). Only a verified zone keeps other organizations
  out of the names nested with it; an unverified one (a zone created for a
  name nobody delegated) gives way. `rdns doctor` lists unverified claims
  older than 30 days (`zone_claim_unverified`, informational).
- **Proof of control before the RedundantDNS nameservers serve a name**:
  attaching `rdns-ns` reads the public delegation of the zone's name and of
  its parents down to the registrable domain. When one of them already
  points at the platform's nameservers (a delegation left behind by a
  deleted zone, or a domain delegated before its zone exists), the attach
  answers `409 delegationOwnedElsewhere` unless the organization registered
  or transferred the domain here (live), created the zone again from its
  own tombstone, or the delegated parent is a zone of the same
  organization. The zone's age never counts (an old zone proves nothing),
  and the check runs at attach only: existing attachments are never
  checked again. The proof is a TXT record `_rdns-challenge.<zone>` whose
  value is the zone's token, answered by a nameserver the delegation lists
  that is not a RedundantDNS nameserver (those would answer from whichever
  organization's zone they hold). The zone view carries it as
  `challenge: {name, value}`; the 409 carries `details.delegatedName`,
  `details.challengeName` and `details.challengeValue`. A domain whose
  dangling delegation lists only the RedundantDNS nameservers proves
  control in one of three ways: add one of its own nameservers to the
  delegation temporarily (serving the TXT) and attach again, register or
  transfer the domain here, or, for the organization that deleted the
  zone, create it again inside the 30-day tombstone window.

In the parent, those record sets carry `managedBy: "delegation"`,
`childZoneId` and `childName` (zone view and `GET .../records`); editing or
deleting one answers `409 recordSetManaged`, and adopting a provider's
records never replaces them. The parent's providers receive the set like
any other record, so any provider works as the parent, including
Cloudflare with "manage an existing zone" access.

### Adopting an existing provider zone (data safety)

Attaching a `zone_admin` connection with `adoptExisting: true`, or a
`zone_editor` connection with `providerZoneId`, adopts a provider zone that
may already serve records. The platform never deletes them silently (the
2026-09-28 incident: a new, empty canonical zone adopted a live zone and
the reconcile queued by the next attach deleted its four record sets).
`POST /v1/zones/{zoneId}/attachments` reads the provider zone first (a zone
it cannot read refuses the attach: `422 providerRejected`) and compares
its record sets with the canonical zone. The provider-managed apex NS and
SOA sets are never compared, imported or deleted.

- **Empty canonical zone** (no record sets): the provider's sets are
  **imported** into it before anything reconciles, with a new serial
  (journal action `zone.records.import`) and the audit entry
  `zone.records.import` (`details: {count, sourceAttachmentId, provider,
  providerZoneId, sets, skipped}`). The answer adds `imported: {sets,
  skipped[]}`; `skipped` lists the sets not imported, with a reason:
  `notModeled` (a type the platform does not model) or a capability reason
  (a set another attached provider cannot serve). The attachment is
  reconciled at once.
- **Canonical zone with records**, and at least one set **only at the
  provider**: `409 adoptWouldDelete` with the diff as `details`:
  `{providerZoneId, providerRecordSets, canonicalRecordSets, providerOnly:
  [recordSet], canonicalOnly: [recordSet], different: [{name, type,
  provider: {ttl, values}, canonical: {ttl, values}}], mirrored}`. Nothing
  is attached. Repeat the call with `onAdopt`:
  - `"import"`: the provider-only sets are merged into the canonical zone
    (the canonical zone wins where both have a set, which needs
    `overwrite: true` when their values differ: see below), as above;
  - `"overwrite"`: explicit; the canonical zone wins and the first
    reconcile deletes the provider-only sets. Audited
    `zone.attachment.adopt.overwrite` (`details: {providerOnly, count,
    via: "attach"}`).
  A mirrored zone cannot import (`409 zoneMirrored` for `onAdopt: import`).
- **Sets both sides hold with other values or TTL** (`different`): the
  canonical zone would overwrite the provider's values, and they would
  exist nowhere else. The attach answers `409 adoptWouldOverwrite` with
  the same diff as `details` unless it carries `overwrite: true` (the
  admin's explicit decision; audited `zone.attachment.adopt.overwrite`
  with `details: {different, count, via: "attach-values"}`) or `onAdopt:
  "overwrite"`. Make the canonical zone match first to keep the provider's
  values. When the attachment writes, the provider zone is snapshotted
  first (overwrites are kept like deletes).
- **No set only at the provider and no different value**: the attach
  proceeds as before (the zone is verified first).
- `409 providerZoneExists` (a `zone_admin` attach without `adoptExisting`)
  carries `details.recordSets`, the number of sets the provider zone holds
  (`-1`: unreadable), so the dashboard shows it before the person confirms.
- **Managed connections** (the platform's account, shared by every
  organization) adopt a zone of that name only when the platform created
  it for the same organization (its ledger, or the owner tag on the zone);
  any other zone answers `409 managedZoneUnavailable` with no details,
  with or without `adoptExisting`. Detaching a managed connection deletes
  its provider zone (snapshot first) unless `keepRemote=true`; `DELETE
  /v1/zones/{zoneId}` does the same for the zone's managed attachments
  (`?keepRemote=true` keeps them), and a billing detach deletes them.

The decision is stored on the attachment (`adoptDecision`: `import`,
`overwrite`, or absent when nothing needed deciding). **First-sync guard:**
until an adopted attachment's first sync has completed (its
`appliedSerial` is still 0), no reconcile deletes a set that exists only at
its provider, whatever queued it (another attach, a record edit, the
reconcile button), unless `adoptDecision` is `overwrite`. The rest of the
diff is written; the kept sets are listed in
`status.attachments[id].adoptKept` and the attachment stays `drift` (and is
not reconciled by the schedule) until the person decides: `POST
.../attachments/{id}/adopt` imports the provider's records, or `POST
/v1/zones/{zoneId}/reconcile {attachmentId, overwrite: true}` (admins
only: `403` for an editor) stores the overwrite decision (audited `zone.attachment.adopt.overwrite`, `via:
"reconcile"`) and deletes them. `overwrite` without `attachmentId`, or on
another job kind, answers `400 invalidOverwrite`. Once the first sync has
completed, the canonical zone is the truth and drift is handled as
before.

### Destructive safety (v0.1.18)

Every write that deletes or overwrites record sets at a provider is
guarded (`planning/destructive-safety.md`). The RedundantDNS nameservers
(`rdns-ns`) have no verify mode and no unmanaged sets, but the snapshot
and the blast-radius limit apply to them too, and so does the limit to a
change of the canonical zone read from a provider (a mirror read, an
import):

- **NS plan: verify and not-yet-synced attachments are not announced
  (v0.1.29).** A new attachment has `nsPending: true` and stays out of
  the zone's NS plan (the other providers' apex NS sets, the delegation
  check, a child zone's delegation in its parent, the registrar's
  nameservers of a domain registered here) until it is in mode `apply`
  and a sync found it in sync (every set the platform manages at its
  provider; unmanaged sets aside). That sync announces it: the plan is
  recomputed, the serial bumped, every attachment reconciled and the
  delegation checked again (journal and audit
  `zone.attachment.announce`). The attach answers the plan without it.
  Its own provider meanwhile gets the plan plus its own nameservers, so
  the announcement changes only the others. Once announced it stays in
  the plan (a later flip to `verify`, a restore or an error does not take
  it out). Attachments created before v0.1.29 are in the plan.
- **Mode.** `attachment.mode` is `verify` (read, diffed and reported, never
  written) or `apply`. A BYO attachment that adopts an existing provider
  zone starts in `verify`; a provider zone the platform creates, a managed
  account and `rdns-ns` start in `apply`; attachments created before
  v0.1.18 have no mode and apply. `PUT
  /v1/zones/{zoneId}/attachments/{attachmentId}/mode {mode}` (admin; a flip
  to `apply` queues a reconcile; audited `zone.attachment.mode`; `400
  invalidMode`, `modeNotApplicable` for `rdns-ns` and `mirror_source`).
- **Origin and unmanaged sets.** Every record set of `GET /v1/zones/{id}`
  carries `origin {kind: platform|imported|mirrored, attachmentId?, at}`.
  A set a provider holds that the zone never had (no origin, and no
  tombstone of the last 90 days) is unmanaged: listed in
  `status.attachments[id].unmanaged`, the attachment stays `drift`, and no
  reconcile deletes it. `POST .../attachments/{attachmentId}/unmanaged
  {action: "import" | "delete", sets: ["www A"]}` (admin) imports them
  (origin `imported`, every attachment reconciled) or deletes them at this
  provider only, after a snapshot; audited
  `zone.attachment.unmanaged.import` / `.delete`; `422 unmanagedNotFound`
  (answer `details`: the labels not found), `409 zoneMirrored` (import).
- **Blast radius.** An apply that would delete more than
  min(max(`maxSets`, `maxPercent` % of the provider zone's sets),
  `maxAbsolute`) (defaults 10, 20 and 100; platform `destructiveMaxSets` /
  `destructiveMaxPercent` / `destructiveMaxAbsolute`, per org `PUT
  /v1/admin/tenants/{orgId}/destructive-limits {maxSets?, maxPercent?,
  maxAbsolute?, windowHours?}`) writes nothing (on `rdns-ns`: no node is written; the
  largest delete across the nodes counts): state `pending_decision`,
  `status.attachments[id].blocked {serial, deletes, count, providerSets,
  limit, summary, at, reason?, window?, decision?}`, alert
  `blast_radius_blocked`, and the schedule does not retry it. `POST
  .../attachments/{attachmentId}/decision {decision: "confirm" |
  "cancel"}` (admin; audited `zone.attachment.decision`; `409
  noPendingDecision`): confirm queues the reconcile that deletes exactly
  those sets; cancel deletes nothing, protects those sets (below) and
  leaves the attachment `drift` until the zone changes. Support: `POST
  /v1/admin/tenants/{orgId}/zones/{zoneId}/attachments/{attachmentId}/decision
  {decision, ticket, reason}`.
- **No piecemeal deletes (v0.1.29, the pilot rehearsal of 2026-09-30).**
  A held delete can no longer go through in slices:
  - *While a hold waits for a decision, the attachment deletes nothing.*
    A later apply that still deletes sets (the zone changed meanwhile, a
    manual reconcile) is held again with its own deletes and `reason:
    "pending"`, whatever their count, so a subset of the held sets under
    the limit is never applied on its own. An apply that deletes nothing
    goes through and ends the hold (audited `zone.reconcile.unblocked`;
    the alert resolves). Nothing else of the attachment is written
    meanwhile either (the held apply writes nothing at all).
  - *A canceled hold protects its sets.* The sets of a canceled hold go to
    `status.attachments[id].protected {sets, since, decidedBy, held}`: no
    apply deletes them, whatever its size (they are taken out of the
    apply, like unmanaged sets; the attachment stays `drift` and `held`
    lists the ones the canonical zone no longer has). The protection of a
    set ends when the canonical zone holds it again, when its origin
    tombstone expires (it is then unmanaged, never deleted automatically),
    or when an admin releases it: `POST
    .../attachments/{attachmentId}/protected {action: "release", sets?}`
    (every protected set when `sets` is empty; audited
    `zone.attachment.protected.release`; `409 noProtectedSets`) queues a
    reconcile that deletes them within the limits (a larger delete is held
    for a decision as usual). A confirm of a later hold also ends the
    protection of the sets it confirms.
  - *Cumulative window.* The sets the automatic applies of one attachment
    delete are counted in `status.attachments[id].deleteWindow {start,
    deletes, baseSets, hours}`; an apply whose deletes, added to the
    window's, would pass the limit of the zone's size at the window's
    start is held with `reason: "cumulative"` and `blocked.window`. The
    window starts with the first deleting apply and lasts
    `destructiveWindowHours` (default 24, 1 to 720; per org `windowHours`
    in `PUT /v1/admin/tenants/{orgId}/destructive-limits`); a confirmed
    decision starts it again (confirmed deletes, restores and unmanaged
    deletes do not count).
- **Canonical holds.** A mirror read of the source (every minute) or an
  "adopt changes" import (`POST .../attachments/{id}/adopt`) that would
  remove more of the canonical zone's sets than the same limit (counted
  on the canonical zone), or whose provider returned no set at all, changes
  nothing: the source (or imported-from) attachment goes to
  `pending_decision` with `blocked.canonical` (`mirror`, `import`,
  `adopt`), `blocked.reason` (`sourceEmpty` for an empty read) and
  `blocked.deletes` the canonical sets it would remove; audited
  `zone.mirror.blocked` / `zone.import.blocked` / `zone.adopt.blocked`;
  alert `blast_radius_blocked`. The same decision route confirms (the
  mirror reconcile or the import runs again and applies exactly those
  removals) or cancels (a canceled mirror read stays canceled for the same
  removals).
- **Snapshots.** Before an apply that deletes or overwrites record sets
  (since v0.1.29 an update of the apex NS set too), a restore, an
  unmanaged delete, a detach with `deleteRemote` and the delete of an
  `rdns-ns` zone on each node (one snapshot per node), the provider zone
  is stored (the write is refused otherwise: every provider write goes
  through one gateway that needs the snapshot; the `zone.reconcile` and
  `zone.detach` audit entries carry its `snapshotId`)
  with the diff (updates carry the provider's previous values), kept 90
  days, also after the zone is deleted. `GET
  .../attachments/{attachmentId}/snapshots` (viewer) lists the last 50
  (`snapshotId, at, reason, serial, recordSets, summary`). `POST
  .../attachments/{attachmentId}/restore {snapshotId, dryRun?, confirm?,
  idempotencyKey?}` (admin) writes the snapshot back (the sets added since
  are deleted after a snapshot of their own): the attachment is put in
  `verify` before the provider is written. `dryRun: true` answers at once
  (`200`) `{dryRun: true, preview: {snapshotId, snapshotAt, summary,
  providerSets, limit, needsConfirm}}` and writes nothing. **Any other
  restore is asynchronous (v0.1.29):** it answers `202` at once with
  `restore {restoreId, zoneId, attachmentId, snapshotId, confirm, status,
  requestedBy, requestedAt, updatedAt}` and runs as a job in the zone's
  job lane (after the zone's jobs queued before it; no reconcile of the
  zone runs meanwhile). Poll `GET
  .../attachments/{attachmentId}/restores/{restoreId}` (viewer) until
  `status` is `done` (`result`: the answer the synchronous route gave:
  `changed`, `summary`, `snapshotId`, `preview`, `jobIds` of the verify
  queued) or `failed` (`error {status, error, message, details}`: e.g.
  `restoreNeedsConfirm` with the preview when it deletes more sets than
  the blast-radius limit without `confirm: true`, `providerRejected`,
  `snapshotFailed`, `reconcileRunning`); a finished restore is kept 24
  hours (`404 restoreNotFound` after). It never runs twice for one
  request: with an `Idempotency-Key` header (or `idempotencyKey`, up to
  200 characters) the same key answers the same restore for 24 hours,
  whatever its status (`422 idempotencyKeyReused` for another snapshot);
  without one, the same restore sent while it is queued or running
  answers it (sent after it finished, it runs again, which rewrites
  nothing when the provider still matches). `409 restoreRunning` (details:
  the running restore) while another restore of the attachment is queued
  or running. A failed restore is not retried on its own and does not put
  the attachment in `error`. Audited `zone.attachment.restore` (with the
  `restoreId`) when it runs; `404 snapshotNotFound`, `400
  invalidSnapshotId`, `409 snapshotZoneMismatch` answer the POST.
- **Journal.** Each zone journal entry (`GET /v1/zones/{id}/journal`)
  carries `previous`: the record sets the change removed or overwrote, as
  they were.
- **Support restore.** Snapshots outlive their zone (with the zone's
  journal and a sealed copy of the zone, 90 days after the delete). `GET
  /v1/admin/tenants/{orgId}/zones/{zoneId}/snapshots` (platform admin)
  lists every snapshot of a zone, deleted or not (`deleted: {zoneName,
  deletedAt, serial}` for a deleted one). `POST
  /v1/admin/tenants/{orgId}/zones/{zoneId}/snapshots/{snapshotId}/restore
  {ticket, reason, attachmentId?, targetZoneId?, dryRun?, confirm?,
  idempotencyKey?}` restores it onto its own attachment while its zone has
  it, else onto `attachmentId` of `targetZoneId` (default: the org's zone
  with the snapshot's zone name), through the same restore path (queued:
  `202`, polled with `GET
  /v1/admin/tenants/{orgId}/zones/{targetZoneId}/restores/{restoreId}`);
  `409 restoreTargetRequired`, `409 snapshotZoneMismatch`, `402
  org_read_only`; audited `support.zone.snapshot.restore` /
  `admin.support.action` when queued (a dry run records nothing), e-mail
  and `support_action` event; the restore itself is audited
  `zone.attachment.restore` with the ticket when it runs.
- **Write intents (v0.1.30).** Every provider write is preceded by a
  write intent the data plane stores and closes once the write is
  recorded; when the data plane that wrote dies before recording it (a
  killed replica), the worker that takes over records what the provider
  holds of the write, exactly once: the `zone.reconcile` (or
  `zone.attachment.restore`, `zone.attachment.unmanaged.delete`,
  `zone.detach.delete`) audit entry then has `details.recovered: true`,
  `intentId`, `outcome` (`applied`, `partial` or `unknown`), `writerId`
  and `targets`, the deletes raise `provider_records_deleted` and count in
  the cumulative window. A write that never reached the provider is not
  audited. The writer's own entries carry `details.intentId` too.
  `status.attachments[id].recordedIntents` lists the last intents the
  status counted (internal bookkeeping).
- **Alerts.** `provider_records_deleted` (info: opened and resolved at
  once, delivered once) per deleting apply with the count; the platform
  admins' organizations get a daily summary (no zone, the day as the
  attachment id) and a copy of every `blast_radius_blocked` (no zone,
  attachment id `<orgId>:<zoneId>:<attachmentId>`).

## Zone modes: standby attachments and mirror mode

**Standby attachments.** Every attachment has a `role`: `active` (default;
its nameservers are in the NS plan and answer queries) or `standby`
(replicated but never announced). `POST /v1/zones/{zoneId}/attachments`
takes `role`. A standby receives every record like any attachment, but
records only: it is left out of the NS plan, gets no platform apex NS set
(it keeps its own), and the delegation check ignores it. It still counts
for the capability intersection (records must fit everywhere) and for
`limits.providersPerZone`. Standby attachments need the `standby` plan
feature (Pro and above): attaching as standby or demoting on the trial or
Starter answers `402 plan_limit_reached` with action `attachment.standby`
("Plans and billing", Entitlements).

| Route | Access | Notes |
|---|---|---|
| `POST /v1/zones/{zoneId}/attachments/{attachmentId}/role` `{role}` | admin + `zones:write` | `active` promotes a standby (its nameservers join the NS plan), `standby` demotes an active attachment; `409 lastActiveAttachment` when a demote would leave no active attachment, `400 invalidRole`. Every attachment is reconciled, the delegation is checked again, and the change is audited (`zone.attachment.promote`, `zone.attachment.demote`) and journaled. Answer: `{attachment, nsPlan, changed, guidance}` |

`guidance` is the TTL-aware registrar step: `{action: add_nameservers |
remove_nameservers | none, nameServers, nsPlan, nsTtlSeconds,
delegationState, message}`. `nsTtlSeconds` is the TTL of the apex NS set
the platform writes (86400): after a demote, keep the standby attached at
least that long after the registrar change (plus the parent zone's NS TTL),
since resolvers that cached the old set still ask it.

A verify of a standby attachment adds, in `status.attachments[id]`:
`findings: [{code: "standby_drift", names, at}]` when the standby differs
from the canonical zone, and `failover: {state: ready | partial |
not_ready | unknown, checked, failing, skipped, reason, nameServerErrors,
sampleOffset, checkedAt}`, the "ready to fail over" check: the canonical
record sets the standby serves resolved directly through each of the
standby's nameservers, up to 200 per check (every type present), and
always the sets named by an open `standby_drift` and those changed since
the previous check (up to 1,000 of those, so `checked` can exceed 200
after a large change). The rest of the sample rotates: each check starts
where the previous one stopped (`sampleOffset`), so a zone larger than
the bound is covered over successive checks. `failing` lists the record
labels (`"www A"`) answered wrong or not at all; an open `standby_drift`
always counts as failing, so `ready` never coexists with it.

Delegations inside the zone are compared the way a nameserver serves
them (the probes use the same rule): a delegation's NS set (`sub NS
ns1.sub`) is answered by a referral, and only its nameserver names count;
its glue, an A or AAAA set of a nameserver that NS set names
(`ns1.sub A`), is answered by a referral too and is compared against the
referral's additional section (name, type and values; the TTL is
ignored). Any other set at or below a delegation (`www.sub A`, `sub
TXT`, a nested `x.sub NS`) is not served by this zone by design (it is
occluded by the cut) and is never sampled; a DS set at the delegation is
the parent's data and is checked as usual.

Right after an attach the state is `unknown` with `reason: "awaiting
first sync"` until the attachment's first reconcile has completed (an
adopted standby that already differs is `not_ready` through its open
`standby_drift`); the first check runs with the verify that follows it. `partial` means every set checked answered correctly but the standby
leaves out the sets in `skipped` (its provider cannot serve them, see
mirror mode, and the sets the provider refuses, below). The check runs on
a verify, and on a reconcile only when it had nothing to write: a
reconcile that writes to a standby (a repaired drift, for example) clears
the `standby_drift` finding, returns the state to `in_sync` and queues a
verify 30 seconds later (the provider serves what was written by then),
which refreshes `failover`; until it runs the previous `failover` stays
(same `checkedAt`). A verify already queued for the attachment (the attach
queues one) waits for that time too, so the first check never runs
seconds after the first write; an explicit verify runs at once and the
recheck still follows. `POST /v1/zones/{zoneId}/verify` runs one at once.

**Reconcile or verify while one runs.** `POST /v1/zones/{zoneId}/reconcile`
(or `/verify`) answers `202 {jobIds}` at once. When a sync of the same
attachment is running, the request queues one follow-up job (a second
request, or the schedule, answers the same queued job: they coalesce),
which starts as soon as the running sync ends; the running sync's result,
listed from the provider before the request, stays in the status until
then (20 to 50 s on OCI for a 2,000-set zone). To wait for a status that
reflects a change, compare `status.attachments[id].listedAt` (when the
provider zone was read, v0.1.30) with the time of the change, not
`lastVerifyAt` (when the sync ended, which may be after the change with a
listing from before it). A failed sync does not move `lastVerifyAt`: it
puts the attachment in `error` (`updatedAt`, `lastError`).

**Record sets a provider refuses.** A provider may refuse a record set
when it is written although its capabilities allow it (OCI: an NS
delegation whose nameserver lies inside the delegated name without glue,
or any set it answers `400` for). One refused set no longer stops the
attachment: the data plane isolates it (a refused write is split in halves
until the refused sets are found), writes the rest, and lists the set in
`status.attachments[id].skipped` with `reason: "provider-rejected"` and the
provider's answer in `message`; sets an adapter knows its provider refuses
are skipped before anything is sent (`reason: "glue-required"`, OCI). The
attachment stays `in_sync`, its `findings` carry `{code: "sync_partial",
names, message, at}`, and the `sync_partial` alert fires (a warning, never
`sync_error`). A verify neither writes nor expects a refused set (it is not
drift); every reconcile tries it again, and the skip, the finding and the
alert clear once the provider accepts it. This holds on every provider
(Route 53: a wildcard NS set, a CAA flag or tag it does not accept;
`docs/providers/route53.md`), also for a reconcile made only of refused
sets (one refused edit alone, typically); which provider errors count as
a refusal is listed per adapter in `docs/providers/README.md`.

**Pending attachments.** `status.attachments[id].pendingReason` says why an
attachment waits: `provider-creating` while the provider is still creating
the zone (OCI can take several minutes). The sync is retried with a
growing delay (30 seconds up to 5 minutes) without an alert; 30 minutes
after the attach the attachment turns `error` and `sync_error` fires.

**Mirror mode.** The zone's `source` is `platform` (default) or
`attachment:<attachmentId>`. With a source attachment, every reconcile of
that attachment (the schedule queues one every minute, and `POST
/reconcile` too) reads the provider's zone, applies the difference to the
canonical zone as a journal entry with `source: "mirror"` and actor
`system:mirror` (audit `zone.mirror`), then reconciles the other
attachments, active and standby. The source provider is never written
except for its apex NS set when it is active (the NS plan stays
platform-owned); a standby source is not written at all ("backup of my
Cloudflare zone"). The canonical zone takes every record set the source
serves (only a set the source's own provider would refuse is left out and
listed in `status.mirror.skipped`); the platform-owned record sets (child
delegations) are kept. A record set another attached provider cannot serve
(a TTL above OCI's 7 days, for example) is skipped at that attachment
only: it is listed with its reasons in `status.attachments[id].skipped`
(`[{providerId, reason, record, message?}]`), neither written to nor expected at
that provider, and the rest of the zone syncs; a standby with skipped sets
reports `failover: partial`. The same holds whether the set was there
before the provider was attached or arrives later: attaching a provider
to a mirrored zone never answers `422 recordSetUnsupported` (the attach
answer is the attachment; its status lists what it skips). On a zone whose
source is the platform the attach still answers `422
recordSetUnsupported` when a record set does not fit the provider: edit
the set first.

| Route | Access | Notes |
|---|---|---|
| `POST /v1/zones/{zoneId}/source` `{source}` | admin + `zones:write` | `"platform"` or `"attachment:<attachmentId>"` (`404 attachmentNotFound`, `400 invalidSource`); audited as `zone.source.update`; the first mirror read is queued at once. Answer: the zone view |

On a mirrored zone, `PUT` and `DELETE /v1/zones/{zoneId}/records` and
`POST .../attachments/{id}/adopt` answer `409 zoneMirrored` (dashboard,
API and MCP alike). Switching `source` back to `platform` keeps the last
mirrored state; detaching the source attachment does the same.
`status.mirror` is `{attachmentId, state: ok | unreadable, checkedAt,
lastChangeAt, lastSerial, lastError, skipped, skippedSets}` (`skippedSets`
holds the left-out record sets themselves, values included: zone insights
list their targets with `source: "skipped"`); when the source cannot be
read the zone keeps its last state and `status.findings` carries
`mirror_unreadable`.

### Mirror source: a read-only credential

A connection with `accessLevel: mirror_source` holds a read-only grant on
one existing provider zone (each guide in `docs/providers/` has its
"Mirror source (read-only)" policy; Route 53: `route53:GetHostedZone` and
`route53:ListResourceRecordSets` on the zone ARN, plus
`route53:ListHostedZones`). The adapters check it with read calls only
(Route 53 `GetHostedZone` + `ListResourceRecordSets`, OCI `GetZone` +
`GetZoneRecords`, Cloud DNS get zone + list rrsets, Azure get zone + list
record sets, Cloudflare zone read + DNS records read, PowerDNS `GET` of the
zone); write permissions are never required to be absent, only never
used.

- **Attach = mirror.** `POST /v1/zones/{zoneId}/attachments
  {connectionId, providerZoneId}` with such a connection adopts the given
  zone (`400 providerZoneIdRequired`, `422 providerZoneNotFound` and
  `providerZoneMismatch` as for `zone_editor`) and sets the zone's
  `source` to `attachment:<new id>` in the same write (audited
  `zone.attach.mirror`); the first mirror read runs at once. The
  attachment's `nameServers` are the source's own apex NS set (read from
  the provider), so the NS plan of a zone whose only attachment is the
  source equals what the source already serves: nothing to write. A
  mirror of an existing zone is two calls: `POST /v1/zones {name}`, then
  this attach (the dashboard's "Mirror an existing zone" also creates the
  connection first and deletes the new zone when the attach fails).
- **Never written.** Reconciles of the source only read it (the mirror
  read); its apex NS set is never written, not even when the NS plan
  changes; a verify reports it `in_sync` (the source is the truth: there
  is no drift at the source); no zone setting is changed (Cloudflare's
  Multi-provider DNS stays as it is).
- **Only as the source.** `role: standby` answers `422 mirrorSourceOnly`;
  a zone that already mirrors another attachment answers `409
  mirrorSourceOnly` (`details: {sourceAttachmentId}`); demoting it
  answers `409 mirrorSourceOnly`. Standbys and other active attachments
  can be attached next to it and promoted (the plan grows; the registrar
  step, and the source's own apex NS if wanted, are the customer's).
- **The source stays.** `POST /v1/zones/{zoneId}/source` with any other
  value answers `409 mirrorSourceRequiresSource` (`details: {attachmentId,
  writableAttachments}`): the platform could never write to it. Detach
  it to make the platform the source again (the zone keeps the last
  mirrored state, the remaining attachments serve it).

## Delegation check and registrar

`POST /v1/zones/{zoneId}/delegation/check` (and the periodic delegation
job) reads the NS set the zone is delegated to **from the parent zone**:
it finds the parent (the closest enclosing name with an NS set, through
the resolver), then asks the parent's own authoritative servers, without
recursion, for the zone's NS set and reads their referral (the authority
section; the answer section when a parent server also hosts the child).
NXDOMAIN or no delegation at the parent is `pending`. The result's
`source` says where `seenNs` came from: `parent` (with `parentZone`), or
`resolver` when no parent server answered and the check fell back on a
recursive resolver (`RDNS_RESOLVER`). A `resolver` answer has lower
confidence: once the resolver has fetched the zone itself it returns the
child's own apex NS set, which the platform writes equal to the plan, so
it can say `complete` while the registry still delegates to fewer
nameservers. The state, the `delegation_broken` alert and the registrar
hint below all follow the parent's referral. Each planned nameserver is
then asked directly for its NS set (`answers`). The check also looks up the registrar of a registrable domain (eTLD+1) over RDAP
(`RDNS_RDAP_URL`, default `https://rdap.org`; 5 s timeout; cached 24 h in
`status.json`): `registrar: {name, ianaId, isCloudflare, checkedAt}`. When
the registrar is Cloudflare Registrar (IANA id 1910), which only accepts
Cloudflare's nameservers, and the delegation is not complete, the result
carries `hint: "cloudflare_registrar"` and the Delegation tab explains the
options. Subdomain zones get no registrar lookup. Checks stored before
v0.1.8 have no `source` (they read a recursive resolver).

`findings` lists what the check found beyond the NS set (omitted when
none). `dnssec_mismatch` (v0.1.18): for an apex zone whose domain the
organization holds at the platform's registrar, the DS at the registry
(`domain.dnssec`, as last synced) does not fit the DNSKEY the delegated
nameservers serve (each is asked for the zone's DNSKEY directly): a DS
while they serve the zone unsigned, a DS that matches none of their keys,
or nameservers that serve different key sets. Validating resolvers then
answer SERVFAIL for the whole zone. `names` are the DS key tags
(`"DS 12811"`), `message` says which case. Fix it with `POST
/v1/domains/{name}/dnssec/reconcile` (below), which checks the delegation
again; nothing is raised when the registry holds no DS or no nameserver
answered.

## Domains (registrar)

Domains held in the platform's reseller account at an ICANN-accredited
registrar (Openprovider in production, an in-memory fake in e2e). The
**customer is the registrant**: every domain's owner contact is built from
the organization's registrant profile; the platform's own contact is only
tech/admin where the TLD allows it. Registrar credentials are platform-level
(`RDNS_OPENPROVIDER_*` on the data plane), never per tenant, and the control
plane never calls the registrar: it writes intent and asks the data plane,
which runs the `registrar_sync` and `registrar_apply` jobs (the mutation is
tried at once; a transient registrar failure leaves the job queued with
backoff, a rejection fails it).

Global ownership: `domain-names/<name>.json` (`{name, orgId, createdAt}`,
If-None-Match on create). Tenant objects: `orgs/<orgId>/domains/<name>.json`
and `orgs/<orgId>/contacts/<contactId>.json`, both sealed.

### Objects

**Domain** (`GET /v1/domains/{name}`; the list omits nothing):

```json
{
  "name": "example.com",
  "orgId": "org-...",
  "registrar": "openprovider",
  "registrarDomainId": "123456789",
  "status": "active",
  "registrarStatus": "ACT",
  "expiresAt": "2027-01-29T00:00:00Z",
  "autoRenew": true,
  "locked": true,
  "nameservers": ["ns-1.awsdns-01.org", "ns1.p01.dynect.net"],
  "contacts": {"owner": "XX123456-XX", "admin": "ZD000001-XX", "tech": "ZD000001-XX", "billing": ""},
  "ownerContactId": "ctc-...",
  "registrant": { "...": "a Contact snapshot (the owner as the registrar holds it)" },
  "transfer": {"state": "pending", "requestedAt": "...", "requestedBy": "usr-...", "completedAt": null, "detail": "", "applyZoneNs": true, "nameservers": [], "nameserverSource": "current"},
  "registration": null,
  "renewal": null,
  "history": [{"at": "...", "op": "register.paid", "detail": "1256 USD"}],
  "zone": {"zoneId": "zone-...", "name": "example.com", "nsPlan": ["..."], "nameserversMatch": false, "delegationState": "pending", "findings": []},
  "dnssec": {
    "state": "present", "enabled": true, "updatedAt": "...",
    "keys": [{"keyTag": 12811, "flags": 257, "algorithm": 8, "protocol": 3, "publicKey": "AwEAAc...", "digestType": 2, "digest": "5E0C..."}],
    "lastChange": {"op": "clear", "removed": [12811], "published": [], "reason": "nameservers", "jobId": "job-...", "at": "..."},
    "mismatch": {"code": "dnssec_mismatch", "message": "DS at the registry (key tags 12811), but ...", "names": ["DS 12811"], "at": "..."}
  },
  "pendingJobs": [{"jobId": "job-...", "op": "nameservers", "status": "queued", "attempts": 1, "lastError": "", "createdAt": "..."}],
  "lastSyncAt": "...", "lastError": "", "createdAt": "...", "updatedAt": "..."
}
```

- `status`: `active`, `payment_pending` (a registration waiting for its
  checkout), `registering` (paid; the register job runs or retries),
  `registration_failed` (paid, refused by the registrar), `transfer_pending`,
  `transfer_failed`, `pending` (registration or change in progress at the
  registry), `expired`, `deleted` or `unknown` (not synced yet).
- `registrarStatus` is the registrar's raw status code (Openprovider `ACT`,
  `REQ`, ...) from the last sync.
- `registration` is null for a domain that was not registered through the
  platform (see Registering a domain); `renewal` is the last renewal
  requested through a checkout (paid or not: `paidAt` null means unpaid).
- `history` is the domain's own timeline (`register.requested`,
  `register.paid`, `register.completed`, `nameservers`, `renew`,
  `renew.paid`, ...), oldest first; the audit log keeps the full record.
- `transfer` is null for a domain that was not transferred in; `state` is
  `pending`, `completed` or `failed`; `completedAt` is set once, when the
  domain is in the account and active (a sync also fills it for a
  completed transfer that lacks it); `nameservers` are the ones the
  request listed; `nameserverSource` is where the nameservers sent with
  the transfer came from: `requested`, `current` (the domain's NS set in
  DNS, kept) or `registrarDefault` (none found).
- `zone` is set when the organization has a zone with the same name:
  `nameserversMatch` compares the domain's nameservers with the zone's NS
  plan (as sets, case-insensitive), `delegationState` is the zone's last
  delegation check.
- `dnssec` is the DS at the registry (v0.1.18): `state` `none` (an
  unsigned delegation), `present` or `unknown` (not read yet); `keys` are
  the DNSKEY the registrar holds with the key tag and the SHA-256 DS the
  registry derives from each; refreshed by every sync. `lastChange` is
  the last DS change the platform made (`op` `clear` or `set`, the key
  tags `removed` and `published`, `reason`: `nameservers`,
  `registration`, `transfer` or `reconcile`). `mismatch` is the zone's
  `dnssec_mismatch` finding while the DS is present.
- `autoRenewal` is the current term's automatic renewal while it waits
  on the customer (omitted otherwise; see "Auto-renewal"): `{status,
  method, expiryDate, amountCents, currency, hostedUrl?, requestedAt,
  failedAt?, cutoffAt?}`, `status` `invoiced`, `failed` or `cutoff`,
  `method` `charge_automatically` or `send_invoice`. `hostedUrl` is the
  invoice to pay (a declined charge, or a sent invoice; never after the
  cutoff). An automatic renewal paid by invoice shows in `renewal` like a
  manual one, with `paidBy: "stripe"` and `invoiceId`; one run without a
  charge has `paidBy` `comped`, `manual`, `unbilled` or `exempt` (see
  "Domain billing exemption").
- `pendingJobs` are the `registrar_apply` jobs not done yet for the domain
  (`op`: `transfer`, `nameservers`, `lock`, `autorenew`, `renew`,
  `registrant`; `status`: `queued`, `running`, `failed`). A failed job
  leaves the list when a later job of the same `op` succeeds, when a sync
  of the domain succeeds (`POST .../sync` is the way to dismiss a failure
  that no longer applies) or 24 hours after it failed.
- `registrant` is a snapshot of the owner contact as the registrar holds
  it: it is refreshed when an edit of that contact reaches the registrar
  (the contact job after `PUT .../contacts/{id}` or the registrant
  profile) and by every sync; an edit the registrar has not received yet
  is not shown.

**Contact** (`orgs/<orgId>/contacts/<contactId>.json`):

```json
{
  "contactId": "ctc-...", "label": "Headquarters", "default": true,
  "companyName": "Example Ltd", "firstName": "Ada", "lastName": "Lovelace",
  "email": "ada@example.com", "phone": "+44.2071234567",
  "street": "Main Street", "houseNumber": "1", "city": "London", "state": "",
  "postalCode": "SW1A 1AA", "country": "GB", "taxId": "GB123456789",
  "handles": {"openprovider": "AL000001-GB"},
  "createdAt": "...", "updatedAt": "..."
}
```

Required: `firstName`, `lastName`, `email`, `phone` (`+<country code>.<number>`,
EPP style), `street`, `city`, `postalCode`, `country` (ISO 3166-1 alpha-2).
`handles` (read-only) are the registrar contact handles created for it.
The **registrant profile** is the organization's `default` contact: the
owner of every domain transferred in unless another contact is chosen.

**Mutation result** (every `registrar_apply` route):
`{"domain": Domain, "job": {"jobId", "op", "status": "done" | "queued" | "failed", "lastError", "registrar"?}}`
with `200` when the registrar applied it, `202` when it is queued for a
retry. A registrar rejection answers `422 registrarRejected` (the job is
kept as failed and listed in `pendingJobs`) with the job as `details`;
`details.registrar` is the registrar's own answer: `{code, message,
registry}`, where `registry` is the registry's message the registrar
relayed. For example, nameservers the registry does not know:

```json
{"error": "registrarRejected",
 "message": "rejected by the registrar: An error has occurred; for more details, please refer to the registry message below. ... Registry message: Nameserver creation or update failed: ns1.example.net, 2201, Authorization error; Registrar does not own the parent domain (code 399)",
 "details": {"jobId": "job-...", "op": "nameservers", "status": "failed", "lastError": "...",
             "registrar": {"code": 399, "message": "An error has occurred; ...", "registry": "Nameserver creation or update failed: ..."}}}
```

A write the registry refuses is never reported as `domainNotFound`: that
answer is kept for a domain the registrar account does not hold (sync,
auth code). A synchronous registrar call (auth code, check) that is
rejected carries the same `details.registrar`.

### Routes

| Route | Access | What it does |
|---|---|---|
| `GET /v1/domains` | viewer + `domains:read` | the organization's domains |
| `POST /v1/domains/transfer` `{name, authCode, contactId?, nameservers?, applyZoneNs?, autoRenew?, acceptDomainTerms?, privacy?, registrant?, currency?}` | admin + `domains:write` | transfer a domain in, **paid like a registration** (see "Transferring a domain in"): claims `domain-names/<name>`, creates the domain in `payment_pending` and answers `201 {domain, checkoutUrl}`; the transfer job runs once the payment arrives (an org exempt from domain charges, or a paid transfer tried again after a registrar refusal: `transfer_pending` at once, `201 {domain, job}`). `422 domainPremium`, `409 tooManyPendingDomains`, `409 transferRetriesExhausted` past 3 registrar attempts on one payment, `503 billing_unavailable` without a payment gateway (like a registration; an exempt org still transfers). The owner is `contactId` or the registrant profile. `applyZoneNs` writes the NS plan of the org's zone with the same name when the transfer completes; `nameservers` sets them in the transfer; otherwise the data plane looks up the domain's current NS set (DNS, through `RDNS_RESOLVER`) and sends it, so the transfer changes nothing in DNS; a failed lookup is retried with the job's backoff, and a name with no NS set in DNS (or a lookup that fails on the last attempt) gets the registrar's default nameservers; `transfer.nameserverSource` and the `transfer.submitted` history line say which. `409 domainHeldByPlatform` when the platform's registrar account already holds the domain (Openprovider code 346, "Reseller cannot add duplicate domain"): it cannot be transferred in; a platform admin assigns it to the organization with `POST /v1/admin/domains/{name}/assign` (the domain is left `transfer_failed` and can be removed). Any other refusal answers `422 registrarRejected` with `details.registrar.code` and also leaves the domain `transfer_failed`, its name released (transfer it again: a paid transfer keeps its payment; or remove an unpaid one); measured on the Openprovider sandbox: `318` wrong auth code, `358` a name no registrar holds. A transfer the registrar completes at once (the Openprovider sandbox between two resellers) answers `active` with `transfer.completedAt` set |
| `GET /v1/domains/check?names=a.tools,b.com&years=1&currency=EUR` (or `?names=a.tools&operation=transfer`: the transfer-in price of one name) | viewer + `domains:read` | availability and price of up to 20 names, in the org's billing currency or `currency` (see Registering a domain) |
| `POST /v1/domains/register` `{name, years?, contactId?, nameservers?, applyZoneNs?, autoRenew?, acceptDomainTerms?, currency?}` | admin + `domains:write` | register a new domain, paid through a one-off checkout in the org's billing currency (`201 {domain, checkoutUrl}`) |
| `POST /v1/domains/{name}/register/retry` | admin + `domains:write` | run the register job again for a paid registration that failed (mutation result; `409 domainNotRetryable` otherwise) |
| `GET /v1/domains/{name}` | viewer + `domains:read` | one domain |
| `DELETE /v1/domains/{name}` | admin + `domains:write` | forget a domain whose transfer failed, remove a registration or transfer support canceled (`registration.canceledAt` / `transfer.canceledAt`: its name was already released), or cancel an unpaid registration or transfer (its checkout is closed first: `503 billing_unavailable` when it cannot be); releases the name. `409 domainNotRemovable` otherwise: a paid registration is never removed by the customer ("contact support, who retries it or cancels and refunds it"), nor a paid transfer that is not submitted yet or that the registrar refused and was not refunded (transfer it again with the right auth code: the payment is kept) |
| `GET /v1/domains/{name}/transfer` | viewer + `domains:read` | `{name, status, transfer}` |
| `POST /v1/domains/{name}/sync` | editor + `domains:write` | refresh status, expiry, nameservers, lock, the registrant snapshot and transfer progress from the registrar now; drops the domain's failed jobs from `pendingJobs` |
| `PUT /v1/domains/{name}/nameservers` `{nameservers}` | editor + `domains:write` | set the nameservers (2 to 13 host names) |
| `POST /v1/domains/{name}/nameservers/apply-zone` `{zoneId?}` | editor + `domains:write` | write the NS plan of a zone (default: the org's zone with the same name; `422 zoneNsPlanEmpty` without attachments) |
| `POST /v1/domains/{name}/dnssec/reconcile` | editor + `domains:write` | make the DS at the registry exactly what the domain's nameservers serve (the `dnssec_mismatch` fix): removed when unsigned, their key-signing keys when signed; `422 dnssecMismatch` when they serve different key sets; checks the zone's delegation again (see DNSSEC below) |
| `PUT /v1/domains/{name}/lock` `{locked}` | admin + `domains:write`; unlocking: a dashboard session or `domains:transfer` | transfer lock on or off (`403 transferScopeRequired` for a token without `domains:transfer` unlocking) |
| `PUT /v1/domains/{name}/autorenew` `{autoRenew}` | admin + `domains:write` | auto-renewal on or off (the registrar's flag follows; the platform charges each automatic renewal, see "Auto-renewal"). Off voids the term's open renewal invoice (audit `domain.autorenew.void`); `409 domainAutoRenewCutoff` turning it on after the cutoff of an unpaid invoice (renew the domain instead) |
| `PUT /v1/domains/{name}/privacy` `{enabled}` | admin + `domains:write` | WHOIS privacy protection on or off (see "WHOIS privacy"): at once when off or free, a one-off checkout of one year when it costs money |
| `POST /v1/domains/{name}/renew` `{years?}` | admin + `domains:write` | renew for 1 to 10 years (default 1). Billing off: renewed at once (mutation result). Billing on: `200 {domain, checkoutUrl}`, the renewal runs when paid (`409 domainRenewalInProgress` while a paid one runs) |
| `POST /v1/domains/{name}/authcode` | admin + `domains:write`, and a dashboard session or `domains:transfer` (`403 transferScopeRequired`) | `{name, authCode}`: the transfer-out auth code, fetched from the registrar, never stored (audit `domain.authcode.reveal`) |
| `POST /v1/domains/{name}/move` `{orgId, confirmName?}` | dashboard session, owner or admin of both organizations | move the domain to another organization of the platform (see "Moving a domain to another organization" below): `200 {domain, fromOrgId, fromOrgName, toOrgId, toOrgName, registrantChange, registrantJob?, zoneStays}` |
| `POST /v1/domains/{name}/handoff` `{orgId?, email?, message?}` | admin + `domains:write`, and a dashboard session or `domains:transfer` (`403 transferScopeRequired`) | offer the domain to an organization the caller does not belong to (see "Handing a domain off to another organization" below): `201 {handoff}`. Shares the invitations' sending limit (10 per recipient, 50 per organization per day; `429 tooManyRequests`) |
| `GET /v1/domains/{name}/handoff` | viewer + `domains:read` | `{handoff}`: the open offer, or `null` (the destination e-mail, message and sender only for owners and admins) |
| `DELETE /v1/domains/{name}/handoff` | admin + `domains:write` | withdraw the open offer (`404 handoffNotFound`, `409 domainHandoffAccepting`) |
| `POST /v1/domains/handoff/view` `{token}` | dashboard session, the recipient | the offer and the caller's eligible organizations |
| `POST /v1/domains/handoff/accept` `{token, orgId, acceptDomainTerms?}` | dashboard session, owner or admin of `orgId` | accept: the move runs, `200` with the move's answer |
| `POST /v1/domains/handoff/decline` `{token}` | dashboard session, the recipient | decline: `200 {ok}` |
| `GET /v1/domains/handoff/{token}`, `POST .../{token}/accept`, `POST .../{token}/decline` | as above | deprecated (the token in the path reaches access logs), accepted until 2026-10-28 with a deprecation log line; `410 tokenInUrlRetired` from 2026-10-29 00:00 UTC (AUTH-L2) |
| `POST /v1/domains/{name}/registrant` `{contactId, confirmName}` | admin + `domains:write`; a session or `domains:transfer` (`403 transferScopeRequired`) | change the registrant to another contact; `confirmName` is the domain name. gTLDs (`.com`, `.net`, `.org`...) and most ccTLDs replace the owner handle with a domain update (applied at once; the registry may apply the ICANN 60-day transfer lock after a change of registrant); the registries that require a trade (`.be`, `.es`, and any extension whose TLD data says so) get one, which can stay pending until the registry confirms it. The contact's registrar handle is created the first time and kept on the contact, so a retry after a refusal reuses it |
| `GET /v1/domains/contacts` | viewer + `domains:read` | contacts |
| `POST /v1/domains/contacts` | admin + `domains:write` | create a contact (`201`) |
| `PUT /v1/domains/contacts/{contactId}` | admin + `domains:write`; for the registrant profile or a contact that owns a domain, a session or `domains:transfer` (`403 transferScopeRequired`) | replace a contact's fields (its registrar handles are updated by a job) |
| `DELETE /v1/domains/contacts/{contactId}` | admin + `domains:write` | delete a contact no domain uses and that is not the registrant profile (`409 contactInUse`) |
| `GET /v1/domains/registrant-profile` | viewer + `domains:read` | `{profile: Contact \| null}` |
| `PUT /v1/domains/registrant-profile` | admin + `domains:write`; replacing an existing profile needs a session or `domains:transfer` (`403 transferScopeRequired`) | create or replace the registrant profile (the default contact) |
| `GET /v1/domains/export` | admin + `domains:read` | export everything: `{exportedAt, org, contacts, domains, zones: [{zoneId, name, zoneFile}], zonesOmitted?}`. `zones` holds every zone of the organization (with or without a domain: the export is the whole exit bundle) only when the caller also has `zones:read` (a session, or a PAT or OAuth token with both scopes); a token without it gets `zones: []` and `zonesOmitted` saying why, since zone files are zone data (`GET /v1/zones` needs `zones:read`). The `domain_export` MCP tool follows the same rule |
| `GET /v1/legal/domains` | viewer + `domains:read` | the organization's acceptance of the Domain Registration Terms (same body as `/legal/managed`) |
| `POST /v1/legal/domains/accept` `{version}` | admin + `domains:write` | accept them for the organization (audit `org.domainTerms.accept`) |
| `GET /v1/admin/domains` | platform admin | every domain of the reseller account merged with its owner: `[{name, registrar, registrarDomainId, status, expiresAt, autoRenew, locked, nameservers, orgId, orgName, inAccount, pendingReason?, platformAction?, cancelable?, cancelOp?, canceledAt?, refund?}]` (`cancelable`: `POST .../cancel` applies to the operation `cancelOp`; `canceledAt` and `refund`: an operation support canceled, listed with its organization although its claim was released) sorted by name, no filters (`orgId` empty: unassigned; `inAccount: false`: a domain an organization claims that the registrar does not list, such as a transfer not submitted or failed). When the registrar cannot be listed, only the claimed domains are returned |
| `POST /v1/admin/domains/{name}/assign` `{orgId}` | platform admin | attach an unassigned domain of the reseller account to an organization (audit `admin.domain.assign`, platform and org), then sync it: `201` with the domain's row (as in the list). The domain becomes `active` with the registrar's expiry, lock, auto-renewal, nameservers and contact handles; the owner handle is kept as the registrar has it (no contact is created or mapped: `registrant` and `ownerContactId` stay `null` until a registrant change). `400 invalidOrgId` for a missing, empty or malformed `orgId` (one key segment: no `/`, `\`, space, `.` or `..`), `404 domainNotFound` when the reseller account does not hold the name, `404 orgNotFound`, `409 domainNameTaken` when an organization already has the domain on the platform |
| `POST /v1/admin/tenants/{orgId}/domains/register` `{..., skipPayment}` | platform admin | the operator path: register for an organization (same body as the org route); `skipPayment: true` skips the checkout (`paidBy: "operator"`, the job runs at once, `201 {domain, job}`). No plan limit; the org must have accepted the Domain Registration Terms itself (`428`). Audit `admin.domain.register` (platform and org, with `skipPayment`). With `skipPayment` the register job runs inside the request, so the answer usually already shows `active` (or the registrar's refusal in `job`). Without it, the org gets a checkout like the org route. The request is audited before the job runs, so the trail reads `admin.domain.register` then `domain.register.complete` (or the failure). `400 invalidOrgId`, `404 orgNotFound`; the org route answers `403 forbidden` to `skipPayment: true` |
| `PUT /v1/admin/tenants/{orgId}/domains-billing-exempt` `{exempt, ticket, reason}` | platform admin | exempt the organization from paying for domains (or revoke it): see "Domain billing exemption". `200 {exempt, reason, ticket, setBy, setAt, domains}`; audited `admin.domains_billing_exempt` (platform and org) |
| `POST /v1/admin/tenants/{orgId}/domains/{name}/renew` `{years?, skipPayment: true}` | platform admin | renew without a payment: the job runs inside the request, `200 {job}`; the domain's expiry moves, its `history` gets a `renew` entry and its `renewal` records the operator renewal like a paid one: `{years, priceCents, currency (the renewal quote, for the books), requestedAt, requestedBy (the admin), paidAt, paidBy: "operator", completedAt, error}` (an unpaid checkout of the org's own renewal is replaced and closed). `400 skipPaymentRequired` without `skipPayment: true`, `400 invalidYears`, `400 invalidOrgId`, `404 orgNotFound`, `404 domainNotFound` when the organization does not have the domain, `409 domainRegistrationPending` before the domain is in the registrar account, `409 domainRenewalInProgress` while a paid renewal is running, `422 registrarRejected` when the job fails (`renewal.error` keeps the reason). Audit `admin.domain.renew` (platform and org, with `skipPayment`, `years` and the price) before the job runs; the job's own `domain.renew` (or `domain.renew.paidFail`) follows |

**Exit guarantee.** The auth code, unlocking (`locked: false`), sync and
the export are never gated: not by the plan, not by a read-only billing
status and not by the Domain Registration Terms. Everything else that
changes a domain needs the organization's acceptance of the current
**Domain Registration Terms** (`/legal/domain-terms`): `428
domain_terms_required` with `details: {version, url}` until an admin
accepts them (`POST /v1/legal/domains/accept`, or `acceptDomainTerms:
"<version>"` in the register or transfer body; each acceptance, even a
repeated one, is recorded again as `org.domainTerms.accept`). A version
other than the current one answers `409 legalVersionMismatch`. Contacts and
the registrant profile can be written before the terms are accepted.

**Domains never depend on a plan.** Domains are sold per item
(registration, transfer, renewal, WHOIS privacy) and are never gated by the
plan, the trial or the billing state: an organization on its trial, without
a plan, or read-only (trial ended, subscription canceled, unpaid, detached)
registers, transfers in, renews, retries a registration, sets its
nameservers (`PUT .../nameservers` and `POST .../nameservers/apply-zone`,
which only writes at the registrar), turns privacy on or off, moves a
domain and hands it off or receives one, with no count limit. Plans and the
trial govern zones and providers only; `GET /v1/plans` says so in
`domainsNote`. The data plane runs domain jobs (renewals, registrar
retries, transfer polling) for read-only organizations too.

### DNSSEC on a nameserver change

A DS at the registry that none of the nameservers' DNSKEY matches makes
every validating resolver answer SERVFAIL for the whole zone (the
2026-09-28 incident: Openprovider publishes a DS for its own signed
nameservers, and moving the domain to the providers left it behind). So
every nameserver change (`PUT .../nameservers`, `POST
.../nameservers/apply-zone`, the zone NS applied when a transfer
completes, a registration that sent nameservers) first asks each
destination nameserver for the zone's DNSKEY:

- **unsigned** (every nameserver answered authoritatively without a
  DNSKEY): the DS is removed before the nameservers change, audited as
  `domain.dnssec.clear` with the key tags, a `dnssec.clear` history line,
  and the answer carries `dnssec: {op: "clear", cleared: [12811],
  published: []}`;
- **signed**, every nameserver serving the same DNSKEY set: its
  key-signing keys' DS is published next to the current DS, so the old
  nameservers keep validating while resolvers move (`domain.dnssec.set`,
  `dnssec.op: "set"`); a DS that already matches a served key is kept;
- **unknown** (a nameserver did not answer, or answered only from a
  non-public address): an existing DS is kept and nothing changes; the
  job is retried (`202` with the queued job, its `lastError` says why), so
  a timeout never downgrades a signed zone to insecure. Nameservers are
  asked only at public addresses, like every other authoritative
  question;
- **mixed** (some signed, some not, or different key sets): `422
  dnssecMismatch`, nothing changed. DNSSEC across several providers is
  only supported when every active provider serves the same DNSKEY set
  (the same keys at each provider). No provider adapter signs zones
  today: OCI DNS and Cloudflare zones the platform creates are unsigned
  unless the customer turned DNSSEC on at the provider.

A registration or a transfer completion cannot be refused: a mismatch
there is recorded in the history (`dnssec.failed`, or the zone NS left
unapplied with the reason) and left to the delegation check's
`dnssec_mismatch` finding. `POST .../dnssec/reconcile` then publishes
exactly what the nameservers serve (the served key-signing keys, or no
DS); with nothing to change it records `dnssec.reconcile` and changes
nothing. Support can run it for an organization (below).

### Moving a domain to another organization

`POST /v1/domains/{name}/move {orgId, confirmName?}` hands a domain to
another organization of the platform: a platform-side change of the
owning organization, never a registrar transfer (same registrar,
registration, expiry, lock and nameservers). Nothing is charged.

- **Who**: a dashboard session of an owner or admin of the source (the
  organization the request acts on) and of the destination. Tokens are
  bound to one organization, so a PAT or an OAuth token (and so an MCP
  tool call) gets `403 sessionRequired`; a destination the caller is not
  an owner or admin of (or that does not exist) answers `403 forbidden`,
  its IP allowlist `403 ipNotAllowed`. `400 invalidOrgId`,
  `domainMoveSameOrg`; `confirmName`, when given, must be the domain
  name (`400 confirmNameMismatch`).
- **When**: only an active domain with nothing in progress: `409
  domainMoveBlocked` with `details.reason` `registration` (a registration
  not complete), `transfer` (a transfer in progress), `renewal` (a renewal
  open), `platformPending` (a job waiting on the platform), `jobPending`
  (a registrar job of the domain queued or running in the source),
  `privacyOrder` (a WHOIS privacy order waiting for its payment or its
  registrar job), `autoRenewInvoice` (the term's auto-renewal invoice is
  open) or `notActive`. The payments belong to the source (REG-3): an
  **owner** of the source may pass `force: true` (`403
  forceRequiresOwner` for an admin), which voids the open auto-renewal
  invoice (audit `domain.autorenew.void`, `reason: moved`) and expires an
  unpaid privacy checkout (audit `domain.privacy.cancel`) in the source
  before the move; a privacy order already paid still blocks until its
  job ran. Turning auto-renewal off also voids the invoice. The moved
  document never carries the source's `autoRenewal` nor `privacyOrder`:
  the destination's auto-renew schedule opens its own invoice. The support
  action takes the same `force`.
- **The destination's rules**, as for a transfer into it: `428
  domain_terms_required` (the destination's own acceptance of the Domain
  Registration Terms). Never its plan nor its billing state: a trial or a
  read-only destination receives the domain.
- **Storage**: the domain document moves from `orgs/<source>/domains/`
  to `orgs/<destination>/domains/` (re-sealed with the destination's key)
  and the global claim `domain-names/<name>.json` is re-pointed, in this
  order: destination copy, claim (`If-Match`), source copy deleted. The
  claim is the authority: a crash after it leaves a source copy that the
  next move (or `rdns doctor`) removes. What belongs to the source stays
  there (ORG-L2): the destination copy's history starts with its `move.in`
  line, its `ownerContactId` is cleared, its `registrant` becomes a label
  ("Previous organization's registrant") until the owner-change job sets
  the destination's profile (or, with `none`, is that profile), and the
  registration, renewal and transfer records lose who requested them and
  their checkout, payment intent and refund ids (amounts, dates and
  `paidBy` stay).
- **Zone**: a zone with the domain's name stays in the source (zones are
  not moved): the answer's `zoneStays` names it (`{orgId, orgName, zoneId,
  name, message}`) and the destination creates or imports its own zone.
  The domain keeps its nameservers at the registrar.
- **Registrant** (`registrantChange`): when the destination has a
  registrant profile that differs from the domain's registrant, the
  owner-change job of `POST .../registrant` runs in the destination
  (`queued`, with `registrantJob`; audited `domain.registrant.request`
  then `domain.registrant`); `none` when the profile already is the
  registrant (same registrar fields); a destination without a registrant
  profile is refused (`422 registrantProfileRequired`, checked before a
  forced move clears anything): the source's person would otherwise stay
  the legal registrant (`kept` is no longer answered); `failed` when the job could not be sent or the registrar refused it (the
  move stands; change the registrant from the domain page).
- **Evidence**: audit `domain.move.out` in the source (`{toOrgId,
  toOrgName, registrantChange, zoneStays?}`) and `domain.move.in` in the
  destination (`{fromOrgId, fromOrgName, registrantChange, zoneStays?}`);
  every owner of both organizations gets an e-mail (category security).

The operator variant is a support action: `POST
/v1/admin/tenants/{orgId}/domains/{name}/move` (see Support actions).

### Handing a domain off to another organization

The move needs owner or admin on both organizations. To give a domain to
**another customer** (a sale, a client leaving an agency), the source
makes an offer and the destination accepts it:

- **Offer**: `POST /v1/domains/{name}/handoff {orgId | email, message?}`
  (owner or admin of the source; a token works, so the MCP tool
  `domain_handoff` offers too). Exactly one of `orgId` (the destination
  organization's id, shown to its members in the organization menu and on
  the Members page) and `email` (a person, who picks the destination
  organization when accepting, or creates one): `400
  handoffDestinationRequired`; `400 invalidOrgId`, `domainMoveSameOrg`,
  `invalidEmail`, `handoffMessageTooLong` (200 characters). An `orgId` no
  organization has answers `201` like a known one (no org-id oracle): the
  offer e-mails nobody on that side and expires. The source never sees the
  destination organization's name before acceptance (the offer, its audit
  entry and the source's e-mails name its id), and the offer e-mail puts
  the message after a fixed notice that it is the sender's own text. The
  move's blocking rules apply at once (`409
  domainMoveBlocked`, `details.reason` as for the move) and a domain has
  one open offer (`409 domainHandoffPending`: withdraw it first). The
  domain stays fully usable while the offer is open; a direct move of it
  withdraws the offer (audit `reason: moved`).
- **Token**: `rdmv_<orgId>_<offerId>_<64 hex>`, valid 7 days, e-mailed
  once to the destination (the address, or the owners and admins of the
  organization) with the link `/domains/handoff#{token}` (the fragment:
  never sent to a server, never logged); only its SHA-256
  is stored. The source's owners (and the member who offered) get a copy
  without the token.
- **Recipient**: `POST /v1/domains/handoff/view {token}` (session) answers the
  offer (`domain`, `sourceOrgName`, `message`, `offeredByEmail`,
  `expiresAt`) and `orgs`: the caller's organizations that can receive it
  (owner or admin, not the source; only the named one for an offer by org
  id), each with `domainTermsRequired`, plus `domainTerms {version, url}`.
  `404 handoffNotFound` (unknown, used, withdrawn or declined), `410
  handoffExpired`, `403 handoffEmailMismatch` (an offer by e-mail read
  with another address), `403 forbidden` (not an owner or admin of the
  named organization).
- **Accept**: `POST .../accept {orgId, acceptDomainTerms?}` runs the move
  with its rules again and the destination's (`428
  domain_terms_required` naming the
  organization unless it accepted the terms or `acceptDomainTerms` carries
  the current version), `400 handoffWrongOrg`, `403 forbidden` (not an
  owner or admin of `orgId`), `ipNotAllowed`. The offer is held
  (`accepting`) while the move runs, so a second acceptance, a decline or
  a withdrawal answers `409 domainHandoffAccepting`; a failed move leaves
  the offer open. The answer is the move's (`DomainMove`). Acceptance
  needs a dashboard session: there is no MCP tool for it.
- **Decline / withdraw / expiry**: `POST .../decline` (the recipient),
  `DELETE /v1/domains/{name}/handoff` (the source), and the data plane's
  sweep on every org pass closes offers past their expiry (the control
  plane also expires one it meets).
- **Storage**: the sealed offer `orgs/<source>/domain-handoffs/<offerId>.json`
  and the claim `orgs/<source>/domain-handoff-names/<name>.json` (one
  open offer per domain), written claim first and deleted offer first; a
  claim left without its offer is stale and taken over by the next offer.
  Open offers are not part of an org export (bound to this installation's
  e-mailed token).
- **Evidence**: audit in the source `domain.handoff.offered` (`offerId`,
  `toOrgId` or `toEmail`, `expiresAt`, `message?`),
  `domain.handoff.accepted` (`toOrgId`, `toOrgName`, `by`,
  `registrantChange`, next to `domain.move.out`), `domain.handoff.declined`,
  `domain.handoff.withdrawn` (`by`, or `reason: moved`) and
  `domain.handoff.expired` (source system); the destination gets
  `domain.move.in`. E-mails (category security) to both sides on every
  outcome: "Domain X offered to you by S", "Domain X offered to D" (the
  source's copy), "Hand-off of X declined | withdrawn | expired", and the
  move e-mails on acceptance.

### Registering a domain

A new domain is paid once, through a Stripe Checkout Session in
`mode=payment` with an ad-hoc `price_data` line (`Domain registration
<name> (<years> year)`), then registered at the registrar by the data
plane. The customer stays the registrant (the registrant profile or
`contactId`); admin, tech and billing are the platform's handle
(`RDNS_OPENPROVIDER_HANDLE`).

1. `GET /v1/domains/check?names=...` answers, per name,
   `{name, available, premium?, priceCents, currency, usdCents, fxRate?,
   fxSafetyPercent?, fxEffectiveRate?, years, reason?}`: the **quoted
   price** (never the registrar's cost) in the org's billing currency
   (see "Billing in BRL and EUR"), or in `?currency=USD|BRL|EUR` (the
   first purchase's choice; `409 billing_currency_locked` once the org's
   currency is locked to another one). `usdCents` is the USD price it
   comes from; a BRL or EUR price is converted,
   `priceCents = ceil(usdCents x fxRate x (1 + fxSafetyPercent/100))`,
   and carries `fxRate` (the market rate), `fxSafetyPercent` (the
   conversion margin) and `fxEffectiveRate` (`fxRate` with the margin, to
   four decimals: the rate the price is charged at, shown by the
   dashboard); `503 fx_unavailable` while that currency has no usable
   exchange rate. Names held by an
   organization on the platform are not available. `422
   invalidDomainName` for an invalid name (one invalid name fails the whole
   list; `details.name` is the culprit), `503 registrarUnavailable`
   without a registrar (`RDNS_REGISTRAR=none`).
2. `POST /v1/domains/register` checks the terms (`428
   domain_terms_required`, or `acceptDomainTerms`), the plan (action
   `domain.register`), the owner (`422 registrantProfileRequired`) and the
   name (`409 domainUnavailable`, `422 domainPremium`: premium names are
   registered on request), claims `domain-names/<name>`, writes the domain
   with status `payment_pending` and a `registration` record `{years,
   priceCents, currency, usdCents?, fxRate?, fxSafetyPercent?, fxEffectiveRate?, checkoutSessionId, checkoutUrl, contactId,
   nameservers, applyZoneNs, autoRenew, requestedAt, paidAt, paidBy,
   paymentIntentId, completedAt, error}`, and returns
   `201 {domain, checkoutUrl}`. The checkout returns to
   `/domains/<name>?checkout=success|canceled`. `503 billing_unavailable`
   with `RDNS_BILLING=off`. The price is in `currency` (default the
   org's billing currency); the first purchase records it on the org
   (`billing.currency` audit), the payment locks it; `409
   billing_currency_locked`, `503 fx_unavailable` (BRL or EUR without a
   usable rate). An organization exempt from paying for domains gets no
   checkout: the domain is `registering` with `paidBy: "exempt"` and the
   job runs at once (see "Domain billing exemption").
3. The webhook `checkout.session.completed` (or
   `checkout.session.async_payment_succeeded` for a delayed method) with
   `mode=payment` and our metadata (`orgId`, `purpose: domain_register`,
   `domainName`, `years`) marks the registration paid (`paidAt`,
   `paidBy: "stripe"`, `paymentIntentId`), sets `registering` and runs the
   `registrar_apply` job `register`: nameservers are the given ones, else
   the NS plan of the org's zone with the same name when `applyZoneNs`,
   else the registrar's default. Success sets `active` with the
   registrar's data. The job is idempotent: a name the account already
   holds completes the registration instead of failing it, and the
   schedule re-queues the job of a paid registration that has none.
4. A **customer-side** rejection (the name is taken, contact data the
   registry refuses, an unsupported extension, a premium price: see
   "Platform-side registrar failures" below) sets
   `registration_failed` with the error and fires the alert
   `domain_registration_failed` (no zone; the event's `zoneName` is the
   domain), notified on the org's channels. **There is no automatic
   refund**: the operator either fixes the cause and retries
   (`POST /v1/domains/{name}/register/retry`, which resolves the alert on
   success) or refunds the payment in the Stripe dashboard (the
   `paymentIntentId` is on the registration and in the audit entry
   `domain.register.paid`).
5. An abandoned checkout: `DELETE /v1/domains/{name}` cancels it at once;
   otherwise the checkout expires after 23 hours and the data plane
   releases the name 24 hours after the request (`domain.register.expire`,
   also on `checkout.session.expired`). A payment that matches no open
   registration (released meanwhile) is logged and audited as
   `domain.payment.orphan` for a refund.

### Transferring a domain in

A transfer-in is **paid like a registration** (security review
2026-10-09, REG-1): the registrar charges the platform for every
transfer, and the charge includes one renewal year where the registry
grants it (gTLDs; Openprovider support article 360014011380, and the
Transfer column of its price list). The price is the registrar's
transfer cost plus the registration margin (`domainMarginPercent`; a
fixed-price extension uses its `transferCents`, else its
`registerCents`), for one year, in the org's billing currency.

1. `GET /v1/domains/check?names=example.com&operation=transfer` quotes
   one name: `{name, available, premium?, priceCents, currency,
   usdCents, fx..., years: 1, privacyAvailable, privacyPriceCents,
   exempt?}`. `premium: true` means the transfer is handled on request.
2. `POST /v1/domains/transfer` checks the terms, the cap on pending work
   (at most 5 domains of the org in `payment_pending` or
   `transfer_pending` at once: `409 tooManyPendingDomains`, REG-2), the
   quote (`422 domainPremium`) and the owner, claims the name, writes the
   domain in `payment_pending` with `transfer: {state: pending,
   priceCents, currency, usdCents?, fx..., checkoutSessionId,
   checkoutUrl, paidAt: null}` and a one-off checkout (`purpose:
   domain_transfer`, line `Domain transfer <name> (1 year)`, bound to the
   org, the name, the amount and the currency), and answers `201
   {domain, checkoutUrl}`. Nothing reaches the registrar yet: the auth
   code is kept sealed with the org DEK on the domain document (never in
   any answer) until the transfer job takes it.
3. The payment webhook checks the checkout, the amount, the currency and
   that the org still holds the name (otherwise `domain.payment.orphan`,
   for a refund), records `transfer.paidAt`, `paidBy: "stripe"`,
   `paymentIntentId` (history `transfer.paid`, audit
   `domain.transfer.paid`), sets `transfer_pending` and runs the transfer
   job; duplicate deliveries change nothing, and the schedule re-queues
   the job of a paid transfer that has none.
4. An abandoned checkout: `DELETE /v1/domains/{name}` cancels it;
   otherwise it expires after 23 hours and the name is released 24 hours
   after the request (`domain.transfer.expire`, also on
   `checkout.session.expired`).
5. A transfer the registrar refuses (a wrong auth code, a lock at the
   current registrar) or the registry fails later ends `transfer_failed`
   and **releases its name** (REG-2): the document stays for the org's
   history. A paid one keeps its payment: `POST /v1/domains/transfer`
   again with the right auth code runs at once without a new checkout
   (history `transfer.retry`; at most 3 registrar attempts per payment,
   `transfer.attempts`: the fourth request answers `409
   transferRetriesExhausted` and marks the domain for the operator,
   `platformAction.operatorAction: refund`); or support cancels and
   refunds it (`POST
   /v1/admin/domains/{name}/cancel {refund: true}`, recorded as
   `transfer.refund`; the owners get the canceled-and-refunded e-mail).
6. An org exempt from domain charges (`paidBy: "exempt"`) transfers at
   once (`201 {domain, job}`). An installation without a payment gateway
   answers `503 billing_unavailable`, like a registration.
7. Free DNS for the zone with the domain's name follows only once the
   transfer completed (`transfer.state: completed`), never while it waits
   for its payment or runs.

A claim whose domain is a transfer that failed before completing, or an
order (registration or transfer) still unpaid past its checkout's
expiry, is taken over by the next registration or transfer of the name,
by any organization (REG-2).

Prices (`platform/config.json`, edited with `PUT /v1/admin/config`):
`domainMarginPercent` (default 20, like the managed cost plus 20%) is
added to the registrar's cost for the period, rounded up to whole cents,
in the registrar's currency, for registrations, renewals and transfers;
`domainPrices: {"tools": {"registerCents": 4000, "renewCents": 4500,
"transferCents": 3900}}` fixes the yearly price of an extension in US
cents instead (`transferCents` optional: the registration price when 0, checked like
`registerCents` against the registrar's transfer cost by `PUT
/v1/admin/config`;
`400 invalidDomainPricing` for a margin outside 0 to 1000 or a
non-positive price).

**Repricing bounds (S2, security review S-M6).** For a value that is new
or changed, `PUT /v1/admin/config` answers `422 configOutOfBounds`
(`details.violations: [{field, message}]`) for a fixed price below the
registrar's current cost (the data plane quotes the extension at save
time and answers only "below cost"; a check that cannot run is a
violation too), a manual exchange rate more than 25% away from the
fetched one or with no fetched rate, and a `domainMarginPercent` above
200. `force: true` with a `reason` of at least 10 characters saves it
anyway (the admin justification's `reason`, which every `/v1/admin` write carries, is the force's; `400 invalidReason` / `forceReasonRequired` otherwise). Every change is audited as
`admin.config.update` with `details.changes: [{field, before, after}]`
(and `force`, `reason`) and raises the `config_changed` installation alert
in the platform admins' organizations for 24 hours.

**Renewals** with billing on go through the same kind of checkout
(`purpose: domain_renew`, the extension's `renewCents` or the renewal cost
plus the margin, in the org's billing currency: a BRL or EUR org pays
the converted price, `renewal.usdCents`, `renewal.fxRate`,
`renewal.fxSafetyPercent` and `renewal.fxEffectiveRate` keep the
conversion, `503 fx_unavailable` without a usable rate): the renew job runs on payment and the `renewal` record
gets `completedAt` (or `error`). `paidAt` is the moment the payment
arrived, before the job ran, and `history` lists `renew.paid` before
`renew` (the history is kept in time order). Money entries of the history
(`register.paid`, `renew.paid`, `register.refund`, `renew.refund`) carry
`amountCents` and `currency` next to `detail`, which reads `"1.47 USD"`
(two decimals and the code; entries written before 2026-09-27 printed the
minor units as units, `"147 USD"`, and are read back as amounts). Asking again before paying replaces the
unpaid renewal and expires its checkout (the old link then shows Stripe's
"session has timed out" page). With billing off, renewals keep running at
once as in phase 1.

**Platform-side registrar failures.** A register, renew or transfer job
the registrar refuses for a reason on the platform's side (no reseller
balance or credit, API credentials or the source IP refused, the reseller
account suspended, the registrar or the registry down or in maintenance,
a network failure; also any refusal the adapter cannot place, which is
treated as the platform's) never reaches the customer as an error:

| Operation | State kept while waiting | Customer sees |
|---|---|---|
| register | `status: registering` | `pendingReason: "platform_action_required"`, `pendingSince`, `statusText` "The platform is completing the registration; nothing is needed on your side." |
| renew | `status: active`, the `renewal` stays open (no `error`) | same, "... completing the renewal ..." |
| transfer | `status: transfer_pending`, `transfer.state: pending` | same, "... completing the transfer ..." |

The payment is kept (nothing is refunded), `lastError`,
`registration.error`, `renewal.error`, `transfer.detail`, the job's
`lastError` and the history carry no registrar text, and the route that
ran the job answers `202` with a queued job whose `lastError` is the same
neutral sentence. The job is retried every `RDNS_REGISTRAR_RETRY_INTERVAL`
(15 min) for up to `RDNS_REGISTRAR_RETRY_WINDOW` (48 h) from the first
platform-side failure (an outage first uses the job's normal backoff of
30 s, 2 min and 10 min). The first success clears `pendingReason`. Past
the window the operation escalates: a registration becomes
`registration_failed` with the neutral `registration.error` "We could not
complete the registration; support will contact you." (and the
`domain_registration_failed` alert with the same neutral text), a renewal
gets that text as `renewal.error`, a transfer becomes `transfer_failed`;
`retryable` is `false` (`POST /v1/domains/{name}/register/retry` answers
`409 domainNotRetryable`): support retries it or cancels and refunds it.

**Canceled by support.** A platform admin who cannot complete the
operation cancels it (`POST /v1/admin/domains/{name}/cancel`, below).
The customer then reads:

| Operation | State | `statusText` |
|---|---|---|
| registration | `registration_failed`, `registration.canceledAt`, `registration.refund {status, refundId, amountCents, currency, at}` (when refunded), `registration.error` "Canceled by support.", history `register.canceled` (and `register.refund`) | "The registration was canceled and refunded." (or "The registration was canceled.") |
| renewal | `active`, `renewal.canceledAt`, `renewal.refund`, `renewal.error` "Canceled by support." | "Active; the renewal was canceled and refunded." (or "... canceled.") |
| transfer | `transfer_failed`, `transfer.state: failed`, `transfer.canceledAt` | "The transfer was canceled." |

`retryable` stays `false`. A canceled registration or transfer has
released its name: another organization may register it, the same
organization may register it again (the canceled document gives way),
and `DELETE /v1/domains/{name}` removes it. The org's owners get an
e-mail (billing category) saying the operation could not be completed
and, when it was, that the payment was refunded.

Every domain view carries `statusText` (a sentence for the customer),
`retryable` (a paid registration refused on the customer's side) and
`freeDns` (the domain is registered or transferred through the platform
and live, so its same-name zone is free on the RedundantDNS nameservers;
see "Free DNS for domains registered here"). The
registrar's own answer is the operator's: `GET /v1/admin/domains` lists
`pendingReason` and `platformAction {op, since, lastAttemptAt,
nextRetryAt, attempts, jobId, responsibility (platform or unknown), code,
message, registry, escalatedAt, operatorAction (refund or contact)}`, and
the installation alert `registrar_action_required` (one event per domain,
in the organizations of the platform admins) carries it too.

| Route | Access | Purpose |
|---|---|---|
| `POST /v1/admin/domains/{name}/retry` | platform admin | run the domain's waiting job now (after adding credit or fixing the credentials); an escalated operation is reopened with a new window and run. `200 {name, orgId, op, job}`; `409 domainNotRetryable` when nothing waits on the platform (or for an escalated transfer: its auth code is not kept, the customer starts it again). Audited `admin.domain.retry` (platform) and `domain.<op>.retry` (org) |
| `POST /v1/admin/domains/retry-pending` | platform admin | the same for every domain with `pendingReason: platform_action_required`; an escalated operation no longer has it and is not included (reopen it with the route above, one domain at a time): `200 {retried: [{name, orgId, op, job?, error?}]}` (`{"retried": []}` when nothing waits) |
| `POST /v1/admin/domains/{name}/cancel` `{reason, refund}` | platform admin | cancel a paid registration, renewal or transfer the platform could not complete: one waiting on the platform (`pendingReason: platform_action_required`), one escalated after the window, a paid registration the registrar refused (`registration_failed`), or a paid transfer the registrar refused (`transfer_failed`, not completed; REG-1). The waiting job is dropped (nothing retries it: not the schedule, not **Retry now**, not retry-pending; a job that escaped the drop refuses to run), `platformAction` is cleared, `registrar_action_required` and `domain_registration_failed` resolve, a registration or transfer releases its `domain-names/` claim, and with `refund: true` the payment is refunded through the billing gateway (Stripe `refunds.create` on the `paymentIntentId`, idempotency key `rdns-refund-<paymentIntentId>`; the reason goes to the refund's metadata). A transfer paid through the gateway is refunded like a registration (`transfer.refund`; also one whose retries ran out, `409 transferRetriesExhausted`); an exempt or operator-granted one has nothing to refund (`refund.status: none`). `200 {name, orgId, op, released, refund?: {status (succeeded, pending, failed, none), refundId, amountCents, currency, at, error?}, refundOnly, mailed}`. A refund the provider refuses is recorded `failed`: canceling again retries only the refund (`refundOnly: true`). `400 invalidReason` (1 to 500 characters), `404 domainNotFound`, `409 domainHeldByRegistrar` when the registrar account holds the name (the operation went through: sync the domain instead), `409 domainNotCancelable` when nothing can be canceled (already canceled and refunded, unpaid, active), `409 domainBusy` while the operation's job runs, `503 registrarUnavailable` when the registrar cannot be asked whether it holds the name (nothing was canceled). Audited `admin.domain.cancel` (platform, with the reason and the refund) and `domain.<op>.cancel` (org, without the reason) |

### Registrant profile inline (first purchase)

`POST /v1/domains/register` and `POST /v1/domains/transfer` take an
optional `registrant` object (the `ContactWrite` fields of `PUT
/v1/domains/registrant-profile`). When the organization has no
registrant profile, it is validated first (`400 invalidContact`, nothing
saved) and saved as the profile once every other check passed (audited
`domain.registrantProfile.create` with `details.inline: true`); the answer
says `registrantCreated: true`. When a profile already exists, the inline
object is ignored and the answer says `registrantIgnored: true` (edit the
profile with its own route). Without a profile and without `registrant`,
`422 registrantProfileRequired` as before. The dashboard shows the profile
form inside the purchase (register page, transfer wizard) with the terms.

### Auto-renewal

The platform, not the registrar, renews a domain with `autoRenew` on, and
charges the organization first (no renewal is paid from the reseller
balance for a customer who did not pay):

1. `RDNS_DOMAIN_AUTORENEW_LEAD` (default 30 days) before the expiry, the
   data plane quotes the one-year renewal (plus the WHOIS privacy
   protection when it is on) in the organization's billing currency and
   opens a Stripe invoice for its customer (created when it has none),
   metadata `purpose: domain_autorenew`, `domainName`, `years`,
   `expiresAt`. With a saved card (every domain checkout saves the card
   and the customer since this release) the invoice is charged
   automatically (Stripe retries a declined card); without one it is
   sent, due in 14 days, and the owners and admins get it by e-mail
   (`domain-autorenew-invoiced`). The domain shows `autoRenewal`; the
   history `autorenew.invoiced`; the audit `domain.autorenew.charge`.
   An exchange rate not usable yet (`fx_unavailable`) delays the invoice.
2. Paid (`invoice.paid`), the renew job runs and the payment is recorded
   in `renewal` (`paidBy: "stripe"`, `invoiceId`, `paymentIntentId`,
   history `renew.paid`, audit `domain.renew.paid` with `autoRenewal:
   true`, the receipt e-mail); `autoRenewal` goes away.
3. A declined charge (`invoice.payment_failed`) sets `status: failed`
   with the hosted invoice, e-mails it (`domain-autorenew-failed`, once
   per invoice) and fires `domain_autorenew_failed` (no zone; the event's
   `zoneName` is the domain), resolved by the payment.
4. Still unpaid `RDNS_DOMAIN_AUTORENEW_CUTOFF` (default 5 days) before the
   expiry, the invoice is voided and the registrar's own auto-renewal is
   turned off (`status: cutoff`, audit `domain.autorenew.cutoff`, history
   `autorenew.cutoff`, e-mail `domain-autorenew-cutoff`, the alert
   fires). `autoRenew` stays `true` for the next term; the expiry
   reminders go out as for auto-renewal off, and `POST .../renew` still
   renews it. Once the term is renewed, the registrar's auto-renewal is
   turned back on and the alert resolves.

A manual renewal paid while an invoice is open voids the invoice (a
payment of both is reported as `domain.payment.orphan` for a refund).
Comped and manually invoiced organizations, organizations exempt from
paying for domains, and installations without a payment gateway, are not
charged: the renewal runs at once (`renewal.paidBy` `comped`, `manual`,
`exempt` or `unbilled`; an exemption wins over the billing mode).

### WHOIS privacy

The registrar's WHOIS privacy protection replaces the registrant's data in
the public WHOIS/RDAP with its proxy's, on the extensions whose registry
allows it (gTLD WHOIS already redacts personal data under GDPR; the proxy
covers every extension that allows it). Openprovider's API documents the
availability per extension (`GET /v1beta/tlds/{ext}`
`is_private_whois_allowed`) and the per-domain switch
(`is_private_whois_enabled` on create, transfer and update) but no price:
Openprovider includes the protection at no cost for members, so the
quoted price is 0 today. The platform prices it anyway as the registrar's
yearly cost plus `domainMarginPercent` (a fake registrar charges 2.50 USD a
year on `.tools` in tests), in the org's currency.

- `GET /v1/domains/check` adds `privacyAvailable` and `privacyPriceCents`
  (for `years`, in `currency`) to every name the registrar answered,
  registered names included.
- The dashboard's register and transfer forms check the protection by
  default wherever `privacyAvailable` is true (a transfer: where it is
  also free); the MCP tools `domain_register` and `domain_transfer_in`
  send `privacy: true` the same way unless the caller passes `false`.
  The API itself keeps `privacy` off unless it is sent.
- `POST /v1/domains/register` with `privacy: true` adds the protection's
  price to the checkout (`registration.privacy`,
  `registration.privacyPriceCents`, its share of `priceCents`) and the
  register job turns it on; `422 privacyUnavailable` where the extension
  does not allow it.
- `POST /v1/domains/transfer` with `privacy: true` turns it on with the
  transfer where it is free (`transfer.privacy`); the transfer's checkout
  carries only the transfer, so a paid protection answers `422
  privacyPaidAfterTransfer` (turn it on from the domain once it arrived).
- `PUT /v1/domains/{name}/privacy {enabled}` (admin, Domain Registration
  Terms) turns it off, or on when it is free or billing is off, at once
  (`DomainMutation`; audited `domain.privacy.request` and, applied,
  `domain.privacy`). Turning a paid one on mid-term opens a one-off
  checkout of **one year at the current price** (`purpose:
  domain_privacy`, `privacyOrder {priceCents, currency, checkoutSessionId,
  checkoutUrl, paidAt, completedAt, error}`); the payment runs the job
  (`domain.privacy.paid`, history `privacy.paid`), an unpaid order is
  dropped after 24 hours. `409 domainPrivacyInProgress` while a paid one is
  being applied, `422 privacyUnavailable`, `400 enabledRequired`.
- The domain view has `privacy {enabled, available?, priceCents?,
  currency?}` (`available` and the yearly price on `GET
  /v1/domains/{name}` only) and the stored `privacyEnabled` flag, refreshed
  from the registrar by every sync.
- A paid renewal of a domain with the protection on renews it for the same
  years as a second line of the same checkout (`renewal.privacyPriceCents`).
- An organization exempt from paying for domains turns a paid protection
  on at once, without a checkout (`privacy.exempt: true` on the domain
  view; the request's audit carries `exempt`, `paidBy: "exempt"` and the
  USD price).

### Domain billing exemption

A platform admin may exempt an organization from paying for domains,
independently of how it pays for its plan (any billing mode): typically
the platform's own organization, for which a checkout would only move
money in a circle while paying the payment provider's fees and issuing an
invoice. The registrar cost (the Openprovider credit) is absorbed.

- `PUT /v1/admin/tenants/{orgId}/domains-billing-exempt {exempt, ticket,
  reason}` (platform admins only, like every admin write: `400
  invalidTicket`, `400 invalidReason` under 10 characters) sets it or, with
  `exempt: false`, revokes it. The write's reason and ticket are stored
  with the exemption in `billing.json` (`domainsBillingExempt {reason,
  ticket, setBy, setAt}`). Answers `200 {exempt, reason?, ticket?, setBy?,
  setAt?, domains}`, where `domains` lists the organization's domains whose
  registration or last renewal was exempt (`{name, registration,
  renewal}`); the admin tenant view (`GET /v1/admin/tenants/{orgId}`)
  carries the same object as `domainsBillingExempt`. Audited as
  `admin.domains_billing_exempt` in the platform's and the organization's
  streams (`{exempt, wasExempt}`). `400 exemptRequired`, `404 orgNotFound`.
- The organization sees it read-only: `GET /v1/billing` answers
  `domainsBillingExempt: true` and `domainsBillingExemptSince`; the
  Billing page says domains are free of charge.
- Effect, on every path the organization triggers itself (dashboard,
  `/v1`, MCP): `POST /v1/domains/register` opens no checkout: the domain is
  `registering` at once with `registration.paidBy: "exempt"` and the
  register job runs inside the request (`201 {domain, job}`, like the
  operator's `skipPayment`; history `register.exempt`). `POST
  /v1/domains/{name}/renew` renews at once (`DomainMutation`,
  `renewal.paidBy: "exempt"`, history `renew.exempt`; an unpaid renewal
  checkout is closed and the term's automatic renewal invoice voided).
  `PUT /v1/domains/{name}/privacy {enabled: true}` applies a paid
  protection at once. Automatic renewals run without an invoice
  (`paidBy: "exempt"`). `POST /v1/domains/transfer` opens no checkout
  either: the transfer job runs at once (`transfer.paidBy: "exempt"`,
  history `transfer.exempt`, audited `domain.exempt.transfer` in the
  platform log with the price kept for the books). The renewed and registered e-mails say "no charge (your
  organization's domains are exempt)".
- Everything else is checked as usual: the Domain Registration Terms
  (`428 domain_terms_required`), the registrant, availability, premium
  names (`422 domainPremium`: still on request), `skipPayment` on the org
  route (`403`). Prices are still quoted and recorded for the books:
  `GET /v1/domains/check` (and the MCP `domain_check`) keeps `priceCents`
  and adds `exempt: true`.
- Revoking never touches what was already registered or renewed; the
  next registration, renewal or automatic renewal is charged again.
- Every exempt operation consumes registrar credit, so it is also
  audited in the platform stream as `domain.exempt.register`,
  `domain.exempt.renew` or `domain.exempt.privacy` (`{orgId, op, paidBy,
  years?, priceCents?, currency?, usdCents?}`) and logged (`domain
  operation exempt from payment: registrar credit consumed`). An exempt
  automatic renewal is audited as `domain.autorenew.charge` with `method:
  "exempt"`.

**Schedule.** The data plane syncs every domain every
`RDNS_REGISTRAR_SYNC_INTERVAL` (6 h) and a domain whose transfer is pending
every `RDNS_REGISTRAR_TRANSFER_POLL` (15 min). When a pending transfer
completes with `applyZoneNs`, the zone's NS plan is written right after.

## Nameserver nodes (platform admin)

The RedundantDNS nameserver nodes (provider `rdns-ns`) come from the data
plane's configuration (`RDNS_MANAGED_NS_NODES`, `RDNS_MANAGED_NS_FILE`;
`docs/operator-handbook.md`, "Managed nameservers"): adding or removing a
node is a configuration change and a restart. Platform admin session only.

| Route | Purpose |
|---|---|
| `GET /v1/admin/nameservers` | `{offered, nodes, updatedAt}`: per node `name`, `region`, `nsName`, `apiHost`, `state` (`active`, `draining`), `stateChangedAt`, `stateChangedBy`, `addresses` (the NS name as resolved) or `addressError`, `version` (PowerDNS), `zones` (zones on the node), `health` (`ok`, `down`, `unknown`: `/healthz` and the API), `healthError`, `checkedAt`, `lastSyncAt`, `lastFailureAt`, `lastFailure`, `failingSince`, `down` (`ns_node_down` open) |
| `POST /v1/admin/nameservers/{name}/drain` | out of every rdns-ns NS set, no more writes (its zones stay). `409 nsNodeLastActive` for the last active node, `404 nsNodeNotFound`. Audit `admin.ns_node.drain` |
| `POST /v1/admin/nameservers/{name}/activate` | every attached zone written to the node first (backfill), then back into every NS set. Audit `admin.ns_node.activate` |

Both actions answer `{node, changed, zones, backfilled, backfillFailed}`
(`zones`: zones whose NS set changed; `backfillFailed`: zone names the
reconciles retry).

## Support actions (platform admin)

A platform admin can fail a zone over or move a domain's delegation on
an organization's behalf, only to answer a support request: every
action carries the request's `ticket` (its id or URL, 1 to 200
characters, required) and a `reason` (10 to 2000 characters, required).
There is no automatic failover: this is how support acts when a
customer's provider is down or a provider migration needs help. Platform
admin session only (no PAT, no OAuth, no MCP tool), like every
`/v1/admin` route. The routes mirror the org routes and follow their
rules; detaching or deleting attachments and zones, record edits and
impersonation stay out of scope.

| Route | Effect |
|---|---|
| `POST /v1/admin/tenants/{orgId}/zones/{zoneId}/attachments/{attachmentId}/role` `{role, ticket, reason}` | promote (`active`) or demote (`standby`), as `POST /v1/zones/{zoneId}/attachments/{attachmentId}/role`: `402 plan_limit_reached` for a standby outside the plan, `409 lastActiveAttachment`, `409 mirrorSourceOnly`, `402 org_read_only`, `404 zoneNotFound`, `attachmentNotFound`. Same answer: `{attachment, nsPlan, changed, guidance}` |
| `POST /v1/admin/tenants/{orgId}/domains/{name}/nameservers/apply-zone` `{zoneId?, ticket, reason}` | write a zone's NS plan (default: the org's zone named like the domain) as the domain's nameservers at the registrar. Only for a domain in the registrar account (registered or transferred in: `409 domainTransferInProgress`, `domainRegistrationPending`); `422 zoneNsPlanEmpty`, `428 domain_terms_required` (the org's own acceptance), `422 registrarRejected`. `200` applied or `202` queued (the registrar job retries), with the mutation result |
| `PUT /v1/admin/tenants/{orgId}/domains/{name}/nameservers` `{nameservers, ticket, reason}` | set the nameservers at the registrar (2 to 13); same rules and answers as apply-zone |
| `POST /v1/admin/tenants/{orgId}/domains/{name}/dnssec/reconcile` `{ticket, reason}` | the org route's DNSSEC reconcile (the DS at the registry made to match what the domain's nameservers serve); same rules and answers (`422 dnssecMismatch`), audited as `support.domain.dnssec.reconcile` |
| `POST /v1/admin/tenants/{orgId}/domains/{name}/move` `{toOrgId, ticket, reason, force?}` | move the domain to another organization with the customer route's rules and answer ("Moving a domain to another organization"): `409 domainMoveBlocked`, the destination's `402` and `428`, `400 domainMoveSameOrg`, `404 orgNotFound` for either organization. The org stream entry `support.domain.move` is written in **both** organizations, next to `domain.move.out` and `domain.move.in` (source `admin`); both get the e-mail and the info event, and the domain's history (in the destination) the `support.move` line |
| `GET /v1/admin/support-actions?orgId&limit&cursor` | the platform audit's support actions, newest first: `{items: [{id, at, orgId, orgName, kind, target, zoneId, operator: {userId, email}, ticket, reason, before, after, nsPlan, result, error?, changed?}], nextCursor}`; `limit` 1 to 200 (default 50), `cursor` the previous page's `nextCursor` (empty on the last page); `400 invalidOrgId`, `invalidCursor`, `invalidLimit` |

`400 invalidTicket` or `invalidReason` (and `invalidOrgId`, `404
orgNotFound`) answer before anything else and are not audited: without a
ticket there is nothing to file the action under. Every other outcome is
audited in both streams, in this order:

- org stream: `support.zone.attachment.role`,
  `support.domain.nameservers.apply-zone`, `support.domain.nameservers`
  or `support.domain.move` (in both organizations of a move)
  (source `admin`, actor the operator, target the attachment or the
  domain; `zoneId` the zone, the apply-zone's zone, or the org's zone
  named like the domain, so the entry is on the zone's timeline) with
  `{by: "platform", operator: {userId, email}, ticket, reason, before,
  after, nsPlan?, result, error?, changed?}`;
- platform stream: `admin.support.action` with the same payload plus
  `orgId`, `kind` (`zone.attachment.role`,
  `domain.nameservers.apply-zone`, `domain.nameservers`, `domain.move`;
  `orgId` is the source of a move) and `target`
  (the entry's own target is the organization).

`result` is `ok`, `queued` (a registrar job that retries) or `refused`
(a guard or the registrar said no: `error: {code, message}` and the
entry's `result: "refused"`). `before` / `after` are `{role, nsPlan}` for
a role change and `{nameservers}` (plus `zoneId` for apply-zone) for a
domain; a refused action's `after` is what was asked. The change itself
keeps its own entries (`zone.attachment.promote`,
`domain.nameservers.request`, ...), recorded with source `admin`.

On success the organization is told: its owners and admins get an
e-mail (category security: what changed, the ticket, the reason, the
operator's e-mail and a link to the zone or domain page), the
organization's alert channels get the info event `support_action`
(opened and resolved at once; see Alerts), and a domain action adds a
`support.nameservers.apply-zone` / `support.nameservers` line (`<ticket>:
<reason>`) to the domain's history. A role change that finds the
attachment already in that role is audited with `changed: false` and
notifies nobody.

`GET /v1/admin/tenants/{orgId}` carries a `support` block for the admin
page: `zones` (each with `nsPlan`, `delegationState` and its attachments'
`role`, `state`, `health` and, for a standby, `failover` readiness) and
`domains` (`status`, `nameservers`, `actionable`: in the registrar
account, `movable`: active with nothing in progress, and the zone named
like the domain).

## Zone insights

Deterministic findings about a zone's records and the targets they point
to (`docs/insights.md`): no model, nothing changes a record. The data
plane analyzes each zone daily (`RDNS_INSIGHTS_INTERVAL`) and on demand.

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/zones/{zoneId}/insights?severity&code&state&ownership&limit&cursor&compact` | viewer + `zones:read` | the last run and one page of findings: `{zoneId, zoneName, run, counts, targets{total, mine, not_mine, unknown, skipped}, total, findings, resolved, nextCursor?}`; `run` is `null` before the first. `severity` and `code` take comma-separated lists; `state` is `open` (not accepted), `accepted` or `resolved` (then the page is the resolved history, in `resolved[]`); `ownership` keeps the findings with a target in that state. `limit` (default 100, max 500) and `cursor` (the previous page's `nextCursor`, absent on the last page) page the findings; `total` counts every match. The first page also carries the latest 50 resolved findings. A finding names its targets by value (`targets[]`); the inventory is the next route. `compact=true` gives each finding's evidence as one `"query -> answer"` line per query (`evidence[]`, `at`) and 10 resolved findings (the MCP form). About 120 KB for a 2,500-record zone at the default page. `400 invalidLimit`, `invalidCursor` |
| `GET /v1/zones/{zoneId}/insights/targets?ownership&kind&reachable&source&limit&cursor` | viewer + `zones:read` | the target inventory of the last run, paged like the findings (default 100): `{zoneId, zoneName, run, counts{total, mine, not_mine, unknown, skipped}, total, targets, nextCursor?}`. `kind` is `ip` or `host`; `reachable=true` keeps the addresses that answered (TCP 443, TCP 80 or ICMP) and the hosts that resolve, `false` the others (unchecked targets match neither); `source` is `zone` or `skipped` (named only by record sets the mirror left out, `status.mirror.skippedSets`). Ownership is resolved from the current registry on every read, with `ownershipEntry` and `ownershipByEmail`. `400 invalidOwnershipState`, `invalidTargetKind`, `invalidReachable`, `invalidTargetSource`, `invalidLimit`, `invalidCursor` |
| `POST /v1/zones/{zoneId}/insights/run` `{fresh?}` | editor + `zones:write` | queue a run now (`202 {jobIds}`; audited `insights.run`); `fresh` (default `true`) checks every target again instead of reusing the checks of the last 24 hours. `503 insightsUnavailable` when the data plane has insights off |
| `POST /v1/zones/{zoneId}/insights/{findingId}/accept` `{reason}` | editor + `zones:write` | accept (mute) a finding: `accepted {by, at, reason}`; it keeps its acceptance while it is seen again, and stops counting for `insights_high` and `dns_hygiene`. Audited `insights.finding.accept` (finding id, code, severity, subject, reason); the zone is analyzed again from its cached checks. `400 insightReasonRequired`, `reasonTooLong` (500), `404 findingNotFound` |
| `DELETE /v1/zones/{zoneId}/insights/{findingId}/accept` `{reason?}` | editor + `zones:write` | remove the acceptance; audited `insights.finding.unaccept` with the previous acceptance |
| `GET /v1/insights` | viewer + `zones:read` | the organization: `{zones[{zoneId, name, run, counts, openHigh}], counts, openHigh, accepted, targets{total, mine, not_mine, unknown, skipped}, topTargets[20], unknownTargets[500], unknownTotal}`; a target is listed once with its `records` count, `zones` and `source` (`skipped` when only mirror-skipped sets name it) |
| `GET /v1/ownership` | viewer + `zones:read` | the ownership registry: `{entries[{value, kind, state, by, byEmail, at, reason, source, via}], counts, updatedAt}` |
| `PUT /v1/ownership/{value}` `{state, reason?}` | editor + `zones:write` | mark an IP, a CIDR network (percent-encode the slash: `192.0.2.0%2F24`) or a host name (`*.example.net` covers every host below it) `mine` or `not_mine`, org-wide; values are normalized (masked networks, lower-case IDNA hosts). Audited `org.ownership.set` with `value`, `kind`, `state`, `previousState`, `reason`. `400 invalidOwnershipValue`, `invalidOwnershipState`, `422 ownershipLimit` (20,000 entries) |
| `DELETE /v1/ownership/{value}` `{reason?}` | editor + `zones:write` | forget an entry (its targets go back to `unknown`); audited `org.ownership.delete` with the previous entry. `404 ownershipNotFound` |
| `POST /v1/ownership/import` `{text?, entries?, state?, reason?}` | admin + `zones:write` | import a list: `text` holds one value per line or a CSV whose first column is the value (`#` comments; a first line that is not a value is a header), `entries[]` the values as a list; every value becomes an entry in `state` (default `mine`, `source: list`). Answers `{total, added, updated, unchanged, matched, invalid[50], invalidCount, state, by, byEmail, at}` where `matched` counts the targets of the zones' last runs the list covers. Audited `org.ownership.import` with the counts and the first 200 values. `400 ownershipImportEmpty`, `ownershipImportTooLarge` (10,000 values) |

A finding: `{id, code, severity, subject, targets, records[{name, type, source?}],
summary, action, evidence{queries, answers, at}, firstSeenAt, lastSeenAt,
resolvedAt?, accepted?, acceptedByEmail?}`; `id` is stable across runs. A
target: `{kind (ip | host), value, records, checks{resolves, rcode,
addresses, reachable{tcp443, tcp80, icmp}, ptr, cloud{provider, range},
private, nsAnswers, takeover}, checkedAt, unreachableRuns, ownership,
ownershipEntry?, source?}` (`source: "skipped"`: only record sets the
mirror left out name it; such records carry `source: "skipped"` too). The
codes, severities and checks are in `docs/insights.md`. Filters that are
not known answer `400 invalidSeverity`, `invalidInsightCode`,
`invalidInsightState`, `invalidOwnershipState`, `invalidTargetKind`,
`invalidReachable`, `invalidTargetSource`; a bad page answers `400
invalidLimit` or `invalidCursor`.

## Alerts

Every data plane probes every zone's nameservers from its region (SOA
plus a sample of up to 5 record sets, UDP with TCP fallback, 3 s timeout,
every `RDNS_PROBE_INTERVAL`, region `RDNS_PROBE_REGION`). The tenant's
lease holder aggregates the regions into the zone status:
`status.probeRegions` (nameserver → region → result: reachable, latency,
serial, match), `status.probes` (the worst result per nameserver),
`status.probedAt`, and per attachment `health` (`ok` when every region's
probes match; `down` when no nameserver answers at all from every region;
`degraded` otherwise, including a server that answers but REFUSES the
zone, or serves other data, from every region) with `regions` (health and
down streak per region). A delegated name below the apex (an NS set such
as a child zone's delegation) is answered as a referral and matches when
the referral's NS set is the zone's; its glue matches the referral's
additional section, and other data below the cut is never sampled (the
failover check's rule, above). A CAA set served with extra `issue`/
`issuewild` values that the attachment's provider adds itself (the
provider capability `caaAdditions`: Cloudflare's Universal SSL CAs) matches
when every canonical value is served; the result carries a `notes` entry
instead of a mismatch (the failover check applies the same rule). Results
of a region that stopped probing drop out after three intervals.

An attachment's `lastDiff` may carry `reasons`: provider-reported reasons
per updated set label, for sets that differ although their TTL and values
may match (`{"www CNAME": ["proxied"]}`: a Cloudflare record with the proxy
on). Such a set is drift, and a reconcile rewrites it DNS-only.
After every reconcile, verify, probe and delegation job it evaluates the
org's rules and opens or resolves **events** (one firing event per rule +
zone + attachment, the dedupe key); each transition is delivered once to
every enabled channel.

| Rule | Fires when | Resolves when | Threshold |
|---|---|---|---|
| `drift` | an attachment's state is `drift` (for an existing provider zone just attached and neither written nor adopted yet, only from the first scheduled verify, 15 minutes after the attach: the attach answer already shows that drift while the user chooses reconcile or adopt) | it is `in_sync` again | |
| `sync_error` | an attachment's state is `error` | the provider answers (`in_sync` or `drift`) | |
| `sync_partial` | an attachment's provider refuses record sets of the zone (skipped with reason `provider-rejected` or `glue-required`); a warning: the rest is in sync | no set is refused any more | |
| `delegation_broken` | the delegation is `partial` or `mismatch`, or went from `complete` back to `pending` (`delegation.lostAt`) | it is `complete` | |
| `provider_down` | no nameserver of an attachment answered N consecutive probes, from at least `minRegions` regions | fewer than `minRegions` regions see it down | N (default 2, 1-20); `minRegions` (default 1, 1-20) |
| `probe_degraded` (off by default) | an attachment is down from some probe regions and answers from others | every region agrees | |
| `insights_high` | the zone's insights run has a high finding not accepted (a new high finding closes the event quietly and opens a new one, so every new high finding notifies) | no high finding is open (fixed, or accepted) | |
| `zone_serial_stale` | no successful verify of an attachment for N hours | a verify succeeds | N (default 24, 1-720) |

Besides these rules, the data plane raises **installation alerts** (not
configurable, no zone, one event per day while the condition lasts, the
day as `attachmentId`): `license_warning`, `license_expired` and
`mail_transport_unavailable` (`docs/licensing.md`), and the audit stream's
`audit_chain_broken`, `audit_stream_write_failed`, `audit_seal_failed` and
`audit_unsigned` (`docs/audit.md`), and `key_custody_warning` (the
installation runs without its offline master key among the key wrappers,
ADR 0004; `docs/deploy.md`). `fx_stale` (for some converted
currency, BRL or EUR, the exchange rate from USD is older than 48 hours
and no manual rate is set: domain checkouts in that currency answer `503
fx_unavailable`; "Billing in BRL and EUR") is one event while it lasts
(attachment id `fx`, labelled with the pairs without a rate, such as
`USD/BRL, USD/EUR`), raised in the platform admins' organizations and
resolved when every converted currency has a usable rate again.
`ns_node_down` (a RedundantDNS nameserver node failed its health check
for `RDNS_NS_NODE_DOWN_AFTER`) is one event per node while it lasts
(attachment id the node name, zone name its NS name, link to Admin >
Nameservers), raised in the platform admins' organizations and resolved
when the node answers again. The daily compliance check raises
`compliance_failed` differently: one event while the report fails
(attachment id `org` for the organization's report, `platform` for the
installation's, raised in the platform admins' organizations), resolved
when the report is back to warn (reason `downgraded_to_warn`) or pass. A
warning report raises nothing (it shows in `GET /v1/compliance`);
`compliance_warn` is no longer raised and stays accepted as a `rule`
filter for older events, which the next check resolves
(`docs/compliance.md`). The same daily check raises `backup_stale` when
no offsite backup was reported, the last run failed, or it is older than
8 days ("Offsite backup reports"): one event while it lasts (attachment
id `backup`), and a second one (attachment id `backup-locked`) while the
daily object-locked backup failed or is older than 2 days (once it
reported a run, or always with `featureFlags.backupLockedRequired`), in
the platform admins' organizations, resolved (and
notified) within a minute of a good report by the data plane's
installation pass. That pass also resolves the installation's
`compliance_failed` as soon as a saved report is back to pass or warn,
and raises `compliance_stale` (attachment id `compliance-check`) when no
installation report was saved for more than two
`RDNS_COMPLIANCE_INTERVAL`s. The platform admins' alerts of an
organization none of whose members is a platform admin any more resolve
with reason `no_longer_platform_admin`. `audit_write_failed` (an
audit entry could not be written: the action went through, the entry is
lost) is one event while it lasts (attachment id `audit-writes`), raised
by the data plane within a minute in the platform admins' organizations
when a process's failure counter grows (every process publishes it to
`platform/audit-health/<processId>.json`), resolved once no process has a
failing or new failed write.
`platform_object_tampered` (a users/, platform/config.json or
platform/stripe-customers/ object failed its integrity check and was
refused) and `config_changed` (a platform admin changed
`/v1/admin/config`; the summary lists the changed fields) come from
installation notices (`platform/notices/`): one event per notice
(attachment id = notice id) in the platform admins' organizations, raised
by the data plane within a minute and resolved when the notice expires
(24 hours after it was last raised).

Support actions (a platform admin acting on the organization with a
support ticket, see "Support actions") raise the info event
`support_action`: opened and resolved at once, delivered once to every
enabled channel as the type `alert.info` (e-mail severity "Info", Slack
title `INFO: support action on <zone>`); a domain action has no zone
(`zoneName` and `attachmentId` hold the domain name). It is not a rule
and cannot be disabled.

Every org starts with the rules enabled except `probe_degraded` (orgs
created before a rule existed get it with its default on first read). A disabled rule resolves its open events. Resolving
an event by hand notifies the channels; if the problem persists the next
check opens a new event. Acknowledging keeps the event firing and records
who is on it.

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/alerts/rules` | viewer + `zones:read` | rules with their effective thresholds |
| `PUT /v1/alerts/rules/{rule}` | admin + `zones:write` | `{enabled, threshold, minRegions}` (`minRegions`: `provider_down` only) |
| `GET /v1/alerts/channels` | viewer + `zones:read` | channels; secrets are never returned; `verified` (false: an e-mail channel waiting for its address) and `verificationExpiresAt` (its open link) |
| `POST /v1/alerts/channels` | admin + `zones:write` | `{kind: email\|webhook\|slack, label, target, secret?}`; a webhook's signing secret is returned once; an e-mail channel answers `verificationSent` (and `verificationError`, the error code, when the verification e-mail was refused or failed) |
| `DELETE /v1/alerts/channels/{channelId}` | admin + `zones:write` | remove a channel |
| `POST /v1/alerts/channels/{channelId}/test` | admin + `zones:write` | send a test notification now (`{ok, attempts, error}`); `409 channelNotVerified` for an unverified e-mail channel; 5 an hour per channel |
| `POST /v1/alerts/channels/{channelId}/verification` | admin + `zones:write` | a new verification e-mail for an unverified e-mail channel (`{sent, verificationExpiresAt}`; the previous link stops working); `409 channelAlreadyVerified`; 3 an hour per channel |
| `POST /v1/alerts/channels/verify` | public (the link is the credential) | `{token}` from the verification link: confirms the channel (`{verified, orgName}`); `400 channelVerifyInvalid` (unknown, replaced or used), `410 channelVerifyExpired` (after 24 hours) |
| `GET /v1/alerts/events` | viewer + `zones:read` | history, newest first; `zoneId`, `rule`, `state`, `limit`. `400 invalidRule` for a rule no event can carry (`details.rules` lists them), `400 invalidState` for a state other than `firing` or `resolved` |
| `POST /v1/alerts/events/{eventId}/resolve` | editor + `zones:write` | resolve a firing event by hand |
| `POST /v1/alerts/events/{eventId}/ack` | editor + `zones:write` | acknowledge a firing event |
| `GET /v1/admin/alerts` | platform admin | per tenant: firing count and events of the last 24 hours; latest firing events; `regions`: probe regions seen (mode, last heartbeat, last probe) |

### E-mail channels: double opt-in

An e-mail address an organization types is not trusted until it says so
(2026-10-09 review, AUTH-5): a new e-mail channel starts unverified and
its address gets one verification e-mail (category `security`, fixed
text with the organization's name, never the channel label). Until
someone at that address opens the link and clicks Confirm, the channel
receives nothing: no alert, no test (`409 channelNotVerified`), and it is
not a recipient of the self-hosted mail relay. Webhook and Slack channels
need no verification. Channels created before this change stay verified.

- The link is `<public URL>/alerts/channels/verify#<token>`: the token
  (`rdcv_<orgId>_<channelId>_<64 hex>`) rides in the URL fragment, which
  browsers never send, so it never reaches an access log. The page posts
  it to `POST /v1/alerts/channels/verify` (no session; limited per client
  IP with the sign-in routes). Stored as its SHA-256 in the sealed
  manifest; valid 24 hours; single use; a new link replaces the previous
  one. Audited as `alert.channel.verify` (and `alert.channel.verification`
  for a resend).
- Every verification e-mail (at creation and each resend) counts against
  the organization's mail limit (10 per recipient and 50 per organization
  a day, shared with invitations and hand-off offers) and resends are
  limited to 3 an hour per channel; beyond, `429 tooManyRequests` with
  `Retry-After`. A channel whose first e-mail was refused still exists
  (`verificationSent: false`): resend later.
- Tests: 5 an hour per channel, and an e-mail test also counts against
  the organization's mail limit.
- A user owns at most 10 organizations (`409 tooManyOrganizations`) and
  creates at most 5 an hour (`429 tooManyRequests`); each organization
  carries its own mail limits, so this bounds how far they multiply.
  Platform admins are not limited.

### Channels and webhook signatures

- **email**: a branded multipart e-mail (plain text + HTML) through the login SMTP settings (`RDNS_SMTP_*`), with a link to the zone (or domain) and to the Alerts page.
- **slack**: an incoming-webhook URL, stored sealed (the API shows it
  masked); the message is Block Kit (header, fields, context) with a text
  fallback.
- **webhook**: `POST` of a JSON body
  `{type: alert.firing|alert.resolved|alert.info|alert.test, orgId, orgName, event: {eventId, rule, state, zoneId, zoneName, attachmentId, attachmentLabel, summary, firstSeenAt, resolvedAt, url}, sentAt}`
  with the headers `X-RDNS-Event` (the type), `X-RDNS-Delivery`
  (`<eventId>-<channelId>-<state>`, stable across retries) and
  `X-RDNS-Signature: sha256=<hex HMAC-SHA256 of the raw body with the channel secret>`.
  Network errors, `429` and `5xx` are retried 3 times with backoff
  (1 s, 4 s, 10 s); other `4xx` fail at once. Redirects are not followed.
  Outside dev mode the URL must be `https` and resolve to a public
  address (checked at dial time).

Verify a delivery by recomputing the HMAC over the exact bytes received:

```js
const expected = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
const valid = crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(request.headers['x-rdns-signature']));
```

A failed delivery makes the notify job retry (30 s, 2 min, 10 min); a
channel that already received a transition is skipped
(`orgs/<id>/alerts/deliveries/<eventId>-<channelId>-<state>.json`), so a
retry never sends it twice.

## Plans and billing

Plans (the catalog is compiled in; `platform/config.json` `plans` replaces
an entry by id, `managedCosts` the managed providers' list prices). There
is no Free plan: every new organization starts on a **30-day trial**.
Yearly prices apply only while yearly billing is on sale
(`billingIntervals` below; monthly only by default) and only to plans that
have one:

| Plan | Price | Zones | Providers per zone | Alert channels | Features |
|---|---|---|---|---|---|
| `trial` (every new org, 30 days; not sold, not listed in `plans`) | no charge | 1 | 2 | email | API, BYO accounts only |
| `starter` | $9/mo (monthly only) | 3 | 2 | email, webhook | + Terraform provider, CLI, managed accounts |
| `pro` | $99/mo, $990/yr | 50 | 3 | + Slack | + MCP (zone and connection tools; the domain tools work on every plan), standby attachments |
| `business` | $299/mo, $2990/yr | unlimited | unlimited | all | + 90-day alert history, audit export, priority support |
| `enterprise` | contract | unlimited | unlimited | all | + self-hosted or your own data plane |

Domains are not a plan feature: they are sold per item and work the same
with any plan, on the trial, without a plan and on a read-only organization
(see Domains above; `domainsNote` in `GET /v1/plans`). A domain registered
or transferred here also gets its zone on the RedundantDNS nameservers for free, one
provider, with or without a plan (`freeDnsNote` in `GET /v1/plans`; see
"Free DNS for domains registered here" under `rdns-ns`).

**The trial.** A new organization is `trialing` on the plan `trial` with
`trialEndsAt` = creation + 30 days (`GET /v1/billing` `trialEndsAt`,
`trialDays`). When `trialEndsAt` passes, the data-plane billing job makes
it `read_only` through the dunning mechanism below (zones keep resolving;
no sync, attachment or edit is applied; export, domains (every domain
route), billing, legal and account deletion keep working;
`402 org_read_only` with `details.reason: "trial_ended"`), until a plan is
bought: a completed checkout (or an admin override to a paid plan) makes
it `active` at once. A read-only trial is detached after the detach period
like any read-only organization. The billing job e-mails the organization's
owners (category `billing`) once per milestone: the day the trial starts,
7, 3 and 1 days before `trialEndsAt`, and when it ends
(`billing.json` `trialNotices`; audited as `billing.trialNotice`). An
organization still on the retired `free` plan moves to a fresh trial
(`trialEndsAt` = now + 30 days, `source: "migration"`, audited as
`billing.migrate`) the first time it is loaded, by the dashboard, the API
or the billing job; a `defaultPlan: "free"` in `platform/config.json`
reads as `trial`.

**Licensed installations.** On a self-hosted installation that requires
a license (`RDNS_LICENSE_REQUIRED`), the license, not this catalog, is the
source of truth (`docs/licensing.md`, "Limits and features"). Every
organization is on the plan `licensed`, `active` (new ones start there,
older ones move on their first load or the next billing-job pass, audited
`billing.migrate`); there is no trial, dunning, usage report or billing
job. Limits and features come from the license claims and every
organization shares them: `limits.zones` counts the zones of the whole
installation, `limits.providers` applies per zone (`0` = unlimited), the
features are the license's `features`, every alert channel kind is
allowed. A refused action answers `402 license_limit_reached` with
`details: {action, feature?, limit?, current?, scope?, licenseId, edition,
state}` (`scope`: `installation` or `zone`; no upgrade hint). `GET
/v1/billing` answers `{source: "license", plan: {id: "licensed", name:
<edition>, limits, channels, features}, status: "active", limits: {zones:
{used, limit, scope: "installation"}, providersPerZone, channels},
features, license: {lid, edition, mode, term, state, reason, expiresAt,
changesStopAt, graceUntil, limits}, prioritySupport, alertHistoryDays,
multiRegionProbes, auditExport, detached: [], gateway: "off"}` (the MCP
tool `billing_get` returns the same); `POST /v1/billing/checkout`, `POST
/v1/billing/portal` and `PUT /v1/admin/tenants/{orgId}/plan` answer `409
billing_not_applicable`; the admin tenant view carries `licensed: true`.
`/v1/me` and `/v1/security.json` carry `license.licensed`. Installations
without the requirement (the hosted service) are unchanged.

`GET /v1/plans` (public, `Cache-Control: max-age=300`, CORS `*`) returns the
catalog in the exact shape of the website's `src/data/plans.json` (the
website renders its pricing from it; a test checks every field of a copy
in `internal/controlplane/testdata/website/`):

- top level: `source` (`"api"`), `status` (`plansStatus` in
  `platform/config.json`: `"draft"`, `"coming_soon"` or `"published"`;
  unset means `"coming_soon"`, and the legacy `plansPublished: true`
  still reads as `"published"` when `plansStatus` is unset; always
  `"sandbox"` on the public sandbox, `RDNS_SANDBOX=1`, whatever
  `plansStatus` says: nothing there is for sale for real; set in the
  dashboard's Admin, Config tab, with `rdns config set plansStatus
  <state>` on a server, or with `PUT /v1/admin/config`, which answers
  `400 invalidPlansStatus` for another value),
  `updatedAt` (`YYYY-MM-DD`), `currency` (`"USD"`: the currency of the
  legacy price fields), `currencies` (`["USD", "BRL", "EUR"]`:
  the billing currencies; organizations in Brazil pay in BRL, in the euro
  area in EUR), `intervals` (the
  subscription intervals on sale, monthly first: `billingIntervals` in
  `platform/config.json`, `"monthly"` and optionally `"yearly"`, must
  include `"monthly"`, `PUT /v1/admin/config` answers
  `400 invalidBillingIntervals` otherwise; unset means `["monthly"]`),
  `annualFreeMonths` (the yearly discount, meaningful only while
  `intervals` lists `"yearly"`),
  `managed: {markupPercent, billing}`, `domainsNote` ("Domains are sold
  per item and never need a plan": no plan lists domains as a feature),
  `freeDnsNote` (a domain registered or transferred here gets DNS on the
  RedundantDNS nameservers for free, one provider, with or without a
  plan),
  `grace: {readOnlyAfterDays,
  detachAfterDays}` (days past due before read-only, then days read-only
  before every attachment is detached; 7 and 30 by default),
  `trial: {days, limits: {zones, providersPerZone}}` (the trial every new
  organization starts on: a note, not a plan; the dashboard also reads its
  `modes`, `alerts`, `access`, `channels` and `features`), `plans`
  (`starter`, `pro`, `business`, `enterprise`; never the trial);
- per plan: `id`, `name`, `priceMonthly` (US dollars, `null` when custom),
  `custom`, `highlight` (only on the recommended plan), `billing`
  (`"annual"` on contract plans), `summary`, `limits: {zones,
  providersPerZone}` (`null` = unlimited), `modes` (`byo`, `managed`,
  `self-hosted`, `byo-data-plane`), `alerts` (channel kinds,
  `multi-region-probes`, `history-90d`), `access` (`dashboard`, `api`,
  `terraform`, `cli`, `mcp`, `audit-export`, `priority-support`, `contract`),
  `available` (the plan can be bought now: every plan once the catalog is
  `"published"`, none before; checkout answers `409 plan_not_available`).

Additions for the dashboard: per plan `priceMonthlyCents`,
`priceYearlyCents` (omitted unless `intervals` lists `"yearly"` and the
plan has a yearly price), `prices` (the price per billing currency:
`{"USD": {monthly, monthlyCents, yearlyCents?}, "BRL": {...}, "EUR":
{...}}`; BRL Starter 4900, Pro 54900, Business 164900 centavos a month,
EUR Starter 900, Pro 8900, Business 27900 euro cents a month, yearly
with the same free months; empty for custom plans; the USD entry repeats the legacy
fields, which stay),
`purchasable`, `channels`, `features`, `auditRetentionDays` (days the
audit trail is kept on write-once storage: Business 365; `null` without a
promise; `platform/config.json` `auditRetentionDays` overrides it per
plan) and `auditRetentionCustom` (Enterprise: its own bucket and
retention); top-level
`managedCosts` (list prices per managed provider). Unlike this document,
`GET /v1/billing` and the admin config keep `-1` for unlimited limits.

**Entitlements.** A limited action answers `402 plan_limit_reached` with
`details: {action, plan, limit?, current?, feature?, channel?, upgradeTo,
upgradeName}` (`upgradeTo` is the cheapest plan that allows it):

| Action | Checked on |
|---|---|
| `zone.create` | `POST /v1/zones` (zones in the org vs `limits.zones`) |
| `zone.attach` | `POST /v1/zones/{id}/attachments` (the zone's attachments, standby ones included, vs `limits.providersPerZone`) |
| `attachment.standby` | `POST /v1/zones/{id}/attachments` with `role: standby` and `POST .../attachments/{attachmentId}/role` `{role: "standby"}` (the `standby` feature: Pro, Business, Enterprise; the trial and Starter lack it). Promoting to `active` is never gated, so an org that lost the feature can leave standby; standby attachments that already exist keep syncing after a downgrade |
| `channel.create` | `POST /v1/alerts/channels` (the channel kind) |
| `connection.managed` | managed connections and attaching them; the data plane also refuses a managed account on a plan without it (queued jobs after a downgrade) |
| `access.mcp` | every `/mcp` request |
| `audit.export` | `GET /v1/audit/export` (the `audit-export` feature) |
| `access.terraform`, `access.cli` (and `access.mcp` for a PAT declared `mcp`) | token requests to `/v1`, by the token's declared client (see Token clients below), then by a `User-Agent` declaring `terraform-provider-redundantdns/` or `rdnsctl/` |

**Features without a 402.** `multi-region-probes`: on a plan without it
the data plane aggregates the probes of one region only (its own, or the
first fresh region by name), `status.regionsLimitedTo` names it and the
Health panel says so. `history-90d`: `GET /v1/alerts/events` (and the
`alert_list` tool) lists resolved events last seen within the plan's
window, 30 days or 90 with the feature (firing events always), and states
the window in the `X-RDNS-History-Days` header. `priority-support`: a flag
(`prioritySupport` in `GET /v1/billing`, next to `alertHistoryDays`,
`multiRegionProbes` and `auditExport`).

**Billing status** (`org.billingStatus` in `/v1/me`): `active`,
`trialing` (the trial is running), `past_due` (a payment failed: the
dashboard shows a banner, everything works), `read_only` (past due for
longer than the grace, `RDNS_BILLING_GRACE`, 7 days, or a trial that
ended: the providers keep serving the last
applied records, reads work, but `402 org_read_only` answers the routes
that change providers: connections create/delete, zone create/delete,
records, attach/detach, adopt, reconcile; queued reconciles only verify;
domains are never read-only: every domain route and domain job keeps
working; a free zone, named like a domain registered or transferred
here, keeps its create, records, reconcile, detach, delete and `rdns-ns`
attachment, which the data plane keeps applying),
`detached` (read-only for `RDNS_BILLING_DETACH_AFTER`, 30 days: the
data-plane billing job detached every attachment of every zone except
`rdns-ns` on free zones, without
deleting the provider zones, which keep serving the last applied records
until the delegation moves; the canonical zones keep their records, the
attachments' firing events are resolved, `billing.detach` is audited with
the list, and writes stay refused like `read_only`), `canceled` (the
subscription ended: there is no free plan to fall back to, so the org keeps
its last plan and is read-only like `read_only`, without the detach, until
it buys a plan again). `402 org_read_only` carries `details: {status,
reason}` with `reason` `unpaid`, `trial_ended` or `canceled`
(`readOnlyReason` in `GET /v1/billing`). Paying the invoice makes the org active
again; detached attachments are not restored by themselves: the Billing
page lists them (`detached` in `GET /v1/billing`, with an "Attach again"
button) and the user attaches each connection again with
`POST /v1/zones/{zoneId}/attachments {connectionId, providerZoneId,
adoptExisting: true, label}`, which adopts the kept provider zone
(verified first, as any adopted zone) and keeps the attachment's label.
An attachment's `label` is optional at attach (up to 80 characters; the
connection's label is shown when it has none); `rdnsctl attach --label`
passes it.

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/billing` | viewer + `zones:read` | plan, status, `readOnlyReason`, the trial's end (`trialEndsAt`, `trialDays`; plan `trial` only) and the trial e-mails already sent (`trialNotices`: milestone to send time), interval, next invoice date, grace end (`graceEndsAt`), detach date of a read-only org (`detachAt`), detached attachments still to re-attach (`detached`), limits with usage, the current period's usage snapshot and managed pass-through lines, gateway; `hasSubscription` (a live subscription: any status but `canceled`), a scheduled cancellation (`cancelAtPeriodEnd`, `cancelAt`: set from the portal's "cancel at period end", cleared when the customer resumes), and for owners and admins `stripeSubscriptionId` masked to its last six characters (`***abc123`); `billingMode` (`stripe`, `comped`, `manual`), `compedReason` and `compedUntil` (comped only), `manualInvoices` (manual invoices, read-only), `discount` (`{coupon, name, percentOff\|amountOffCents, currency, duration, durationInMonths, promotionCode, start, end}`), `billingIdentity` (`{name, email, country, taxIds: [{type, value}]}`), and for an invoiced Enterprise subscription `customPrice` (`{amountCents, currency}`) and `collectionMethod: "send_invoice"`; `currency` (`USD`, `BRL` or `EUR`, USD until chosen), `currencySet`, `currencyLocked`, `currencyLockedAt`, `currencies`, and for a BRL or EUR org `fxSafetyPercent` (the conversion margin of its managed usage and domain prices); `domainsBillingExempt` (a platform admin exempted the org from paying for domains, read-only) and `domainsBillingExemptSince` |
| `PUT /v1/billing/currency` | admin, session | `{currency: "USD"\|"BRL"\|"EUR"}`: the org's billing currency, editable while no live subscription or invoiced price holds it (`409 billing_currency_locked`, `details.reason: "subscription"`; switch with the route below) and a paid domain never locks it; `details.reason: "stripe_balance"` when Stripe refuses the currency on a customer without a subscription (a balance or an open invoice in the old one); `200 {currency, currencyLocked, currencyLockedAt?}`; audited as `billing.currency`; `400 invalidCurrency` |
| `GET /v1/billing/currency/switch-preview?currency=EUR` | admin, session | what a switch would do: `{currency, from, needsSwitch, plan?, interval?, periodEnd?, firstChargeAt?, newPriceCents?, pending?}` (`needsSwitch` false without a live subscription: the currency simply changes) |
| `POST /v1/billing/currency/switch` | admin, session | `{currency}`: without a live subscription, the same as `PUT /v1/billing/currency` (`switched: false`). With one, see "Switching currency with a subscription" below: `200 {currency, switched: true, checkoutUrl, currencySwitch}`; `409 currency_switch_pending`, `409 billing_currency_locked` with `details.action: "cancel_and_resubscribe"` (an invoiced price), `400 currencyUnchanged`, `400 currencyNotAvailable`, `409 currency_switch_unavailable` (no period end known) |
| `DELETE /v1/billing/currency/switch` | admin, session | undo the switch in progress before the old period end: `200 {currency, currencyLocked, currencySwitch}`; `409 no_currency_switch`, `409 currency_switch_unavailable` (the period already ended) |
| `POST /v1/billing/checkout` | admin, session | `{plan, interval: monthly\|yearly, currency?}` (default monthly; currency default the org's, recorded on the org by the first checkout, `409 billing_currency_locked` for another one while a subscription holds it, `409 currency_switch_pending` while a currency switch is in progress, `400 currencyNotAvailable` when the plan has no price in it; the answer adds `currency`). Without a live subscription: `{url}` of the hosted checkout. With one: the subscription changes plans in place and the answer is `{changed: true, plan, interval}` (no redirect; see "Changing plans"). `409 billing_mode_no_checkout` for an org on a comped or manual plan (checked before availability); `409 plan_unchanged` for the current plan and interval; `409 downgrade_over_limits` when the org's usage exceeds the target plan; `402 payment_failed` when the proration charge is declined (the plan did not change); `409 plan_not_available` while the plan is not available (catalog `draft` or `coming_soon`); `400 intervalNotAvailable` for an interval the catalog's `intervals` does not list |
| `POST /v1/billing/portal` | admin, session | `{url}` of the customer portal (invoices, payment method, cancel); `409 billing_no_customer` before a subscription |
| `PUT /v1/admin/tenants/{orgId}/plan` | platform admin | `{plan, status?, trialEndsAt?, note?, billingMode?, reason?, until?, cancelSubscription?, priceMonthlyCents?, currency?}`; see "Billing modes" below for `billingMode`, `reason`, `until`, `cancelSubscription` and the Enterprise price. In stripe mode (the default): manual override (enterprise deals; any plan, available or not, or `trial`), recorded on billing.json and audited as `admin.tenant.plan`; the next Stripe event of the org may change it again. `plan: "trial"` starts a trial (`trialing`, `trialEndsAt` defaults to now + 30 days; a past `trialEndsAt` makes it read-only at once); `trialEndsAt` with another plan answers `400 invalidTrialEndsAt`; leaving the trial without a `status` makes the org `active`. `currency` (`USD`, `BRL` or `EUR`) sets the org's billing currency while it is not locked (`409 billing_currency_locked` otherwise; audited as `billing.currency`, and in the `admin.tenant.plan` details); with `priceMonthlyCents` it is also the invoiced price's currency (default the org's), and the invoiced subscription locks it |
| `POST /v1/admin/tenants/{orgId}/coupon` | platform admin | `{coupon}` (a Stripe coupon id: `FOUNDER100`, `PILOT50`, `PARTNER30`...): applied to the org's live subscription, replacing any discount; answers `{discount}`; audited as `admin.tenant.coupon`. `409 billing_no_subscription` without a live Stripe subscription (comped and manual orgs have none), `404 couponNotFound`, `400 invalidCoupon` |
| `DELETE /v1/admin/tenants/{orgId}/coupon` | platform admin | removes the subscription's discount; audited as `admin.tenant.coupon.remove`; `409 billing_no_subscription` |
| `GET /v1/admin/tenants/{orgId}/invoices` | platform admin | `{billingMode, status, invoices}`: the manual invoices (kept when the mode changes) |
| `POST /v1/admin/tenants/{orgId}/invoices` | platform admin | `{amountCents, currency, reference, issuedAt, dueAt?, paidAt?, note?}` (manual mode only, else `409 billing_not_manual`; `dueAt` defaults to `issuedAt` + 30 days; currency stored upper case): `201 {invoice, billing}`, the invoice numbered 1, 2, ...; the status follows at once; audited as `admin.tenant.invoice.create` |
| `PUT /v1/admin/tenants/{orgId}/invoices/{number}` | platform admin | `{paidAt, note?}`: `paidAt` marks it paid, `null` or absent marks it unpaid; the status follows; `404 invoiceNotFound`; audited as `admin.tenant.invoice.update` |
| `POST /webhooks/stripe` | Stripe signature | `Stripe-Signature` verified with `RDNS_STRIPE_WEBHOOK_SECRET` (5-minute tolerance); handles `checkout.session.completed` (subscriptions, and one-off payments with `mode=payment`: domain registrations and renewals), `checkout.session.async_payment_succeeded` and `checkout.session.expired` (one-off payments), `customer.subscription.created\|updated\|deleted`, `invoice.paid`, `invoice.payment_succeeded`, `invoice.payment_failed`, and `customer.updated`, `customer.tax_id.created\|updated\|deleted` (the billing identity only, in every billing mode); idempotent by event id (`platform/stripe-events/<id>.json`, `processing` then `done`); a failed event returns 500 and is processed again on Stripe's retry; a delivery while another one processes the event returns 409 `event_in_progress` (`docs/billing-stripe.md`, "Webhook processing") |

**Billing in BRL and EUR.** The catalog is in USD; organizations in
Brazil pay in BRL (a Stripe account in Brazil charges Brazilian cards in
BRL only) and organizations in the euro area may pay in EUR. The org's
billing currency (`billing.json` `currency`, `GET /v1/billing`
`currency`) is `USD`, `BRL` or `EUR` (`internal/model` `CurrencyTable`):
chosen in the dashboard's header selector (mirrored on the Billing page
and the first domain purchase; owners and admins; the browser locale
suggests it on first use: `pt-BR` BRL, a euro-area locale EUR),
recorded by the first checkout of any kind (USD when none was chosen),
and **locked only while** the org has a live subscription (any status but
`canceled`) or an invoiced price, which is what Stripe refuses to mix
currencies with (`currencyLocked`; `currencyLockedAt` is when the current
subscription locked it). A paid domain, renewal or other one-off never
locks it (orgs locked in v0.1.11 by a one-off alone read as unlocked), and
the lock ends with the subscription. Organizations that subscribed before
the currency existed read as USD, locked while subscribed. Every checkout passes the currency explicitly. Plans have fixed
prices per currency (`GET /v1/plans` `prices.BRL`, `prices.EUR`);
domains, renewals and the managed pass-through, which cost the platform
USD, are converted: `ceil(USD cents x rate x (1 + fxSafetyPercent/100))`
in the currency's minor unit, where the rate is the currency's manual
rate (`fxRate.manual.<CODE>` of `platform/config.json`) when set, else
the rate from USD the data plane fetches hourly into `platform/fx.json`
(`usdBrl`, `usdEur`; `RDNS_FX_SOURCE_URL`), and `fxSafetyPercent`
defaults to 4. A fetched rate older than 48 hours without a manual one
is unusable: domain checkouts in that currency answer `503
fx_unavailable` (`details.currency`) and the platform admins get the
`fx_stale` installation alert. The managed pass-through of a BRL or EUR
org is reported in its minor unit at the report's rate (the report waits
for a usable one). `GET /v1/admin/config` adds `fx: {safetyPercent,
stale, unusable: [currency...], currencies: {BRL: {currency, rate,
source: manual|fetched, safetyPercent, manual?, fetched?, fetchedAt?,
fetchedFrom?, stale}, EUR: {...}}}`; `PUT /v1/admin/config` takes
`fxSafetyPercent` (0 to 100) and `fxRate: {manual: {BRL?, EUR?}}` (a
plain number still reads as the BRL rate; another key, a negative or
absurd rate: `400 invalidFx`; a 0 entry is dropped).
The admin tenant view adds `currency: {currency, set, locked, lockedAt,
currencies}`. Refunds, receipts and dunning are unchanged (amounts and
currency come from Stripe).

**Changing plans.** An org has at most one subscription. Once it pays
through one (`hasSubscription`), `POST /v1/billing/checkout` never opens a
second checkout: the platform updates the live subscription at Stripe
(the plan item takes the new price, the metered pass-through item is
kept, `proration_behavior=always_invoice`,
`payment_behavior=error_if_incomplete`, `cancel_at_period_end=false`),
records the new plan at once and answers `{changed: true, plan,
interval}`; the `customer.subscription.updated` webhook that follows maps
the new price back to the same plan. An upgrade is charged the prorated
difference for the rest of the period immediately; a downgrade credits
the unused part to the customer balance, used by the next invoices; the
billing period is kept (Stripe restarts it only when the interval
changes). A declined charge answers `402 payment_failed` and leaves the
old plan. A change is refused with `409 downgrade_over_limits` when the
org holds more than the target plan allows, with the same limits the
entitlements enforce: zones, attachments on one zone, standby
attachments (plans without `standby`), domains beyond one (plans without
`domains`); `details` is `{plan, over: [{limit, allowed, current}]}` with
`limit` one of `zones`, `providersPerZone`, `standby`, `domains`. The
change is audited as `billing.subscription.update` (actor, plan before
and after). A `canceled` org has no live subscription and goes through
checkout again.

**One subscription per org (webhook safety net).** The webhook acts only
on the org's current subscription (`billing.json`
`stripeSubscriptionId`): a `customer.subscription.*` or `invoice.*` event
that names another subscription is ignored (logged and audited as
`billing.webhook.ignored` with both ids), so canceling a stale duplicate
never touches the org. The one exception is `checkout.session.completed`
for a new subscription while another one is live (a race, or a client
that still got a checkout URL): the new one replaces it and the previous
one is canceled at Stripe at once, prorated with a final invoice
(`billing.subscription.replaced`, warning in the log). Events without a
subscription id resolve through the customer as before.

**Scheduled cancellation.** "Cancel at period end" in the Customer Portal
arrives as `customer.subscription.updated` with `cancel_at_period_end`
(or `cancel_at`): `billing.json` records `cancelAtPeriodEnd` and
`cancelAt` (the period end when Stripe sends no date), the org keeps its
plan and status, and the Billing page shows when it ends with a link to
the portal to resume. A later event without a scheduled end clears both;
the `customer.subscription.deleted` at that date makes the org
`canceled` (read-only).

**Domains are apart from the billing mode**: an organization may be
exempt from paying for domains whatever its mode (see "Domain billing
exemption"); `GET /v1/billing` shows `domainsBillingExempt`.

**Billing modes.** `billing.json` `billingMode` says how an org pays;
`PUT /v1/admin/tenants/{orgId}/plan` sets it (platform admins only),
recorded in the override and audited as `admin.tenant.plan` (with
`billingModeBefore`, `billingMode`, `reason`, `compedUntil`,
`canceledSubscriptionId`, and for an invoiced subscription
`subscriptionId`, `priceMonthlyCents`, `currency`):

- `stripe` (the default, also what a request without `billingMode`
  sets): a Stripe subscription through Checkout, or an invoiced
  Enterprise subscription (below). A plan granted without a subscription
  stays the override it always was.
- `comped`: a complimentary plan. Any paid plan (not the trial), status
  `active`, no subscription and no invoice; `reason` is required (`400
  reasonRequired`) and shown on the Billing page ("Complimentary plan");
  `status` is refused (`400 invalidStatus`). `until` (optional, future,
  `400 invalidUntil` otherwise or outside comped) ends it: the billing job
  then returns the org to stripe mode and, without a live subscription,
  makes it a read-only ended trial (`plan: trial`, `read_only`, reason
  `trial_ended`, `trialEndsAt` = `until`, no trial e-mail; audited as
  `billing.comped.ended`) until a plan is bought. Checkout answers `409
  billing_mode_no_checkout` and the Billing page hides the checkout buttons.
- `manual`: invoiced outside Stripe (contract, purchase order, bank
  transfer). Any paid plan, `reason` required, no subscription; the
  operator records each invoice (`POST .../invoices`). The org is `active`
  while no invoice is overdue (unpaid after `dueAt`) and `past_due` as soon
  as one is (when it is recorded, marked unpaid, or when the billing job
  finds its due date passed; audited as `billing.change` with `event:
  manual.invoices`); the usual grace, read-only and detach follow; marking
  the invoices paid makes it `active` again. The Billing page lists the
  invoices read-only; checkout answers `409 billing_mode_no_checkout`.

A switch to `comped` or `manual`, or a new invoiced subscription, while
the org pays through a live subscription answers `409 subscription_active`
(`details.subscriptionId`) unless the request carries `cancelSubscription:
true`: the subscription is then canceled at Stripe at once, prorated
(unused time credited, a final invoice for any metered usage), before
`billing.json` changes. Stripe subscription, invoice and checkout events of
a comped or manual org never change it (`billing.webhook.ignored`, reason
`billing mode ...`); a checkout that completes anyway (a race) has its new
subscription canceled at once. Customer events (identity) still apply.

**Switching currency with a subscription.** No refunds (owner decision
2026-09-27: a refund may reach a card the customer no longer has). `POST
/v1/billing/currency/switch {currency}` with a live subscription:

1. sets the current subscription to `cancel_at_period_end` (it keeps
   serving until its period end);
2. creates a new Stripe customer for the org (name, e-mail, country and
   tax ids copied from the billing identity; the old one is kept in
   `billing.json` `previousCustomers[]`, for its invoices and the events
   that still name it);
3. opens a subscription checkout in the new currency for the same plan
   and interval with `subscription_data.trial_end` = the old period end
   plus one day (at least 48 hours ahead, a Stripe Checkout rule): the
   card is collected and checked now, the first charge is the day after
   the old period ends; the answer carries its `checkoutUrl`;
4. records `billing.json` `currencySwitch = {from, to, state, plan,
   interval, scheduledAt, firstChargeAt, oldSubscriptionId,
   oldCustomerId, newCustomerId, newSubscriptionId?, checkoutSessionId}`,
   state `pending_checkout`.

When that checkout completes the org's currency and customer become the
new ones (one-off purchases from then on are priced in the new currency
and paid by the new customer) and the state is `scheduled`; the old
subscription keeps serving. When the old subscription is deleted at its
period end the new one becomes the org's subscription (state `done`; its
bridge trial reads as `active`, no trial e-mails). A checkout never
completed leaves the old subscription to end at its period end and the org
follows the normal no-plan path (state `abandoned`). `DELETE
/v1/billing/currency/switch` before the period end undoes it:
`cancel_at_period_end=false` on the old subscription, the new (trialing)
subscription canceled or the checkout expired, currency and customer back
(state `canceled`). A plan change while a switch is open answers `409
currency_switch_pending`. `GET /v1/billing` adds `currencySwitch: {from,
to, state, plan, interval, scheduledAt, firstChargeAt, requestedAt,
checkoutUrl?}` (the checkout URL for owners and admins while
`pending_checkout`). Every step is audited as `billing.currency.switch`
(`step`: `requested`, `scheduled`, `completed`, `undone`, `abandoned`).
An invoiced (Enterprise) subscription is switched by an operator: the
admin plan route answers `409 billing_currency_locked` with
`details.action: "cancel_and_resubscribe"` (cancel the subscription, set
the currency, create it again; no automatic re-subscription).

**Enterprise at a custom price (Stripe-sent invoices).** `PUT
/v1/admin/tenants/{orgId}/plan {plan: "enterprise", priceMonthlyCents,
currency?}` (stripe mode; `currency` defaults to the org's billing
currency, `USD`, `BRL` or `EUR`, and the subscription locks it; `400 invalidPrice`
for another plan, another mode or a non-positive amount; `status` refused)
creates the org's Stripe customer when it has none (named after the org,
e-mailed at the first owner's address; `422 billing_no_email` without
one), reuses or creates a per-org monthly price on the Enterprise product
(lookup key `rdns_enterprise_<orgId>`, metadata `rdns_org`; a different
amount or currency makes a new price that takes the lookup key over) and
starts a subscription with `collection_method=send_invoice` and
`days_until_due=30` (plus the metered pass-through item): Stripe e-mails
each invoice, the customer pays by card or bank transfer on the hosted
invoice page, no payment method is needed up front. `billing.json` records
the subscription, `customPrice` and `collectionMethod: "send_invoice"`;
from there the webhooks drive the state as for any subscription
(`past_due` once an invoice is overdue, then the grace). The Enterprise
product comes from `RDNS_STRIPE_PRODUCT_ENTERPRISE`, else the active
product with metadata `rdns_plan=enterprise`.

**Coupons and promotion codes.** `scripts/stripe-configure.sh` creates
`FOUNDER100` (100% forever), `PILOT50` (50% for 3 months) and `PARTNER30`
(30% forever), each with a promotion code of the same name. Checkout
sessions do not accept promotion codes (`allow_promotion_codes=false`:
customers never redeem a coupon on their own), and an operator applies a coupon to a live subscription with `POST
/v1/admin/tenants/{orgId}/coupon`. The discount is recorded on
`billing.json` (`discount`, shown on the Billing page). Webhook payloads
carry a subscription's discounts as bare ids (`di_...`) and a discount
cannot be fetched by id, so the subscription is retrieved with
`expand[]=discounts` (plus `discounts.source.coupon` and
`discounts.promotion_code`; when those are refused or left as ids, the
coupon and the promotion code are read on their own). That read runs on
`checkout.session.completed` (subscription mode), on every
`customer.subscription.created|updated` that lists discounts (an empty
list removes it) and after the admin route applies a coupon. A failed
read fails the webhook, which Stripe retries. A 100% forever coupon keeps invoices flowing at USD 0
(a paper trail for partners and pilots); `comped` needs no invoice at all.

**Billing identity.** Checkout sessions collect the billing address
(`billing_address_collection=required`) and tax ids
(`tax_id_collection[enabled]=true`; with an existing customer,
`customer_update[name]` and `[address]` are `auto`), so Stripe invoices
carry the customer's legal name, country and tax id (VAT, EIN, CNPJ). The
completed session's `customer_details` (the business name, else the name;
the e-mail, the address country and the tax ids) is stored as
`billingIdentity`; `customer.updated` refreshes the name, e-mail and
country and `customer.tax_id.*` the tax ids. The Billing page shows it
with a link to the portal, whose configuration lets the customer edit the
name, e-mail, address and tax id.

**Managed pass-through.** Each managed attachment pays its provider's
zone-month plus its queries (from the adapter's `QueryMetrics`) per
million, at list price plus 20%, shown line by line on the Billing page.
The data plane refreshes the current period (a UTC calendar month) every
`RDNS_BILLING_JOB_INTERVAL` and reports a closed period once as a Stripe
Billing Meter event (`RDNS_STRIPE_METER_EVENT`, value in cents,
identifier `rdns-usage-<org>-<period>`), billed by the metered price
`RDNS_STRIPE_PRICE_MANAGED_USAGE` that checkout adds to plans with managed
accounts.

**Stripe setup.** Products and prices per plan and interval
(`RDNS_STRIPE_PRICE_<STARTER|PRO|BUSINESS>_<MONTHLY|YEARLY>`; the yearly
ones are needed only once `billingIntervals` lists `"yearly"`), a meter
plus metered price for the pass-through, the Customer Portal enabled,
and a webhook endpoint `https://<host>/webhooks/stripe` with the events
above, the coupons with their promotion codes, and
`RDNS_STRIPE_PRODUCT_ENTERPRISE` for invoiced Enterprise subscriptions. Checkout sets the org id as `client_reference_id` and as metadata
of the session and the subscription. Domain payments need nothing more in
the dashboard: their line is an ad-hoc `price_data` (no product or price
to create); only the webhook endpoint must include
`checkout.session.completed` (plus `checkout.session.async_payment_succeeded`
and `checkout.session.expired` if delayed payment methods are enabled).

## Audit export

`GET /v1/audit/export` (admin + `zones:read`; plans with `audit-export`,
Business and above) returns every audit entry of a period, oldest first:
`format=json` (default: `{orgId, from, to, truncated, entries}`) or
`format=csv` (columns `at, id, action, source, actorId, zoneId,
targetType, targetId, targetLabel, ip, details`, cells that a spreadsheet
would read as a formula prefixed with `'`). `from` and `to` (exclusive)
take RFC 3339 or `YYYY-MM-DD` (UTC); the default period is the last 90
days; `zoneId` narrows it to one zone. One export holds at most 50000
entries (`X-RDNS-Truncated: true` and `truncated` otherwise: export the
rest with a later `from`). Each export is audited as `audit.export`.

`GET /v1/audit` (viewer + `zones:read`), the list the dashboard shows,
returns the entries newest first, one page at a time, as a plain array:

| Parameter | Meaning |
|---|---|
| `zoneId` | only the entries of this zone |
| `limit` | page size, 1 to 500 (default 100); anything else is `400 invalidLimit` |
| `before` | the `id` of the last entry of the previous page: the page continues after it (`400 invalidCursor` when the organization has no such entry) |

A page shorter than `limit` is the last one. The page is chosen by the
control plane's read index (one indexed query on `(org_id, sort_key)` or
`(org_id, zone_id, sort_key)`, whatever the size of the history) and the
sealed entries are then read from the bucket concurrently; entries of the
last two days that another process (the data plane, another control
plane) wrote since the index last caught up are merged in from the bucket
listing of those two days. Measured: the index query for a page is under
1 ms with 5,000 entries of the org; reading 100 entries at a 10 ms object
GET went from 1.08 s (one by one) to 0.11 s. The export above is the full
list of a period.

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/admin/audit?orgId` | platform admin | the cross-tenant audit list, read from the derived SQLite index: the newest 200 rows, newest first (`orgId` filters one organization): `[{id, orgId, at, actorId, action, zoneId, targetType, targetId, targetLabel}]`. Unlike `GET /v1/audit` it has no `source` and no `details` (the index keeps only these columns); read them in the org's `GET /v1/audit` or its export |

## Org export (exit guarantee)

The whole organization, secrets included, can leave the platform at any
time (ADR 0004, K3). Never gated by plan, billing state (read-only, trial
ended, detached) or license state (degraded): the routes skip the
access-channel check and pass the license gate.

| Route | Access | Purpose |
|---|---|---|
| `POST /v1/orgs/{orgId}/export` | owner + `connections:write`; a dashboard session or a PAT with `org:export` (`403 exportScopeRequired` otherwise, OAuth always) | queue the bundle; body `{passphrase}` (12 characters at least); `202 {export}`; `409 exportInProgress` while one is queued |
| `GET /v1/orgs/{orgId}/exports/{jobId}` | as the export | `{export}`: `status` (`queued`, `ready`, `failed`), `size`, `sha256`, `zones`, `expiresAt`; a ready export gets a new one-time `downloadPath` / `downloadUrl` on every call (the previous link stops working); `410 exportExpired` after 24 hours |
| `POST /v1/orgs/{orgId}/exports/{jobId}/download` `{token}` (or `Authorization: Bearer <token>`) | the token | the tar (`application/x-tar`, `X-RDNS-SHA256`); no session needed, the token works once (`403 downloadTokenInvalid` after). The export's `downloadToken` goes here; its `downloadUrl` is a link for a person, the dashboard's `/exports/download#<orgId>.<jobId>.<token>` page, which posts it (the fragment is never sent to a server, so no access log holds the token) |
| `GET /v1/orgs/{orgId}/exports/{jobId}/download?token=` | the token | deprecated (the query reaches access logs), accepted until 2026-10-28 with a deprecation log line; `410 tokenInUrlRetired` from 2026-10-29 00:00 UTC (AUTH-L2) |

The data plane builds the bundle as an `org_export` job (the passphrase
lives only inside that sealed job, which is deleted once the bundle is
written), stores it at `orgs/<orgId>/exports/<jobId>.tar` and e-mails the
requester (category security). Every owner of the organization is
e-mailed (category security) on each request ("An export of <org> was
requested": who, through what, when) and on each download ("... was
downloaded", with the bundle's size and SHA-256). Audited as
`org.export`, `org.export.ready` and `org.export.download` (the download
has no session: it is attributed to the user the link was issued to).
No MCP tool (removed with AUTH-1, 2026-10-09: the bundle opens every
provider credential, so an AI connection never requests it); `rdnsctl`
and other API clients need a PAT minted with `org:export`.

**Bundle format `rdns.orgbundle.v1`** (a tar, in this order):

- `manifest.json`: `format`, `orgId`, `orgName`, `createdAt`,
  `platformVersion`, `kdf`, `dekVersions`, `zones`, `domains`,
  `managedConnections`, `files[]` (`path`, `size`, `sha256`), `stripped[]`
  (what was removed and why), `excluded[]` (kinds of objects left out) and
  `auditStream` (below).
- `keys.json`: every DEK version of the org, encrypted with AES-256-GCM
  under a key derived from the passphrase with Argon2id (random 16-byte
  salt; `time`, `memoryKiB`, `threads` recorded; default 3, 64 MiB, 4). The
  encrypted part also holds the SHA-256 of `manifest.json`, so the
  passphrase authenticates the manifest and the manifest every file.
- `orgs/<orgId>/**`: the org's objects named by their bucket keys. Sealed
  values stay sealed (the DEKs of `keys.json` open them). Left out: the
  lease, probe results, the job queue, exports and OAuth authorization
  codes. Stripped: the installation's wrapped key records of the manifest,
  and the sealed credentials of managed-mode connections (the platform's
  accounts; `rdns export-org --include-managed` keeps them, operator only).
- `audit-stream/<orgId>/**`: the org's hash-chained audit stream
  (`docs/audit.md`), every segment (`<day>/<seq>.jsonl`), seal
  (`.seal.json`) and repair (`.repair.json`) byte for byte as stored. The
  export first closes the open segment (close reason `export`), so the
  stream ends with a sealed segment; lines written after that close stay
  behind. Not encrypted (the stream holds no tenant secret) but covered by
  the manifest hashes. Left out: `head.json` (this installation's append
  pointer). Other organizations and the platform's own seal objects never
  appear.
- `audit-evidence/`: the offline evidence of that stream, the layout of
  `GET /v1/audit/stream/export` without a copy of the segments:
  `bundle.txt` (its `segments=` line points at `../audit-stream/<orgId>`),
  `verify.sh`, `README.txt`, `seals/` (signed messages and raw signatures),
  `platform/` (the platform seals of the finished days with this org's
  inclusion proofs) and `keys/<kid>.pem`. `tar -xf bundle.tar -C out && sh
  out/audit-evidence/verify.sh` checks the stream with no RedundantDNS
  software.

`manifest.auditStream` (absent when the exporting process had no audit
stream): `format` (`rdns.orgbundle.audit.v1`), `org`, `evidence`
(`audit-evidence/`), `segments`, `lines`, `seals`, `repairs`,
`platformSeals`, `lastSeq`, `lastLineHash`, `lastSealHash`, `keys[]`
(`kid`, `publicKey` PKIX PEM: the audit keys that signed the seals),
`ranges[]` (runs of segments by installation: `sourceOrg`,
`sourceInstallation`, `first`, `last`, `lines`, `lastLineHash`,
`lastSealHash`, `keys`, `platform[]` proofs; a stream imported earlier
keeps its ranges, then comes the exporting installation's), `files[]`
(`path`, `size`, `sha256` for every `audit-stream/` and `audit-evidence/`
entry) and `leftOut[]`. The files are listed here, not in `files`: a
reader checks both lists and refuses any tar entry neither lists, so a
reader older than this section refuses such a bundle instead of dropping
the stream silently (the format stays `rdns.orgbundle.v1`).

Not in the bundle: the members' user records (the import creates them with
their user ids and memberships; each member accepts the target's Terms and
Privacy Policy at the next sign-in). API tokens are in the org manifest, so
under the same org id they keep working on the target.

On import the stream is written under the target org's prefix as it is and
continued: see `docs/audit.md`, "Exported and imported streams". An import
whose stream objects already exist on the target with another content (or
whose org id already has a stream of its own there) is refused before
anything is written.

`rdns import-org` restores a bundle into any installation (see
`docs/deploy.md`). Every writable attachment of the imported zones arrives
in mode `verify` with its applied serial cleared (the report's
`verifyAttachments` counts them): the installation the bundle came from
may still write those provider zones, so switch each one to `apply` (`PUT
.../attachments/{attachmentId}/mode`) once it no longer does.

A bundle is customer-made, so the import resets everything billing or
registrar related: the organization starts on the installation's default
plan (`--keep-billing` keeps the bundle's), managed connections are
dropped (`--include-managed` keeps them), RedundantDNS nameservers
attachments are dropped (attach them again), contact handles another
organization uses are dropped, and every domain loses its registrar id
and its payment ids and waits with `adoptPending` (registrar operations
answer `409 domainAdoptPending`) until the registrar sync finds it by name
with an owner handle of one of the organization's contacts. A domain
another organization holds on the target installation is not imported
(listed in the report's `untrusted.skippedDomains`).

## Audit stream

Every audit entry and zone journal entry is also appended to the org's
hash-chained, sealed audit stream (`docs/audit.md`).

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/audit/stream/verify?from&to` | admin + `zones:read` | verification report: `{org, ok, segments, lines, sealed, signed, open, platformSeals, firstSeq, lastSeq, lastSeal, keys, problems, warnings}`; `from`/`to` are inclusive days (`YYYY-MM-DD`, UTC; default the last 30 days, at most 366) |
| `GET /v1/audit/stream/export?from&to` | admin + `zones:read`, plans with audit export | the evidence bundle (`application/x-tar`: segments, seals with signed messages and raw signatures, platform seals with the org's inclusion proofs, public keys, `verify.sh`, README); audited as `audit.stream.export` |
| `GET /v1/admin/audit/stream/verify?orgId&from&to` | platform admin | one org's report (`orgId=platform`: the platform stream); without `orgId`, `{ok, reports, platform}` for every org plus the platform seal chain |
| `GET /v1/admin/audit/stream/export?orgId&from&to` | platform admin | one org's bundle; audited as `admin.audit.stream.export` (platform and org) |
| `POST /v1/admin/audit/stream/seal` | platform admin | `{day?, orgId?}`: seal on demand (today: close and seal the open segments; a past day: also its platform seal); idempotent; audited |

`ok` is false when a line or seal was changed, removed, added or reordered
(problem codes in `docs/audit.md`). Without an audit stream on the instance
the routes answer `503 auditStreamUnavailable`. The MCP tool `audit_verify`
runs the org route.

## Compliance

The live answer to "are we compliant right now?" (`docs/compliance.md`):
a profile (`baseline`, `iso27001`, `soc2`, or an extra profile of the
operator) runs its controls against the current state and returns
`{format, profile, profileTitle, scope, orgId, status, checkedAt, summary,
controls}`; each control has `id`, `title`, `status` (`pass`, `warn`,
`fail`, `not_applicable`), `required`, `evidence` (`[{name, value, at}]`),
`mapping` (`{iso27001, soc2}`) and `remediation`. `status` is the worst
control; `warn` never makes a profile fail.

| Route | Access | Purpose |
|---|---|---|
| `GET /v1/compliance?profile&scope` | admin + `zones:read`; `scope=platform`: platform admin session with a step-up (`403 stepUpRequired`, like `/v1/admin`) | run a profile now (read only). Default scope `org`: the organization's controls; `platform`: the installation's |
| `POST /v1/compliance/run?scope` `{profile}` | same; `scope=platform` also needs `{ticket, reason}` in the body like every `/v1/admin` write (`400 invalidTicket` / `invalidReason`; AUTH-L6) | run it and record it: the audit log (`compliance.run`, or `admin.compliance.run` in the platform log), a `compliance` line in the audit stream (each control's status and the report's SHA-256) and the last report; allowed while the license is degraded |
| `GET /v1/compliance/last?scope` | same | `{report}`: the last report (daily check or last run), `null` before the first |

An unknown profile answers `400 unknownProfile` (`details.profiles` lists
the loaded ones); `scope` other than `org` or `platform` answers `400
invalidScope`. The MCP tool `compliance_report` runs the org route
(`record: true` uses the run route).

## Security summary

`GET /v1/security.json` (public, cached, CORS `*`) feeds the website's
`/security` page in the exact shape of its `src/data/security.json` and
holds no secret; unknown values are `null`:

- `source` (`"api"`), `generatedAt`;
- `encryption`: `algorithm` (`AES-256-GCM`), `scope`, `keyWrappers` (the
  wrappers configured on this deployment: `local`, `aws-kms`,
  `oci-vault`), `keyWrappersNote`, plus `keyScheme`, `credentials`,
  `sessions`, `dekVersion` (`format`: `orgv3`, the envelope new values
  are sealed in; `legacyValues`: values still in the unbound `orgv1`/
  `orgv2` format after the last full `rdns rewrap`, `null` when never
  counted; `strictBinding`: whether they are refused on open; `rotation`,
  `rotationDays`, `retiredKeyGraceDays`) and `findings`;
- `replication`: `replicas` (replica targets with a ledger), `healthy`
  (no pending keys and no overflow on any target; `null` without
  replicas), `lastReconcileAt` (the oldest target's), plus `pendingKeys`;
- `restoreDrill`: `lastRunAt`, `result` (`passed`/`failed`), plus
  `durationSeconds`, from `platform/drills/last.json` (written by
  `scripts/restore-drill.sh` through `rdns drill-record`);
- `probes`: `regions` (regions seen), `uptime30d` (fraction, 0 to 1, of
  the probe runs of the last 30 days where every nameserver answered, from
  the read index; `null` without runs), plus `activeRegions` (heartbeat in
  the last 15 minutes) and `lastProbeAt`;
- `license`: the self-hosted installation's license (`null` on the hosted
  service);
- `audit`: `stream` (`on`/`off`), `lastSeal`, `signed`, `kid` and
  `publicKey` (the audit signing key auditors pin), `devKey`; the
  write-once audit store of compliance mode: `mode` (`standard` or
  `compliance`), `immutable`, `locked`, `provider` (`aws-s3`,
  `s3-compatible`, `oci`, `fs`; empty without an audit store) and
  `retentionDays` (`null` unless write-once; `docs/audit.md`); and
  `findings` (`{level: warn, code, message}`: `audit_unsigned`,
  `audit_dev_key`, `audit_seal_failed`, `audit_store_unlocked`,
  `audit_store_unreadable`, `audit_archive_failed`). Which orgs failed
  verification is never public;
- `compliance`: the installation's last daily compliance check
  (`{profile, status, checkedAt}`, baseline profile; `null` until it ran
  once, `docs/compliance.md`);
- `backup`: the last offsite backup run (`rdns backup`,
  `deploy/backup/`): `lastRunAt`, `result` (`passed`/`failed`; both
  `null` before the first report), `maxAgeDays` (8) and `stale` (no run
  reported, the last one failed, or older than `maxAgeDays`). The
  destination is never public.

The probe-run history lives only in the read index (`probe_runs`, fed
when a region probe object is written, kept 31 days, preserved by
`rdns doctor --reindex`); in a split deployment the control plane's index
refresh picks up the region probe objects by ETag, so the history is
sampled at the refresh interval.

## Offsite backup reports

The backup host reports every run of `rdns backup run` (the weekly
offsite export of the bucket, `deploy/backup/README.md`), failed runs
too. Authentication: a PAT with the `ops:backup-report` scope whose owner
is a platform admin; a session or any other token answers `403
insufficientScope`, a token whose owner is no longer a platform admin
`403 forbidden`. Allowed while the license is degraded.

| Route | Access | Purpose |
|---|---|---|
| `POST /v1/ops/backups/report` `{startedAt, finishedAt, result, destination, objects, bytes, manifestSha256, excludedObjects, version, error?, target?, uploadedObjects?, uploadedBytes?, retentionDays?, lockMode?}` | PAT with `ops:backup-report` (platform admins) | record a run: `result` is `passed` or `failed`; a passed run needs `manifestSha256` (64 hex) and `objects > 0`; `finishedAt` at most an hour ahead; `destination` at most 512 characters, `error` 2000. `target` is `offsite` (default: the weekly export) or `locked` (the daily export to the object-locked bucket, `rdns backup run --locked`), whose passed runs also need `retentionDays > 0` (the destination's retention as the run read it). `200` with the stored record (`receivedAt`, `reportedBy`, `tokenId` added). Kept per target, in `platform/backups/history/<finishedAt>.json` or `platform/backups/locked/history/<finishedAt>.json` (the last 12 each) and as that target's `last.json` (`platform/backups/last.json`, `platform/backups/locked/last.json`) unless a later run was already reported; audited `platform.backup.reported` in the platform log. `400 invalidBackupReport` |

The last reports feed `GET /v1/security.json` (`backup`, `lockedBackup`),
the compliance control `backups` (`docs/compliance.md`) and the
`backup_stale` installation alerts ("Alerts"; attachment `backup` for the
offsite export, `backup-locked` for the locked one, which counts once it
reported a run or with the platform flag
`featureFlags.backupLockedRequired`).

## Invoices to issue (platform admin)

Every payment received gets a fiscal record with what the NFS-e issuer
needs (`docs/nfse.md`). Platform admins only (the `/v1/admin` gate; writes
carry `ticket` and `reason`):

- `GET /v1/admin/fiscal-invoices?status=&classification=&orgId=&from=&to=&q=`:
  the records, newest payment first, and `counts` by NFS-e state (days in
  Brasília time, inclusive). Audited as `admin.read.fiscalInvoices`.
- `GET /v1/admin/fiscal-invoices/{id}`: one record (404
  `fiscalInvoiceNotFound`).
- `POST /v1/admin/fiscal-invoices/{id}/mark {status, nfNumber, nfIssuedAt,
  notRequiredReason, notes}`: `issued` needs `nfNumber` and `nfIssuedAt`
  (`YYYY-MM-DD`, 400 `invalidNfNumber`, `invalidNfIssuedAt`),
  `not_required` needs `notRequiredReason` (400
  `invalidNotRequiredReason`), `pending` clears them. Audited as
  `fiscal.invoice.mark`.
- `GET /v1/admin/fiscal-invoices/export?from=&to=&separator=`: the CSV of
  the period (`from` and `to` required, 400 `invalidPeriod`).
- `POST /v1/admin/fiscal-invoices/backfill {since}`: records the paid
  invoices and paid one-off checkouts Stripe lists since the day (409
  `fiscalBackfillUnavailable` without the Stripe gateway). Answers
  `{listed, created, existed, skipped}`; audited as
  `fiscal.invoice.backfill`.

## Ad attribution

First-party, cookieless ad attribution (`docs/attribution.md`):

- `POST /collect/landing {path, query}` (public, outside `/v1`; served on
  the website's host through Caddy): the website's landing beacon. Stores
  one landing when the query has `gclid`, `gbraid`, `wbraid` or `utm_*`
  (the click id only as a hash), not from crawlers, at most 20 a minute per
  client IP; `rdns_nav=1` (a page reached through the site's links) is
  skipped. Always 204; 404 when `RDNS_ATTRIBUTION` is off.
- `POST /auth/verify` and `POST /v1/orgs` accept `attribution` (an object of
  the parameters above plus `rdns_lp`, the landing page, and `rdns_c=1`, the
  website banner's consent): a sign-in that creates the account records a
  `sign_up`, a new organization a `trial_start`.
- `GET /v1/admin/attribution?from=&to=` (platform admin, UTC days, default
  the last 30): `{from, to, days: [{day, landings, clicks, signUps,
  trials}], campaigns: [{source, medium, campaign, term, landings,
  signUps, trials}], conversions: [{id, kind, at, orgId, landingPath,
  params, consent, ads, ga4}], totals, dropped, ads, enabled,
  adsConfigured, ga4Configured, conversionAction, retentionDays}`; never a
  click id. Audited as `admin.read.attribution`.
- `GET /v1/admin/attribution/export?from=&to=`: the Google Ads offline
  conversion CSV of the consented sign-ups with a gclid. Audited as
  `admin.read.attributionExport`.
- `POST /v1/admin/attribution/upload` (`ticket`, `reason`): uploads every
  pending consented sign-up now: `{conversionAction, attempted, uploaded,
  failed, waiting}`; 409 `adsNotConfigured`, 502 `adsUploadFailed`.
  Audited as `attribution.upload`.

## Licenses (self-hosted installations)

The platform issues the licenses of self-hosted installations
(`docs/licensing.md`). Records live in `platform/licenses/<lid>.json`;
the signing key only in the environment (`RDNS_LICENSE_SIGNING_KEY`,
`RDNS_LICENSE_SIGNING_KID`, `RDNS_LICENSE_ACCOUNT_SALT`). Every operator
action is in the platform audit (target type `license`).

| Route | Access | |
|---|---|---|
| `GET /v1/admin/licenses?acct=` | platform admin | the licenses (without tokens): `[{lid, acct, acctHash, status, claims, attestationName, createdAt, createdBy, updatedAt, updatedBy, statusChangedAt}]`; `acct` filters one organization |
| `POST /v1/admin/licenses` `{claims}` | platform admin | issue (`201 {license, token, published?, publishError?, publish?}`): `claims.acct` is the customer organization id (`400 invalidOrgId` when malformed, `404 orgNotFound` when unknown); defaults: `lid` generated, `product` rdns-enterprise, `edition` enterprise, `mode` offline, `term` yearly, `nbf`/`iat` now, `exp` one term later; `acctHash` is always derived (`sha256(acct + salt)`), `kid` is the signing key's. An online license's attestation is published at once (`published: false` with `publishError` when the data plane could not, e.g. `license_zone_missing`: the hourly pass catches up). Audit `license.issue`. `503 license_issuer_unavailable` without a signing key; `400 invalidClaims` |
| `POST /v1/admin/licenses/{lid}/status` `{status}` | platform admin | `active`, `suspended` (the installation degrades after its grace period) or `revoked` (degrades at once); publishes the attestation now. Audit `license.status` (`{from, to}`); the same status again changes nothing. `400 invalidLicenseStatus`, `404 licenseNotFound` |
| `GET /v1/admin/licenses/{lid}/token` | platform admin | `{lid, token}`: the signed license to hand to the customer (audit `license.token.reveal`) |
| `GET /v1/me/licenses` | any member; tokens need `zones:read` | the licenses of the caller's organizations (a token: its own organization's), never the token: `[{lid, orgId, status, product, edition, mode, term, features, limits, graceDays, issuedAt, notBefore, expiresAt, statusChangedAt, attestation?}]`; `attestation` (online licenses) is what the platform publishes: `{state, standing?, issuedAt?, expiresAt?}` with `state` `ok` or why not (`attestation_zone_missing`, `attestation_not_found`, `attestation_expired`...). MCP tool `license_list` |
| `GET /v1/me/licenses/{lid}/token` | owners of the licensed organization, dashboard session only (`403 sessionRequired` for PATs, OAuth and MCP: the file authenticates the installation to the mail relay; AUTH-L5) | `{lid, token, filename}`: the license file (the dashboard's Billing page downloads it as `<lid>.license`). 10 per hour per user (`429 too_many_requests`); audit `license.token.download` in the organization. `404 licenseNotFound` for another organization's license (or a caller no longer in its members), `403 forbidden` for non-owners (the role is read from the organization, as on every org route), `403 ipNotAllowed` outside the organization's IP allowlist. No MCP tool |
| `PUT /v1/admin/tenants/{orgId}/plan` | platform admin | (billing, above) when the new plan has the `selfHosted` feature (Enterprise) and `RDNS_LICENSE_AUTO_ISSUE` is on, an online yearly license is issued if the organization has no active one: the response adds `license: {issued, license?, existing?, published?, error?}`; audit `license.issue` with `auto: true` |
| `GET /v1/admin/relay/{acct}?day=` | platform admin | the mail relay metadata of an account for one UTC day (default today): `{acct, day, deliveries: [{id, at, lid, recipientHash, category, outcome}], refused: {<code>: n}}`; never an address or a message |

The attestation publisher (data plane) writes one managed TXT set per
account (`managedBy: "license"`, read-only: `409 recordSetManaged`) into
the attestation zone, an ordinary zone of the operator's organization:
`<first 32 hex of acctHash>.<zone>`, TTL 300, one string per online
license (`v=rdns1; lid=...; st=...; iat=...; exp=...; kid=...;
sig=...`). It re-signs an attestation after 7 days (hourly pass in the
lease of the zone's organization) and at once on issue or status change
(internal API `POST /internal/licenses/publish`), then queues a reconcile
of every attachment. `409 license_zone_missing` until the operator
creates the zone.

`/v1/security.json` and `/v1/me` (`license`) of a licensed installation
add, for online licenses, `attestation` (`ok`, `stale`, `missing`,
`suspended`, `revoked`, `not_checked`), `attestationSource` (`dns`,
`https`, `cache`), `attestationIssuedAt`, `attestationExpiresAt`,
`attestationAgeSeconds` and `attestationCheckedAt`; in warning and grace
they also carry `changesStopAt`, when DNS changes pause unless the
condition clears (`graceUntil` for the license's own expiry, the
attestation's grace end for `suspended` and the attestation reasons). The
license section is never cached.


### Mail relay (self-hosted installations)

Installations with an online license and `RDNS_MAIL_TRANSPORT=platform`
send their e-mail through the platform. Both routes authenticate with the
license itself: `Authorization: Bearer v4.public...` (no user, no org
header). Details and what is stored: `docs/licensing.md`, "E-mail
transport".

| Route | Who | What |
|---|---|---|
| `GET /v1/relay/mail` | an installation | a check that sends nothing: `{status: "ok", restricted, reason?, categories, limitPerHour, remaining}` |
| `POST /v1/relay/mail` `{to, category, subject, heading, preheader?, blocks, reason?, unsubscribeUrl?, installation?}` | an installation | send one structured e-mail (blocks: `paragraph`, `code`, `note` `{text}`, `button` `{label, url}` (http/https), `keyValues` `{items: [{key, value}]}`; never HTML), rendered with the platform's layout, from `no-reply@redundantdns.com`, subject prefixed `[<installation>]`. `200 {status: "sent", ...}` as the check. Only to the members and the enabled, verified e-mail alert channels of the licensed organization (an e-mail channel whose address has not confirmed it is refused, `403 relay_recipient_not_allowed`); categories `license` and `security` only while the license is restricted (degraded, suspended, revoked, or its attestation not published and active), and then as fixed templates only: a login code (a `security` e-mail whose `code` block holds 6 to 8 digits) goes out in the platform's own login-code e-mail, anything else as a fixed notice that names the kind of e-mail and asks the recipient to sign in to the installation; the caller's text, buttons and links are never relayed for a restricted license. Audit `relay.mail` at platform level (counts, no addresses; actor `license:<lid>`, the installation) |

## Customer e-mails

Every e-mail the platform sends, all through the one mail package
(`internal/mail`: one branded layout, plain text and HTML; SMTP in
production, Postmark with a message stream per category,
`RDNS_SMTP_STREAM_<CATEGORY>`; the e2e outbox `GET /e2e/mail` under
`RDNS_E2E=1`; a sample of each kind at `GET /dev/mail/preview/<kind>` and
as golden files under `internal/mail/samples/testdata`). Stripe's own
customer e-mails are off in the dashboard: the receipts and subscription
e-mails below are the only ones a customer gets. "Owners and admins" are
the organization's members with those roles (the members who can buy).

| E-mail (sample kind) | Subject | Category | To | Sent when | Once per |
|---|---|---|---|---|---|
| Login code (`login-code`) | Your RedundantDNS access code: 123456 | security | the address signing in | `POST /auth/code` | request |
| Invitation (`org-invite`) | You're invited to <org> on RedundantDNS | security | the invitee | `POST /v1/invites` | invitation |
| Alert firing / resolved / test (`alert-firing`, `alert-resolved`, `alert-test`) | [RedundantDNS] FIRING: <rule> on <zone> ... | alerts (license for license and mail transport alerts) | the org's enabled e-mail alert channels | an alert event opens or resolves; the channel test | event |
| Support action, info alert (`alert-support-action`) | [RedundantDNS] INFO: ... | alerts | the org's e-mail alert channels | a platform admin acted with a ticket | action |
| Support action (`support-action`) | Support changed the zone <zone> | security | the org's owners and admins | a support action (zone attachment role, domain nameservers, move) | action |
| Domain registration failed alert (`domain-registration-failed`) | [RedundantDNS] FIRING: domain registration failed ... | alerts | the org's e-mail alert channels | a paid registration refused on the customer's side | event |
| Registrar action required | [RedundantDNS] FIRING: registrar action required ... | alerts | the platform admins | a platform-side registrar failure | condition and hour |
| Domain canceled / refunded (`domain-registration-canceled`, `domain-registration-refunded`) | The registration of <domain> was canceled (and refunded) | billing | the org's owners | `POST /v1/admin/domains/{name}/cancel` | cancellation |
| Domain moved (`domain-move`) | Domain <domain> moved into <org> | security | the owners of both organizations | a domain move (customer or support) | move |
| Hand-off offer, copy, outcome (`domain-handoff-offer`, `domain-handoff-offer-copy`, `domain-handoff-declined`) | Domain <domain> offered to you by <org> ... | security | the destination address (or the destination organization's owners and admins) and the source's owners plus the member who offered it | a hand-off is offered, accepted, declined, withdrawn or expires | offer and outcome |
| Trial (`trial-started`, `trial-ends-7d`, `trial-ends-3d`, `trial-ends-1d`, `trial-ended`) | Your 30-day RedundantDNS trial started ... | billing | the org's owners | the billing job (data plane) | milestone (`billing.json` `trialNotices`) |
| Org export ready | Your RedundantDNS export is ready | security | the member who asked | the export job finished | export |
| License renewal (`license-renewal-30d`, 7d, 1d) | Your RedundantDNS license expires in 30 days | billing | the licensed org's owners | the license reminder job | milestone |
| Domain registered (`domain-registered`) | <domain> is registered | billing | the org's owners and admins | the register job completed (data plane): expiry, nameservers, WHOIS privacy, auto-renewal, amount paid, the zone hint (a zone with the same name: Apply zone NS is one click) | registration (`domain-registered:<requestedAt>`) |
| Domain renewed (`domain-renewed`) | <domain> was renewed | billing | owners and admins | a paid renewal's job completed: new expiry, amount | renew job (`domain-renewed:<jobId>`) |
| Domain renewed automatically (`domain-auto-renewed`) | <domain> was renewed automatically | billing | owners and admins | the sync saw the expiry move forward (a day or more) with auto-renewal on and no renewal by the platform in the last 7 days | new expiry (`domain-auto-renewed:<date>`) |
| Transfer complete (`domain-transferred`) | The transfer of <domain> is complete | billing | owners and admins | the sync recorded the transfer's completion: expiry, auto-renewal, the zone hint | transfer (`domain-transferred:<requestedAt>`) |
| Operation failed (`domain-registration-escalated`) | We could not complete the registration of <domain> | billing | owners and admins | a platform-side failure past the retry window (48 h) escalated: registration, renewal or transfer; neutral (support is on it; nothing to pay again), never the registrar's answer | escalation (`domain-operation-failed:<op>:<since>`) |
| Domain expiring (`domain-expiring-30d`, `-7d`, `-1d`) | <domain> expires in 30 days / in 7 days / tomorrow | billing | owners and admins | the data plane's sweep, auto-renewal off (or cut off: its invoice unpaid), 30, 7 and 1 days before the expiry (a late sweep sends the latest reminder only and marks the earlier ones) | threshold and expiry (`domain-expiring:<date>:<n>d`) |
| Auto-renewal invoice (`domain-autorenew-invoiced`) | Renewal invoice for <domain> | billing | owners and admins | the data plane opened an auto-renewal invoice for an org without a saved card (`send_invoice`, due in 14 days): amount, expiry, due date, the hosted invoice | invoice (`domain-autorenew-invoiced:<invoiceId>`) |
| Auto-renewal payment failed (`domain-autorenew-failed`) | The renewal payment for <domain> failed | billing | owners and admins | `invoice.payment_failed` of an auto-renewal invoice (the saved card was declined; Stripe retries): amount, expiry, the hosted invoice to pay now | invoice (`domain-autorenew-failed:<invoiceId>`, on `billing.json`) |
| Auto-renewal stopped (`domain-autorenew-cutoff`) | <domain> will not renew automatically | billing | owners and admins | the cutoff: the invoice still unpaid `RDNS_DOMAIN_AUTORENEW_CUTOFF` (5 days) before the expiry was voided; renew by hand (the expiry reminders already due go with it) | term (`domain-autorenew-cutoff:<date>:<attempt>`) |
| Subscription started (`subscription-started`) | Your <plan> subscription started | billing | owners and admins | `checkout.session.completed` of a subscription: plan, interval, currency, list price, next invoice | subscription (`subscription-started:<subscriptionId>`) |
| Subscription changed (`subscription-changed`) | Your subscription changed to <plan> | billing | owners and admins | a plan change in the dashboard (at once), or a `customer.subscription.updated` with another plan or interval (portal): before and after, the proration note | change (`subscription-changed:<eventId>`) |
| Subscription canceled at period end (`subscription-cancel-scheduled`) | Your subscription ends on <date> | billing | owners and admins | `customer.subscription.updated` scheduling the end: when it ends, zones read-only after it, domains keep working | scheduled end (`subscription-cancel-scheduled:<subscriptionId>:<cancelAt>`) |
| Subscription resumed (`subscription-resumed`) | Your subscription continues | billing | owners and admins | `customer.subscription.updated` withdrawing a scheduled end | event |
| Subscription ended (`subscription-ended`) | Your subscription ended | billing | owners and admins | `customer.subscription.deleted` of the current subscription | subscription (`subscription-ended:<subscriptionId>`) |
| Payment receipt (`payment-receipt`, `payment-receipt-domain`) | Receipt for your payment of 9.00 USD | billing | owners and admins | every successful payment: `invoice.paid` / `invoice.payment_succeeded` with an amount (the invoice's hosted page when it is a Stripe URL), and a paid one-off checkout (domain registration, renewal, privacy: the payment intent's latest charge gives the card and the receipt URL); otherwise the Billing page | invoice (`payment-receipt:<invoiceId>`) or payment (`payment-receipt:<paymentIntentId>`) |

The customer lifecycle e-mails (the last fifteen rows) are claimed before
they go out: the key goes into `mailNotices` of the domain document
(domain e-mails) or of `billing.json` (subscription e-mails and receipts),
so a replayed webhook, the two invoice events Stripe sends for one
payment, a retried job or a second sync never sends one twice; a claim
no recipient could get is released for the next delivery. Each one sent
is audited as `mail.sent` with `details {kind, key, recipients}`
(`docs/audit.md`). Sending never fails the webhook or the job. The fake
gateway follows the same paths: its checkout sends the first invoice's
`invoice.paid`, and a one-off payment reads a test card.

## Sandbox

On the public sandbox (`RDNS_SANDBOX=1`, `docs/sandbox.md`) the API is the
same, with these differences:

- `GET /v1/me` adds `sandbox: true` and `sandboxInfo: {limits: {zones,
  recordSets, domains, requestsPerMinute}, purgeAfterDays, docsUrl}`;
  `GET /v1/security.json` adds `sandbox: true`; `GET /v1/plans` answers
  `status: "sandbox"`. None of these fields exist elsewhere.
- Personal access tokens start with `rdns_sbx_`; OAuth `client_id`s with
  `sbx_`. The MCP server is `redundantdns-sandbox`, titled "RedundantDNS
  (sandbox)".
- Every organization has the Business entitlements (no `402
  plan_limit_reached`, the trial never ends) under abuse caps: `403
  sandbox_limit_reached` with `details: {resource, limit, current}` past 20
  zones (`POST /v1/zones`, free zones included), 2,000 record sets across
  the organization's zones (`PUT /v1/zones/{zoneId}/records` creating a
  set) or 50 domains (`POST /v1/domains/register`, `POST
  /v1/domains/transfer`); `429 tooManyRequests` (`Retry-After`) past 200
  `/v1` requests per minute per API token, MCP tool calls included.
- `POST /v1/invites` returns `acceptUrl` (the sandbox e-mails only its
  members, so the inviter passes the link on).
- Only the `fake` provider (and `rdns-ns`, on in-memory nodes) is in
  `GET /v1/providers`; the registrar is the fake one with the Openprovider
  price table.

## Errors

Every error is `{ "error": "<code>", "message": "<English>", "details"?: … }`
with an HTTP status; the code is stable (the SPA maps it to
`errors.<code>`). OAuth endpoints use the RFC 6749 shape
`{ "error", "error_description" }`. The public sandbox's abuse caps
answer `403 sandbox_limit_reached` (`details: {resource, limit, current}`,
see Sandbox above). Billing errors: `402
plan_limit_reached` and `402 org_read_only` (above), `409
plan_not_available` (checkout of a plan not open yet), `503
billing_unavailable` (no gateway configured), `409
billing_currency_locked` (another currency while a subscription holds
it; `details: {currency, lockedAt?, reason: subscription|stripe_balance,
action?: cancel_and_resubscribe}`), `409 currency_switch_pending`, `409
no_currency_switch`, `409 currency_switch_unavailable`, `503 fx_unavailable` (a BRL or EUR
price without a usable exchange rate; `details.currency`), `400 invalidCurrency`, `400
currencyNotAvailable`, `400 invalidFx` (admin config); on a licensed installation
`402 license_limit_reached` (the license does not allow the action) and
`409 billing_not_applicable` (checkout, portal, plan override). Managed mode: `428
managed_terms_required` (`details: {version, url}`), `428
nameservers_terms_required` (rdns-ns, same details), `409
legalVersionMismatch`. Scopes: `403 insufficientScope`. Zones: `404
zoneNotFound`, `400 invalidZoneName`, `400 invalidLimit` and `400 invalidCursor` (paged lists: record sets, audit), `409 zoneExists`, `409 zoneNameTaken` (another organization manages the name, holds it here as a domain, or deleted its zone less than 30 days ago: `details.releasedUntil`), `422 zoneNamePublicSuffix`, `409 delegationOwnedElsewhere` (rdns-ns attach without proof of control: `details.delegatedName`, `challengeName`, `challengeValue`), `409 zoneNameUnderAnotherOrg` (the name is a strict subdomain of a verified zone another organization manages), `409 zoneNameAboveAnotherOrg` (another organization manages a verified zone that is a strict subdomain of the name; neither code names the other organization), `409 domainAdoptPending` (a domain imported by `rdns import-org` that the registrar sync has not confirmed yet),
`400 confirmNameMismatch` (detach with `deleteRemote`; "confirmName must be the zone name (<name>)", the same text as the MCP tools; the registrant change answers it for the domain name), `409 recordSetManaged`, `409
zoneMirrored`, `409 lastActiveAttachment`, `400 invalidRole`, `400
invalidSource`, `409 mirrorSourceRequiresSource`, `422 parentZoneNotFound`. Insights: `404 findingNotFound`, `400 insightReasonRequired`, `reasonTooLong`, `invalidOwnershipValue`, `invalidOwnershipState`, `invalidSeverity`, `invalidInsightCode`, `invalidInsightState`, `invalidTargetKind`, `invalidReachable`, `invalidTargetSource`, `invalidLimit`, `invalidCursor`, `ownershipImportEmpty`, `ownershipImportTooLarge`, `404 ownershipNotFound`, `422 ownershipLimit`, `503 insightsUnavailable`. Records: `400 recordTypeInvalid`,
`400 invalidTtl`, `400 recordSetEmpty`, `400 recordInvalid` (the syntax
of the owner name or of a value, checked whatever the providers: A IPv4,
AAAA IPv6, CNAME exactly one hostname, MX `preference host`, SRV `priority
weight port target`, CAA `flags tag value`, NS and PTR a hostname, labels
of `[a-z0-9_-]` (IDN in `xn--` form) with a wildcard only leftmost; the
message names the value, `details: {field, value, reason}`), `400
apexNsManaged`, `404
recordSetNotFound`, `409 recordSetExists` (rename onto an existing set),
`409 cnameConflict`, `422 recordSetUnsupported` (`details`: the
rejections per provider). Connections: `400 providerUnavailable` (a
provider the deployment does not offer), `422 providerComingSoon` (a new
connection to a provider listed as `coming_soon`: Azure DNS), `404 connectionNotFound`, `409
connectionInUse` (delete of a connection still attached to a zone), `422
providerRejected` (the provider refused the call: a connection create or
test with bad credentials, an attach, a detach with `deleteRemote`; the
message is the provider's, except for a managed connection, whose
platform-owned account's answer is replaced by a neutral text naming
`providerErrorManaged`, as is the `lastError` of its attachment and jobs;
the operator finds the provider's answer in the data plane's log). Attachments: `409 providerZoneExists` (a
zone_admin attach found a provider zone of that name: repeat with
`adoptExisting`, `details: {providerZoneId, recordSets}`), `409
managedZoneUnavailable` (a managed connection found a zone of that name
in the platform's account that is not this organization's; no details),
`409
adoptWouldDelete` (the adopted provider zone holds sets the canonical zone
lacks: repeat with `onAdopt` `import` or `overwrite`, `details`: the diff;
see "Adopting an existing provider zone"), `400 invalidOnAdopt`, `400
invalidOverwrite`, destructive safety ("Destructive safety (v0.1.18)"):
`400 invalidMode`, `400 modeNotApplicable`, `400 invalidDecision`, `409
noPendingDecision`, `400 invalidAction`, `400 invalidSets`, `422
unmanagedNotFound`, `400 invalidSnapshotId`, `404 snapshotNotFound`, `403
readOnlyAttachment`, `503 snapshotFailed` (nothing was deleted), `409
restoreNeedsConfirm` (a failed restore's error), `409 reconcileRunning`,
`409 restoreRunning`, `422 idempotencyKeyReused`, `400
invalidIdempotencyKey`, `404 restoreNotFound`, `409 noProtectedSets`, `409
restoreTargetRequired`,
`409 snapshotZoneMismatch`, `409 adoptWouldOverwrite` (the adopted
provider zone holds sets with other values: repeat with `overwrite: true`,
`details`: the diff), `400 invalidDestructiveLimits`, `400 providerZoneIdRequired`
(a zone_editor attach without `providerZoneId`), `422 providerZoneNotFound`
(a zone_editor attach whose `providerZoneId` the connection cannot see,
`details: {providerZoneId}`), `422 providerZoneMismatch` (that provider zone
has another name, `details: {providerZoneId, providerZoneName, zoneName}`),
`409 providerZoneDeleting` (the provider is still deleting a zone of that
name or id, e.g. right after a detach with `deleteRemote` on OCI: retry in
a few minutes, `details: {zoneName}`), `409 providerZoneAlreadyAttached`
(the provider zone the attach found or was given already serves the zone
through another attachment, e.g. a second connection of the same account:
it would add no redundancy, `details: {providerZoneId, attachmentId}`),
`422 mirrorSourceOnly` / `409 mirrorSourceOnly` (a read-only
`mirror_source` connection attached as a standby, to a zone that already
mirrors another attachment, or demoted), `409 alreadyAttached`, `404
attachmentNotFound`, `403
deleteRemoteNotAllowed` (detach with `deleteRemote` through a zone_editor
connection). Any route: `400 invalidBody` (a JSON body that does not
parse, has unknown fields or trailing data), `415 unsupportedMediaType`
(a cookie or unauthenticated body that is not `application/json`), `403
csrf` (a cross-site request with the session cookie, or a cross-site
sign-in/sign-out), `410 tokenInUrlRetired` (a one-time token in a URL
path or query after 2026-10-28; AUTH-L2). Members: `409 alreadyMember`, `404
inviteNotFound`, `410 inviteExpired`, `403 inviteEmailMismatch`, `403
ownerOnly`, `403 ownerProtected`, `403 cannotChangeOwnRole`, `400
cannotRemoveSelf`, `409 lastOwner`, `404 memberNotFound`, `400
invalidTransfer`, `400 invalidRole`. Domains: `428 domain_terms_required`, `409
domainNameTaken`, `409 domainExists`, `409 domainTransferInProgress`,
`409 domainHeldByPlatform`,
`409 contactInUse`, `409 domainNotRemovable`, `409 domainNotCancelable`,
`409 domainHeldByRegistrar`, `409 domainBusy`, `422 registrantProfileRequired`,
`422 registrarRejected`, `422 zoneNsPlanEmpty`, `400 invalidDomainName`,
`400 invalidNameservers`, `400 invalidContact`, `404 domainNotFound`,
`404 contactNotFound`, `503 registrarUnavailable`. Registration: `409
domainUnavailable`, `409 domainRegistrationPending`, `409
domainNotRetryable`, `409 domainRenewalInProgress`, `409 domainAutoRenewCutoff`, `409 domainPrivacyInProgress`, `422 privacyUnavailable`, `422 privacyPaidAfterTransfer`, `400 enabledRequired`, `422 domainPremium`,
`422 invalidDomainName` (check), `400 invalidYears`, `400
skipPaymentRequired` (admin renew), `410 checkoutExpired` (fake checkout
page), `503 billing_unavailable`. Licenses: `503 license_issuer_unavailable`,
`400 invalidClaims`, `400 invalidLicenseStatus`, `404 licenseNotFound`,
`409 licenseExists`, `503 license_degraded` (a degraded installation),
`429 too_many_requests` (license downloads). Invitations and hand-off
offers: `429 tooManyRequests` (sending limit). API, domain checks: `429
tooManyRequests`; verify, delegation check, insights run: `409 cooldown`
("Rate limits"). Sign-in: `400 invalidCode`,
`400 codeExpired`, `429 tooManyRequests` and `429 loginLocked` (both with
`Retry-After`). Mail relay: `401
relay_unauthorized`, `403 relay_offline_license`, `403
relay_license_restricted`, `403 relay_recipient_not_allowed`, `400
relay_invalid_message`, `429 relay_rate_limited`, `502 relay_send_failed`,
`503 relay_unavailable`.

## Examples

```sh
# list zones with a PAT
curl -s https://<host>/v1/zones -H "Authorization: Bearer rdns_..."

# create a record set
curl -s -X PUT https://<host>/v1/zones/<zoneId>/records \
  -H "Authorization: Bearer rdns_..." -H 'Content-Type: application/json' \
  -d '{"name":"www","type":"A","ttl":300,"values":["192.0.2.10"]}'
```
