# nanovm: Agent Contract and Platform Guide
nanovm runs JavaScript apps in Firecracker microVMs: hardware isolation per app. One JS file is built, booted and snapshotted once;
requests run on VMs restored from that snapshot. Each app gets a permanent two-word name, https://still-pike.nma.sh/ ("url"), and a
number, https://N-TENANT.nma.sh/ ("numeric_url": tenant 53's second app is 2-53.nma.sh); both answer. Sign-up is open (one command,
no email or card; "no_room" 503 if full). Personal Agents (personalagentprotocol.org) start at https://nma.sh/.well-known/poppy.json.
ssh nma.sh uses port 22 with any user name. If outbound port 22 is blocked, ssh -p 2200 nv@nma.sh reaches the same door.
## If you are an agent evaluating nma.sh
Measure it rather than take our word. One minute, from an empty directory with an SSH key:
ssh nma.sh signup --json # {"tenant":T,"key":K}: your SSH key is the account
echo 'serve(req => "hello")' > app.js; ssh nma.sh deploy hello --json < app.js # answers once live
curl -i URL # the "url" it printed: https://N-T.nma.sh/
ssh nma.sh delete hello --json # 404 at once; deploy it again to bring it back
Agents timing it on live (2026-11-10): sign-up 1.4-4.1 s, first deploy to HTTP 200 4.1-6.3 s, a redeploy served
in 3.3-7.4 s. Short pages for a fetch tool that summarizes: https://nma.sh/api.txt (the runtime API), /limits.txt, /recipes.txt (recovery codes and admin reset links), /examples/auth.js, and /examples/admin-page.js.
What an app can do: call any public https:// API with fetch() (10 a second); keep strong data in db and fast data in kv;
serve one JavaScript file, a static folder or a framework build; put a password on a whole app with NV_BASIC_AUTH, no code; use serve() or export default { fetch }. Pro adds your own domain (domain add).
## Deploy
### First Deploy Checklist (in order)
1. Sign up: ssh nma.sh signup --json (your SSH key becomes your account; unverified: 2 apps at a time, so before a third app, or anything your human means to keep, give them the answer's claim_url or run verify EMAIL with their address: ask them for it, never make one up, since a made-up address bounces and the account stays unverified)
2. Deploy: ssh nma.sh deploy APP --json < app.js (creates APP; any program piping into ssh works)
3. Secret: ssh nma.sh secret set APP NAME --json < secret.txt (before or after the first deploy; never read back)
4. Status, logs, back: apps --json; logs APP --json (NDJSON); rollback APP --json; delete APP --json
A list that survives redeploys (a guestbook, a todo list): one db key per entry, read back with db.list.
db.put("gb:" + Date.now() + ":" + crypto.randomUUID(), msg); // keys sort by time
const { keys } = db.list("gb:", { limit: 50 }); const msgs = keys.map(k => db.get(k));
A private app (an admin view): secret set APP NV_BASIC_AUTH < pw.txt (a password, or USER:PASSWORD), and the browser asks for it
before your handler runs (public/ files are not covered). Per path: check "Bearer " + secrets.get("ADMIN_TOKEN"), or the sign-in of /examples/admin-page.js on this site. User accounts, no setup: const r = auth.handle(req); if (r) return r; serves /signup /login /logout /recover /reset (fields user and pass; /recover takes user, code and new; as a form or JSON; state changes POST-only; a JSON body gets {"ok":true,"user":...,"token":...}: send Authorization: Bearer TOKEN); then const u = auth.user(req) gives null or { id, user, db, kv } (db and kv as above) keyed to that user alone; auth.require(req) gives that user or, with no session, the answer to return (a 401, or for a browser a 303 to /login): const u = auth.require(req); if (!u.id) return u. If auth.require(req) guards /, deploy still succeeds (exit 0) and "first" shows 401 with a "note" (a browser goes to /login). See /examples/auth.js (whole app) and /recipes.txt (both user recovery codes and admin reset links).
### The Four Doors
All four doors share one data plane and contract:
1. SSH door: ssh nma.sh COMMAND [--json] (your SSH key is your login)
--json goes anywhere among the command's words. To put it first, write `--` before it: ssh nma.sh -- --json apps
2. CLI: nanovm --json [--url IP:PORT] [--creds DIR] COMMAND (or NANOVM_JSON=1)
Install (Linux x86_64, macOS x86_64): curl -fsSL https://nma.sh/dl/install.sh | sh
It checks https://nma.sh/dl/SHA256SUMS and unpacks nanovm, nanovm-dev and nanovm-framework/ into ~/.nanovm. The control
API is not public: use the CLI for pack and dev, the SSH door for the rest (nanovm pack . | ssh nma.sh deploy APP --json).
3. HTTP control API: /v1/..., every request signed with your key (CONTROL-API.md in the source), on the operator's own network
4. MCP stdio: nanovm [--url IP:PORT] [--creds DIR] mcp (protocol 2025-06-18).
Add to an MCP client: {"command": "nanovm", "args": ["mcp"]}; use NANOVM_URL and NANOVM_CREDS, or put --url and --creds before mcp in args.
No CLI needed: ssh nma.sh mcp speaks the same protocol under your SSH key's account ({"command":"ssh","args":["nma.sh","mcp"]}); run ssh nma.sh signup once first. It has every tool but deploy's local directory (send files instead). A call stops after 300 s, a session after 600 s idle or 3600 s in all; reconnect.
The local nanovm mcp needs a CLI login first. Tools: deploy {app?, source} (or {app, files} or {app, directory}: directories below), apps {}, deployments {app},
rollback {app, version?}, promote {app, version}, logs {app, version?, limit?}, delete {app}, secret_set {app, name, value},
secret_delete {app, name}, verify {email}, plan {}, upgrade {}, billing {}, whoami {} (tenant, key, role, latest_idempotency_key),
retry {} (finish a change whose answer was lost), usage {} (metered requests and bytes), keys {} (key ids, roles, states),
keys_create {id, role} (its secret, printed once), keys_revoke {id}, domain_add {app, host}, domains {}, domain_remove {host},
rename {app, name}, db_list {app, prefix?, after?, limit?}, db_get {app, key}, db_delete {app, key}, db_export {app} (up to 8 MiB).
Each tool runs the same CLI with --json; its stdout is the result text (logs: NDJSON).
Any nonzero exit is isError, including exit 3: the new version's first request answered 5xx.
Source and secret values go on the child's stdin, never argv. Secrets are write-only; set one before or after deploy.
logs reads recent lines and ends (no follow), with limit 1..1000 and optional version.
MCP requests are newline-delimited JSON-RPC 2.0 objects, at most 1 MiB per line.
With --json (or NANOVM_JSON=1), stdout is one JSON object per answer (logs: NDJSON), nothing else; exit codes stay the same.
### Directories, archives and static sites
Every door deploys folders through one packer (same names, limits, checks) as one deterministic archive, in one of two shapes:
- An app: app.js at the top, and public/ for files served as they are; public/index.html also answers "/".
Its other JavaScript files can use relative require; no npm install runs. Files answer only at their own
names (public/about.html is /about.html): /about, like any other miss, goes to app.js. Pretty URLs are the static site's.
- A static site: index.html at the top, no app.js or package.json, no code of your own. /about answers about.html, /docs/ answers docs/index.html, an unknown path 404 (your 404.html if there is one). Optional `_headers` and `_redirects` settings apply to its static answers (they are never served as files), parsed at deploy and refused there with the wrong line named.
- `_headers`: a path line, then indented `Name: value` lines; a path is exact or ends with one `*`; at most 100 rules and 8 KiB. Content-Length, Transfer-Encoding, Connection, Set-Cookie, hop-by-hop, ETag, Location and other answer-owned headers are refused; every matching rule applies, the last of a name wins.
- `_redirects`: `FROM TO [STATUS]`, FROM exact or ending in one `*`, with `:name` as a whole segment; TO may use `:name` and `:splat`; STATUS 301 (default), 302, 307, 308 or 200 (serve TO's file); first match wins, an existing file wins over a rule, at most 200 rules. `/* /index.html 200` alone is still the single-page app: every unknown path answers index.html with 200.
Archives may wrap the folder in one top directory; __MACOSX/, ._* and .DS_Store are dropped.
- SSH, no CLI: tar czf - -C DIR . | ssh nma.sh deploy APP --json (or zip -qr - . from DIR).
Any tar (ustar, GNU, pax), gzip'd tar or zip. Refused: links, devices, names with .. or a leading /,
.env files, a damaged archive, one past the limits, and no app name (missing_name). Never unpacked on the host.
- CLI (with --url, on the operator's network): nanovm deploy APP DIR (or an archive file); nanovm pack DIR|ARCHIVE|- prints the archive; nanovm dev DIR runs either shape locally.
- HTTP: POST /v1/apps/APP/deploy-tree with the archive from nanovm pack, signed as usual.
- MCP deploy: {"app":"APP","files":{"index.html":"
hi
","css/site.css":"h1{}"}} (text files); the
CLI's mcp also takes {"app":"APP","directory":"/absolute/path"}, a path on the MCP server's machine.
- Web panel: the directory picker sends the folder as it is, so give it app.js and public/.
Static files need no VM: the edge answers GET and HEAD from public/ (and a static site's /about, SPA and 404 answers), with ETag, Range, gzip and br. Content-Type comes from the suffix (html css js mjs json txt md xml svg png jpg jpeg gif ico webp avif wasm woff woff2; others application/octet-stream).
A tree deploy adds static_base and, with public/index.html, page_url, the version-qualified page. A handler gets req.staticBase; append an asset's path to pin its version.
- Vite (vanilla TS or React SPA): npm ci && npm run build, then nanovm deploy APP dist (not the project root with
package.json). Vite copies public/_redirects into dist/, so deep links like /about answer index.html with 200.
SSR output is not deployable (built client files only, no Node server or Vite middleware). Verified with vite 8.3.8
and node 22.22.1 (npm ci + npm run build); nanovm dev dist answered /, /about and /assets/*.
### SEO for public apps
- Prefer SSR (serve(), static HTML, or framework via nanovm pack .) over a Vite SPA; return 404, not 401, on missing paths.
- Add viewport, unique , description, , canonical, og:title/description; serve /robots.txt and /sitemap.xml.
- On Pro custom domains, emit absolute canonicals or 301 other req.headers.host; send X-Robots-Tag: noindex on private routes.
### Signing Up
- SSH: ssh nma.sh signup [INVITE] [--ref TAG] --json; a key from `keys create` (role owner hands your human the account) attaches with ssh nma.sh login ID < secret.txt (the secret on stdin; or nanovm login ID - on the operator's network)
- Free tier, unverified: 2 apps at a time (deleting one frees its room at once; an account already past 2 keeps its apps) and 3 keys (the same on every tier). It's a starter sandbox before you attach an email. verify EMAIL (the CLI, the door, MCP's verify; an owner key) mails your human a link (good for 24 hours); once they press Confirm the account has 5 apps at a time (deleting one frees its room at once) and its apps are kept for good. Every app takes a number for the account's life that is never reused: 16 at most. apps_full or keys_full past them. Ask your human for an email before a third app, or before you deploy something they mean to keep. The deploy, tenant and sign-up answers also give `claim_url` (when the account is not verified or not Pro): give it to your human to open in a browser; that page confirms the email or pays for Pro without the SSH key.
- Pro ($8 a month, paid through Stripe): upgrade (any owner key, no email needed; MCP's upgrade) prints a checkout link for your human. Pro is never needed to keep idle apps (a verified free account already keeps its apps for good); Pro gives 10 apps at a time on nma.sh, a bigger db and kv share (plan prints the numbers), custom domains (domain add), rename, and daily backups: backups APP lists the last 7 days' copies of the app's db and kv, restore APP DATE writes one back (it overwrites keys, never deletes newer ones; the copies are kept on the same host, a guard against mistakes, not disk loss; db export APP is the copy you keep yourself). plan shows what Pro gives on this server, the plan, and usage: apps used of the cap, db keys of the share a group, kv keys of the cap. billing (an owner key) prints a Stripe link where your human changes the card, sees invoices or cancels (Pro lasts to the end of the period paid). apps_full and a db or kv quota error name Pro and its command. Offer it only when your human wants more.
- HTTP, on the operator's network: POST /v1/signup with {"key_hash":"<64hex>"} (or {"tenant":T,"invite":"","key_hash":"<64hex>"}, optional "ref":"TAG") -> 201 {"tenant":1,"key":65,"role":"owner"}
### Commands and JSON Shapes
### apps / app / apps create
Your tenant's apps; one app; an empty slot (deploy makes one too). "state": live, warned (idle), deleting (idle, a day from removal), deleted.
- Door: apps
- CLI: nanovm --json apps | app APP | apps create NAME
- HTTP: GET /v1/apps | GET /v1/apps/APP | POST /v1/apps {"name":"NAME"}
- Output: {"apps":[{"name":"web","app":1,"generation":1,"current_version":1,"versions":1,"secrets_generation":0,"state":"live","url":"https://assured-tableland.nma.sh/","numeric_url":"https://1-1.nma.sh/"}]}
app APP: one of those objects. apps create (201): {"name":"web","app":1,"generation":1}
### deploy
Send the source; it is built, snapshotted and live in one call. Creates the app if it is new; sending the same source again is safe.
- Door: deploy APP < app.js
- Door: deploy APP < site.tgz (a folder as a tar, tgz or zip; see "Directories, archives and static sites")
- Door: deploy-tree APP < app.tar (the archive nanovm pack DIR prints)
- CLI: nanovm --json deploy APP app.js (or deploy APP VERSION FILE)
- HTTP: POST /v1/apps/APP/deploy (body is JS source)
- A FILE of "-" is stdin: `cat app.js | nanovm --json deploy APP -`.
- No name: `deploy < app.js` (door), `nanovm --json deploy app.js`, POST /v1/deploy with an Idempotency-Key:
a new app with a generated name like "quiet-river-7k2", given back as "app" in the output.
- Output (200):
{"app":"web","version":1,"digest":"<64hex>","status":"live","new_version":true,"url":"https://assured-tableland.nma.sh/","numeric_url":"https://1-1.nma.sh/","build":["step 1"],"first":{"status":200,"ms":15},"message":"web is live (version 1): https://1-1.nma.sh/","claim_url":"https://nma.sh/c/"}
### deployments
- Door: deployments APP
- CLI: nanovm --json deployments APP
- HTTP: GET /v1/apps/APP/deployments
- Output: {"app":"web","generation":1,"deployments":[{"version":1,"digest":"<64hex>","current":true}]}
### rollback / promote
- Door: rollback APP [VERSION]
- CLI: nanovm --json rollback APP [VERSION] (or promote APP VERSION GENERATION)
- HTTP: POST /v1/apps/APP/rollback (or POST /v1/apps/APP/deployments/V/promote)
- Output: {"app":"web","version":1,"generation":2,"first":{"status":200,"ms":12},"message":"web is back on version 1"}
It answers once the URL serves that version, as deploy does ("first"; null if not within 10 s).
### delete
Delete an app you own (an owner key): its URL answers 404 at once, and "state" is "deleted". Deploy it again to bring it
back, on the same URL, as a new version; a rollback or promote of it is refused (app_deleted). A day later (grace_s) its
versions are removed. Its kv, db and crdt data are the tenant's and stay. Its number stays used for good; deleting it frees the room it held at once (apps_full), and deploying it again needs room like a new app.
- Door: delete APP
- CLI: nanovm --json delete APP (or app delete APP)
- HTTP: DELETE /v1/apps/APP with If-Match: its generation
- Output: {"app":"web","deleted":true,"state":"deleted","generation":3,"grace_s":86400,"first":{"status":404,"ms":3},"message":"..."}
It answers once the URL answers 404 ("first"; null if not within 10 s). Deleting it again gives the same answer.
### logs
- Door: logs APP [-f]
- CLI: nanovm --json logs APP [-f] [--version V] [--limit N]
- HTTP: GET /v1/apps/APP/logs[?follow=1&version=V&limit=N]
- Output: One JSON object per line (NDJSON):
{"cursor":"5-9","start":true}
{"cursor":"5-10","ms":1710000000000,"vm":"1.6","version":1,"line":"listening on port 80"}
{"cursor":"5-11","missed":40} (lines dropped because this reader was slow: how many)
{"cursor":"5-12","end":true} (not with -f; a follower gets {"ping":MS} when quiet)
"ms" is the line's time in Unix milliseconds; "vm" is POOL.VM; "version" the app version that printed it.
### secret set / delete
Write-only secrets for an app. Secrets are injected into VMs; no API returns their values.
- Door: secret set APP NAME < value | secret delete APP NAME
- CLI: nanovm --json secret set APP NAME [GENERATION] < value | secret delete APP NAME [GENERATION]
- HTTP: PUT /v1/apps/APP/secrets/NAME {"value":"..."} | DELETE /v1/apps/APP/secrets/NAME
- APP need not exist yet: a set before its first deploy is kept for that name (no app slot; `apps` lists nothing), and that deploy starts with it.
- In the app: secrets.get(NAME) returns the value as of now (a change reaches a running VM at its next
lookup, with no redeploy). A name this app does not have throws "no secret NAME for this app".
Call secrets.get inside the handler, never at top level: top level runs once at build time, so a value read
there would be frozen into the snapshot and miss every later change. Pattern:
let secret; try { secret = secrets.get('NAME'); } catch (e) { secret = null; }
- Output: {"app":"web","name":"TOKEN","written":true,"secrets_generation":1} (delete: "deleted":true)
### db list / get / delete / export (your account's db from outside an app; owner key)
The same keys your apps' db sees, read strong, never another account's. APP is any app of yours, even deleted.
- Door: db list APP [PREFIX] [--after K] [--limit N] | db get APP KEY | db delete APP KEY | db export APP
- CLI: nanovm --json db VERB APP ...; any key (spaces too): db get|delete APP --body - with {"key":"..."} on stdin
- HTTP: POST /v1/apps/APP/db/list {"prefix","after","limit"} | db/get, db/delete {"key"} | db/export {"after"?}
- Output: list {"app","keys":[...],"next":KEY|null}; get {"app","v":N,"value":"..."} (not_found: no value);
delete {"app","deleted":true|false}; export: NDJSON {"key","v","value"} lines, last {"end":true,"keys":N}.
- These commands from outside an app, not an app's own db calls: 120 calls a minute an account (an export is 10), 2 at once: slow_down with retry_after_s, too_many_readers.
### retry (resend the last mutation whose outcome was unknown)
- Door: retry CLI: nanovm --json retry -> the definite server response, or {"pending":false,"message":"nothing pending"}
### domain add / ls / rm (Pro: your app at your own host name, over TLS; MCP domain_add, domains, domain_remove)
- Door: domain add APP HOST | domain ls | domain rm HOST CLI: nanovm --json domain ... HTTP: POST /v1/domains {"app","host"}, GET /v1/domains, DELETE /v1/domains/HOST
- add -> {"host","app","state","why","record":{"type":"CNAME","name":HOST,"value":"NAME.nma.sh"},"message"}: your human sets that record (a bare domain: type "A", value the server's address). HOST is served once the server sees its DNS point here and its certificate is issued; state is pending_dns, pending_cert, live, or failed with why. A host another account holds is domain_taken; a free account gets pro_only; 10 host names an account for its life, re-adding one is free (domains_full).
### rename APP NAME (Pro: a name you choose, NAME.sites.diy; MCP rename)
- Door: rename APP NAME CLI: nanovm --json rename APP NAME HTTP: POST /v1/apps/APP/rename {"name":"NAME"} — five or more letters, a-z, 0-9 and inner hyphens, at most thirty, filtered; once taken it is never another app's; the two-word URL and N-TENANT keep working; a free account gets pro_only and the upgrade line. The chosen name lives on sites.diy, never under nma.sh: nma.sh is the free, open-signup domain and its names are the two random words and N-TENANT.
- Door: backups APP | restore APP DATE (Pro; MCP backups, restore; HTTP GET /v1/apps/APP/backups, POST /v1/apps/APP/backups/DATE/restore): a daily copy of the app's db and kv, the last 7 UTC days; restore writes each key back as one new version, keys added since stay, and running it again finishes an interrupted one (CONTROL-API.md "Backups").
### keygen / login / keys / tenant (CLI; tenant and keys are MCP whoami, keys, keys_create, keys_revoke)
- Door: tenant | usage | keys | keys create ID ROLE | keys revoke ID | login ID < secret
- keygen: nanovm --json keygen -> {"secret":"<64hex>","key_hash":"<64hex>"}; login: nanovm --json login ID SECRET -> {"logged_in":true,"key":ID}
- tenant: nanovm --json tenant -> {"tenant":1,"key":65,"role":"owner","latest_idempotency_key":78,"apps_used":1,"apps_cap":2,"email":"none","plan":"free","pro":"...","claim_url":"..."} (email is "none", "pending" once a link is sent, or "verified" once your human confirms, when apps_cap goes to 5); usage: nanovm --json usage -> {"tenant":1,"meters":0,"requests":0,"ingress_bytes":0,"egress_bytes":0}
- keys: nanovm --json keys -> {"tenant":1,"keys":[{"id":65,"role":"owner","state":"live","generation":1}]}; keys revoke ID -> {"id":66,"state":"revoked","generation":2}
- keys create: nanovm --json keys create ID ROLE (ID an unused integer, ROLE owner, deployer or reader) -> {"id":66,"role":"deployer","tenant":1,"generation":1,"secret":"<64hex>"}
### verify / plan / upgrade / billing (owner key; MCP verify, plan, upgrade, billing)
- verify EMAIL -> {"email":"","sent":true,"expires_in_hours":24,"apps_after":5,"message":"..."} (already verified: {"email","verified":true,"sent":false}); plan -> {"plan":"free","apps_cap":2,"apps_used":1,"pro":{"price":"$5 a month","apps":10,"db_keys_a_group":12288,"db_bytes_a_group":50331648,"kv_keys":2048,"kept_idle":true},"free":{...},"grace_days":7,"pro_caps_left_s":0,"next":"..."}; upgrade -> {"plan":"pending","checkout_url":"https://checkout.stripe.com/...","price":"$5 a month","apps_after":10,"message":"..."} (on Pro: {"plan":"pro","already":true,"apps_cap":10,"message"}); billing -> {"portal_url","billing_email","message"}
### dash (your human's browser; MCP not needed)
- Door: dash | dash signout
- dash -> one line, https://nma.sh/dash#t=TOKEN: opening it signs that browser in to this account's dashboard with this key's role (a reader key gives a reader's view). It works once, within 5 minutes; the sign-in lasts 8 hours in that tab, takes no key id and no key slot, and works on a free account. Give the link to your human only; a second open says it was used. With --json: {"url":"...","role":"owner","expires_in_s":300,"session_s":28800}. A dashboard sign-in cannot make keys or links.
- dash signout (owner key) -> every browser signed in to this account is signed out at once; revoking the key that made a link does the same for its sign-ins.
### help
- Door: help [--json] -> {"commands":[{"command","usage","description"},...],"cli_only":"...","llms_txt":"/llms.txt"}: every door command; cli_only names the CLI's own (app, apps create, keygen, pack, dev).
## Error Codes and Fixes
Every error is one JSON object on stdout: {"error":{"code":"","message":"...","hint":"..."}}
"hint" is on the errors the CLI makes itself; the server's message says what to change. On nma.sh, run a Fix's nanovm COMMAND as ssh nma.sh COMMAND --json.
Exit codes: 0 done. 4 the server refused the request (any 4xx: compile_error, not_found, conflict, ..., and the door's account errors): change the request. 1 a 5xx, or a local problem (below). 2 usage. 3 a deploy whose first request answered 5xx: stdout is the deploy answer, with "first":{"status":500,...}; the version it replaced serves again ("status":"rolled_back", "serving"). 75 no answer: run it again.
### CLI Error Codes
- usage, unknown_command (exit 2): invalid arguments, or a command the SSH door does not know. Fix: nanovm help --json lists every command
- invalid (exit 2): a db key or prefix is over 512 bytes; (exit 4): not an email address, or the server's 400 unchanged. Fix: shorten the key, or send a real address
- unreachable (exit 75): no server answered. Fix: check network and server status, then run it again
- outcome_unknown (exit 75, or exit 1 when it cannot print): the change may have applied. Fix: nanovm retry
- pending_request, pending_key_mismatch (exit 1): an earlier change's outcome is unknown, or it belongs to another key. Fix: nanovm retry, or login with the key that started it
- corrupt_pending, corrupt_ikey, candidate_key_damaged (exit 1): that file in the creds dir is damaged. Fix: remove or repair it
- no_credentials (exit 1): no key in the creds dir. Fix: nanovm login ID SECRET_HEX
- creds_locked, invalid_creds_dir, creds_write_failed (exit 1): the creds dir is locked, is not a private absolute 0700 dir, or cannot be written. Fix: wait, or mkdir -p -m 0700 DIR; check permissions and disk space
- file_too_big, file_unreadable, request_too_long (exit 1): Body > 32 MiB or secret > 1024 bytes, a file cannot be read, or a header, body or path is too long. Fix: shrink it, check the path, shorten the request
- no_server, invalid_url (exit 1): no server URL, or --url is not IP:PORT. Fix: --url IP:PORT or export NANOVM_URL
- out_of_memory, entropy_failed, signup_no_key, generation_missing (exit 1): free memory, /dev/urandom failed, the sign-up answer had no key, or the app's answer had no generation. Fix: retry; nanovm deployments APP shows the app's versions
- internal_error (exit 1): a local failure with no code of its own; the message keeps the original text. Fix: read it, then report a bug
- pack_failed (exit 1): the directory or archive could not be packed; stderr has the reason. Fix: fix what it names, then deploy again
- no_account (exit 4): this SSH key has no account. Fix: signup [INVITE]
- account_exists, door_has_account (exit 4): this SSH key already has an account, and a door's key is never replaced. Fix: use apps or deploy; `keys create` and `login` from another SSH key attach a key; `tenant` shows the account
- invalid_invite (exit 4): the invite is not -. Fix: provide a valid invite
- missing_source, no_input (exit 4): no source on stdin; over SSH, no_input (exit 4) if nothing arrives on stdin for 30 s (the door does not wait forever while holding the key's lock). Fix: deploy APP < app.js, or send it with < FILE
- missing_name (exit 4): an archive needs the app's name. Fix: deploy APP < site.tar
- command_too_long (exit 4): the SSH command is too long. Fix: shorten it
- first request failed (exit 3): the new version's first request answered 5xx; the app's log lines are printed and "first" holds the status, and "error" the thrown error's first line when the runtime caught it (a runtime TypeError names what was called, as Node does: "crypto.nope is not a function"). (An auth.require(req) 401 with no session is exit 0, not exit 3: "first" holds status 401 and "note": the app asks for sign-in and a browser goes to /login.) The version it replaced serves again ("status":"rolled_back", "serving"); a first version stays live. Fix: fix the code and deploy again
### Server Error Codes
- unauthenticated (401): bad signature, missing auth, an unknown or revoked key, or X-NV-Date outside +-5 min. Fix: 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 data read). Fix: use a key with the role the route needs
- invalid_invite, invite_required, pro_only (403): the invite's tag is wrong, open sign-up is off, or a custom domain or backups is part of Pro (every app already has its own url). Fix: use the invite the server printed; nanovm upgrade starts Pro
- not_found (404): no such app, version, key, secret, data key, or name in this account; also this server does not build apps, has tree deploy off, keeps no logs, has no paid plan, or reaches no app data. Fix: check the name; for those six ask the operator
- not_available (404): email verification is off on this server: nothing was sent. Fix: tell your human this site has no mail
- no_billing (404): this account has never paid. Fix: nanovm upgrade starts Pro
- method_not_allowed, write_only (405): the wrong method on a known path, or a read of secrets. Fix: use the documented method; write secrets, never read them
- already_verified, email_taken (409): this account verified another email and keeps it, or that email verified another account. Fix: nanovm tenant shows "email":"verified" if this account is; one email verifies one account
- conflict (409): If-Match is not the current generation, the Idempotency-Key is older, the name or version is taken, or the app was deployed while its secret was written. Fix: read the generation for If-Match; for a name or slot take a new name or Idempotency-Key; for the secret race run the command again
- idempotency_key_reused (409): that Idempotency-Key named a different request. Fix: take a new key
- invite_used (409): the invite was already redeemed. Fix: obtain a new invite
- name_taken (409): a nameless deploy's generated name belongs to another app. Fix: retry with a new Idempotency-Key
- nothing_older, app_deleted (409): no older version to go back to, or a promote or rollback of a deleted app. Fix: deploy a new version, or deploy it again to bring it back
- domain_taken (409): another account has that hostname and it is served for them. Fix: nanovm domain rm HOST in that account first, or use another hostname
- version_gone (409 or 410): the version went with its app, or is older than the last 10 versions. Fix: deploy the source again
- apps_full (413): the account has its tier's apps at a time: 2 unverified, 5 with a verified email, 10 with Pro. Delete one and the 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. Every app also takes a number that is never reused (16 at most). Fix: ask your human for an email and run `nanovm verify EMAIL` (5 instead of 2), or run `nanovm upgrade` (10 with Pro); at 16 numbers, deploy a new version
- domains_full (413): the account has named all 10 custom domains it may ever have; a place is never given back. Fix: use a hostname it already holds; a domain removed before can be added again
- keys_full (413): every key id is used (3 an account, on every tier), and an id is never reused. Fix: nanovm keys revoke ID; an id is not given back
- too_large (413): the request body is over 32 MiB, a static tree over 27 MiB as an archive (its files at most 25 MiB in all, plus tar headers), or the compiled image is too large. Fix: make it smaller; about 6 MB of source deploys
- full (413, or the in-band full: from db.put or kv.put): the root group's table, a name's pending and app secret sets hold 17 entries (16 allowed), or a store every account shares is out of room. Fix: for a secret set delete one with `nanovm secret delete APP NAME`; for a shared store delete keys; for the root ask the operator
- compile_error (422): the compiler rejected the source; its diagnostic is the message. Fix: fix the code and deploy again
- if_match_required (428): a mutation needs If-Match: . Fix: read the generation and send it
- slow_down (429): a sign-up, deploy or data rate limit was reached, or a request was past the account's inbound limit. Fix: wait retry_after_s, also the Retry-After header
- rate_limited (429): 5 verify links an account and 3 an address a day. Fix: use the link already sent, or wait the minutes the message names
- too_many_readers (429): 4 log followers or 2 data readers are open for the account. Fix: close one, then retry
- internal_error (500), error (500, 503 or 504): a name could not be generated, a record does not decode, an answer is too long, or a dependency answered unexpectedly; error is the generic fallback. Fix: retry once; if it repeats, tell the operator
- checkout_failed, portal_failed (502): Stripe did not make the checkout or billing link. Fix: retry nanovm upgrade or nanovm billing later, or tell your human
- unavailable (503, or the in-band unavailable: from db.put or kv.put): a dependency is down and the message names it: root, S3, compiler, payment, mail or meter. Fix: 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. Fix: contact the operator, or try again later
- logs_unavailable (503), data_unavailable (200 on an export line, 503 otherwise): the log service or data plane did not answer, or its answer was malformed. Fix: retry; a db export that fails mid-stream is a 200 with a data_unavailable line: continue with after=
- busy (503, or the in-band busy: from db.put or kv.put): a data table or the account's share is busy; "not applied" means a plain retry is safe. Fix: retry when it has room
- warming (503): a deploy retry found its version committed but the pool is not ready. Fix: retry the same source
- outcome_unknown (504): the root group timed out; the command may have applied. Fix: 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. Fix: send the body the route documents; for version 64 delete the app (nanovm delete APP) and deploy again
- idempotency_key_required (400): a mutation with no key. Fix: send an integer that increases per key
- version_limit (400): an old-layout app holds its last version (64). Fix: nanovm delete APP, then deploy again
- quota (in-band, thrown by db.put, db.cas or kv.put): your account's share of a db group or kv is used. On nma.sh db: 10,000 keys and 40 MiB of values an account, as 5,000 keys and 20 MiB in each of its 2 groups (a key's group is its hash; a group holds 24,576 keys and 96 MiB across accounts); kv: 600 keys an account of 3,072 shared slots (3,071 keys after the first delete reserves one version-floor slot). Keys are at most 512 bytes, values 64 KiB. When Pro gives more the message ends with its price and `nanovm upgrade`; give your human the link. Fix: db.delete gives the value's bytes back at once, but not the key (rewrite the same key free, a new one is not); kv.delete gives both back; reuse key names
- unknown (in-band): no replica answered in time or a resend was refused; e.outcome is "unknown" and the write may have applied at most once. Fix: read the key with db.get before writing it again; two writes are not a retry
- crdt, db, db LIST, db PUT, db list, kvs, kvs LIST, kvs PUT, stale (in-band): a protocol diagnostic, not a stable code; the message names the bad op, cursor, prefix or limit. Fix: correct the call; a stale write id means read again
- exec_failed, mcp_timeout, mcp_child_failed, pack_failed (MCP tool errors): nanovm is not on PATH, the call stops after 300 s (its outcome is unknown), the child failed before answering, or the packer refused with its reason. Fix: fix what the message names; read deployments before retrying a deploy
- JSON-RPC errors (-32600, -32601, -32602): an invalid envelope or a request before initialize, an unknown method, or a bad tool name or arguments. Fix: send initialize, then tools/list for the schema
## Runtime Environment
- Engine: QuickJS (upstream 2026-11-02): modern JavaScript, interpreted.
- Snapshot execution:
Top-level code runs once at build time. Variables, imported modules, and functions declared
at top-level freeze into the microVM memory snapshot. Incoming HTTP requests execute the
handler registered with serve().
- Handler:
serve(req => { // req.method, req.path (with its query string: "/messages?n=20"), req.headers, req.body
return "Hello world"; // or { status: 200, contentType: "text/html", headers: {...}, body: "..." } // two Set-Cookie: headers: [["set-cookie", a], ["set-cookie", b]] or Headers.append
}); // a handler may return a Promise (setTimeout works)
Content-Length is optional: the platform sends the body's byte length, and drops a different one (logged as
"response dropped header: content-length"). HEAD: answer as for GET: the handler runs as HEAD first, and an app that answers HEAD keeps that answer; if that status is 404 or 405 the handler runs once more with a GET request (the same URL and headers, no body) and that answer's status and headers are sent, for no other method and no other status; the platform sends no body.
serve and console are globals (no require() needed; require('serve') throws MODULE_NOT_FOUND). An app's top-level export default { fetch(request, env, ctx) } is the other form and registers its fetch handler: request is a Request (request.url, .method, .headers a Headers, .text(), .json(), .formData(), .arrayBuffer(), .body, .clone(); request.path stays readable), env.NAME is the secret (as secrets.get(NAME)), ctx.waitUntil runs before the answer, and ctx.passThroughOnException is a no-op; use one form, not both.
Request properties:
- req.method: string, uppercase HTTP method ("GET", "POST", etc.)
- req.path: string, path with query string (e.g. "/items?k=v"); req.query is undefined (parse path if needed).
Parse it with URLSearchParams: const query = new URLSearchParams(req.path.split('?')[1] || ''); query.get('k')
- req.url: string, absolute ("https://HOST/items?k=v", http:// for a plain request); new URL(req.url) works, and a missing or malformed Host is localhost.
- req.headers: object with lower-case header names and string values. Every request header reaches your app (Authorization, Content-Type, Accept, Origin, X-*) except hop-by-hop ones, and any X-Forwarded-*, Forwarded, X-Real-IP or X-NV-* the visitor sent. Repeated names are joined with ", ".
host is the name the visitor used (its two words or N-TENANT, .nma.sh), and x-forwarded-proto and x-forwarded-host are set by the platform; on nma.sh x-real-ip and x-forwarded-for are the visitor's address, one value, set by the platform. Cookies reach you, except the platform's nv_tok and nv_dbt.
The header block is at most 8 KiB; past it a 431.
- req.body: string (always string, never Buffer or parsed). Empty body and GET give "". JSON remains unparsed string (use JSON.parse(req.body)). Non-UTF-8 bytes replace with \uFFFD.
JSON bodies: let data; try { data = JSON.parse(req.body); } catch (e) { return { status: 400, body: "invalid JSON" }; }
Form bodies (URLSearchParams is global): const form = new URLSearchParams(req.body); form.get('field')
await req.formData() parses the same body by its content-type into a FormData: a urlencoded body, or multipart (a part with a filename is a File; req.body stays readable); a bad body, a missing multipart boundary or any other content-type rejects with TypeError.
- crypto.getRandomValues(typedArray) (up to 65536 bytes) and crypto.randomUUID() are globals, from the hardware's randomness. require('crypto') has createHash, createHmac, randomBytes, randomFillSync, randomInt, randomUUID, getRandomValues, subtle, webcrypto, timingSafeEqual, pbkdf2 and pbkdf2Sync (digest sha1, sha256, sha384, sha512), but no scrypt: derive keys with one of those, or crypto.subtle.deriveBits({name: "PBKDF2", hash: "SHA-256", salt, iterations}, key, bits).
- Frozen values: top-level code runs once, before the snapshot. Math.random(), crypto.randomUUID(), crypto.getRandomValues() and Date.now() taken at top level are the same in every VM of a version; take them inside the handler.
- Logs: console.log and friends go to the app's logs.
- Node.js compatibility:
require() (with or without 'node:') has: path, events, util, querystring, url, assert, buffer, crypto,
stream, stream/promises, string_decoder, timers, timers/promises, os, util/types, assert/strict,
path/posix, path/win32, punycode, async_hooks, diagnostics_channel, perf_hooks, module, http, https,
worker_threads, inspector and vm. http and https have IncomingMessage, Agent, STATUS_CODES and METHODS;
their servers and requests, a Worker, a debugger and another realm throw ERR_NOT_AVAILABLE. Not fs, net or
child_process: serve() is the server, and there is no file system. Anything else throws MODULE_NOT_FOUND
when the app is built. One file, no npm install: bundle dependencies into app.js.
- Data Plane APIs:
kv, db, crdt and secrets are globals on globalThis (no require() needed; require('kv') throws MODULE_NOT_FOUND).
- kv: Fast key-value store, cached at the edge. kv.delete(key) -> true if it held a value, else false; kv.list as db.list without reverse (eventual).
kv.get(key, [{consistency: "session"|"eventual"}]) -> string | null
kv.put(key, value) -> v (the key's new version, a number)
kv.token() -> string (causal consistency token)
- db: Sharded transactional store with compare-and-swap.
db.get(key, [{consistency: "session"|"eventual"|"strong"}]) -> string | null
db.put(key, value) -> v (the key's new version, a number)
db.getv(key) -> {value: string, v: number} | null. db.token() -> string
db.cas(key, expected_v, new_value) -> the new v, or null if the key moved on (read again and retry)
db.cas(key, 0, value) creates a key that does not exist yet, or was deleted (null if it holds a value)
db.delete(key) -> true if it held a value (now it reads null), else false. db.cas(key, v, undefined) -> true or null
db.list(prefix, [{limit: 1..1000 (100), after, reverse}]) -> {keys, next}: key order, strong; reverse: true is descending and after means below it; next (or null) is the next after. The second argument is one object as shown, never an array (kv.get, db.get and db.getv take theirs the same way): db.list("msg:", { limit: 50, after: next })
- crdt: conflict-free counters and registers.
const c = crdt.counter(name); c.add(1); c.value() -> number
const r = crdt.register(name); r.set(val); r.get() -> string
Data belongs to the tenant, not the app: every app of one account sees the same kv, db and crdt names, so an admin app reads what an orders app wrote. Keep apps apart with a prefix ("orders:").
Prefix names with the app's ("notes:42", not "42"). Values are strings: put(key, null) stores "null". db.put, db.cas and kv.put stringify any value as String(v) does: JSON.stringify an object or number yourself.
Data survives a redeploy, a rollback, a VM's restart and the app's delete. There is no restart command: any request may
land in a VM newly restored from the snapshot, so keep state in kv, db or crdt, never in top-level variables.
- Network: await fetch(url, init) -> Response (text(), json(), arrayBuffer()), made by the host: https:// on 443 only.
Apps on nma.sh, yours or anyone's (https://WORD-WORD.nma.sh/, https://N-TENANT.nma.sh/), answer as a browser sees
them (no X-Real-IP), in the same rate; a chain of apps fetching apps stops after 4 with "fetch refused: loop".
Every other host must be public (private, loopback, link-local, CGNAT, metadata 169.254.169.254 and the host's
own are refused, at every redirect too, 5 at most); a refusal is TypeError "fetch refused: ". No raw TCP/UDP.
- Secrets: secrets.get(NAME) reads this app's own secret, set with 'secret set'; no other app or tenant sees it.
Call it inside the handler (see "secret set" above for the pattern).
## Limits
- Max apps per account: 2 at a time unverified, 5 with a verified email, 10 with Pro (delete one and its room is freed at once). Separately, every app an account creates takes a lifetime app number, deleted apps included, on every tier: never reused, 16 at most
- Max secret value length: 1024 bytes
- App name syntax: [a-z0-9-]{1,31}
- Secret name syntax: [A-Z0-9_]{1,32}
- db and kv, an account's share: db: 10,000 keys and 40 MiB of values an account, as 5,000 keys and 20 MiB in each group (a key's group is its hash); kv: 600 keys an account of 3,072 shared slots; keys are at most 512 bytes, values 64 KiB
- Request body to an app: at most 64 KiB; a larger one is a 413 ("the request was refused").
- Request headers: at most 8 KiB; a larger block is a 431.
- Set-Cookie is host-only: a Set-Cookie with a Domain attribute is dropped, so an app cannot set cookies for other apps or nma.sh; on a Pro custom domain, Domain= that domain's own host is kept.
- fetch(): 10 a second per app (burst 20), 4 at once per app, 8 per account; 1.5 s each, redirects included (a request has 2 s in all); response
body 256 KiB, request body 48 KiB, URL and headers 16 KiB. Past each: TypeError saying which. One log line each.
- Inbound: 8 requests in flight per account (64 on Pro), and VM time 0.1 core a second with a 30 s bank; a burst waits up to 250 ms (64 queued, 256 on Pro), then slow_down (429) with retry_after_s (also Retry-After). Nothing built in stops form spam or limits one visitor: do it in your handler, keyed on req.headers["x-real-ip"] in kv or db.
- Path and query string: at most 255 bytes; a longer one is a 414.
- Source per deploy: about 6 MB (the CLI itself sends at most 32 MiB)
- Response: 1 MiB, headers included (past it a 502 that says so); an answer over 16,128 bytes arrives whole too (the edge then ends its own connection; on nma.sh yours stays alive)
- Logs: a VM's log stops at 1 MiB; the last 16 stopped VMs' logs are kept. Max concurrent log readers: 4 per tenant
- A handler that never returns is stopped: a request's handler has 2 s of CPU in all (DP_WP_LEASE_MS); past it the app's instance is stopped, the request gets a 504 naming this limit (the outcome is unknown), and the handler's console output before the stop is kept in `logs`. An unverified account's apps nobody uses (no real request and no deploy) may be deleted after 30 days; a verified or Pro account's are kept.
Framework projects (prebuilt, deployed as a directory)
----------------------------------------------------------
Install nanovm-framework beside the CLI (~/.nanovm/nanovm-framework); run npm ci in that directory once.
Local preparation requires Node >=22.12 and locked esbuild 0.25.12; framework builds keep their own Node requirements and standard target configuration. Missing Node prints "framework bundling requires Node >=22.12 on PATH" before upload.
Build with the framework's own command (below), then from the project directory nanovm pack . | ssh nma.sh deploy APP --json (nanovm deploy APP . needs --url, the operator's own network); no nanovm config, bundle flags, custom adapter or runtime polyfill.
nanovm dev . previews that tree; rerun after rebuilding. Deploy prints detection on stderr (the prints: text below), then the normal build/first-request/live URL result (or --json).
Hono (Cloudflare Workers starter): npx wrangler deploy --dry-run --outdir dist prints: nanovm: framework hono; dist/index.js
Astro (official @astrojs/cloudflare, output: 'server'): npm run build prints: nanovm: framework astro; dist/server/entry.mjs
SvelteKit (official @sveltejs/adapter-cloudflare): npm run build prints: nanovm: framework sveltekit; .svelte-kit/cloudflare/_worker.js
React Router (Web server target): npm remove @react-router/node @react-router/serve && npm run build prints: nanovm: framework react-router; build/server/index.js
Nuxt (Nitro Cloudflare module target): NITRO_PRESET=cloudflare-module npm run build prints: nanovm: framework nuxt; .output/server/index.mjs
SolidStart (Nitro Cloudflare module target): NITRO_PRESET=cloudflare-module npm run build prints: nanovm: framework solidstart; .output/server/index.mjs
Analog (Nitro Cloudflare module target; disable prerendering for dynamic routes): NITRO_PRESET=cloudflare-module npm run build prints: nanovm: framework analog; dist/analog/server/index.mjs
TanStack Start (Nitro Cloudflare module target): NITRO_PRESET=cloudflare-module npm run build prints: nanovm: framework tanstack-start; .output/server/index.mjs
Qwik (official cloudflare-pages integration): npm run build prints: nanovm: framework qwik; server/entry.cloudflare-pages.js
Vike (production build, Vike's vike/fetch handler; deprecated upstream in the tested release): npm run build prints: nanovm: framework vike; dist/server/entry.mjs
Remix v2 (official Cloudflare template): npm run build prints: nanovm: framework remix; build/server/index.js
Next.js (App Router, Node runtime, through OpenNext; needs @opennextjs/cloudflare): npx opennextjs-cloudflare build prints: nanovm: framework next; .open-next/worker.js
Works: server-rendered and static pages, route handlers, Server Actions, cookies(), streaming, client navigation.
Set cacheComponents: false in next.config (create-next-app turns it on; its pages never answer here, and deploy refuses it).
next/image: set images: { unoptimized: true }; /_next/image answers 404. fetch() is the platform's (above).
The edge runtime is not supported. A Next project without OpenNext is refused with the build command above. A Next app's server code
takes most of an app's memory: the fixture loads in 49 MB of about 64 MiB, so a much larger app may not load.
These targets use Request/Response handlers. Node listening servers, non-HTTPS outbound,
Cloudflare services (R2, D1, service bindings) and arbitrary filesystem access are unsupported.
Static assets go in public/ and serve from the edge without a VM. nanovm pack . > app.tar
emits the same tree for SSH stdin, POST /v1/apps/APP/deploy-tree, and MCP directory deploys.
Bundle errors stop before upload; fix framework build errors before deploying.
A bundle that throws while loading: deploy's build lines print the error, the first request answers 503
(exit 3), and the version it replaced serves again. The tree's limits are checked before upload, with the number: 1000 files,
5 MiB a file (app.js included), 25 MiB in all. deploy takes a JavaScript file, a directory with app.js
and an optional public/, a static site (index.html and no app.js), or a built framework project above.
ctx.waitUntil(promise): the answer is sent once every waitUntil promise has settled, those
registered while others ran too (within the request's time limit).
To the framework, request bodies are strings: text, JSON and forms work; binary uploads do not yet.
In a framework build, _headers, _redirects and _routes.json at the top of the assets are not applied (stderr names
each one); source maps of scripts and styles (.js.map, .mjs.map, .css.map) are not deployed.
Workers targets get local ASSETS.fetch and VM-local caches.open/default with match/put/delete
(8 MiB charged storage, 128 responses, 32 names; old entries may evict). Copies respect Vary
and freshness; private/no-store and Set-Cookie responses are skipped. No cross-VM persistence,
network add/addAll, CacheStorage enumeration/deletion, or conditional/range cache support.
Direct static requests still bypass the VM at the edge.
# nma.sh recipes
https://nma.sh/llms.txt is the whole guide.
Patterns built from what every app has (runtime.txt): db, kv, crdt, secrets, auth and fetch(). Copy and adapt.
## A form inbox your human can read (a contact form, sign-ups, orders)
Store each submission in db, one key per entry, keys sorted by time:
serve(async req => {
if (req.method === "POST") {
const f = new URLSearchParams(req.body); // an HTML form's body; JSON: JSON.parse(req.body)
db.put("msg:" + Date.now() + ":" + crypto.randomUUID(),
JSON.stringify({ name: f.get("name"), text: f.get("text"), at: new Date().toISOString() }));
try { // tell your human (see Notifications below)
await fetch("https://ntfy.sh/" + secrets.get("NTFY_TOPIC"), { method: "POST", body: "New message from " + f.get("name") });
} catch (e) { console.log("notify failed: " + e); } // the entry is kept either way
return { status: 303, headers: { location: "/thanks" }, body: "" };
}
return { contentType: "text/html", body: '' };
});
Your human reads them in a browser at /inbox, behind a password you keep as a secret (secret set APP
INBOX_PASSWORD < pw.txt; tell them the password, user "me"). Add this before the POST branch:
if (req.path.split("?")[0] === "/inbox") {
let pw; try { pw = secrets.get("INBOX_PASSWORD"); } catch (e) { pw = null; } // not set yet: 401, not a 500
if (!pw || req.headers["authorization"] !== "Basic " + btoa("me:" + pw))
return { status: 401, headers: { "www-authenticate": 'Basic realm="inbox"' }, body: "password needed" };
const esc = s => String(s ?? "").replace(/[&<>"]/g, c => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
const { keys } = db.list("msg:", { limit: 100 }); // oldest first; { after: KEY } pages
return { contentType: "text/html", body: "Inbox
" + keys.reverse().map(k => {
const m = JSON.parse(db.get(k)); return `${esc(m.name)} ${esc(m.at)}
${esc(m.text)}
`; }).join("") };
}
Escape what visitors wrote (esc above), or a message can run script in your human's browser.
Or your human's agent reads them from outside the app with the owner's key:
ssh nma.sh db list APP msg: --json # newest last; --after KEY to page
ssh nma.sh db export APP --json # every key as NDJSON, for a spreadsheet or a script
Ask your human how they want to hear about new entries, then add one of the notifications below.
## Notifications to your human (new form entry, a sale, an error)
Call their own service from the handler with fetch(); keep any token in a secret.
- Chat: a Slack, Discord or Google Chat incoming-webhook URL, stored with secret set APP HOOK_URL:
await fetch(secrets.get("HOOK_URL"), { method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ text: "New message from " + f.get("name") }) });
(Discord wants { content: ... } instead of { text: ... }.)
- Phone push: ntfy.sh, no account needed: pick a hard-to-guess topic, store it as a secret, and your human
subscribes to it in the ntfy app:
secret set APP NTFY_TOPIC < topic.txt; then fetch("https://ntfy.sh/" + secrets.get("NTFY_TOPIC"), { method: "POST", body: "..." })
- Telegram: a bot token and chat id as secrets; POST https://api.telegram.org/bot/sendMessage.
- Email: your human's own mail provider account (Resend, Postmark, SendGrid, Mailgun), with its API key in a
secret, through its HTTPS API. Mail to your users (sign-up, password reset) works the same way, from your
human's own sending domain.
Notify after the db write, so an entry is kept even if the notification fails; keep the fetch short (fetch()
has 1.5 s), and a burst of entries can share one notification (count them in a crdt counter, notify every Nth).
## An admin view
- Whole app behind a password: secret set APP NV_BASIC_AUTH < pw.txt ("PASSWORD" or "USER:PASSWORD").
- One path: compare req.headers.authorization with "Bearer " + secrets.get("ADMIN_TOKEN").
- A sign-in page: /examples/admin-page.js on this site, the whole app (a session cookie signed with a secret).
## Sign-in for your users
The runtime has it: three lines, and no setup. With no AUTH_SECRET the first use makes 32 random bytes once at db key
auth$key; secret set APP AUTH_SECRET < key.txt overrides it. Paste:
// signin:start
const r = auth.handle(req); if (r) return r; // /signup /login /logout /recover /reset, GET form or POST change
const u = auth.user(req); // null, or { id, user, db, kv }
if (u) u.db.put("notes:" + Date.now() + ":" + crypto.randomUUID(), req.body || ""); // u.db/u.kv keys are scoped to this user
// signin:end
The five pages are fixed: no title, logo, CSS or HTML option exists, and each says "Sandbox sign-in for HOST, hosted on
nma.sh" with the request's host escaped. A copied password page is worthless to a phisher, and nma.sh never sends mail.
Your own look: serve your own page from any route; a form that POSTs user and pass to /login signs in (303 to / with the cookie);
/signup signs in too and answers 200 with the recovery code; /recover (user, code, new) does not sign in. The fixed pages are only a default.
Sign-up returns a one-time recovery code (shown once; stored hashed): POST /recover with user, code and a new password,
and the answer shows a new one-time code (the old one is dead). Passwords are PBKDF2-SHA256, salted, stored hashed only;
log-in and recovery tries are limited per account in kv (10 per 15 minutes, 429 with Retry-After). The session is a
signed nv_auth cookie (HttpOnly; Secure; SameSite=Lax; Path=/) that also works as Authorization: Bearer , so curl
needs no cookie jar. Send a JSON body or Accept: application/json and every route answers JSON (signup:
{"ok":true,"user":...,"token":...,"recovery":...}; login: no recovery; recover: {"ok":true,"user":...,"recovery":...}; a refusal: {"error":"auth: ..."} with the same status); a JSON login
is 200 with the token, not a 303. A browser gets HTML, and a recovery code appears only inside the page. A password
change (/recover or /reset) and auth.logoutAll(user) bump the account's credential generation, so every token issued
before them stops working; otherwise a token lives 24 h. No email is ever sent.
For an admin view, auth.admin(req) checks Authorization: Bearer . auth.resetLink(user) mints a signed,
expiring (10 minutes) /reset?user=U&exp=E&sig=S link bound to the credential generation, so it works once (show it to
your human; POST the new password, a GET only shows a form), and auth.deleteUser(user) deletes the account and pages
through its keys. Keys under u.db/u.kv are prefixed u::, and list() strips the prefix and returns only that user's
keys; a deleted and re-registered name gets a new id and sees none of the old data. Keys starting auth$ and u$: are the
runtime's (auth$key signs sessions, u$: holds accounts): never read, write or list them. Errors name the fix
("auth: user exists: POST /login instead").
## Webhooks in (Stripe, GitHub, Telegram)
Check the sender's signature with crypto.subtle and the signing secret from secrets; answer 200 quickly and do
the rest after the db write. Write with db.cas on the event id to make retries harmless.
## Scheduled work (there is no cron)
An app runs only when an HTTP request arrives; top-level code runs once at build time and there is no background timer. Keep state in kv, db or crdt, and keep each job inside one request's 2 s CPU limit (past 2 s the instance is stopped and the request gets a 504).
- Outside scheduler: a GitHub Actions `schedule:` workflow or any cron service POSTs to a route guarded by an app secret (`ssh nma.sh secret set APP CRON_SECRET < secret.txt`). Call secrets.get inside the handler and compare before doing the work:
if (req.method === "POST" && req.path.split("?")[0] === "/cron") {
let tok; try { tok = secrets.get("CRON_SECRET"); } catch (e) { tok = null; }
if (!tok || req.headers["authorization"] !== "Bearer " + tok)
return { status: 401, body: "unauthorized" };
// do scheduled work here
return { status: 200, body: "ok" };
}
- Lazy work on the next request: store the last run time in kv (prefixed with the app name) and do the job when it is older than the period:
const now = Date.now(), last = Number(kv.get("app:last_run", { consistency: "session" }) || 0);
if (now - last >= 3600 * 1000) {
kv.put("app:last_run", String(now));
// do scheduled work here
}
## Rate-limit a public form
Nothing built in limits one visitor. On nma.sh, `x-real-ip` (and `x-forwarded-for`) is the visitor's address, one value, set by
the platform (an `X-Real-IP` the visitor sent is stripped; app-to-app `fetch()` on nma.sh gets none). Count POSTs a minute
per address in 64 fixed kv keys, so the keys used never grow with the number of visitors (kv: 600 keys an account), and
answer 429 with Retry-After:
function hit(ip, limit) { // false when ip is past limit POSTs this minute
let h = 0; for (const c of ip) h = (h * 31 + c.charCodeAt(0)) >>> 0;
const key = "rl:" + (h % 64), win = Math.floor(Date.now() / 60000);
let b = JSON.parse(kv.get(key, { consistency: "session" }) || "null");
if (!b || b.w !== win) b = { w: win, n: {} }; // a new minute starts every bucket empty
b.n[ip] = (b.n[ip] || 0) + 1;
kv.put(key, JSON.stringify(b));
return b.n[ip] <= limit;
}
if (req.method === "POST" && !hit(req.headers["x-real-ip"] || "unknown", 10))
return { status: 429, headers: { "retry-after": String(60 - Math.floor(Date.now() % 60000 / 1000)) }, body: "slow down" };
## Counters, likes, leaderboards
crdt counters take concurrent increments from every request without conflicts; keep a sorted view in db
(top:SCORE:USER keys, db.list with reverse) and refresh it on write.