# Control API Status: v1 built, 2026-11-03 (branch wt/ctlapi): the `dp-ctlapi` server and the `nanovm` CLI, over the authorized root group (spec/ControlAuth.tla), specified first in spec/ControlApi.tla. Design note: spec/NOTES-ctlapi.md. Sections marked **(v1, built)** are implemented as written here; the rest is still a draft. The plain site is `dp/web`: sign up with an invite, create an app, upload a compiled image and deploy it. ## Four doors, one implementation SSH, HTTP (including the web panel), CLI and MCP share the same control routes. Doors only parse and print. The MCP door runs as `nanovm mcp` over stdio: newline-delimited JSON-RPC 2.0, protocol 2025-06-18. Client configuration: ```json {"command": "nanovm", "args": ["mcp"]} ``` Use the CLI's credentials and connection options (`--creds`, `--url`, `--timeout` before `mcp`, or NANOVM_CREDS and NANOVM_URL). Log in first. Initialize, notifications/initialized, ping, tools/list and tools/call are supported; unknown methods return -32601. The static tool catalog exposes deploy (optional app name), apps, deployments, rollback, promote, logs (recent only, optional version and limit), secret_set, secret_delete, delete, whoami, retry, usage, keys, keys_create, keys_revoke, rename (Pro's chosen name), and an app's data: db_list, db_get, db_delete and db_export ("An app's data, from outside"). Each call spawns the same binary with `--json` and the corresponding CLI command; whoami is tenant (GET /v1/tenant), promote uses the CLI's generation-aware rollback-to-version command. No API route is reimplemented. The child stdout is text content; every nonzero exit sets isError, preserving the CLI JSON, including a deploy whose first request answered 5xx (exit 3). Deploy source, secret values and db keys are piped on stdin, never argv or environment. Requests are bounded at 1 MiB, 4096 JSON tokens and depth 32; malformed and oversized lines return an error and the next line remains usable. See spec/NOTES-mcp.md for the parser and transport contract and srv/test_ctlapi_e2e.py under dp for the pipe and process-argv checks. ## v1: what is built, and the decisions it rests on - **Stateless servers.** Every mutation is exactly one command on the root group, built from the request alone. Every read is a linearizable read of the group's applied state. No server caches principals, apps or versions. - **API keys only** (no console login in v1). A key is an id and a 32-byte secret that the CLI generates; the server receives only its hash (the record's `key_hash`), so a retried creation cannot hand back a different secret. Requests are signed with HMAC-SHA256 over the key id, method, path and query, a timestamp (+-5 min), the body hash, the Idempotency-Key and If-Match (srv/ctlapi.h). The server verifies, then submits a command naming that key's principal. Commands are refused at apply once the key is revoked. Reads are checked by the server's own fresh read of the key's record, every request. - **The tenant always comes from the key**, never from the path or the body. A request naming another tenant (`?tenant=`) gets 404. - **Concurrency.** Promotes take `If-Match: `, secret writes `If-Match: `; a mismatch is 409, a missing If-Match 428. A write for a name that has no app yet has no generation a client can read, so it may send no If-Match: the server reads the pending set's generation and changes that. If an app of that name is created while the write is in flight, the server looks again after the write and moves the set into the app's own set (a CAS loser is 409: run it again). - **Idempotency.** `Idempotency-Key` is an unsigned integer that increases per key (the root group's per-principal slot). An equal key on the same request returns the first result, an equal key on another request is 409 `idempotency_key_reused` (not applied), a lower one is 409 (stale), a timeout is 504 (outcome unknown: retry with the SAME key). `GET /v1/tenant` returns `latest_idempotency_key`, so any client of a key can take a fresh one. The CLI keeps a durable counter. It refuses new mutations, and `login`, while an earlier outcome is unknown (`nanovm retry`): a newer key would make the old one unanswerable, and another key would run it as another principal. - **Reads are one state.** A GET of an app or of its deployments is one state of the group, though assembled from several reads (spec/ControlApiRead.tla). A list of apps is one such state per app. - **Resources:** tenant (read), keys (create, list, revoke), apps (create, list, get), deployments (upload, list, promote; rollback is a promote of an older version), secrets (write and delete only) and usage (read from the meters). - **Sign-up is by invite** (spec/ControlSignup.tla). `dp-ctlapi invite --invite-key KEY T` prints `T-HMAC`; `POST /v1/signup` checks it and adds the browser's key as tenant T's first owner, key id T*64+1. That is the admin's claim, so at apply only the first one wins. The admin's slot is every sign-up's, so a retry is refused like any later claim; the server then reads the first key, and the same hash is 201, another is 409 `invite_used`. - **Sign-up with no invite** (spec/ControlSignupOpen.tla, `--open-tenants N`, off until abuse limits land). `POST /v1/signup` with only a key hash takes a tenant of 1..N. The API cannot tell a retry from a new visitor, so nothing is stored to tell them apart: each key walks the tenants in one order, from a start in its hash, to the first that is free or its own. A claim is never removed, so the walk cannot pass the key's tenant and a retry finds it. So tenants are never reused: deletion must keep the first key's record. When all N are taken the answer is 503 `no_room`. New accounts are limited per server (`--open-rate`, 60 a minute): past it, 429 `slow_down`. The limit comes before the claim, so a key with an account is never held by it. Anyone holding an invite can redeem it: it is a bearer token until used. - **The dashboard** (`--web DIR`) serves `GET /dash` without authentication. The browser generates new keys and signs control API requests using WebCrypto on HTTPS or localhost. Signing in takes the key ID and secret. A user who selects “Remember me on this device” also saves the key in that browser. A person who signed up over SSH has no secret to type: `dash` at the door prints a link, `SITE/dash#t=TOKEN`, that signs one browser in, once, within 5 minutes, for 8 hours, with that key's role, taking no key id (DASHLOGIN.md, spec/DashLogin.tla). The legacy local page at `/` and the module at `/nv.js` are still served by the control API. - **Out of scope in v1:** open sign-up, tenant creation without an invite (an operator action on the host: `bundle-launcher ... principal add 0 ID T owner HASH`), members and console login, custom domains and TLS certificates, quotas, app deletion, instances, plain env config, owner recovery, signed commands, sharding the root group. Where the spec changed these decisions (spec/NOTES-ctlapi.md has each): - the client, not the server, generates a key's secret; - uploads and key creations name their version and id; - reads need the server's own per-request check of revocation; - apps and secret sets became tenant records checked at apply (one new key shape in dp/core/root.h); - secret values live sealed in S3, with their digest in the root group. ### App URLs (built) `GET /v1/apps/{app}`, each entry of `GET /v1/apps`, and a deploy's answer have `"url"`, the app's own origin, its name of two words, and `"numeric_url"`, the same app by number; both route: https://squeezing-beagle.D/rest?query https://APP-TENANT.D/rest?query \______________/ | \________/ the app's name --base-domain the app by number - `D` is the server's `--base-domain` (dp-ctlapi and dp-front both, required; `SITE_BASE_DOMAIN` in `site.sh`, default `localhost`). The scheme, and the port if it names one, are those of `--public-url`. Without `--public-url` `url` is null. A URL exists from the app's creation; it answers 404 until a version is promoted. Live: `https://1-3.nma.sh/`. - The name (2026-11-11, srv/hostname.c, spec/AppHostNames.tla) is not stored: it is a fixed bijection of the slot, an adjective and a noun (1,079 x 1,857 words, 2,003,703 names) picked by an invertible mix of the slot index `(TENANT-1) x 16 + APP-1`, cycle-walked into the word space. So it is unique and never reused because the slot is (a CAS from generation 0 on `NVROOT1:n:T:F`, kept on delete), costs no root key, and dp-front inverts it with no lookup, as for a number. Tenants past 125,231 have only `numeric_url` (their `url` is it). The word lists and the mix never change once live: `srv/test_hostname.c` pins names, and `onbox/hostnames.py` is a second implementation. - `TENANT` is the tenant's id and `APP` the app's slot (the `app` field, 1..16). Slots are numbers, and names are not in the URL, so that dp-front needs no lookup: serving reads nothing from the root group, and a control-plane outage stops changes, not serving. A slot is never reused, and a deleted app keeps its name on its slot ("Apps nobody uses"), so a URL keeps meaning one app. Numbers are canonical: `01-1.D` is 404. **Chosen names** (Pro, 2026-11-15; `rename APP NAME`, spec/AppHostNames.tla). A Pro account may also give an app a name it chooses, NAME.sites.diy, beside the two-word and numeric URLs (which keep answering). The chosen names have a domain of their own, `--names-domain` (`SITE_NAMES_DOMAIN` in `site.sh`, sites.diy on live; staging may point it elsewhere), and it must differ from `--base-domain`: the base domain is the free, open-signup one, so a NAME.nma.sh host never routes a chosen name. A name is five or more characters of `a-z`, `0-9` and inner hyphens, at most 30, starting with a letter and at least one letter; it is filtered by the server's built-in reserved words and `--name-deny FILE`, and may not be a generated two-word name or `N-F`. An entry in that file is refused as one whole hyphen-separated part, and as a prefix or a suffix of the name with hyphens removed (`paypal-login`, `pay-pal`, `mypaypal`), never merely in the middle; `meta`, `apple`, `bank` and `visa` are ordinary words too, so those entries match a whole part only. A refusal names the entry that matched. It is a root key of its own, `NVROOT1:e:NAME`, taken once by a CAS from empty and never rewritten or cleared: it is unique over every tenant and is never reused, even after a rename to another name or the app's deletion. The app's current choice is its record `NVROOT1:t:T:F`; its `chosen_name` and `chosen_url` fields (null without one) are in `GET /v1/apps/{app}` and the app list. dp-front reads a `--names-file` of NAME.sites.diy T F lines, one immutable line per claim, and matches it only under `--names-domain`: a claim that has just committed may lag by a second (404, never another tenant's app). A free account is refused `pro_only` with Pro's sentence. A name whose write is answered `route: "pending"` is claimed; run the same rename again to finish publishing it. - The Host is the address and the whole path is the app's. D itself, and any Host in neither form, is 404. - Every request goes to the version the pool has adopted, and the `X-NV-Version` response header says which one answered. A promote or rollback reaches the URL once the pool has polled the pointer and built the snapshot (0.5 s on chi, for an image the size of a small app; 1-1.5 s on nma.sh); the old version serves until then. A deploy, a promote and a rollback answer only once `GET /` through the front has named the new version four times in a row, or after 10 s with `"first": null`. The front takes the pools in turn, so that is likely both pools, not certainly (other requests interleave); the app sees those `GET /`s with User-Agent `nanovm-deploy`. - A deploy whose first request answered 5xx gives the app back to the version it replaced, with the same compare-and-set a promote makes, from the generation the deploy wrote, so a later deploy is never undone. The answer is still 200, with `"status": "rolled_back"` and `"serving"`: the version now live. An app's first version, or one whose previous version is gone, stays live (`"status": "live"`). The CLI exits 3 either way. It answers once the front serves the old version again, as a promote does (on nma.sh, 2026-11-11, the front served the failing version for about a second after an early answer). Mutants 44 (a failing version stays live) and 45 (the answer comes first) are caught by FailedStaysOff. - `"first"` is `{"status", "ms"}`; on a 5xx whose body the runtime wrote (a handler's throw, which begins `handler threw: `), it also has `"error"`: that body's first line after the prefix, at most 200 bytes once escaped, never cut inside a character. Read from the same answer, so it adds no request (0-1 ms either way on OVH, 2026-11-17). An app's own 5xx page is the app's and gives no `"error"`. The CLI and the web door print it as `first request error: ...` under the status. Mutants 99 (no error), 100 (not escaped) and 101 (the CLI does not print it) are caught by FirstError in srv/test_logs_e2e.py. - When the runtime's own sign-in answered 401 (auth.require, whose body begins `{"error":"auth: `, as it does for a request with no session), `"first"` also has `"note"`: "the app asks for sign-in (auth.require): / answers 401 to a request with no session; a browser is sent to /login". An app's own 401 (any other body) gives no `"note"`. The CLI and the web door print it as `first request note: ...` under the status. Mutant 104 (the note on any 401) is caught by FirstAuthNote in srv/test_logs_e2e.py. - Each app has its own origin. Clients should use `url`, not build it. The stack behind it is `dp/onbox/site.sh` (start, stop, status, invite). Its dp-ctlapi has `--compiler`, so an app can be deployed as source (the site's form, `nanovm deploy APP app.js`), or as an image from `uni/compile-js.sh OUT.elf APP.js` (`nanovm deploy APP VERSION image`, then `nanovm promote`). **The path a request takes:** client, one of two `dp-front`s (srv/front_main.c: public HTTP to one line on the pool's `tenant-T.sock`), one of two `dp-warmpoold`s, Firecracker guest. The other router, `dp-srv router`, is on a different path: it takes a guest's `db` calls to the shard groups. `site.sh` runs those groups and their gateways too: see "An app's data". **The API's protocol did not change**: its commands are untouched (`url` is computed from the tenant and slot in the request), and an API-uploaded image was already segments and a manifest (`bundle_upload`, as `deploy.sh`). dp-front speaks dp-warmpoold's request line with version 0, the path Deploy.tla's pools already serve, plus the START line below (spec/FrontRetry.tla). **A promote reaches the two pools separately.** Each adopts it on its own next poll, so until both have, about a second, either version can answer. `X-NV-Version` says which. ### An app's data (built) `kv`, `db` and `crdt` work in a deployed app with no setup: `nanovm deploy APP app.js` and the handler calls them (uni/uni_js.c). `site.sh` runs the tiers `crud.sh` tests: two shard groups of three replicas, their ctl group and two routers (`db`), an origin and four edges (`kv`), three CRDT replicas (`crdt`), and one gateway (`dp-srv dpl`) per pool, under `DIR/data` with their own key and table. A data value is at most 64 KiB, and a request body through dp-front is at most 64 KiB. **Whose data it is.** A VM's vsock port 5001 is a link the pool makes when it starts the VM, to `DIR/data/gR/tT.sock` for the VM's tenant (`--tenant-port`). The guest names a port and nothing else. The gateway takes the tenant from the listener it was reached on, and every key and name gets that tenant's prefix. So data is per tenant, and a tenant's apps share it. One tenant cannot read or write another's, whatever it asks for (`DataIsolated`, with a mutant for the link and one for the prefix). **What survives.** What a call acknowledged is in the tier, not the VM or the gateway: killing every VM of an app, deploying a new version, `kill -9` of any one process, or stopping the whole stack loses no acknowledged write (`DataRecycled`, `DataKill`, `DataRestart`; spec/SiteData.tla). App variables are the VM's, and go with it. **Reading your own writes.** A client that keeps its cookies does, across requests, whichever pool and edge answers (`DataRyw`). A client that keeps none gets a value that may be behind, as `kv` with `eventual` does; `db.get(key, {consistency: 'strong'})` needs no cookie. **What one read costs.** On chi, on two cores shared with the whole stack and the Python client, with other work on the box; one client, a new connection per request, six rounds of 2,000 over two runs. The ranges are that wide: the high end of each data row is one round, 4.5 ms against 1.6 ms for the same work a minute later, and the cause was not found. | Handler | p50 | p99 | |---|---|---| | no data call | 0.41-0.57 ms | 3.8-4.7 ms | | one `kv.get`, session | 1.6-4.6 ms | 8.0-11.5 ms | | one `kv.get`, eventual | 1.6-4.6 ms | 7.4-11.1 ms | | one `db.get`, session | 1.6-4.7 ms | 7.5-10.4 ms | | one `db.get`, strong | 1.8-4.5 ms | 7.2-11.5 ms | `make onbox-site-bench` measures it again. Compare only on one host under one load. **What is left.** The gateway is one per pool: while a pool's gateway is restarting, about 0.1 s, that pool's guests' calls throw, and an app that does not catch that answers an error, which dp-front does not retry, since the guest answered. Nothing acknowledged is lost. One or two reads saw that per gateway kill, and now and then one per origin kill; the other tiers' kills cost a reader nothing in these runs, which is a sample of one client, not a bound. The gateways' `--meter` files are not read by `dp-ctlapi --meter` yet, and the tiers' checker journals under `DIR/data` grow with use: neither is ready for a long-lived site. ### Apps nobody uses (built, off unless `SITE_DELETE` is set) An app with no real request and no deploy for the window is deleted (spec/AppDelete.tla). The default the owner has yet to confirm is 30 days. All of it is below the doors: `dp-ctlapi sweep`, and `state` in an app's JSON, which is `live`, `warned`, `deleting` or `deleted`. `SITE_DELETE=WINDOW:NOTICE:GRACE:TICK_MS` turns it on, the first three in ticks: for 30 days, a week's notice, a day's grace and an hour's tick, `720:168:24:3600000`. Unset, nothing is recorded and nothing goes. - **A real request** is one a front sent on a link and the pool gave to the app: not a line straight to a pool (a probe), and not one the pool or the front refused. A request that reached the app and then failed counts: the mistake to avoid is deleting something in use. - **Recording one** costs the request a hash and a store into a mapped file. A process's death loses none of them; losing the machine loses the uses since the last report, a minute by default. A timer reports them through the catalog agent, at most one root write per app per tick. - **Time** is a count of ticks in the root group (`NVROOT1:u:clock`), raised by exactly one by a sweeper that has seen one tick pass on its own clock with nobody else raising it. So a clock that jumps costs one tick, downtime or a lost root group ages nothing, and two sweepers run at the rate of one. - **In order:** a warning at the window (a line in `SITE_DIR/warnings`, the seam for email: nothing is sent), a tombstone after the notice, which stops serving within a poll and can still be undone by a report that was on its way or by a deploy, then after Grace the app's versions are condemned and their manifests removed. - **What goes is only manifests.** A manifest names its tenant, app and version, so it is theirs alone. Segments are shared by every app, so they stay until a collector with its own proof exists. So do root keys (the root has no delete), sealed secrets and the tenant's data. Local caches on the pools keep their copies until reused. - **Coming back:** the same name deployed again gets the same slot and URL and a new version, even from identical source. A version that went can never be promoted (409 `version_gone`) or rolled back to. A different name never takes a retired slot, so a tenant's 16 slots are not freed. - Anything that moves the pointer first sets the record by compare-and-set, so a promote and a condemnation cannot both win. - A record that does not decode is never a reason to delete: the sweeper logs it and leaves the app. - **Its owner deletes it** (`DELETE /v1/apps/{app}` with If-Match: the app's generation; the door's and the CLI's `delete APP`, the CLI's `app delete APP`, MCP `delete`): an owner key only (403 otherwise), and only where the sweeper runs (`--app-delete GRACE_S`, which site.sh sets from `SITE_DELETE`; 405 elsewhere). The same tombstone, set at once by compare-and-set on the record, with the record's owner byte set (spec/AppDelete.tla OwnerDelete, OwnerDeleteHolds): no use reported later undoes it, nor does a pointer that moves after it (a promote begun before it), and a promote or a rollback is refused (409 `app_deleted`). Only a deploy brings it back, on the same URL; after Grace its versions are condemned as an idle app's, and a deploy is a new incarnation. "state" is "deleted" from the first moment (the sweeper's own tombstone is "deleting"). It answers once `GET /` has answered 404 four times in a row (`"first"`, or null after 10 s), with `"grace_s"`. Twice is once. The name keeps its number for good; deleting it frees the room it held at once (a deploy that brings it back needs room like a new app), and the tenant's data stays. Mutants: ctlapi 44 (OwnerStays, onbox), 47 (DeletedStays), 48 (OwnerDeletes); appdel 6 and 7 (OwnerStays). ### Verified email (built; nma.sh sets `SITE_VERIFY`, `SITE_VERIFIED_APPS` and `SITE_MAIL_KEY`; staging the first two with `SITE_VERIFY_SPOOL`) An account is anonymous until a human proves an email (spec/EmailVerify.tla, core/verify.h). `SITE_VERIFY=N` turns it on; `--anon-apps N` is an unverified account's apps at once and `--verified-apps M` (`SITE_VERIFIED_APPS`, default 5) is a verified one's. Idle deletion passes over a verified account. Both are live caps: they count the apps it may bring back without asking. An owner's delete stops counting at once, so a delete frees room; the sweeper's own tombstone still counts while a late use can restore it without asking, and a gone app does not. A deploy that brings a deleted app back needs room like a new app. The slot numbers (`SITE_CAPS`'s APPS, at most 16) are every account's life: a number is never reused, and `apps_full` says so when all 16 are used. An account that already holds more than its cap keeps every app and can deploy new versions of them; it takes no new number. The tiers' live caps are 2 unverified, 5 verified and 10 with Pro on nma.sh; a test copy enforces its own first two (staging: the same 2 and 5, with no Pro to buy). - **Asking:** `POST /v1/verify {"email"}`, an owner key only (`nanovm verify EMAIL`, the door's `verify EMAIL`, MCP's `verify`). 202 with `message`, the words for the agent's human. The address is trimmed, lowercased, and only letters, digits and `. _ % + -` pass. Refusals: 409 `email_taken` (it verified another account), 409 `already_verified`, 429 `rate_limited` (5 links an account and 3 an address a day), 404 where verify is off. `GET /v1/tenant` adds `email` (`none`, `pending`, `verified`) and `apps_cap`. The sign-up answer adds `apps_cap`, `email` and `next`, and an unverified account's `apps_full` ends with the same sentence: what a verified email gives (the apps, kept for good, chosen names soon) and the exact command, so an agent asks its human unprompted. - **The link:** `PUBLIC_URL/v/TOKEN`, 32 random bytes. The root keeps the first 16 bytes of its SHA-256 as the link's key (`NVROOT1:k:H`: account, email, expiry, used), never the token. A day long; only the latest link an account asked for works. - **The claim page:** when an account is not verified, or (where payments are on) not Pro, the deploy answer, `GET /v1/tenant` and the sign-up answer add `claim_url`: `PUBLIC_URL/c/TOKEN`. The token is stateless: the tenant, the week's window `floor(now / 7 days)`, and an HMAC-SHA256 tag over both with a secret derived from the server's root key file (never argv, env or the boot line). Every answer in a window therefore gives the same URL and none writes a key; a token works through the next window. `GET /c/TOKEN` is a small page with the account's apps (names and URLs only), an email box and, with payments on, an Upgrade button; it changes nothing and sends no mail. `POST /c/TOKEN` with `email=...` does exactly what `POST /v1/verify` does for that account (same windows, email cap, pending cap and mail), and with `action=upgrade` does what `POST /v1/upgrade` does and answers 303 to the checkout. Once the account has a verified email the page says verified and no form changes it. The page grants nothing else: no key, data, delete or deploy. A wrong or expired token is the 404 page of any unknown path. - **GET shows, POST confirms.** Mail scanners follow links, so a GET is a page with a Confirm button and changes nothing. The POST marks the link used, claims the email (`NVROOT1:m:E`, set once from nothing), marks the account verified (`NVROOT1:v:T`), then bumps every app's idle record, each by compare-and-set. A sweeper that read the account before the change then fails its own compare-and-set, so once the page says "Verified" no app of the account is warned or condemned. A crash between steps leaves a used link: the agent asks for a new one. - **Sending:** the API never holds the provider's key. It writes the mail, whole and renamed into place, to `SITE_DIR/outbox`, and `dp-mail` (srv/mail_main.c, started when `SITE_MAIL_KEY` names a file only its user can read) POSTs it to Resend with the file's name as the Idempotency-Key. 4xx: to `outbox/failed`. Otherwise tried again until the link expires. From `SITE_MAIL_FROM`, `nma.sh ` by default (sites.diy has Resend's DKIM record). With `SITE_VERIFY_SPOOL=1` and no `SITE_MAIL_KEY` dp-mail never starts: the mail stays in the outbox for a test to read (staging's rounds read it as the human's inbox, dp/tools/rounds/human.sh), and nothing is ever sent. ### Pro (built; nma.sh sets `SITE_PAY_KEY`, `SITE_PAY_PRICE` and `SITE_PRO_APPS`) Pro is $5 a month (`--pro-price`), flat, paid through Stripe Checkout (spec/ProPlan.tla, core/plan.h, NOTES-pro.md). What it gives: apps at once from the account's own cap (2 unverified, 5 verified) to `SITE_PRO_APPS` (10), within the same 16 slot numbers; apps kept however long they sit idle; with `SITE_STORE` set, `SITE_PRO_STORE` db keys a data group and kv keys (default 10 times free's; NOTES-pro.md on sizing). Any owner key may ask; no email is needed. - **Asking:** `POST /v1/upgrade`, an owner key (`nanovm upgrade`, the door's `upgrade`, MCP's `upgrade`). The plan is written `pending` by compare-and-set and dp-pay makes a Checkout Session (a subscription to `SITE_PAY_PRICE`; the account in `client_reference_id` and in both metadata). 200 with `checkout_url` and `message`, the words for the human. Asked again within the day, the same session comes back (Idempotency-Key `nma-T-ASKED`). Already pro: 200 `already`, and the message names `nanovm billing`. Stripe's refusal: 502 `checkout_failed` with its message. Pending gives nothing. - **Billing:** `POST /v1/billing`, an owner key (`nanovm billing`, the door's `billing`, MCP's `billing`): 200 `portal_url` (a Stripe customer portal session: the card, invoices, cancelling), `billing_email`, `message`. No completed checkout yet: 404 `no_billing`. Stripe's refusal (as before the portal is configured): 502 `portal_failed`. - **Reading:** `GET /v1/plan` (`nanovm plan`, MCP's `plan`): `plan` (`free`, `pending`, `pro`, `lapsed`), `apps_cap`, `apps_used` (the apps it has at once, not the numbers it has used), `pro` and `free` (what each gives: `apps`, `db_keys_a_group`, `db_bytes_a_group` (0: no byte cap), `kv_keys`, Pro's `price` and `kept_idle`), `grace_days`, `pro_caps_left_s`, `next` (the one sentence to say, with its command), and `usage` (`db_keys`, every app's in every data group, of `db_keys_a_group` in each of `db_groups`; `kv_keys` of `kv_keys_cap`: the caps it has now; `null` if the gateway did not answer; absent with no app). `GET /v1/tenant` adds `plan`, `apps_used`, and `pro` (the sentence) when not pro, and its `apps_cap` counts it. `apps_full` and a guest's db or kv `quota:` error end with Pro's sentence when Pro would give more. - **Verify without mail:** with no outbox (no `SITE_MAIL_KEY`, no `SITE_VERIFY_SPOOL`), `POST /v1/verify` answers 404 `not_available`, "nothing was sent", and no pitch names it. - **The webhook:** `POST /v1/stripe` (nginx: `nma.sh/stripe/`), no key. The API passes Stripe-Signature and the body's bytes to dp-pay, which checks a v1 HMAC-SHA256 of `TIME.BODY` under the signing secret, compared in constant time, `TIME` within 5 minutes. Not checked: 400. Checked and acted on: `checkout.session.completed` (paid), `invoice.paid`, `invoice.payment_failed`, `customer.subscription.deleted`; anything else, or no account in it: 200 `{"applied":false}`. - **At most once, any order.** The plan (`NVROOT1:b:T`) keeps the created time of the last event that moved it; an event no newer changes nothing, so Stripe sending one again is a no-op, with no list of event ids. An ending sets `NVROOT1:x:S` (S: the subscription id's SHA-256, first 16 bytes) before it writes the plan, and always writes it (a fence); a paid reads the plan, then that key, then compare-and-sets. So a paid that comes after its ending, or beside it, never makes the account pro. - **Lapsing:** a failed payment or an ending makes a pro account `lapsed`. It keeps Pro's caps for `SITE_PRO_GRACE` (7 days), then has free's. No cap takes an app away: an account over its cap keeps every app and deploys new versions; it takes no new one. `invoice.paid` makes it pro again. - **Keys:** only dp-pay (srv/pay_main.c) holds them: `SITE_PAY_KEY` and `SITE_PAY_HOOK` name files only its user can read (0600, not a link), read once at start, never in argv, env or a log. A live key (`sk_live_`, `rk_live_`) is refused unless `SITE_PAY_LIVE=1` (dp-pay `--live`), which in turn refuses a test key. - **What follows a paid,** on a no-op too (an api that died after the plan's write): the billing record (`NVROOT1:y:T:I`, the customer and the email the human gave Checkout: a billing email, never a verified one), the fence of the account's idle records (so a sweeper that read it free fails its tombstone), and Pro's data share (`$D/pro`). Any failure: 503. ### Custom domains (built, off unless `SITE_DOMAINS=1`; not on nma.sh) A Pro account's app answers on a hostname of its own (spec/DomainClaim.tla, NOTES-domains.md). An owner or deployer key, every door: `nanovm domain add APP HOST`, `domain ls`, `domain rm HOST`; MCP's domain_add, domains, domain_remove. - **Adding:** `POST /v1/domains` `{"app","host"}`. 200 `host`, `app`, `state`, `why`, `record` (`type` CNAME to the app's `N-TENANT` name, or A to `--domains-ip` for a bare domain; `name`, `value`) and `message`, the words for the human. Adding a host the account holds again checks it now. A free account: 403 `pro_only`, Pro's sentence, nothing written. Another account holds it: 409 `domain_taken`. The account has named `--pro-domains` hosts in its life: 413 `domains_full`. Not a host name (letters, digits, dots and dashes, a dot in it, no reserved TLD): 400 `invalid`. No such app: 404. - **States:** `pending_dns` (its record not set, or some address not ours), `pending_cert`, `live`, `failed` with `why` (an account no longer on Pro: "not on Pro"). Only `live` is served. - **Listing:** `GET /v1/domains`: `domains` (`host`, `app`, `state`, `why`, `target`), `limit`, `message`. - **Removing:** `DELETE /v1/domains/HOST`: 200 `removed`. dp-domains drops the route and the certificate before the claim is freed, so once the answer comes, the host is not served for this account. The slot stays the account's: adding the host again is free. Not held by this account: 404. - **Unavailable:** the root group or dp-domains not answering: 503, nothing changed that a retry does not finish. ### When a process dies Target: no client sees a failed request when any one process of the stack dies. Each line below is asserted exactly, per kill, by `make onbox-site` (site_test.py's `KILLS`), with clients running through the kill and requests held in guests at that moment. Times are ranges over 3 rounds on chi, on two cores shared with other jobs. | Killed (`kill -9`) | What clients see | Process back | Path ready | |---|---|---|---| | `dp-front` | nothing | 0.05-0.27 s | at once: its peer took over its connections | | `dp-warmpoold` | a POST in one of its guests: 502, outcome unknown. Nothing else | 0.19-0.32 s | 3.3-4.2 s (fetches each app again; a request sent there meanwhile waits, 2 s at most seen) | | Firecracker (one guest) | a POST in that guest: 502, outcome unknown. Nothing else | 0.12-0.24 s | 0.9-1.2 s | | `bundle-launcher` (a pool's agent) | nothing | 0.55-0.65 s | at once | | `dp-srv replica` (root group) | nothing | 0.11-0.57 s | at once | | Garage (S3) | nothing | 0.30-0.61 s | at once | | `dp-ctlapi` | a raw API client it was serving: its connection resets. `nanovm` retries it and sees nothing | 0.11-0.53 s | at once: the other one serves | | the `site.sh` supervisor | nothing, but nothing is restarted until `site.sh stop` and `start` | never | serving goes on | What makes this true is in the kernel, not in any process's memory: - **Two pools, and a rule for trying again.** Each pool has its own VMs and requests alternate. A request runs again only if it is GET or HEAD, or if it provably never started. The pool writes `START` on the request's connection before anything can reach a guest, so end-of-file with no `START`, or `REJECT` naming no VM, is that proof. The pool says no VM only if no byte of the request left it: everything before its one `send()` (the VM's kept connection found dead by a peek, connect, the `CONNECT` handshake, a refusal), or that `send()` returning an error, which on a Unix stream socket means no byte went. Any byte gone is no proof. In particular a kept connection that gives end-of-file and no answer after a send is *not* stale: the guest may have died after the peek, and a send can succeed into a dead peer, or into a guest that runs it and then dies. Those look the same, so that POST is a 502 (`FrontRetryEofIsUnsent`). Three attempts at most; a pool refusing the connection is not an attempt. - **A link to a pool is kept, and judged a request at a time.** A front's connection to a pool stays for the next request. It carries one at a time, and the peer is told which before a byte goes. The evidence is the same bytes, peeked: `START`, then a frame that says its length, taken off the link only after the client has the answer (`FrontRetryNoDrain`). A pool may close an idle link as a request arrives: no `START`, so nothing ran, and that request's retry dials afresh, so it happens to one request once at most (`FrontRetryStaleRetry`). - **Requests wait in the front, not the pool.** A front has at most 32 requests at a pool at once (`FRONT_POOL_WINDOW`), so two fronts cannot fill a pool's queue, and no client is refused for being one too many. The rest wait, unsent, one line per tenant taken in turn; a pool's work grows with its queue and a front's does not with its line. Past 4096 connections per front they wait in the listening socket's backlog. - **A listening socket no process owns.** The supervisor runs under `dp-listen`, which holds the sockets, and both `dp-front`s accept from one queue. So a killed front loses nothing queued, and a connection made during a restart waits where it would have been refused. `SO_REUSEPORT` was rejected: each process gets its own queue, which dies with it. - **Each front holds the other's connections.** A front passes its peer a dup of every client socket when accepted (`SCM_RIGHTS` over `front-0.link`), and of every pool socket before writing the request to it. It only peeks, so the request stays in the client's socket and the answer in the pool's. When the link ends, the survivor finds everything the dead front had: no pool socket means nothing was sent, so it starts the request; with one, it half-closes it, so a pool holding part of a request drops it (no `START`: nothing ran) and one holding all of it answers. It asks the kernel whether the client was already written to; one write of an answer with twice its length free in the send buffer is all or nothing, and a kill does not interrupt it. - **A kept connection is judged a request at a time.** HTTP/1.1 stays open unless either end says `Connection: close`; HTTP/1.0 only if it asks; five seconds quiet and it closes (clients are told four, in `Keep-Alive`, so they go first). Pipelined requests are answered in order, each when the one before is done. An answer the client could not find the end of, and any answer the front makes itself (404, 408, 502 ...), closes. Each request gets the rule above from the same evidence as the first, because where it starts is the kernel's too: a kept answer is taken off the socket first and written second, and a closing answer is never taken off. So the two counters the kernel has (bytes written, bytes taken off), against what the peer was last told, say where the dead front was: neither moved, the request is still at the head, as for any first request; taken off, not written, a whole answer is in the pool's socket, so the survivor writes it; both, a kept answer is out, so it goes on; written alone, a closing answer is out, so it finishes. (`FrontRetryWriteFirst`, `FrontRetryRxBlind`, `FrontRetryEverWritten` are what goes wrong otherwise.) **A front that dies between requests costs its clients nothing: they see no change, and the survivor answers their next request.** A client sees its connection close only by asking, or by being quiet for the timeout; then a request already on its way gets end-of-file and no answer, and it did not run (`ClosedNeverRan`), the ordinary keep-alive race. A peer that stops reading the link costs no client an error, but once the link's buffer is full (about 90 requests) new requests wait for their hand-off. Five seconds with nothing read and it is killed (`FRONT FENCE`), which is the case above, and it is restarted: a stopped process could wake holding what it holds, so it cannot just be forgotten. **What is left, and why:** - *A POST in a guest that dies.* It is a 502 saying the outcome is unknown. The guest may have done its work and died before answering, and from outside that is the same as dying before starting: run it again and it may happen twice (`FrontRetryRetryUnknown`), or do not and this client sees this error. `OnlyUnavoidable` in spec/FrontRetry.tla allows an error in this case and no other. Unavoidable without the app's help: an app that takes its own idempotency key could be retried, and dp-front cannot know that. A pool's kill reaches this case because its VMs die with it (parent-death signal, so that no VM outlives its scheduler). So there, *not* unavoidable in principle: VMs that outlive their pool and answer through a successor would remove it, at the cost of that guarantee. - *The accept window.* Killed between `accept()` and passing the socket on, a front takes that one connection with it: the client sees a reset, and nothing was read or run (`AcceptWindow`). 6 us on chi per connection (mean, `accept` to `sendmsg` done): at 100 connections a second, one kill in 1700 lands there and costs one connection. Not unavoidable in principle: two fronts sharing one descriptor table (`clone(CLONE_FILES)`) would have no window, but cannot be started by `exec`, so the survivor would have to fork its own replacement. Not done. - *A raw API client whose `dp-ctlapi` dies mid-request.* One connection, since one instance serves one at a time. Every mutation has an `Idempotency-Key` for exactly this, and `nanovm` retries reads and mutations. Not unavoidable in principle: the fronts' hand-off would work for small requests, but `dp-ctlapi` reads uploads as it goes, blocking. - *The supervisor.* Clients see nothing, but no process comes back until someone runs `site.sh stop` and `start`, which is an outage. Children cannot be adopted: bash cannot wait for them, or get the listening sockets back. Run it under something that restarts it and tells you. A hung process is not a dead one, and no test covers it: by the code, a stopped pool's GETs move on after 12 s and its POSTs get 504; a stopped front's connections wait until it resumes, while new ones go to its peer. **Each app has its own origin.** Every app is at its own hostname, so the browser keeps one app's cookies and storage from every other's: dp-front forwards `Cookie` and `Authorization` as sent and passes an app's `Set-Cookie`, dropping one that names a `Domain`, which could reach a sibling app through the parent domain (HostCookieDomain). The runtime's read tokens `nv_tok` and `nv_dbt` are cookies like these, kept out of `req.headers` by the guest; a token names a time and no data, so a forged one affects only the freshness of the forger's own reads (`DataScoped`, spec/SiteData.tla). dp-ctlapi is on its own port, a different origin. **Limits today**, each refused rather than truncated: | Limit | Value | From | Beyond it | |---|---|---|---| | request body | 64 KiB | `FRONT_BODY_MAX` | 413 | | request headers | 8 KiB as sent; every header reaches the app but hop-by-hop ones and a visitor's X-Forwarded-*, Forwarded, X-Real-IP and X-NV-* (spec/NOTES-reqheaders.md) | `FRONT_HDR_MAX`, `FRONT_FWD_MAX` | 431 | | path and query | 255 bytes | dp-warmpoold `conns[].path` | 414 | | response, with its headers | 1 MiB; over 16,128 bytes it travels as a memfd and closes the connection | `FRONT_RESP_MAX` | 502 that says the response was too large; the instance is replaced | | resident functions per pool | 8 cached, and a host runs two pools | `DP_WP_KEYS` | 503 | | VMs per pool | 16 (`SITE_POOL_CAP`), one for each function and the rest shared by demand | `DP_WP_VMS` | a request waits | | VMs one function may scale to, per pool | 8. A busy function gives up what it holds over its share as each lease ends, so it cannot keep another from its first VM (`spec/WarmPoolScale.tla`) | `DP_WP_KEY_VMS` | a request waits | | tenants per pool | all tenants with deployed apps; optional `SITE_TENANTS` / `--tenant` operator pin | root catalog, loaded on demand | cache capacity temporarily gives 503; absent apps give 404 | | connections | 4096 per dp-front; each has at most 32 requests at a pool at once, and the rest wait there | `FRONT_CONNS`, `FRONT_POOL_WINDOW` | wait in the backlog | No TLS and no rate limit: dp-front is plain HTTP, and a flood of requests for undeployed apps can make a real first request wait or get 503 (the bounded catalog tracks at most 16 keys). No startup tenant list is required: the front sends a canonical tenant number on the private shared apps socket. Only a linearizable root read establishes absence, and NONE answers only requests waiting before that read was sent. Later waiters get another read; failed reads give 503 or failover, never 404. Tenant IDs are never reused. Status codes: 404 no such app or nothing deployed, never a pool that is down, 502 the instance failed or its response was malformed (the outcome is unknown), 503 not available yet or no room (`Retry-After`), 504 no answer in time (the outcome is unknown), including a handler stopped at its 2 s budget (`DP_WP_LEASE_MS`), which names that limit. ### An app's data, from outside (built) An owner reads and deletes the account's db from outside any app, through every door: the door's and CLI's `db list APP [PREFIX] [--after K] [--limit N]`, `db get APP KEY`, `db delete APP KEY` and `db export APP`; MCP's `db_list`, `db_get`, `db_delete` and `db_export`; and the routes below. APP is any app of the account that still resolves, a deleted one too: the data is the tenant's, not the app's, and stays after a delete. A deployer or reader key is 403 `forbidden`. **The same path an app takes.** For each request `dp-ctlapi` forks a reader. The reader writes `WHO_DIR/PID` (`TENANT APP`, mode 0600), then connects to a gateway's `--guests` listener named by `--data SOCKET:WHO_DIR` (two, one per gateway, tried in turn). The gateway names it as it names a pool's guest (spec/GuestIdentity.tla, srv/guestid.c): the kernel's peer pid, that file, a live peer. Every key it reads or deletes gets that tenant's prefix, so no request can name another tenant's keys; a `?tenant=` of another is 404 as on every route. Each gateway has its own listener for this, `gR/api.sock` with `gR/apiwho`, so the API's files never share a directory with the pools'. Reads are `strong`, a delete is `db.delete`'s unconditional one, a list `db.list`'s (spec/KeyList.tla, spec/KeyDelete.tla): no new protocol path, so no new spec. The reader removes its files before it exits; one killed (15 s, 300 s for an export) has them removed by the parent. A new pid for each request means a reader never carries another request's tenant. **What it costs.** Nothing is counted against the account's room. Calls are rate-limited per account on each server, `--db-rate N` a minute (120; an export costs 10), with 2 at once per account and 8 per server: 429 `slow_down` with `retry_after_s` and Retry-After, or 429 `too_many_readers`. The reader answers the client itself, so a large export does not hold the API's one request at a time. **Answers.** `list`: `{"app","keys":[...],"next":KEY|null}`. `get`: `{"app","v":N,"value":"..."}` or 404 `not_found`. `delete`: `{"app","deleted":true|false}`, sent once (a 504 `outcome_unknown` means read the key). `export`: NDJSON, 200 keys a page, a strong read for each, lines `{"key","v","value"}` then `{"end":true,"keys":N}`; a failure partway writes an error line, and `{"after": KEY}` resumes (the CLI does it itself). Keys and values are UTF-8 in JSON strings, invalid bytes as U+FFFD; a key is at most 512 bytes with no NUL or tab. A data tier that does not answer is 503 `data_unavailable` or `busy`. The e2e (`make srv-test-ctlapi-e2e`) runs it against a stand-in gateway that names peers the same way, with mutants 50 DbOwnTenant, 51 DbOwnerOnly, 52 DbRate, 53 DbExportWhole, 54 DbWhoCleared and 55 DbDeletedReadable; `make onbox-site` runs it against the real gateways. ### Backups (Pro, built) Pro keeps a daily copy of every app's db and kv and can put one back (NOTES-backups.md, spec/Backups.tla). Off unless the site sets `SITE_BACKUPS=1`: one `dp-ctlapi backup` process takes the copies, and the API servers get `--backups` for these routes. A server without it answers 404 `not_found` ("this server has no backups"). | Method and path | Who | Command | Answer | |---|---|---|---| | `GET /v1/apps/{app}/backups` | an owner key | `backups APP`, MCP `backups {app}` | `{"app","backups":[{"date","db_keys","kv_keys","bytes"}]}`, newest first | | `POST /v1/apps/{app}/backups/{date}/restore` | an owner key | `restore APP DATE`, MCP `restore {app,date}` | `{"app","date","db_written","kv_written","keys"}`, after every record | `date` is `YYYY-MM-DD`, a UTC day. Only the last seven are visible; an older date, or one with no manifest, is 404 `not_found` ("backups APP lists the last 7 days"). A free account is 403 `pro_only` with Pro's sentence and `nanovm upgrade`; a deployer or reader is 403 `forbidden`. **What a backup is.** For each of the app's db keys, a strong read gives the key's value and the version it had then; kv keys are read eventual (kv has no strong read). It is one committed version per key, not a cross-key snapshot: a key written after it was read is in the next day's. It is stored in the site's S3 origin as `backups/TENANT/SLOT/YYYY-MM-DD` (a small manifest, at most 512 parts) over the existing content-addressed chunks (at most 256 KiB each); seven days are kept per app, and deleting the app deletes its manifests. Chunks are content-addressed and shared, so they stay for a collector, as deploy segments do. **What a restore does.** It reads every record and writes it back: db with `db.cas` at the version it reads just before (retrying if a writer moved the key), so every key gets exactly one new version; kv with `kv.put`, also a new version. It is not atomic across keys: a reader sees each key either before or after its write, never a torn value, and across keys any mix. Keys added after the backup are not deleted, and a restore interrupted partway leaves that mix; run it again to finish. The answer counts what it wrote; a tier failure is 503 `data_unavailable` with how far it got. The e2e (`make srv-test-ctlapi-e2e`) takes a backup, changes keys, restores, lists, shows the 8th day dropping the oldest, refuses a free account, and shows a deleted app's backups gone; mutants 80 BackupFree, 81 BackupTake, 82 BackupRestore, 83 BackupKeep7 and 84 BackupDeleted are each caught by name. ### v1 wire summary (built) | Method and path | Who | Body / headers | Command | |---|---|---|---| | `POST /v1/signup` | an invite, no key | `{"tenant": T, "invite": hex, "key_hash": hex, "ref"?: TAG}` | read `p:0`, admin add on `p:T*64+1`, optional CAS from 0 on `w:s:T` | | `POST /v1/signup` | no key, `--open-tenants` | `{"key_hash": hex, "ref"?: TAG}` | read `p:T*64+1` along the key's walk, then as above | | `GET /v1/tenant` | any | | read `p:ID` and `w:s:T` (`ref`: TAG or `null`) | | `GET /v1/keys` | any | | read `p:T*64+1..63` (no hashes returned) | | `POST /v1/keys` | owner | `{"id": N, "role": ..., "key_hash": hex}`, Idempotency-Key | add on `p:N`, tenant = the caller's | | `DELETE /v1/keys/{id}` | owner | Idempotency-Key | revoke on `p:id` | | `GET /v1/apps`, `GET /v1/apps/{app}` | any | | read `n:T:1..16`, `a:T:F`, `c:T:F:*`, `s:T:F` | | `POST /v1/apps` | owner, deployer | `{"name": ...}`, Idempotency-Key | CAS `n:T:F` from 0 | | `GET /v1/apps/{app}/deployments` | any | | read `c:T:F:1..` | | `POST /v1/apps/{app}/deploy` | owner, deployer | the JS source; no key, version or If-Match: sending it again is safe | compiles, creates the app if new, reuses the version holding these bytes or commits the next, moves the pointer (`spec/ControlDeployOp.tla`); 422 `compile_error` carries the diagnostic; needs `--compiler`. The answer's `build` is what the app printed while it loaded (50 lines at most) and `first` the status and time of a GET through the front once that version answers (`--first-request`; null when off or nothing answered in 10 s) | | `POST /v1/deploy` | owner, deployer | the JS source and an Idempotency-Key | as the deploy above, to a new app named from (tenant, key) alone, `quiet-river-7k2`: a retry with the key is the same app; a new key whose name is taken is 409 `name_taken`, and the CLI retries once with another (spec/NOTES-ctlapi.md) | | `POST /v1/apps/{app}/deployments/{V}` | owner, deployer | the image, Idempotency-Key; V the next version | S3 upload, CAS on the ring's slot for V (see below) | | `POST /v1/apps/{app}/deployments/{V}/promote` | owner, deployer | If-Match, Idempotency-Key | CAS `a:T:F` | | `POST /v1/apps/{app}/rollback` | owner, deployer | If-Match, Idempotency-Key | CAS `a:T:F`; 409 `app_deleted` after an owner's delete (also promote) | | `POST /v1/apps/{app}/rename` | owner, deployer | `{"name": ...}`, Idempotency-Key | Pro only: CAS `e:NAME` from 0 (never rewritten), then the record `t:T:F` and dp-front's `--names-file` line, NAME.sites.diy; 409 `name_taken` | | `DELETE /v1/apps/{app}` | owner | If-Match, Idempotency-Key | CAS on the record `u:T:F`: the owner's tombstone ("Apps nobody uses") | | `PUT /v1/apps/{app}/secrets/{NAME}` | owner, deployer | `{"value": ...}`, Idempotency-Key; If-Match when the app exists | sealed set to S3, CAS `s:T:F` naming the request; before the app's first deploy, CAS `q:T:F` | | `DELETE /v1/apps/{app}/secrets/{NAME}` | owner, deployer | Idempotency-Key; If-Match when the app exists | CAS `s:T:F`, or `q:T:F` before the first deploy, naming the request | | `GET /v1/apps/{app}/secrets[/{NAME}]` | | | none: 405, write-only | | `POST /v1/dash` | any key (not a dash session) | none; no Idempotency-Key: nothing is written | `{"url": "PUBLIC_URL/dash#t=TOKEN", "role", "expires_in_s": 300, "session_s": 28800}`: the token is the account, key, role and mint time under an HMAC of the root key; 404 with no `--public-url`; a session is 403 | | `POST /v1/dash/redeem` | no key: the token | `{"token": hex}` | read `p:ID`, then CAS `u:dash:T` (the newest mint redeemed, the sign-out epoch) from the generation read; `{"tenant","key","role","session","secret","expires"}`, or 400 `link_invalid`, 410 `link_expired` or `link_used`, 401 for a revoked key | | `POST /v1/dash/signout` | owner | none | CAS `u:dash:T`: the epoch + 1, ending every session of the account | | `GET /v1/usage` | any | | the server's `--meter` files | | `GET /v1/admin/usage` | any key of the `--admin-tenant` | `?days=N` (1..366, 30), `?after=T` | linearizable reads of `p:`, `v:`, `w:T`, `w:T:F`, `w:a:T` and the plan per tenant, and `w:d:S` per day ("Usage of the site"); another account's key gets 404 `not_found` | | `GET /v1/admin/emails` | any key of the `--admin-tenant` | `?after=T` | verified accounts (`NVROOT1:v:T`) with sealed S3 addresses (`emails/`) unsealed and hash-verified; another account's key gets 404 `not_found` | | `GET /v1/apps/{app}/logs` | any | `?follow=1`, `?after=E-S`, `?limit=N` (1..1000), `?version=V` | none: the socket goes to dp-logd, which answers NDJSON (below); needs `--logs` | | `POST /v1/apps/{app}/db/list` | owner | `{"prefix"?, "after"?, "limit"?}` (1..1000, 100) | a forked reader's DBLIST through the gateway ("An app's data, from outside"); needs `--data` | | `POST /v1/apps/{app}/db/get` | owner | `{"key"}` | the reader's strong GET | | `POST /v1/apps/{app}/db/delete` | owner | `{"key"}`, no Idempotency-Key | the reader's DBDEL, unconditional | | `POST /v1/apps/{app}/db/export` | owner | `{}` or `{"after": KEY}` | DBLIST pages and strong GETs, NDJSON | A HEAD request is answered as the GET of the same path would be, with the same status and headers and no body; on a /v1 route, where every read is signed for its method, it is 405. Keys are `NVROOT1:` root-group keys (dp/core/root.h). Roles are enforced at apply; readers can read and nothing else. The control API is how a tenant manages apps: deploy code, set configuration and secrets, see instances and usage. It is not on the request path: function traffic goes through the routers, gateways and warm pools, never through this API, so a control-plane outage stops changes, not serving. ### Versions kept, deploys per hour, and what a tenant can hold (built) An app keeps its last 10 versions, the current one always among them. A deploy past that frees the oldest that is not current, in the one command that commits the new version, so a retry frees nothing more. Promoting or rolling back to a freed version is 410 `version_gone`; a number that never existed is 404. A retry that starts while its first attempt is still in flight can commit twice under two numbers: two versions freed, the key count unchanged (spec/VersionLimit.tla, RetryFreesOne). A tenant has at most 60 deploys an hour (`--deploy-rate`, 0 for none), on the one route all four doors use, charged before the compile; past it, 429 `slow_down` with Retry-After. The count is one root key per tenant, so every server shares it and a restart keeps it. A retry is charged too. The bound, keys in the root group a tenant can hold: 63 principals + 16 apps x 14 (name, pointer, secrets record, usage record, 10 versions) + 1 for the rate + 1 for the dash record (`u:dash:T`, made by the account's first sign-in link) + up to `--max-apps` sets for names not deployed yet = **305**. Measured end to end (a real replica's store, counted): an app with 10 versions holds 12 keys, after 12 deploys still 12, with 3 secrets 13: all secrets are one sealed record. Open sign-up's tenant cap N must keep N x X + reserve <= capacity, X being the keys one tenant can hold under the site's caps, plus a reserve (the operator's keys and apps still in the old layout of up to 64 versions). With live's 16 slot numbers and 3 key ids, X = 3 + 16 x 14 + 1 + 1 + 16 = 245, so the root's 65,536 slots (49,152 keys) hold 200 tenants that fill every slot. SITE_OPEN=340 is a cap, not a reservation, as it was at 10 slots (154 keys a tenant); the root's room is watched in NOTES-status.md. The tiers' live caps change no key count: a number is never reused. An app's hostname (squeezing-beagle, "App URLs") adds nothing: it is computed from the slot, not stored. A chosen name is stored: one `NVROOT1:e:NAME` key per name ever taken (never reused, not even after a rename), and one `NVROOT1:t:T:F` record for the app that has one now. Neither is part of the caps below. The caps are built: `--max-apps N` (1..16) and `--max-keys N` (1..63) on every server of a site (site.sh `SITE_CAPS=APPS:KEYS`), off by default. `--max-apps` caps the slot numbers creation may use, for every tier, and not a count, so two servers creating at once cannot pass it; since a number is never reused it holds for good: a deleted app keeps its number, a revoked key its id. `--anon-apps N`, `--verified-apps N` and `--pro-apps N` cap the apps at once by tier. Past them, 413 `apps_full` (an app create, or a deploy that would create one; a deploy to an app the tenant has still works) or `keys_full`. They apply to every tenant, invited ones too; an app or key made before them stays. Growing the root is not free: `test-rootfill` on the laptop, three runs each, at 3,072 keys a write averages 17 to 22 us, worst 30 to 46 ms, recovery about 30 ms; at 12,288 keys 186 to 203 us, worst 515 to 696 ms, recovery about 340 ms. At 49,152 keys it did not finish filling in 200 s. Four times the keys, about 18 times the worst stall: compaction's insertion sort is the first suspect, not yet measured on its own. Fix that before growing the root. ### The SSH door (built) `ssh nma.sh deploy hello < app.js` is the deploy above. OpenSSH authenticates, and `srv/nanovm-ssh-keys`, its AuthorizedKeysCommand, lets every key in with a forced command carrying that key's hash, restricted to no port, agent or X11 forwarding and no user rc. A PTY is left to a person: with no command and a terminal the door prints a short welcome (the key's account or the `signup` command, one deploy example, `help` and llms.txt), and `ssh nma.sh -- cmd` has no terminal and reads the agent list, byte for byte as before. The welcome's own address and site come from the door's sshd config — `SetEnv NV_DOOR` and `SetEnv NV_WEB` — so one binary serves live and staging (`dp/onbox/live/sshd_door.conf` and `dp/onbox/staging/sshd_door_stg.conf`); with either unset it prints the nma.sh text. Both configs say `PermitTTY yes`. Set dp-ctlapi's `--door` to the command readers should copy from verify and Pro answers. Use `ssh nma.sh` for the public door, or specify the site's non-22 port with `ssh -p PORT HOST`. `nanovm door` holds one directory of credentials per key and sends the same request as the CLI and the site. `signup [INVITE] [--ref TAG]` gives a new key its account: nothing to save, and the door keeps the API key. TAG is 1-24 chars of `[a-z0-9-]`, stored once at sign-up and shown in `tenant --json` as `ref`. The client controls the command words and stdin; the words never reach a shell. `login ID < secret` attaches a key made elsewhere (the HTTP sign-up, `keys create`, another CLI) to this SSH key: the secret is stdin's first line, one line of hex, and the door checks it with one signed `GET /v1/tenant` before writing anything. It then stores the key as `signup` does: the same private directory, the same lock, the same atomic write, the hash of the secret and never the secret. A wrong id or secret stores nothing and answers the API's error; a key that already has an account is refused with `door_has_account` (naming `keys` and `tenant`), because a door's credentials are never replaced. The secret is never printed. `dash` prints one line, a link to the web dashboard (`POST /v1/dash`; DASHLOGIN.md). The browser that opens it is signed in to this key's account with this key's role, once, within 5 minutes of the link, for 8 hours, and no key id is taken. A second open answers 410 `link_used`, naming `dash` again and `dash signout`, which (owner key) signs every browser of the account out. A dashboard session cannot make keys or links. Free accounts have it. `mcp` is MCP over this connection, each tool a child of the door under the key's own account (spec/NOTES-mcp.md): `{"command":"ssh","args":["nma.sh","mcp"]}`. `rollback APP` goes to the newest older version that differs from the live one, through `POST /v1/apps/{app}/rollback`; `rollback APP V` is a promote of V. The site's button and the CLI's `nanovm rollback APP` are the same request, at the generation the door just read. Sent again after a lost answer it reports the first outcome and moves nothing; with nothing older it is 409 `nothing_older`. `secret set APP NAME` takes the value on stdin, dropping one final newline, and `secret delete APP NAME` removes it; both work before APP's first deploy, which then starts with the set. When either returns, the app's next `secrets.get` sees the change. `retry` finishes a change whose answer was lost. `logs APP` prints the app's recent lines, and `logs APP -f` follows them until the SSH client goes. Match User nv AuthorizedKeysFile none AuthorizedKeysCommand /path/nanovm-ssh-keys /path/nanovm /var/lib/nanovm/door IP:PORT %t %k AuthorizedKeysCommandUser nobody PasswordAuthentication no PermitTTY yes SetEnv NV_DOOR="ssh nma.sh" NV_WEB=https://nma.sh ## Principles - **Authority lives in the replicated roots.** Every mutating call becomes one linearizable operation on a Raft group (the deployment root of NOTES-origin.md, the ctl group for tenants). The API server is stateless; any replica of it can serve any call. - **Optimistic concurrency.** Every mutable resource carries a `generation` (the Raft root generation). Updates take `If-Match: ` and fail with 409 on a mismatch; creates take an `Idempotency-Key` so a retried request applies at most once. A timeout is reported as unknown, never retried under a new key (the same rule as `kv` and `crdt` writes). - **Credentials never round-trip.** Secret values are write-only: they go into the per-app NVS1 store on the host (uni/NOTES-secrets.md) and are never returned, logged, put in bundles, argv, environment, boot args or the FC config. - **Tenant isolation is structural.** The tenant comes from the authenticated principal, never from the request body or path; the API resolves names inside that tenant only. This matches the host-bound tenant id of the data plane (NOTES-meter.md). ## Authentication and principals - A **principal** is a user or an API key, belonging to exactly one tenant. - API keys: an id plus a 32-byte secret, shown once at creation; stored as a hash. Requests are signed (HMAC-SHA256 over method, path, body hash and a timestamp, rejected outside a +-5 min window; replay cache per key) rather than sent as bearer tokens, reusing srv/auth.c's primitives. TLS in front regardless. - Roles: `owner` (everything, including keys and members), `deployer` (apps, deployments, config), `reader` (read-only, usage). Secrets: owner and deployer may write, nobody may read. - Users (console login) get short-lived session tokens bound to the same roles; the mechanism (OIDC or passkeys) is an open question. Built: a `dash` session (DASHLOGIN.md) is such a token for an API key's own role: `Authorization: NV1-HMAC-SHA256 Key=ID, Session=HEX, Signature=...`, signed as a key's request is, with SHA-256 of the session's secret as the key. Each request reads the key's record and the account's `u:dash:T` record, so a revoke or a sign-out ends it. ## Resources All paths are under `/v1`. Names are `[a-z0-9-]{1,31}` (they become tier key prefixes and NVS1 identity fields, which allow 1..31 bytes). ### Tenants and members (owner; v1 built: tenant read, keys create/list/revoke) - `GET /v1/tenant`: the caller's tenant: id, name, plan limits, generation. - `GET|POST|DELETE /v1/members`, `/v1/keys`: users and API keys with roles. Deleting a key revokes it: the revoke is a command in the tenant's root group, so every command ordered after it is refused at apply, whatever the API servers have cached (spec/NOTES-ctlauth.md). - Tenant creation is an operator action (not in this API). ### Apps (v1 built: create, list, get, delete; PATCH is draft) An app is a named function with its configuration; it has a current deployment. - `POST /v1/apps {name, regions: [...], consistency: "session"}`: create. `regions` bounds where warm pools may serve it; `consistency` is the default for `kv` reads (uni_js.c's handler default). - `GET /v1/apps`, `GET /v1/apps/{app}`: includes `current_version`, generation, `url` and `last_deploy`. The latter is the UTC Unix time in seconds of the latest recorded source deployment that moved the live pointer. It is null when no timestamp has been recorded. Rollbacks and explicit promotes leave it alone. - `PATCH /v1/apps/{app}` (If-Match): regions, consistency, scaling hints (`min_warm`, `max_instances` per region, fed to core/warmpool.c targets). - `DELETE /v1/apps/{app}` (built; If-Match, Idempotency-Key, an owner key): as "Apps nobody uses" says; data in `kv`/`crdt`/`db` is the tenant's and is kept. ### Deployments (v1 built: upload, list, promote, rollback) A deployment is an immutable version: a compiled bundle whose manifest digest is committed in the deployment root (the launcher of NOTES-origin.md). - (v1, built: `POST /v1/apps/{app}/deployments/{V}`, the compiled image as the body; the client names V, which must follow a committed V-1. See above.) - `POST /v1/apps/{app}/deployments` (Idempotency-Key): upload source; the trusted builder (uni/deploy-bundle.sh) compiles in isolation, uploads the segments and manifest to the S3 origin, then the API commits `(tenant, app, version) -> manifest digest` to the root. Returns `{version, digest, status: "building" | "committed" | "failed"}`. Credential files in the upload are refused, not stripped. - `GET /v1/apps/{app}/deployments[/{version}]`: status, digest, size, created_at, the builder's log (sanitized). - `POST /v1/apps/{app}/deployments/{version}/promote` (If-Match on the app): makes it current. Warm pools learn it from the root, drain the old version's leases (WarmPool.tla's drain) and serve the new one. Rollback is promoting an older version. Every promote, a rollback included, is a new, higher generation of the pointer, and pools adopt by generation, not by "higher version" (spec/Deploy.tla, spec/ControlAuth.tla). Publication does not wait for pool or front readiness; the response has `first: null`. Source deploys prepare all configured pools concurrently for at most three seconds, then publish even if some pools are unavailable. ### Instances (read-only; draft, not in v1) - `GET /v1/apps/{app}/instances?region=`: per region, the warm pool's view: instances, their version, state (warm, leased, draining), started_at. Sourced from each warmpoold; eventually consistent, labelled with its as-of time. ### Configuration and secrets (v1 built: secrets PUT and DELETE with If-Match; env is draft) - `PUT /v1/apps/{app}/env/{NAME}` `{value}` and `PUT .../secrets/{NAME}` `{value}`: names `[A-Z0-9_]{1,32}`, values per the NVS1 bounds (1024 bytes, printable). Writing creates a new store generation for the app; running instances see it on their next lookup (atomic replacement, as today). - `GET .../env` returns names and values; `GET .../secrets` returns names and `updated_at` only. `DELETE` revokes a name (later lookups throw). - Limits: 16 entries across both namespaces (the NVS1 bound). - Before APP's first deploy the same PUT/DELETE write a set kept for that name in the tenant (`q:T:F`, F in 1..`--max-apps`): no app is created, `apps` does not list it, and no app slot is taken. The limits are the app's own (16 entries, 1024 bytes); a tenant may hold at most `--max-apps` such names. The first deploy of that name merges the set into the app's own `s:T:F` and empties the pending record before the version is published, so its first request sees the secret. - Built: a PUT or DELETE answers 200 once the app's store on the host is written, so the app's next `secrets.get` has the change. A 503 saying the secret has not reached the app means it is saved: retry with the same Idempotency-Key. In the app, `secrets.get(NAME)` throws `no secret NAME for this app` for a name it does not have. ### Logs (built: NOTES-logs.md, spec/LogFollow.tla) - `GET /v1/apps/{app}/logs`: the app's recent console lines, oldest first, each with the time it was read, the VM (`P.V`, pool and VM) and the version. `follow=1` keeps the answer open and sends lines as they come. The API server authenticates the request, resolves the app in the principal's tenant, and hands the client's socket and that (tenant, app) to dp-logd, one per host, over a private Unix socket; nothing else from the request reaches it. - The answer is NDJSON, one object a line: a start, then lines, each with its cursor `E-S`. A reader that fell behind is told `{"missed": N}`; a cursor from before dp-logd restarted gets `{"missed": "unknown"}` and goes on from the newest line. `{"ping": MS}` comes every 15 s to a follower with nothing new; `{"end": true}` closes a read without `follow`. To go on after a lost connection, send `after=` the last cursor read: `nanovm logs -f` does. - Bounds: 64 KiB of lines per app, 16 KiB and a 64 KiB socket buffer per reader, 4 readers per tenant (429 `too_many_readers`) and 64 in all; a reader that takes nothing for 30 s is closed, and a follow ends after 5 minutes, so a revoked key's follow ends too (the CLI asks again and is authenticated again). A slow reader never makes a VM or another reader wait. - What is shown is the app's: the guest's boot banner and its runtime's own lines are dropped, the app's top-level lines kept. A handler that throws prints `Uncaught` and the error, then the app's own frames (`app.js:LINE:COL`), none of the runtime's. A deploy's answer carries its build lines and first request, and the doors print those and that version's logs before the URL. ### Usage (v1 built: summed from the server's `--meter` files until a collector exists) - `GET /v1/usage?from=&to=&app=&granularity=hour|day`: requests, frame bytes, `kv`/`crdt`/`db` operations and stored bytes, compute seconds. Sourced from the durable gateway meters (NOTES-meter.md, already conserved and checked by dp-srv-meter) once a collector aggregates them; until then this endpoint is the contract the collector must meet (deferred: the metering collector). ### Usage of the site (built; admin only; NOTES-usage.md, spec/UsageFacts.tla, spec/FunnelFacts.tla) The site's own funnel, for its operator. Not a door command and not in llms.txt: the CLI has `nanovm admin-usage [DAYS]`, and examples/admin-usage shows it as a page. - `GET /v1/admin/usage?days=N&after=T`, signed by any key of the tenant `--admin-tenant` names (live: 2, `SITE_ADMIN_TENANT`). Any other key gets the 404 `not_found` an unknown route gets, byte for byte; no admin tenant set: 404 for everyone. `days` 1..366 (default 30) and `after` (a tenant number) at most once each, else 400 `bad_request`. 503 `unavailable` when the root group does not answer. - Facts are kept only with `--usage-facts 1` (site.sh's `SITE_USAGE_FACTS`, default 1), in plain root records `w:T` (an account's) and `w:T:F` (an app's). dp-ctlapi writes them beside the event: sign-up, a verify link asked and confirmed, a new version deployed, a checkout made, Stripe's paid with Pro, an app deleted by its owner or the sweeper. A day is set once; a write is read, change, CAS, retried four times; a write the root does not answer is dropped and never fails its operation. "Used" is the sweeper's: an app whose idle record's tick count passed the count its latest deploy read (spec/UsageFacts.tla), counted once a UTC day. - The funnel (spec/FunnelFacts.tla), written after each answer is sent, same rules (a lost CAS read again, one with no answer dropped, so a count can be low, never high): - a refusal: the error code of the answer the client got, from a signed request (and `no_room` at sign-up), counted on the day's slot `w:d:S` (S = day mod 400). The codes are `apps_full pro_only rate_limited verify_first version_limit full no_room` and `other`, any other 4xx after the signature (a path no route knows, and a bad signature, are not an account's refusal). Ours and others apart, decided at the write. - a conversion: a checkout made (`upgrade`) or a verify confirmed within 86,400 s of a refusal of the account's. Its marker `w:r:T` keeps the time of the latest refusal of each code; the conversion clears the codes it claims, so each refusal converts once, and counts one per code claimed. - active: an account with a signed request that day, in its ring `w:a:T` (its first and latest day, a bit per day for 208 days). "back": active that day and on an earlier one. Ours and others decided at the read. - room: a new marker or ring is made only while the root's table holds under half its usable keys (core/root.h `DP_ROOT_SHARE`, decided at apply); past it the write is refused FULL and dropped, so an account made then is not counted active or converted. A write over one that exists still goes in. Sign-ups and every other key keep the whole table. - "Ours": the admin tenant, each tenant number in the `--internal` file (`SITE_INTERNAL`, re-read on every request; an email line counts the account that verified it), any account that confirmed an @nma.sh address, and any account whose sign-up `ref` (`w:s:T`, 1-24 chars of `[a-z0-9-]`, set once from 0 at sign-up and never rewritten) starts `int-`. The rest are "others". - The answer: `today`, `days`, `tenants_scanned`, `internal {listed, by_email}`; `totals {ours, others, by_ref}`, each of `ours` and `others` with `accounts verified first_deploy first_used checkout paid apps_deleted active back` (accounts with that day ever set, apps deleted summed; active: ever active, back: active on two days or more), `pro_now`, `verified_now` and `no_facts` (accounts from before the facts), and `by_ref` splitting `others` by sign-up ref (top 20 refs by accounts, the rest as `"other"`, untagged as `"(none)"`); `columns`; `refusal_codes`, the eight codes in order; `per_day` newest first, each `{day, ours: [...], others: [...], by_ref: {TAG: [...]}, refused: [...], converted: [...], ours_refused, ours_converted}`: ours, others, and each active ref in `columns` order, refused and converted others' per code in `refusal_codes` order, ours' every code together; `others_columns` (`tenant created verified pro apps deploys days_used last_used ref`) and `others`, one row per other account, at most 300, with `next_after` the `after` of the next page or null. No email, key, address or app name is in it. - Not counted: requests per app (the meters count data operations; `days_used` and `last_used` stand in), who sent a request (the owner's own curl is use), and account deletion (there is none: tenants are never reused). - Verified email list (`GET /v1/admin/emails[?after=T]`, CLI `nanovm admin-emails [AFTER]`): separate admin-only route so `/v1/admin/usage` stays PII-free (`UsageNoPrivate`) and no plaintext emails consume Raft root keys. On verify request, `dp-ctlapi` seals the normalized email under `--seal` and stores it in S3 at `emails/<32hex-eid>`. `GET /v1/admin/emails` reads only accounts whose Raft `NVROOT1:v:T` record is verified, unseals and hash-verifies each S3 object (`email: null` for pre-change accounts that hold only a hash), and returns `today`, `tenants_scanned`, `total_verified`, `ours_verified`, `others_verified`, `missing_email`, `emails` (up to 200 rows or ~56 KiB per page), and `next_after`. ## Errors Every refusal is JSON `{"error":{"code","message"}}`; `code` is a stable snake_case token an agent may branch on, and `message` names the condition and the next step. A resource of another tenant is 404, never 403: the API never says that a name exists elsewhere. ### Error codes (built) | Code | Status | When | What to do next | |---|---|---|---| | `unauthenticated` | 401 | no signature, an unknown or revoked key, a bad signature, or `X-NV-Date` outside +-5 min | sign with a live key and the clock in the window | | `forbidden` | 403 | the key's role cannot do this (a reader deploy, a non-owner's data read) | use a key with the role the route needs | | `pro_only` | 403 | the feature (a custom domain, a chosen name, backups) is part of Pro | run `nanovm upgrade` for a checkout link | | `invalid_invite` | 403 | the invite's tag does not match the key | use the invite `dp-ctlapi invite` printed | | `invite_required` | 403 | open sign-up is off and no invite was sent | sign up with an invite | | `not_found` | 404 | no such app, version, key, secret, data key, or a name of another tenant; also a server that does not build apps, has tree deploy off, keeps no logs, has no paid plan, offers no chosen names, or reaches no app data | check the name in this account; for those seven ask the operator | | `not_available` | 404 | email verification is off on this server (no `SITE_MAIL_KEY`/`SITE_VERIFY_SPOOL`): nothing was sent | tell your human this site has no mail; a retry will not send it | | `no_billing` | 404 | this account has never paid | run `nanovm upgrade` to start Pro | | `method_not_allowed` | 405 | a known path with the wrong method, or a site that does not delete apps | use the method the wire table documents | | `write_only` | 405 | a read of secrets | write the secret; secrets are never read back | | `already_verified` | 409 | this account already verified another email, and keeps it | run `nanovm tenant` to see the address; nothing was sent | | `email_taken` | 409 | that email verified another nma.sh account | ask your human for another address and run `nanovm verify OTHER@EMAIL`; one email verifies one account | | `conflict` | 409 | If-Match is not the current generation, the Idempotency-Key is older than this key's latest, the app name or version is taken, or the app was deployed while its secret was written | read the generation for If-Match; for a name or slot take a new name or a new Idempotency-Key; for the secret race run the command again | | `idempotency_key_reused` | 409 | the same Idempotency-Key named a different request | take a new Idempotency-Key | | `invite_used` | 409 | the invite was already redeemed | obtain a new invite | | `name_taken` | 409 | a nameless deploy's generated name, or a chosen name, already belongs to another app | retry with a new Idempotency-Key (a generated name), or choose another chosen name | | `domain_taken` | 409 | another account has that hostname and it is served for them | run `nanovm domain rm HOST` in that account first, or use another hostname | | `nothing_older` | 409 | a rollback with no older version to go to | deploy a new version | | `app_deleted` | 409 | a promote or rollback of an owner-deleted app | deploy it again to bring it back | | `version_gone` | 409, 410 | 409: the version went with its app; 410: it is older than the last `CTL_KEEP` versions | deploy the source again | | `apps_full` | 413 | the account has its tier's apps at once: 2 unverified, 5 with a verified email, 10 with Pro; or all 16 app numbers are used (they are never reused, so a deleted app keeps its number) | delete one and its room is freed at once, or deploy a new version of one it has; bringing a deleted app back needs room like a new app; run `nanovm verify THEIR@EMAIL` for 5 instead of 2, or `nanovm upgrade` for 10 with Pro | | `domains_full` | 413 | the account has named all 10 custom domains it may ever have; a place is never given back, even after its domain is removed | use a hostname it already holds; a domain removed before can be added again | | `keys_full` | 413 | every key id of the account is used (3 on the free tier), and an id is never reused | run `nanovm keys revoke ID`, or keep using a key it has | | `full` | 413 | the root group's fixed key table is full, a name's pending and app secret sets hold 17 entries (16 allowed), or a store every account shares is out of room | for a secret set delete one with `nanovm secret delete APP NAME`; for a shared store delete keys; for the root the operator must grow it, then retry | | `too_large` | 413 | the body is over 32 MiB, a static tree over 27 MiB, or the compiled image is too large | make it smaller; about 6 MB of source deploys | | `compile_error` | 422 | the compiler rejected the source; the message is its diagnostic | fix the code and deploy again | | `if_match_required` | 428 | a mutation that needs If-Match sent none | read the generation and send If-Match | | `slow_down` | 429 | the sign-up, deploy or data-call rate limit was reached; `retry_after_s` and Retry-After say how long | wait that many seconds, then retry | | `rate_limited` | 429 | 5 verify links an account and 3 an address a day were asked for | use the link already sent, or wait the minutes the message names | | `too_many_readers` | 429 | 4 log followers or 2 data readers are already open for the account | close one, then retry | | `internal_error` | 500 | the server could not generate a name for a nameless deploy | retry; report it if it repeats | | `error` | 500, 503, 504 | the generic fallback: an unexpected answer, a verification or plan record that does not decode, or an over-long answer | retry once; if it repeats, tell the operator | | `checkout_failed` | 502 | Stripe did not make a checkout; the message is Stripe's | retry `nanovm upgrade` later, or tell your human | | `portal_failed` | 502 | Stripe did not make a billing link; the message is Stripe's | retry `nanovm billing` later, or tell your human | | `unavailable` | 503 | a dependency is down: the message names root, S3, compiler, payment, mail or meter | retry where it says so (a mutation: the same Idempotency-Key); otherwise tell the operator | | `no_room` | 503 | every open sign-up tenant is taken | contact the operator, or try again later | | `logs_unavailable` | 503 | dp-logd did not answer | retry | | `data_unavailable` | 200, 503 | the data plane did not answer or its answer was malformed; a db export that fails mid-stream answers 200 with a `data_unavailable` line | retry; for an export continue with `after=`, do not restart from the first key | | `busy` | 503 | the data tier is busy (a table or the account's share) | retry when it has room | | `warming` | 503 | a source retry found its version committed but the pool not ready | retry the same source | | `outcome_unknown` | 504 | the root group did not answer in time; the command may have applied | retry with the same Idempotency-Key (a deploy: the same source) | | `invalid` | 400 | a malformed body, path, name or number; `version too large` (over 64); a non-Stripe body to `/v1/stripe`; or a signature that does not check | send the body and names the route documents; for version 64 delete the app and deploy again | | `idempotency_key_required` | 400 | a mutation with no Idempotency-Key | send an integer key that increases per key | | `version_limit` | 400 | an app on the old key layout holds its last version (64) | run `nanovm delete APP`, then deploy again | A server that is a test copy of this one (`--test-copy NAME:HOST`, staging's `SITE_TEST_COPY`) says where those features run instead, when it builds none of them: `not_available` for a mailed verification, and the no-paid-plan and no-custom-domains `not_found`, answer "email verification runs on nma.sh itself: this is staging, a test copy of nma.sh, and nothing was sent" (and the same sentence for `Pro (upgrade)` and `custom domains`). A copy that builds verify never says it: its `verify` is 202, its mail spooled, its link on the copy's own `--public-url`, and its own words name the copy (`--base-domain`), never the site it copies. Live sets no `--test-copy`, so its answers are the rows above. The test for every row is `dp/srv/test_ctlapi_errors.py`, which runs the real server and prints the answer each produced (`ANSWER `). `dp/tools/verify-errs.sh` extracts this table and requires each code to be produced or listed with a reason in `CONTROL-API-ERRS.md`. The CLI's side of the same promise is `dp/srv/test_cli_errors.py`: it runs the real `nanovm` binary against the real server, and for every code a command can meet checks a non-zero exit, the code's meaning and next step in the words above, and `--json` carrying the server's code and message unchanged. `dp/tools/verify-clierrs.sh` extracts this table and requires 80% of the codes to be checked on the CLI or listed with a reason in `CONTROL-API-CLI-ERRS.md`. ### Data plane errors (in-band) An app's db, kv and crdt calls answer no HTTP status: a refusal is prose on the ERR frame, prefixed by the operation and a word, and the app sees `db.put: : `. `quota:` is the account's share of a db group or kv; `full:` is a store every account shares (the root group's table; a name's pending and app secret sets, 17 entries with 16 allowed; or the db/kv store); `busy:` means a table or slot was busy and the write was not applied; `unavailable:` means the gateway, router or replica did not answer (a write may have applied only if it says `unknown:`); `unknown:` means the outcome is unknown and the write applied at most once, so read the key before rewriting it. `crdt:`, `db:`, `db LIST:`, `db PUT:`, `db list:`, `kvs:`, `kvs LIST:`, `kvs PUT:` and `stale:` are protocol diagnostics: the message names the bad op, cursor, prefix, limit or write id, and the fix is in the words. The exact text of each is in `NOTES-erraudit.md`. ## What the model checks (spec/ControlAuth.tla) Authorization is checked AT APPLY in the Raft group that holds both the tenant's roots and its principals. Every root command carries {principal, idempotency key, op}. The state machine refuses it unless the principal exists, is not revoked, belongs to the root key's tenant and has the role the op needs. The API servers and the future host-side broker are not trusted for isolation; the model treats the submitter as an adversary (spec/NOTES-ctlauth.md has the trust model). Checked, each with known-bad designs that fail: - TenantConfined: every applied change to a tenant's roots or principals was authorized at its log position. - RevokedIsDead: no command of a principal applies after its revoke. So no request authenticated by a revoked key is accepted after the revoke commits. - AtMostOnce: one application per (principal, Idempotency-Key), and a retry returns the first result. - SlotBindsCommand: a command is answered only with its own result; a key reused for another command is refused. - ClaimHasOwner: the admin claims a tenant only with an owner. - CurrentIsCommitted: the pointer always names a committed version. - Deploy's NeverUncommitted, NeverUnverified and FreshServe. - Convergence: every region serves the current pointer's version and drains the others, after a rollback too. Idempotency-Key, as modelled and as the core's dedup allows: an integer that increases per API key. An equal key returns the first result, and a lower one is refused (409: read before retrying). The operator's deploy.sh keeps working for tenants that have no principal yet ("unclaimed"). Adding a tenant's first owner claims it for good. Not covered: authenticity of the principal name. A component holding the cluster key can act as any *live* principal, within that principal's tenant and role. Signed commands verified at apply would close this (spec/NOTES-ctlauth.md, "Trust model"). ## What the API model checks (spec/ControlApi.tla) Stateless servers, sequential clients that retry unknown outcomes with the same key, lost and duplicated requests and responses, server timeouts, the group applying a command more than once, If-Match races and revocation racing in-flight requests. Checked: ControlAuth's invariants, NoLostUpdate, RetryIsSafe, TenantFromPrincipal, SecretsNeverRead, RevokedReadsDead, SecretBeforeDeploy and the liveness property Learns. Nine known-bad designs fail their properties, and four reach configs show a 504 then a retry returning the original result, a 409 loser, a rollback through the API and a revoke landing on an in-flight request. ## Open questions Settled by v1 (above): API keys and request signing, integer Idempotency-Keys, If-Match on promotes and secret sets (a set for a name not deployed yet needs none), write-only secrets, tenant from the key. - Signed commands (the user's key signs, the root group verifies at apply), so that a compromised broker cannot act as a live principal. Asymmetric signatures would also stop the stored `key_hash` from being a credential. - Random-string Idempotency-Keys: they need a retained-key table with expiry per principal. - Owner recovery when every owner of a claimed tenant is revoked. - Sharding the root group: it holds 3,072 keys in all (`dp-srv-root`), some hundreds of apps. - Console login mechanism (OIDC, passkeys); members. - Data lifecycle on app deletion; per-tenant quotas and rate limits; billing from the meters; custom domains and TLS certificates. ### Experimental tree deployment and static files (off by default) The compiler API accepts `POST /v1/apps/{app}/deploy-tree` only with `--static-trees 1`. Its signed body is an opaque, uncompressed ustar archive, bounded at 27 MiB. The existing deploy operation, authentication, retry handling, version commit and pointer CAS are shared with the source endpoint. The host never extracts the archive or parses application source. The compile guest validates paths, file kinds, checksums, duplicates and limits, loads app.js and its relative modules, and generates the static table and compressed bodies. The limits and format are in NOTES-static.md. A directory must contain app.js; assets belong under public/. public/index.html also answers the app root. A successful tree deploy returns static_base and, when that index exists, page_url: open page_url for the version-qualified page. Use `nanovm deploy APP DIR`, the site's optional directory picker, or `nanovm pack DIR | ssh HOST deploy APP`. The native CLI and browser WASM use the same C ustar writer. SSH recognizes the writer's ustar transport marker; it does not validate or unpack its files. The explicit SSH command `deploy-tree APP` also forwards opaque tree bytes. These doors call the same control endpoint. The MCP deploy tool accepts {"app":"APP","directory":"/absolute/path/to/DIR"}. The directory is local to the MCP server; it requires an app name and an absolute path, and cannot be combined with source. It runs the same CLI packer. For HTTP, sign POST /v1/apps/APP/deploy-tree with the bytes from nanovm pack DIR. In the web panel, choose the app name and directory picker, then Deploy. Credential filenames and links are refused; no package manager runs on the host. The directory picker is offered only when the API serves its WASM packer. Enable the pool and front with `--static 1`; the site harness exposes all three options as `SITE_STATIC=1`. Upgrade both paired fronts and their pools before enabling it. Each pool publishes an immutable version descriptor only after verified installation and adoption. Each front learns complete descriptors outside request dispatch and pins a version for its answer. Static GET/HEAD hits use the front's own file descriptor and sendfile, without a pool request or VM. An unknown app can use the existing pool path for discovery; its held answer is inspected against that actual lease's descriptor before a public-file hit is answered. A pool may evict the key and reuse its view before the front reads it; the front then reads that one version's descriptor from the answering pool's catalog, and serves it only after a pool answers for that version. Missing admission returns an error rather than another version's file. Dynamic handlers receive `req.staticBase`, also available as the internal X-NV-Static-Base request header. The pool derives it from that VM lease's version and verified manifest, including for a draining old VM. It is a version-qualified base within the app's route; append a public file's path. Such URLs resolve a retained immutable descriptor or return 410. They never fall back to a newer version. Unqualified names follow independent front/pool adoption as before. Full verified SHA256 filenames and qualified URLs get immutable caching; mutable names require revalidation. ETag, conditional GET, HEAD, single byte ranges, Accept-Encoding and representation-specific hashes are covered in NOTES-static.md. The option includes bounded admission, per-front static quota with `--quota`, and static use reporting through the existing inactivity mechanism. The local catalog's static bytes have separate per-pool bounds. Shared object-segment GC remains open: app deletion removes manifests and retires views, and does not unlink a shared child merely because one app stopped referencing it.