dropto.run docs
Guides

Build an app with sign-in

This guide builds a small notes app from nothing: people create an account, sign in, write notes only they can see, and sign out. It has the three parts any app with accounts has —

  • pages the browser loads: plain HTML, CSS and JavaScript, with no build step;
  • an API the pages call: functions under _functions/, one file per route;
  • sign-in: passwords hashed with PBKDF2, sessions kept in the site's store, and a cookie the page's own script cannot read.

All of it is one folder, published in one step, and it rolls back as one version. There is no server to keep running and no database to sign up for. The code here is complete — copy the files as they are and the app works.

You need a plan that includes functions and a store; Pricing lists which do. Functions run only on the site's live address, so you test by publishing, not on localhost.

The folder

Code
notes-app/ ├─ index.html ├─ app.js ├─ style.css └─ _functions/ ├─ _lib/ │ ├─ auth.js passwords, sessions, the cookie │ └─ http.js reading a JSON body, answering an error └─ api/ ├─ signup.js POST /api/signup ├─ login.js POST /api/login ├─ logout.js POST /api/logout ├─ me.js GET /api/me ├─ notes.js GET /api/notes POST /api/notes └─ notes/ └─ [id].js DELETE /api/notes/:id

Everything outside _functions/ is served as a file. Everything inside it is code that runs on the server side and is never served — /_functions/api/login.js answers 404. A folder starting with _, like _lib, holds modules the routes import and is not a route itself.

What the store holds

The store keeps text values under text keys, and finds them two ways: by exact key, or by listing every key that starts with a prefix. There are no queries by value, so the keys are the schema. Decide them first:

KeyValue
user:<email>The account: an id, the address, the password's salt and hash
claim:<email>A counter that is 1 once an address is taken
session:<digest>Who a session belongs to and when it ends — keyed by a hash of the token
attempts:<email>Failed sign-ins in the last 15 minutes
note:<userId>:<id>One note

Two choices in that table do the security work later on. A note's key starts with its owner's id, so a list of one account's notes is a prefix that cannot reach anybody else's. And a session is stored under a hash of its token, not the token itself, so an export of the store holds nothing anybody could sign in with.

Shared code

Two helpers every route imports. The first reads a JSON body, and only a JSON body:

JavascriptCode
// _functions/_lib/http.js // Small helpers every route shares. A file under _lib/ is a module the routes import, never a route itself. /** * Reads a JSON body, or null when the request did not send one. * * Requiring `Content-Type: application/json` is part of the defence against cross-site requests: a plain HTML * form on another site cannot send that type, and a script on another origin cannot send it without a CORS * preflight this site never answers. */ export async function readJson(request) { const type = request.headers.get("content-type") ?? ""; if (!type.startsWith("application/json")) return null; try { const body = await request.json(); return body !== null && typeof body === "object" ? body : null; } catch { return null; } } /** A JSON error answer with a short machine-readable code and a message a person can read. */ export function problem(status, error, message, headers = {}) { return Response.json({ error, message }, { status, headers }); }

Requiring Content-Type: application/json is not fussiness. A form on someone else's page can post to your site, but it cannot send that type; a script on another origin can only send it after a CORS preflight, which these routes never answer. Together with the cookie below, that is what stops another site from acting as a signed-in visitor.

The second is everything about accounts:

