// The notes API over database and sign-in doubles. import assert from 'node:assert/strict'; import { before, test } from 'node:test'; import { createAccountDouble } from '@turnzero/account/testing'; import { createDataLayer } from '../lib/db.js'; import { createNotesApi } from '../lib/notes.js'; import { createUserReader } from '../lib/session.js'; // A database double recording each query. function databaseDouble() { const rows = []; const calls = []; let next = 1; const visible = ({ owner, ...row }) => row; const run = async (text, values) => { calls.push({ text, values }); if (text.startsWith('INSERT')) { const row = { id: String(next), owner: values[0], body: values[1], created_at: new Date(Date.UTC(2026, 0, 1, 0, 0, next)) }; next += 1; rows.push(row); return { rows: [visible(row)], rowCount: 1 }; } if (text.startsWith('SELECT')) { const mine = rows.filter((row) => row.owner === values[0]).sort((a, b) => Number(b.id) - Number(a.id)); return { rows: mine.map(visible), rowCount: mine.length }; } if (text.startsWith('DELETE')) { const at = rows.findIndex((row) => row.owner === values[0] && row.id === String(values[1])); if (at >= 0) rows.splice(at, 1); return { rows: [], rowCount: at >= 0 ? 1 : 0 }; } throw new Error(`unexpected query: ${text}`); }; return { run, calls }; } const BASE = 'https://example-app.ai.host'; let accounts, sam, kim; before(async () => { accounts = await createAccountDouble(); sam = accounts.signIn({ id: 'user-sam' }); kim = accounts.signIn({ id: 'user-kim' }); }); function app(run) { const database = databaseDouble(); const api = createNotesApi({ db: createDataLayer(run ?? database.run), userIdOf: createUserReader(() => accounts.client()) }); return { api, calls: database.calls }; } const signedIn = (user) => ({ cookie: `__Host-turnzero_cloud_realm=${user.session}`, 'x-turnzero-cloud-session': user.header }); const post = (api, row, user = sam, more = {}) => api(new Request(`${BASE}/api/notes`, { method: 'POST', headers: { 'content-type': 'application/json', ...signedIn(user), ...more }, body: JSON.stringify(row) })); const listOf = async (api, user = sam) => (await api(new Request(`${BASE}/api/notes`, { headers: signedIn(user) }))).json(); const remove = (api, id, user = sam, more = {}) => api(new Request(`${BASE}/api/notes/${id}`, { method: 'DELETE', headers: { ...signedIn(user), ...more } })); test('each method answers 401 with no session, and a Bearer session is read', async () => { const { api } = app(); for (const [method, path] of [['GET', '/api/notes'], ['POST', '/api/notes'], ['DELETE', '/api/notes/1']]) { const response = await api(new Request(`${BASE}${path}`, { method })); assert.equal(response.status, 401, `${method} ${path}`); assert.deepEqual(await response.json(), { error: 'sign_in_required' }); } const bearer = await api(new Request(`${BASE}/api/notes`, { headers: { authorization: `Bearer ${sam.session}`, 'x-turnzero-cloud-session': sam.header } })); assert.equal(bearer.status, 200); assert.equal(bearer.headers.get('cache-control'), 'no-store'); }); test('POST keeps a multi-line, non-ASCII note with its time, and GET lists it', async () => { const { api } = app(); const body = 'Line one.\n\nLine two, café ☕ 東京'; const response = await post(api, { body }); assert.equal(response.status, 201); const added = await response.json(); assert.equal(added.body, body); assert.ok(Number.isFinite(Date.parse(added.created_at))); assert.deepEqual((await listOf(api)).map((row) => [row.id, row.body]), [[added.id, body]]); }); test('POST refuses a blank, non-string or over-long text, or one the database refuses', async () => { const { api } = app(); for (const body of ['', ' \n\t ', 123, 'x'.repeat(20001)]) { const response = await post(api, { body }); assert.equal(response.status, 400); assert.deepEqual(await response.json(), { error: 'invalid_note' }); } assert.deepEqual(await listOf(api), []); // Counted in characters. assert.equal((await post(api, { body: '😀'.repeat(20000) })).status, 201); const checked = app(async () => { throw Object.assign(new Error('check'), { code: '23514' }); }); const refused = await post(checked.api, { body: 'first' }); assert.equal(refused.status, 400); assert.deepEqual(await refused.json(), { error: 'invalid_note' }); }); test('rows list newest first, and another user can neither list nor delete them', async () => { const { api } = app(); const first = await (await post(api, { body: 'first' })).json(); const second = await (await post(api, { body: 'second' })).json(); assert.deepEqual((await listOf(api)).map((row) => row.id), [second.id, first.id]); assert.deepEqual(await listOf(api, kim), []); assert.equal((await remove(api, first.id, kim)).status, 404); assert.equal((await listOf(api)).length, 2); }); test('DELETE removes one row, then the last, and answers 404 once it is gone', async () => { const { api } = app(); const first = await (await post(api, { body: 'first' })).json(); const second = await (await post(api, { body: 'second' })).json(); const removed = await remove(api, second.id); assert.equal(removed.status, 204); assert.equal(removed.headers.get('cache-control'), 'no-store'); assert.deepEqual((await listOf(api)).map((row) => row.id), [first.id]); assert.equal((await remove(api, first.id)).status, 204); assert.deepEqual(await listOf(api), []); assert.equal((await remove(api, first.id)).status, 404); }); test('POST answers 400 to broken JSON, 415 to non-JSON and 413 past 100,000 bytes', async () => { const { api } = app(); const broken = await api(new Request(`${BASE}/api/notes`, { method: 'POST', headers: { 'content-type': 'application/json', ...signedIn(sam) }, body: '{' })); assert.equal(broken.status, 400); assert.deepEqual(await broken.json(), { error: 'invalid_json' }); const form = await api(new Request(`${BASE}/api/notes`, { method: 'POST', headers: signedIn(sam), body: 'field=value' })); assert.equal(form.status, 415); const large = await post(api, { body: 'x'.repeat(100001) }); assert.equal(large.status, 413); assert.deepEqual(await large.json(), { error: 'body_too_large' }); assert.deepEqual(await listOf(api), []); }); test("a write from another origin is refused 403; the app's own origin passes", async () => { const { api } = app(); process.env.APP_PUBLIC_HOST = 'example-app.ai.host'; const elsewhere = { origin: 'https://unrelated.example' }; const response = await post(api, {}, sam, elsewhere); assert.equal(response.status, 403); assert.deepEqual(await response.json(), { error: 'origin_refused' }); assert.equal((await remove(api, 1, sam, elsewhere)).status, 403); assert.ok((await post(api, {}, sam, { origin: BASE })).status !== 403); }); test('the data layer sends its three statements, each binding the signed-in user', async () => { const { api, calls } = app(); const added = await (await post(api, { body: 'first' })).json(); await listOf(api); await remove(api, added.id); assert.deepEqual(calls.map(({ text }) => text), [ 'INSERT INTO "notes" (owner, body) VALUES ($1, $2) RETURNING id, body, created_at', 'SELECT id, body, created_at FROM "notes" WHERE owner = $1 ORDER BY created_at DESC, id DESC', 'DELETE FROM "notes" WHERE owner = $1 AND id = $2', ]); for (const { values } of calls) assert.equal(values[0], 'user-sam'); }); test('a path or method the API does not serve is answered 404', async () => { const { api } = app(); for (const [method, path] of [['GET', '/api/notes/abc'], ['PUT', '/api/notes'], ['GET', '/api/other']]) { const response = await api(new Request(`${BASE}${path}`, { method, headers: signedIn(sam) })); assert.equal(response.status, 404); } });