// lib/notes.js: the notes API over any data layer and any reader of the // signed-in user. Code under lib/ is shared by the functions and answers no // path. functions/api/notes.js gives this API the database and the live // sign-in, and the tests give it doubles. // The most a request body may hold, in bytes; a longer one is answered 413. const BODY_LIMIT = 100_000; // One row's route: /api/notes/ and its id, a positive whole number. const ROW_ROUTE = /^\/api\/notes\/([1-9][0-9]{0,17})$/; const send = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }); // The body as text, read in one decoder so a character whose bytes arrive in // two chunks is read whole. A body past the limit is read to its end and // dropped, so the sender gets its answer, not a reset. async function readBody(request) { if (!request.body) return ''; const reader = request.body.getReader(); const decoder = new TextDecoder(); let text = ''; let bytes = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; bytes += value.byteLength; if (bytes <= BODY_LIMIT) text += decoder.decode(value, { stream: true }); } if (bytes > BODY_LIMIT) throw Object.assign(new Error('body_too_large'), { status: 413 }); return text + decoder.decode(); } // The API 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 createNotesApi({ db, userIdOf }) { return async function fetch(request) { 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).pathname; } catch {} const row = ROW_ROUTE.exec(pathname ?? ''); if (pathname === '/api/notes' || row) { // Every route answers the signed-in user alone. 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; const origin = request.headers.get('origin'); if (request.method !== 'GET' && origin && host && 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' }); return new Response(null, { status: 204, headers: { 'cache-control': 'no-store' } }); } if (!row && request.method === 'GET') return send(200, await db.listNotes(user)); if (!row && request.method === 'POST') { if (!/^application\/json(?:;|$)/i.test(request.headers.get('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)); } } return 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; // A function's console lines reach the application's logs. if (refused === null) console.error(error); return send(refused === null ? 500 : 400, { error: refused ?? 'internal' }); } }; }