JavascriptCode
// _functions/_lib/auth.js // Passwords, sessions and the cookie that carries a session, for every route under api/. // // What the store holds: // user:<email> {"id","email","salt","hash","iterations","created"} // session:<digest> {"userId","email","expires"} — keyed by a SHA-256 of the token, never the token itself // attempts:<email> {"window","count"} — failed sign-ins in the current 15 minutes /** PBKDF2 rounds. About 20 ms of CPU, which fits a function's 50 ms budget with room for the rest of the call. */ const ITERATIONS = 100_000; /** How long a session lasts. */ const SESSION_SECONDS = 30 * 24 * 60 * 60; /** The cookie's name. `__Host-` makes the browser refuse it unless it is Secure, has Path=/ and no Domain. */ export const COOKIE = "__Host-session"; /** Failed sign-ins allowed for one address in one window. */ const MAX_ATTEMPTS = 10; /** The window failed sign-ins are counted in. */ const ATTEMPT_WINDOW_MS = 15 * 60 * 1000; const encoder = new TextEncoder(); /** Bytes to URL-safe base64 with no padding. */ function toBase64Url(bytes) { let binary = ""; for (const byte of bytes) binary += String.fromCharCode(byte); return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); } /** URL-safe base64 back to bytes. */ function fromBase64Url(text) { const binary = atob(text.replaceAll("-", "+").replaceAll("_", "/")); return Uint8Array.from(binary, (char) => char.charCodeAt(0)); } /** Compares two byte arrays in time that does not depend on where they first differ. */ function sameBytes(a, b) { if (a.length !== b.length) return false; let difference = 0; for (let i = 0; i < a.length; i++) difference |= a[i] ^ b[i]; return difference === 0; } /** PBKDF2-SHA-256 of a password. */ async function derive(password, salt, iterations) { const key = await crypto.subtle.importKey("raw", encoder.encode(password), "PBKDF2", false, ["deriveBits"]); const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", salt, iterations }, key, 256); return new Uint8Array(bits); } /** A stored password check for an address nobody signed up with, so a wrong address costs the same time. */ const NOBODY = { salt: "AAAAAAAAAAAAAAAAAAAAAA", hash: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", iterations: ITERATIONS }; /** An email address as it is stored and compared: trimmed and lowercase, or null when it is not one. */ export function normalEmail(value) { if (typeof value !== "string") return null; const email = value.trim().toLowerCase(); return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : null; } /** Whether a password is one this app accepts. */ export function acceptablePassword(value) { return typeof value === "string" && value.length >= 8 && value.length <= 200; } /** Creates the stored record for a new account. */ export async function newUser(email, password) { const salt = crypto.getRandomValues(new Uint8Array(16)); const hash = await derive(password, salt, ITERATIONS); return { id: crypto.randomUUID(), email, salt: toBase64Url(salt), hash: toBase64Url(hash), iterations: ITERATIONS, created: new Date().toISOString(), }; } /** Whether a password matches a stored account, or the dummy one when `user` is null. */ export async function passwordMatches(password, user) { const record = user ?? NOBODY; const hash = await derive(password, fromBase64Url(record.salt), record.iterations); return user !== null && sameBytes(hash, fromBase64Url(record.hash)); } /** The store key of a session: a digest, so an exported store holds no token anybody could sign in with. */ async function sessionKey(token) { const digest = await crypto.subtle.digest("SHA-256", encoder.encode(token)); return `session:${toBase64Url(new Uint8Array(digest))}`; } /** Starts a session for an account and answers the `Set-Cookie` header that hands it to the browser. */ export async function startSession(store, user) { const token = toBase64Url(crypto.getRandomValues(new Uint8Array(32))); const expires = Date.now() + SESSION_SECONDS * 1000; await store.put(await sessionKey(token), JSON.stringify({ userId: user.id, email: user.email, expires })); return `${COOKIE}=${token}; Path=/; Max-Age=${SESSION_SECONDS}; Secure; HttpOnly; SameSite=Strict`; } /** Reads one cookie from a request. */ function readCookie(request, name) { for (const part of (request.headers.get("cookie") ?? "").split(";")) { const [key, ...value] = part.trim().split("="); if (key === name) return value.join("="); } return null; } /** The signed-in account behind a request, as `{ userId, email }`, or null. */ export async function currentUser(request, store) { const token = readCookie(request, COOKIE); if (!token) return null; const key = await sessionKey(token); const raw = await store.get(key); if (raw === null) return null; const session = JSON.parse(raw); if (session.expires < Date.now()) { // The store keeps a key until it is deleted, so an expired session is removed the first time it is seen. await store.delete(key); return null; } return { userId: session.userId, email: session.email }; } /** Ends the request's session, if any, and answers the `Set-Cookie` header that clears the cookie. */ export async function endSession(request, store) { const token = readCookie(request, COOKIE); if (token) await store.delete(await sessionKey(token)); return `${COOKIE}=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Strict`; } /** Whether an address has used up its failed sign-ins for now. */ export async function tooManyAttempts(store, email) { const raw = await store.get(`attempts:${email}`); if (raw === null) return false; const { window, count } = JSON.parse(raw); return Date.now() - window < ATTEMPT_WINDOW_MS && count >= MAX_ATTEMPTS; } /** Counts one failed sign-in for an address, starting a new window when the last one is over. */ export async function countFailedAttempt(store, email) { const raw = await store.get(`attempts:${email}`); const now = Date.now(); const last = raw === null ? null : JSON.parse(raw); const next = last !== null && now - last.window < ATTEMPT_WINDOW_MS ? { window: last.window, count: last.count + 1 } : { window: now, count: 1 }; await store.put(`attempts:${email}`, JSON.stringify(next)); } /** Forgets an address's failed sign-ins, after one that succeeded. */ export async function clearAttempts(store, email) { await store.delete(`attempts:${email}`); }

