Level recap · Back end with Node · Level 3
Data and security
Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.
What this level teaches: Keep data in a real database, sign people in safely and test the API.
13 classesLevel exam
1From a file to a database
node:sqlite: open a database, create a table, read rows.
The idea
Ticket CL-501: two people edited
products.jsonat the same time and one change was lost. The products move into a real database.SQLite keeps a whole database in one file, and Node has it built in:
const { DatabaseSync } = require("node:sqlite"); const db = new DatabaseSync("shop.db");.db.exec(sql)runs SQL that gives nothing back, likeCREATE TABLE IF NOT EXISTS ....The code
const http = require("http"); const fs = require("fs"); const { DatabaseSync } = require("node:sqlite"); const db = new DatabaseSync("shop.db"); db.exec("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)"); if (db.prepare("SELECT COUNT(*) AS n FROM products").get().n === 0) { const add = db.prepare("INSERT INTO products (id, name, price) VALUES (?, ?, ?)"); for (const p of JSON.parse(fs.readFileSync("products.json", "utf8"))) add.run(p.id, p.name, p.price); } console.log("Products in the database: " + db.prepare("SELECT COUNT(*) AS n FROM products").get().n); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } const server = http.createServer((req, res) => { if (req.method === "GET" && req.url === "/products") { return sendJson(res, 200, db.prepare("SELECT id, name, price FROM products ORDER BY id").all()); } …What it shows
PASS GET /products answers the rows of the products table
2SQL injection
Never build SQL from what the caller sends: use ? parameters.
The idea
Ticket CL-502 (security, urgent): a tester typed
' OR 1=1 --into the shop's search box and got back every product, including the hidden ones. With a different string they could have deleted the table.The search builds its SQL by gluing the caller's text into it:
"... LIKE '%" + q + "%'". A quote inqends the SQL string early, and the rest ofqruns as SQL. That is SQL injection.The code
const http = require("http"); const fs = require("fs"); const { DatabaseSync } = require("node:sqlite"); const db = new DatabaseSync("shop.db"); db.exec("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)"); if (db.prepare("SELECT COUNT(*) AS n FROM products").get().n === 0) { const add = db.prepare("INSERT INTO products (id, name, price) VALUES (?, ?, ?)"); for (const p of JSON.parse(fs.readFileSync("products.json", "utf8"))) add.run(p.id, p.name, p.price); } function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } const server = http.createServer((req, res) => { const url = new URL(req.url, "http://localhost"); if (req.method === "GET" && url.pathname === "/products/search") { const q = url.searchParams.get("q") ?? ""; const rows = db.prepare("SELECT id, name, price FROM products WHERE name LIKE ? ORDER BY id").all("%" + q + "%"); …What it shows
PASS A normal search finds the products whose name has the word
3Add and remove rows
INSERT and DELETE with run(): lastInsertRowid and changes.
The idea
Ticket CL-503: the stock team adds and removes products through the API now, not by editing a file.
stmt.run(...)answers{ changes, lastInsertRowid }. After an INSERT,lastInsertRowidis the id the database gave the new row. After a DELETE,changessays how many rows went: 0 means there was no such row, so the answer is 404.The code
const http = require("http"); const fs = require("fs"); const { DatabaseSync } = require("node:sqlite"); const db = new DatabaseSync("shop.db"); db.exec("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)"); if (db.prepare("SELECT COUNT(*) AS n FROM products").get().n === 0) { const add = db.prepare("INSERT INTO products (id, name, price) VALUES (?, ?, ?)"); for (const p of JSON.parse(fs.readFileSync("products.json", "utf8"))) add.run(p.id, p.name, p.price); } function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } …What it shows
PASS POST /products saves a new row and answers it with 201
4Join tables
One order, its lines and their products, in one query.
The idea
Ticket CL-504: the order page shows only the customer. It needs each line (product name, qty, price) and the total.
An order's lines live in
order_items(order_id, product_id, qty), and the names and prices inproducts. A JOIN puts them side by side:SELECT p.name, i.qty, p.price FROM order_items i JOIN products p ON p.id = i.product_id WHERE i.order_id = ?.The code
const http = require("http"); const fs = require("fs"); const { DatabaseSync } = require("node:sqlite"); const db = new DatabaseSync("shop.db"); db.exec("CREATE TABLE IF NOT EXISTS products (id INTEGER PRIMARY KEY, name TEXT NOT NULL, price REAL NOT NULL)"); if (db.prepare("SELECT COUNT(*) AS n FROM products").get().n === 0) { const add = db.prepare("INSERT INTO products (id, name, price) VALUES (?, ?, ?)"); for (const p of JSON.parse(fs.readFileSync("products.json", "utf8"))) add.run(p.id, p.name, p.price); } db.exec("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer TEXT NOT NULL)"); db.exec("CREATE TABLE IF NOT EXISTS order_items (order_id INTEGER NOT NULL, product_id INTEGER NOT NULL, qty INTEGER NOT NULL)"); if (db.prepare("SELECT COUNT(*) AS n FROM orders").get().n === 0) { const ids = db.prepare("SELECT id FROM products ORDER BY id").all().map((p) => p.id); db.prepare("INSERT INTO orders (id, customer) VALUES (1, 'Mia')").run(); db.prepare("INSERT INTO order_items (order_id, product_id, qty) VALUES (1, ?, 2), (1, ?, 1)").run(ids[0], ids[1]); } function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); …What it shows
PASS A new order comes back with its lines and total
5Store passwords safely
A salt and a slow hash, never the password itself.
The idea
Ticket CL-505: before anyone can sign in, the team needs the two functions every account system has: one to store a password, one to check it.
Never store the password itself, and never a plain hash of it: when a database leaks, plain hashes of common passwords are looked up in seconds. Store a salted, slow hash instead. The salt is random bytes made for each password, so two people with the same password get different stored values. PBKDF2 runs the hash many thousands of times, so guessing is slow:
crypto.pbkdf2Sync(password, salt, 100000, 32, "sha256"). (Real systems often use 600,000 rounds; this practice copy uses 100,000 to keep the checks quick.)The code
const crypto = require("crypto"); const ITERATIONS = 100000; function hashPassword(password) { const salt = crypto.randomBytes(16).toString("hex"); const hash = crypto.pbkdf2Sync(password, salt, ITERATIONS, 32, "sha256").toString("hex"); return salt + ":" + hash; } function verifyPassword(password, stored) { const [salt, hash] = String(stored).split(":"); if (!salt || !hash) return false; const want = Buffer.from(hash, "hex"); const got = crypto.pbkdf2Sync(password, salt, ITERATIONS, 32, "sha256"); return want.length === got.length && crypto.timingSafeEqual(want, got); } module.exports = { hashPassword, verifyPassword }; const stored = hashPassword("correct horse battery"); console.log("Stored value is " + stored.length + " characters"); console.log("Right password: " + verifyPassword("correct horse battery", stored)); …What it shows
PASS The stored value is salt:hash in hex, never the password
6Sign up
POST /register: check, refuse duplicates, store only the hash.
The idea
Ticket CL-506: customers get accounts. First step: sign up with an email and a password.
Clean the email before you use it:
.trim().toLowerCase(), soMia@Example.comandmia@example.comare one account. Check its shape, and ask for a password of at least 10 characters: length matters more than odd characters.The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const { hashPassword } = require("./passwords"); const db = new DatabaseSync("app.db"); db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member')"); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } async function register(req, res) { const body = await readJson(req); const email = String(body.email ?? "").trim().toLowerCase(); const password = String(body.password ?? ""); …What it shows
PASS A new account is saved with a hash and answered without it
7Sign in
POST /login: one answer for every wrong try.
The idea
Ticket CL-507: sign-up works; now people need to sign in. A successful sign-in answers a token (from
tokens.js) that the app sends with its next requests.Find the user by the cleaned email and check the password with
verifyPassword. The answer for a wrong password and for an unknown email must be exactly the same, 401 and{ "error": "Wrong email or password" }. Otherwise anyone can find out who has an account.The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const { hashPassword, verifyPassword } = require("./passwords"); const { makeToken, readToken } = require("./tokens"); const db = new DatabaseSync("app.db"); db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member')"); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, text TEXT NOT NULL)"); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } async function register(req, res) { const body = await readJson(req); …What it shows
PASS The right email and password answer 200 with a token for that user
8Signed tokens
HMAC: a token nobody can change or fake, that runs out.
The idea
Ticket CL-508: the API needs to know who sends each request without asking for the password every time. After sign-in it hands out a token; the app sends it back with each request.
The token holds a small payload,
{ sub: userId, exp: time }(sub is the user, exp is when it stops working), as base64url text, then a dot, then a signature:crypto.createHmac("sha256", SECRET).update(payload).digest("base64url"). Only someone with the secret can make a signature that matches, so changing the user id in the payload breaks it.The code
const crypto = require("crypto"); const SECRET = process.env.TOKEN_SECRET; const HOUR = 60 * 60 * 1000; const sign = (payload) => crypto.createHmac("sha256", SECRET).update(payload).digest("base64url"); function makeToken(userId) { const payload = Buffer.from(JSON.stringify({ sub: userId, exp: Date.now() + HOUR })).toString("base64url"); return payload + "." + sign(payload); } function readToken(token) { const [payload, sig] = String(token || "").split("."); if (!payload || !sig) return null; const want = Buffer.from(sign(payload)), got = Buffer.from(sig); if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return null; let data; try { data = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); } catch { return null; } if (typeof data.exp !== "number" || data.exp < Date.now()) return null; return data.sub; } …What it shows
PASS A token made for a user reads back as that user, for one hour
9Protect the routes
Read the token on each request; only your own data.
The idea
Ticket CL-509: notes are live, but anyone can read anyone's notes by changing
?user=in the address. Each person must see and add only their own.The app sends the token in a header:
Authorization: Bearer <token>. WriteuserFrom(req): take the token from that header,readTokenit, and look the user up. No header, a bad token or a deleted user means no user, and the answer is 401.The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const { hashPassword, verifyPassword } = require("./passwords"); const { makeToken, readToken } = require("./tokens"); const db = new DatabaseSync("app.db"); db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member')"); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, text TEXT NOT NULL)"); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } async function register(req, res) { const body = await readJson(req); …What it shows
PASS Without a valid token, notes answer 401
10Admins only
401 is "who are you?"; 403 is "not you".
The idea
Ticket CL-510: support staff need to close accounts. Only admins may do it; the account named in
ADMIN_EMAILis made an admin when it signs up.Two different answers: 401 (Unauthorized) means there is no valid sign-in; 403 (Forbidden) means we know who you are and you may not do this. Check the role on the server, from the database, never from something the caller sends.
The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const { hashPassword, verifyPassword } = require("./passwords"); const { makeToken, readToken } = require("./tokens"); const db = new DatabaseSync("app.db"); db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member')"); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, text TEXT NOT NULL)"); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } async function register(req, res) { const body = await readJson(req); …What it shows
PASS A member gets 403 and nothing is deleted; no token gets 401
11Slow down password guessing
A rate limit on sign-in: 429 and Retry-After.
The idea
Ticket CL-511: the log shows one address trying thousands of passwords on one account. Sign-in must stop answering after a few wrong tries.
Count the tries per address,
req.socket.remoteAddress, in aMap: when the first try was, and how many since. After 5 tries in 15 minutes, answer 429 (Too Many Requests) before you even look at the password, with aRetry-Afterheader: the seconds until the 15 minutes are over.The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const { hashPassword, verifyPassword } = require("./passwords"); const { makeToken, readToken } = require("./tokens"); const db = new DatabaseSync("app.db"); db.exec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'member')"); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, text TEXT NOT NULL)"); function sendJson(res, status, data) { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(data)); } async function readJson(req) { let body = ""; for await (const chunk of req) body += chunk; return JSON.parse(body || "{}"); } async function register(req, res) { const body = await readJson(req); …What it shows
PASS The 6th try from one address answers 429 with Retry-After, even with the right password
12Secrets in the environment
Config from env, refuse to start without the secret, never print it.
The idea
Ticket CL-512 (security): the token secret is written in the code, so it is in the repository and in every copy of it, and the start-up line prints it into the logs.
Secrets and settings come from the environment:
process.env.TOKEN_SECRET,PORT,DB_FILE. Settings may have a default; a secret may not. If it is missing or short (under 32 characters), print a clear message withconsole.errorand stop withprocess.exit(1), before anything else starts.The code
const http = require("http"); const { DatabaseSync } = require("node:sqlite"); const secret = process.env.TOKEN_SECRET ?? ""; if (secret.length < 32) { console.error("TOKEN_SECRET is missing or shorter than 32 characters"); process.exit(1); } const port = Number(process.env.PORT ?? 3000); const dbFile = process.env.DB_FILE ?? "app.db"; console.log("Config: port " + port + ", database " + dbFile); const db = new DatabaseSync(dbFile); db.exec("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY KEY, text TEXT)"); const server = http.createServer((req, res) => res.end("ok")); server.listen(port, () => console.log("Listening on port " + port));What it shows
PASS Without a long enough TOKEN_SECRET it stops with exit code 1
13Test the API
node:test: tests that send real requests and catch real bugs.
The idea
Ticket CL-513: last week a change let empty tasks through and nobody noticed for days. From now on the task API has tests, and they run before every deploy.
Node has a test runner built in:
const test = require("node:test"); const assert = require("node:assert");.test("name", async () => { ... })is one test; inside it,assert.strictEqual(got, want)fails the test when they differ.test.beforeruns once first (start the server),test.afteronce at the end (stop it).The code
const test = require("node:test"); const assert = require("node:assert"); const { server } = require("./app"); const base = "http://localhost:3000"; const post = (body) => fetch(base + "/tasks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); test.before(() => new Promise((ok) => server.listen(3000, ok))); test.after(() => server.close()); test("POST /tasks with a title answers 201 and the task", async () => { const r = await post({ title: "Call the courier" }); assert.strictEqual(r.status, 201); const task = await r.json(); assert.strictEqual(task.title, "Call the courier"); assert.strictEqual(task.done, false); }); test("POST /tasks with an empty title answers 400", async () => { const r = await post({ title: " " }); assert.strictEqual(r.status, 400); }); …What it shows
PASS Your tests run and pass on the real app
Ready for the exam? The level exam is one real task that uses what this recap covers.
Take the level exam