# 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.