What each part is for:

  • PBKDF2 at 100,000 rounds. A password is never stored, only a salted hash that is slow to compute, so a copy of the store does not hand over passwords. OWASP's guidance for PBKDF2-SHA-256 is 600,000 rounds, but a function has 50 ms of CPU a call, and 600,000 rounds is several times that. 100,000 measured about 20 ms, which leaves room for the rest of a sign-in. If your plan gives a function more CPU, raise ITERATIONS: each stored account keeps the count it was hashed with, so old passwords keep working.
  • crypto.subtle, not an npm package. Functions run on the Web Crypto API that browsers have; Node's crypto module is not there, and nothing here needs it.
  • __Host-session. The __Host- prefix makes the browser refuse the cookie unless it is Secure, has Path=/ and names no Domain — so it belongs to your site's exact address and no other site under dropto.live can set or overwrite it. HttpOnly keeps it out of reach of the page's JavaScript, and SameSite=Strict keeps the browser from sending it with a request another site starts.
  • The dummy record. Signing in with an address that has no account still runs a full PBKDF2, against a record that can never match. Without it, "no such account" would answer 20 ms faster than "wrong password", and anybody could tell which addresses have accounts.
  • Expired sessions are deleted when they are read. The store has no expiry of its own, so a session past its date is removed the first time it shows up. One nobody comes back with stays until you delete it.

Creating an account

JavascriptCode
// _functions/api/signup.js // POST /api/signup — creates an account and signs it in. Body: {"email","password"}. import { acceptablePassword, newUser, normalEmail, startSession } from "../_lib/auth.js"; import { problem, readJson } from "../_lib/http.js"; export async function onRequestPost({ request, store }) { const body = await readJson(request); const email = normalEmail(body?.email); if (email === null) return problem(400, "invalid_email", "Enter an email address."); if (!acceptablePassword(body.password)) { return problem(400, "invalid_password", "Use a password of 8 to 200 characters."); } // Two sign-ups for one address at the same moment would both see no account with a get, and the second put // would replace the first. incr adds in one step, so exactly one of them gets 1 back. if ((await store.incr(`claim:${email}`)) !== 1) { return problem(409, "email_taken", "There is already an account with that address. Sign in instead."); } const user = await newUser(email, body.password); await store.put(`user:${email}`, JSON.stringify(user)); const cookie = await startSession(store, user); return Response.json({ email }, { status: 201, headers: { "Set-Cookie": cookie } }); }

