// test/app.test.mjs import assert from 'node:assert/strict'; import { after, before, beforeEach, test } from 'node:test'; import { fileURLToPath } from 'node:url'; import { PGlite } from '@electric-sql/pglite'; import { createAccountDouble } from '@turnzero/account/testing'; import { createDatabaseDouble, migrationsFrom } from '@turnzero/database/testing'; import { createDataLayer } from '../src/db.mjs'; import { createAppServer } from '../src/server.mjs'; import { createUserReader } from '../src/session.mjs'; const MIGRATIONS = fileURLToPath(new URL('../migrations/', import.meta.url)); // The doubles: PostgreSQL in this process, and the realm's sign-in. let double, accounts, db, server, base, sam, kim; const signedIn = (user) => ({ cookie: `__Host-turnzero_cloud_realm=${user.session}`, 'x-turnzero-cloud-session': user.header }); const post = (row, user = sam, more = {}) => fetch(`${base}/api/notes`, { method: 'POST', headers: { 'content-type': 'application/json', ...signedIn(user), ...more }, body: JSON.stringify(row) }); const listOf = async (user = sam) => (await fetch(`${base}/api/notes`, { headers: signedIn(user) })).json(); const remove = (id, user = sam, more = {}) => fetch(`${base}/api/notes/${id}`, { method: 'DELETE', headers: { ...signedIn(user), ...more } }); before(async () => { double = await createDatabaseDouble({ engine: new PGlite(), files: migrationsFrom(MIGRATIONS) }); accounts = await createAccountDouble(); db = createDataLayer(double.pool); server = createAppServer({ db, userIdOf: createUserReader(accounts.client()) }); await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); base = `http://127.0.0.1:${server.address().port}`; sam = accounts.signIn({ id: 'user-sam' }); kim = accounts.signIn({ id: 'user-kim' }); }); beforeEach(() => double.reset()); after(async () => { await new Promise((resolve) => server.close(resolve)); await double.close(); }); test('the migration applies', () => { assert.deepEqual(double.applied, ['0001_notes.sql']); }); test('the data layer adds a row for its owner, with the time it was added, and lists it to that owner alone', async () => { const { created_at: added, ...kept } = await db.addNote('user-sam', 'first'); assert.deepEqual(kept, { id: '1', body: 'first' }); assert.deepEqual((await db.listNotes('user-sam')).map(({ created_at, ...row }) => row), [{ id: '1', body: 'first' }]); assert.ok(added instanceof Date); assert.deepEqual(await db.listNotes('user-kim'), []); }); test('GET /health reads the database and returns 200', async () => { const response = await fetch(`${base}/health`); assert.equal(response.status, 200); assert.deepEqual(await response.json(), { ok: true }); }); test('a local run serves the page, its script, and its stylesheet from client/', async () => { for (const [path, type] of [['/', 'text/html'], ['/app.js', 'text/javascript'], ['/styles.css', 'text/css']]) { const response = await fetch(`${base}${path}`); assert.equal(response.status, 200, path); assert.ok(response.headers.get('content-type').startsWith(type), path); assert.ok((await response.text()).length > 0, path); } }); test('the API answers 401 to a request with no session, for each of its methods, and reads a session sent as a Bearer', async () => { for (const [method, path] of [['GET', '/api/notes'], ['POST', '/api/notes'], ['DELETE', '/api/notes/1']]) { const response = await fetch(`${base}${path}`, { method }); assert.equal(response.status, 401, `${method} ${path}`); assert.deepEqual(await response.json(), { error: 'sign_in_required' }); } const bearer = await fetch(`${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 /api/notes keeps a text of several lines with characters outside ASCII for the signed-in user, with the time it was added, and GET /api/notes returns it to that user alone', async () => { const body = "For the next version, let's use more robots.\n\nEspecially the debugging robot. café ☕ 東京"; const response = await post({ 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()).map((row) => [row.id, row.body]), [[added.id, body]]); assert.deepEqual(await listOf(kim), []); }); test('POST /api/notes refuses an empty text, white space alone, a text that is not a string, and a text over 20,000 characters, and GET /api/notes returns no row', async () => { for (const body of ['', ' \n\t ', 123, 'x'.repeat(20001)]) { const response = await post({ body }); assert.equal(response.status, 400, JSON.stringify(body).slice(0, 20)); assert.deepEqual(await response.json(), { error: 'invalid_note' }); } assert.deepEqual(await listOf(), []); // Characters, not UTF-16 units, are counted. assert.equal((await post({ body: '😀'.repeat(20000) })).status, 201); }); test('a text that holds SQL is kept as the text it is', async () => { const body = "'); DELETE FROM rows; --"; assert.equal((await post({ body })).status, 201); assert.equal((await listOf())[0].body, body); }); test('rows list newest first, and another user can neither list nor delete them', async () => { const first = await (await post({ body: 'first' })).json(); const second = await (await post({ body: 'second' })).json(); assert.deepEqual((await listOf()).map((row) => row.id), [second.id, first.id]); assert.deepEqual(await listOf(kim), []); assert.equal((await remove(first.id, kim)).status, 404); assert.equal((await listOf()).length, 2); }); test('DELETE /api/notes/ removes one row, then the last, and answers 404 for a row already gone', async () => { const first = await (await post({ body: 'first' })).json(); const second = await (await post({ body: 'second' })).json(); assert.equal((await remove(second.id)).status, 204); assert.deepEqual((await listOf()).map((row) => row.id), [first.id]); assert.equal((await remove(first.id)).status, 204); assert.deepEqual(await listOf(), []); assert.equal((await remove(first.id)).status, 404); }); test('POST /api/notes answers 400 invalid_json for a body that is not JSON, 415 for one not sent as JSON, and 413 for one over 100,000 bytes', async () => { const broken = await fetch(`${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 fetch(`${base}/api/notes`, { method: 'POST', headers: signedIn(sam), body: 'field=value' }); assert.equal(form.status, 415); const large = await post({ body: 'x'.repeat(100001) }); assert.equal(large.status, 413); assert.deepEqual(await large.json(), { error: 'body_too_large' }); assert.deepEqual(await listOf(), []); }); test("a write from another origin is refused 403, a delete as a post, while the application's own hostname passes", async () => { const previous = process.env.APP_PUBLIC_HOST; process.env.APP_PUBLIC_HOST = 'example-app.ai.host'; const elsewhere = { origin: 'https://unrelated.example' }; try { const response = await post({}, sam, elsewhere); assert.equal(response.status, 403); assert.deepEqual(await response.json(), { error: 'origin_refused' }); assert.equal((await remove(1, sam, elsewhere)).status, 403); // Its own origin passes, meeting the row's own refusal. assert.ok((await post({}, sam, { origin: 'https://example-app.ai.host' })).status !== 403); } finally { if (previous === undefined) delete process.env.APP_PUBLIC_HOST; else process.env.APP_PUBLIC_HOST = previous; } });