// src/server.mjs import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; // The web client's three files, by the path a browser asks for them. On the // platform, the deploy serves them from client/ ahead of these routes, and a // local run that names a port answers them the same way. A test, or a local // run that names none, has nothing in front of it, so this server answers them. const CLIENT_FILES = Object.freeze({ '/': ['index.html', 'text/html; charset=utf-8'], '/index.html': ['index.html', 'text/html; charset=utf-8'], '/app.js': ['app.js', 'text/javascript; charset=utf-8'], '/styles.css': ['styles.css', 'text/css; charset=utf-8'], }); // The most a request body may hold, in bytes; a longer one is answered 413. const BODY_LIMIT = 100_000; const readBody = async (request) => { // One decoder for the whole body: a character whose bytes arrive in two chunks is read whole. request.setEncoding('utf8'); let text = ''; let bytes = 0; // A body past the limit is read to its end and dropped, so the sender gets its answer, not a reset. for await (const chunk of request) { bytes += Buffer.byteLength(chunk); if (bytes <= BODY_LIMIT) text += chunk; } if (bytes > BODY_LIMIT) throw Object.assign(new Error('body_too_large'), { status: 413 }); return text; }; // One row's route: /api/notes/ and its id, a positive whole number. const ROW_ROUTE = /^\/api\/notes\/([1-9][0-9]{0,17})$/; // A request's abort signal. The deployed runtime attaches its own signal to each // request, and it aborts at the request's window. A local run has none of its own, // and Node's request.signal can abort at a normal request end on some Node 24 // releases, so a local run's signal aborts when the response closes unfinished. function abortSignalOf(request, response) { const own = Object.hasOwn(request, 'signal') ? request.signal : undefined; if (own) return own; const controller = new AbortController(); response.once('close', () => { if (!response.writableFinished) controller.abort(); }); return controller.signal; } // The server over its two parts: db, the data layer; and userIdOf, which // reads the signed-in user's id from a request, or null. export function createAppServer({ db, userIdOf }) { return createServer(async (request, response) => { // End the response when the request is aborted (abortSignalOf, above). const signal = abortSignalOf(request, response); signal.addEventListener('abort', () => response.destroy(), { once: true }); const send = (status, body) => { if (response.destroyed) return; response.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); response.end(JSON.stringify(body)); }; try { // A target that does not parse as a URL names no route, so it is answered 404 below. let pathname = null; try { pathname = new URL(request.url, 'http://localhost').pathname; } catch {} if (request.method === 'GET' && pathname === '/health') { return (await db.reachable()) ? send(200, { ok: true }) : send(503, { ok: false }); } if (request.method === 'GET' && Object.hasOwn(CLIENT_FILES, pathname)) { const [file, type] = CLIENT_FILES[pathname]; try { const body = await readFile(new URL(`../client/${file}`, import.meta.url)); if (!response.destroyed) response.writeHead(200, { 'content-type': type }).end(body); return; } catch (error) { if (error?.code === 'ENOENT') return send(404, { error: 'not_found' }); throw error; } } // Every route under /api/ answers the signed-in user alone. const row = ROW_ROUTE.exec(pathname ?? ''); if (pathname === '/api/notes' || row) { const user = await userIdOf(request); if (user === null) return send(401, { error: 'sign_in_required' }); // A browser's writes come from the application's own page. Where the request names // its origin, it must be the platform's hostname for this application, never one read // from the request's own Host header. const host = process.env.APP_PUBLIC_HOST; if (request.method !== 'GET' && request.headers.origin && host && request.headers.origin !== `https://${host}`) { return send(403, { error: 'origin_refused' }); } if (row && request.method === 'DELETE') { if (!(await db.deleteNote(user, row[1]))) return send(404, { error: 'not_found' }); if (!response.destroyed) response.writeHead(204, { 'cache-control': 'no-store' }).end(); return; } if (!row && request.method === 'GET') return send(200, await db.listNotes(user)); if (!row && request.method === 'POST') { if (!/^application\/json(?:;|$)/i.test(request.headers['content-type'] ?? '')) return send(415, { error: 'json_required' }); const posted = JSON.parse(await readBody(request)); const body = typeof posted?.body === 'string' ? posted.body.trim() : ''; if (!body || [...body].length > 20000) return send(400, { error: 'invalid_note' }); return send(201, await db.addNote(user, body)); } } send(404, { error: 'not_found' }); } catch (error) { if (error?.status === 413) return send(413, { error: 'body_too_large' }); const refused = error instanceof SyntaxError ? 'invalid_json' : error?.code === '23514' ? 'invalid_note' : null; if (refused === null) console.error(error); send(refused === null ? 500 : 400, { error: refused ?? 'internal' }); } }); }