The incr is the interesting line. The obvious check — get the account, and put one if there is none — has a gap: two sign-ups for the same address arriving together both see nothing and both write, and the second one replaces the first. incr adds in one step, so of two calls at the same moment exactly one gets 1. Reach for it whenever "only the first one wins" matters.

Signing in and out

JavascriptCode
// _functions/api/login.js // POST /api/login — signs in. Body: {"email","password"}. import { clearAttempts, countFailedAttempt, normalEmail, passwordMatches, startSession, tooManyAttempts, } from "../_lib/auth.js"; import { problem, readJson } from "../_lib/http.js"; export async function onRequestPost({ request, store }) { const body = await readJson(request); const email = normalEmail(body?.email); if (email === null || typeof body.password !== "string") { return problem(400, "invalid_request", "Enter your email address and password."); } if (await tooManyAttempts(store, email)) { return problem(429, "too_many_attempts", "Too many wrong passwords. Try again in 15 minutes.", { "Retry-After": "900", }); } const raw = await store.get(`user:${email}`); const user = raw === null ? null : JSON.parse(raw); // Checked against a dummy record when there is no account, so "no such address" and "wrong password" take // the same time and read the same — neither tells a stranger which addresses have accounts. if (!(await passwordMatches(body.password, user))) { await countFailedAttempt(store, email); return problem(401, "wrong_credentials", "That email address and password do not match."); } await clearAttempts(store, email); const cookie = await startSession(store, user); return Response.json({ email }, { headers: { "Set-Cookie": cookie } }); }

Ten wrong passwords for one address hold it for 15 minutes, which turns guessing into years of work. The same answer for "no such address" and "wrong password" is deliberate, for the reason the dummy record exists.

JavascriptCode
// _functions/api/logout.js // POST /api/logout — ends the session and clears the cookie. import { endSession } from "../_lib/auth.js"; export async function onRequestPost({ request, store }) { const cookie = await endSession(request, store); return new Response(null, { status: 204, headers: { "Set-Cookie": cookie } }); }
JavascriptCode
// _functions/api/me.js // GET /api/me — who is signed in, or 401. import { currentUser } from "../_lib/auth.js"; import { problem } from "../_lib/http.js"; export async function onRequestGet({ request, store }) { const user = await currentUser(request, store); if (user === null) return problem(401, "signed_out", "Sign in first."); return Response.json({ email: user.email }); }

Signing out deletes the session from the store, not just the cookie from the browser. A copied cookie stops working the moment its owner signs out.

Notes

JavascriptCode
// _functions/api/notes.js // GET /api/notes?after=<cursor> — the signed-in account's notes, newest first, 50 at a time. // POST /api/notes — adds a note. Body: {"text"}. import { currentUser } from "../_lib/auth.js"; import { problem, readJson } from "../_lib/http.js"; /** Notes a page returns. One list, one get per note and one session read stay well under 100 store calls. */ const PAGE = 50; /** The longest note, in characters. A value may be 64 KB; this app keeps notes short. */ const MAX_TEXT = 2000; export async function onRequestGet({ request, store }) { const user = await currentUser(request, store); if (user === null) return problem(401, "signed_out", "Sign in first."); // Every key starts with the account's own id, so a list can only ever see that account's notes. const prefix = `note:${user.userId}:`; // The cursor is the last key of the previous page. The prefix bounds a list whatever the cursor says, so this // check is only there to turn a mangled one into the first page rather than an error. const after = new URL(request.url).searchParams.get("after"); const cursor = after?.startsWith(prefix) ? after : null; const page = await store.list({ prefix, cursor, limit: PAGE }); const notes = await Promise.all(page.keys.map(async ({ key }) => JSON.parse(await store.get(key)))); return Response.json({ notes, next: page.cursor }); } export async function onRequestPost({ request, store }) { const user = await currentUser(request, store); if (user === null) return problem(401, "signed_out", "Sign in first."); const body = await readJson(request); const text = typeof body?.text === "string" ? body.text.trim() : ""; if (text.length === 0 || text.length > MAX_TEXT) { return problem(400, "invalid_text", `Write a note of 1 to ${MAX_TEXT} characters.`); } // Keys sort as text and a list walks them in that order. Counting down from a far-off time puts the newest // note first; fixed width keeps "9" from sorting after "10". The random part keeps two notes written in the // same millisecond apart. const id = `${String(9_999_999_999_999 - Date.now()).padStart(13, "0")}-${crypto.randomUUID().slice(0, 8)}`; const note = { id, text, created: new Date().toISOString() }; await store.put(`note:${user.userId}:${id}`, JSON.stringify(note)); return Response.json(note, { status: 201 }); }
JavascriptCode
// _functions/api/notes/[id].js // DELETE /api/notes/<id> — deletes one of the signed-in account's notes. import { currentUser } from "../../_lib/auth.js"; import { problem } from "../../_lib/http.js"; export async function onRequestDelete({ request, params, store }) { const user = await currentUser(request, store); if (user === null) return problem(401, "signed_out", "Sign in first."); if (!/^\d{13}-[0-9a-f]{8}$/.test(params.id)) return problem(404, "not_found", "No such note."); // The key is built from the session's account and the id together. Somebody else's note id, sent with this // account's cookie, names a key that does not exist — which is the whole of the authorisation check. const deleted = await store.delete(`note:${user.userId}:${params.id}`); return deleted ? new Response(null, { status: 204 }) : problem(404, "not_found", "No such note."); }

There is no access check that compares a note's owner to the visitor, because there is nothing to compare: the key is built from the visitor's own account id. A note id from somebody else, sent with your cookie, names a key that does not exist, and the answer is 404 — the same as for a note that was never written.

The newest-first order comes from the key, not from sorting. Keys sort as text, so notes.js counts down from a far-off time and writes it at a fixed width; the most recent note has the smallest key and a list returns it first. A page is 50 notes, so one call makes at most 52 store calls — a session read, a list, and a get for each note — against a limit of 100 a call.

The page

Code
<!-- index.html --> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="fixture" content="notes-app"> <title>Notes</title> <link rel="stylesheet" href="/style.css"> </head> <body> <main> <header> <h1>Notes</h1> <p id="who" hidden><span id="email"></span> · <button id="logout" type="button" class="link">Sign out</button></p> </header> <p id="loading">Loading…</p> <section id="signed-out" hidden> <form id="auth"> <h2 id="auth-title">Sign in</h2> <label>Email <input name="email" type="email" autocomplete="email" required></label> <label>Password <input name="password" type="password" autocomplete="current-password" minlength="8" required></label> <p class="error" id="auth-error" role="alert"></p> <button type="submit" id="auth-submit">Sign in</button> <p class="switch"><span id="switch-text">No account yet?</span> <button type="button" id="switch" class="link">Create one</button></p> </form> </section> <section id="signed-in" hidden> <form id="new-note"> <label for="text" class="sr">New note</label> <textarea id="text" name="text" rows="3" maxlength="2000" placeholder="Write a note…" required></textarea> <p class="error" id="note-error" role="alert"></p> <button type="submit">Save</button> </form> <ul id="notes"></ul> <button type="button" id="more" hidden>Show more</button> </section> </main> <script src="/app.js" type="module"></script> </body> </html>
JavascriptCode
// app.js // The page: one view when signed out, another when signed in, both talking to /api/* on the same site. const $ = (id) => document.getElementById(id); /** Calls the site's own API. The session cookie goes along by itself: same origin, HttpOnly, never read here. */ async function api(path, { method = "GET", body } = {}) { const response = await fetch(path, { method, headers: body === undefined ? {} : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); const data = response.status === 204 ? null : await response.json(); return { ok: response.ok, status: response.status, data }; } /** Shows exactly one of the three states. */ function show(state, email = "") { $("loading").hidden = state !== "loading"; $("signed-out").hidden = state !== "signed-out"; $("signed-in").hidden = state !== "signed-in"; $("who").hidden = state !== "signed-in"; $("email").textContent = email; } // --- Signing in and creating an account ------------------------------------------------------------------- let creating = false; $("switch").addEventListener("click", () => { creating = !creating; $("auth-title").textContent = creating ? "Create an account" : "Sign in"; $("auth-submit").textContent = creating ? "Create account" : "Sign in"; $("switch-text").textContent = creating ? "Already have an account?" : "No account yet?"; $("switch").textContent = creating ? "Sign in" : "Create one"; $("auth").password.autocomplete = creating ? "new-password" : "current-password"; $("auth-error").textContent = ""; }); $("auth").addEventListener("submit", async (event) => { event.preventDefault(); const form = event.currentTarget; const { ok, data } = await api(creating ? "/api/signup" : "/api/login", { method: "POST", body: { email: form.email.value, password: form.password.value }, }); if (!ok) { $("auth-error").textContent = data?.message ?? "Something went wrong. Try again."; return; } form.reset(); await signedIn(data.email); }); $("logout").addEventListener("click", async () => { await api("/api/logout", { method: "POST" }); show("signed-out"); }); // --- Notes -------------------------------------------------------------------------------------------------- let next = null; /** * Adds one note to the list — at the top for one just written, at the bottom for one from a page. * textContent, never innerHTML: a note is whatever somebody typed. */ function render(note, atTop = false) { const item = document.createElement("li"); const text = document.createElement("p"); text.textContent = note.text; const meta = document.createElement("small"); meta.textContent = new Date(note.created).toLocaleString(); const remove = document.createElement("button"); remove.type = "button"; remove.className = "link"; remove.textContent = "Delete"; remove.addEventListener("click", async () => { const { ok } = await api(`/api/notes/${encodeURIComponent(note.id)}`, { method: "DELETE" }); if (ok) item.remove(); }); item.append(text, meta, remove); if (atTop) $("notes").prepend(item); else $("notes").append(item); } /** Loads the next page of notes. */ async function loadNotes() { const query = next === null ? "" : `?after=${encodeURIComponent(next)}`; const { ok, data } = await api(`/api/notes${query}`); if (!ok) return; for (const note of data.notes) render(note); next = data.next; $("more").hidden = next === null; } $("more").addEventListener("click", loadNotes); $("new-note").addEventListener("submit", async (event) => { event.preventDefault(); const form = event.currentTarget; const { ok, data } = await api("/api/notes", { method: "POST", body: { text: form.text.value } }); if (!ok) { $("note-error").textContent = data?.message ?? "Could not save the note."; return; } $("note-error").textContent = ""; form.reset(); render(data, true); }); /** Switches to the signed-in view and loads the first page. */ async function signedIn(email) { $("notes").replaceChildren(); next = null; show("signed-in", email); await loadNotes(); } // --- Start ---------------------------------------------------------------------------------------------------- show("loading"); const me = await api("/api/me"); if (me.ok) await signedIn(me.data.email); else show("signed-out");
CSSCode
/* style.css */ :root { color-scheme: light dark; --fg: #1c1c1e; --muted: #6b6b70; --bg: #fafaf8; --card: #ffffff; --line: #e3e3df; --accent: #2f5bd3; --error: #b3261e; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; } @media (prefers-color-scheme: dark) { :root { --fg: #ececec; --muted: #9a9aa0; --bg: #141416; --card: #1d1d20; --line: #2e2e33; --accent: #8aa8ff; --error: #ff8a80; } } * { box-sizing: border-box; } body { margin: 0; background: var(--bg); color: var(--fg); line-height: 1.5; } main { max-width: 34rem; margin: 0 auto; padding: 2rem 1rem 4rem; } header { display: flex; align-items: baseline; justify-content: space-between; gap: 1rem; flex-wrap: wrap; } h1 { margin: 0 0 1.5rem; font-size: 1.6rem; } h2 { margin: 0 0 1rem; font-size: 1.15rem; } #who { margin: 0; color: var(--muted); font-size: 0.9rem; } form { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 1.25rem; margin-bottom: 1.5rem; } label { display: block; margin-bottom: 0.75rem; font-size: 0.9rem; color: var(--muted); } input, textarea { display: block; width: 100%; margin-top: 0.25rem; padding: 0.6rem 0.7rem; font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--line); border-radius: 6px; } textarea { resize: vertical; } button { font: inherit; cursor: pointer; border: 0; border-radius: 6px; padding: 0.55rem 1.1rem; background: var(--accent); color: #fff; } button.link { background: none; color: var(--accent); padding: 0; text-decoration: underline; } .error { color: var(--error); min-height: 1.5em; margin: 0 0 0.5rem; font-size: 0.9rem; } .switch { margin: 1rem 0 0; color: var(--muted); font-size: 0.9rem; } .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); } #notes { list-style: none; margin: 0; padding: 0; } #notes li { background: var(--card); border: 1px solid var(--line); border-radius: 10px; padding: 0.9rem 1rem; margin-bottom: 0.75rem; } #notes p { margin: 0 0 0.4rem; white-space: pre-wrap; overflow-wrap: anywhere; } #notes small { color: var(--muted); margin-right: 0.75rem; }

The page never sees the session token. The browser sends the cookie with every call to the site's own /api/* and keeps it from the script, so a bug that lets someone run JavaScript on the page cannot copy it somewhere else. Notes are put on the page with textContent, never innerHTML: a note is whatever somebody typed, and <img onerror=…> typed into a note should show up as text.

Publish it

From the folder above notes-app/:

TerminalCode
npx drop2run deploy notes-app --subdomain my-notes

Open https://my-notes.dropto.live, create an account and write a note. Then look at what was stored, from the site's Store tab or the CLI:

TerminalCode
npx drop2run store list --site my-notes

There are the keys from the table at the top: one claim:, one user:, a session: per sign-in, and a note: per note. Open the user: value and there is a salt and a hash, and no password.

The routes can be tried with curl too. The first call keeps the cookie the way a browser would:

TerminalCode
curl -c jar -H 'content-type: application/json' \ -d '{"email":"you@example.com","password":"correct horse"}' \ https://my-notes.dropto.live/api/login curl -b jar https://my-notes.dropto.live/api/notes

Before real people use it

The app is complete, but a sign-up form open to the internet meets scripts as well as people.

  • Bots can create accounts. Every sign-up writes a few hundred bytes, and a script can repeat it until the store is full. Put a challenge such as Cloudflare Turnstile in front of /api/signup: the page gets a token, and the function checks it with a fetch and a secret key from env.
  • Nobody can reset a password. That needs email: a function that stores a one-time token and sends a link through an email API. The pieces are the ones above — a key per token, a fetch with a secret key — and the token deserves the same treatment as a session's: store its hash, delete it once used.
  • Every route is public. Anybody can call /api/login without your page, so the limits in the code are the only limits. Your plan's monthly function calls and store calls are shared by every site of the account, and a busy script spends them. The per-site hourly limits in Functions stop one site from spending everything at once.
  • The store keeps what it is given. There is no expiry yet. Sessions nobody returns with and old attempts: keys stay until deleted — from the Store tab, the CLI's store delete, or a route you write for it.

Where the limits are

This shape — static pages, a few routes, a key-value store — fits apps whose data is looked up by who it belongs to: notes, bookmarks, a guestbook, sign-ups, settings, a small shop's orders. It does not fit an app that needs to search across everybody's data, join one table to another, or run something every hour. For those, keep the pages and routes here and have the functions call a hosted database over its HTTP API, with its key in env where the page never sees it.

Last modified on