notes-app example #
On this page
A web app with sign-in and private notes in PostgreSQL.
These files come from the same source as the scaffold command. They are the starter files before the command adds library packages, application settings, and installed dependencies.
With a shell #
This template downloads Turn Zero library packages. The command needs this computer's token, kept by turnzero login or turnzero authorize, or TURNZERO_CLOUD_MINTED_TOKEN set for this invocation. Without either, it writes nothing, prints the authorization steps, and exits with status 3.
Authorize this computer, or read How the command finds its credential to use an existing token.
With no CLI token, follow From a chat to adapt these files and deploy through a signed-in MCP connection.
Run this in a new project's root:
turnzero scaffold --template notes-app
Follow the command's next steps. It writes the application in app/, takes the required library packages, installs dependencies, and runs the tests. The turnzero command explains setup and options.
From a chat #
A Cloud tool name without a prefix is its HTTP API name; your MCP connection lists it with tzcloud_ before it. The copied AGENTS.md instructions below use the names listed by the MCP connection.
Follow Deploy from a chat. Adapt this example if it fits the app the person requested.
The scaffold can bind its manifest to an application with --application <application id>. From a chat, name the application explicitly in submit_manifest and deploy_files. The platform uses the application named in the call and checks an uploaded manifest's optional application ID only for lowercase UUID form. turnzero deploy and turnzero check refuse a folder whose manifest names another application.
Keep the application paths shown in the table. The download URLs end in .txt so a browser reads the code instead of running it; that suffix is not part of the application filename. Each file is also reproduced below for tools reading this page through MCP.
The template manifest starts with an empty packages list. Read each @turnzero/ dependency's library entry and copy its current name and version into that list. Keep the file:lib/… dependencies in package.json. Leave the files under those lib/ paths out of the deploy_files request; Cloud supplies them from the library. Send no placeholder versions or hashes.
The tests import @turnzero/database/testing and src/db.mjs imports @turnzero/database, so both need the package. To test a data layer before you sign in, write one that imports no Turn Zero package, as Without the Database package shows.
Files #
Paths are relative to the application root—the folder containing package.json. deploy_files uses these paths without an app/ prefix.
| Application path | Read source |
|---|---|
.gitignore |
Text |
AGENTS.md |
Text |
client/app.js |
Text |
client/index.html |
Text |
client/styles.css |
Text |
manifest.json |
Text |
migrations/0001_notes.sql |
Text |
package.json |
Text |
src/db.mjs |
Text |
src/main.mjs |
Text |
src/server.mjs |
Text |
src/session.mjs |
Text |
test/app.test.mjs |
Text |
File contents #
.gitignore #
node_modules/
.env
.env.*
AGENTS.md #
# This service runs on Turn Zero Cloud
The service in this folder is hosted on Turn Zero Cloud. It started from the platform's `notes-app` template: a Node.js service with a web page, sign-in for its users, and each user's own rows in the platform's database. This file describes the template the service started from: keep it current as the service changes.
## Where you build
- The page: `client/`, plain HTML, CSS, and script, which the platform serves at the application's address.
- The routes: `src/server.mjs`. The service started with routes under `/api/` that each read the signed-in user, and keep, list, and delete that user's own rows.
- The tables: `migrations/`, one file for each change, applied in order at each start.
## Where the rules are
Turn Zero Cloud serves its rules to a coding tool through the MCP server `turnzero`, one connection to the products your account holds. The rules change with the platform, so none is repeated here.
- Where the server is not connected, set up Turn Zero Cloud first: https://turnzero.ai/cloud/getting-started/set-up/
- Before you change or deploy this service, read the server's `deploy` skill, and before you change its sign-in, the server's `add-sign-in` skill.
## What you run here
- The tests: `npm test`, in this folder.
- A local run and a deploy: the `deploy` skill gives each step and the line to run, in this order: `tzcloud_submit_manifest`, the local run, `tzcloud_deploy_command`.
- Sign-in on a local run: start it with `--sign-in` and the application's own hostname, then open the address its port line names; the command sends the sign-in routes to that hostname. Without `--sign-in`, the page a local run serves has no sign-in routes, sign-in is on the deployed application's own address, and a local run's API routes take a session as a Bearer.
client/app.js #
// client/app.js: the page's script, calling the backend on its own address.
// The rows' names, and the route that adds, lists, and deletes the signed-in user's rows.
const PLURAL = 'notes';
const SINGULAR = 'note';
const ROUTE = '/api/notes';
// The fields of one row, each with its kind. The first text field is the row's
// text: the list shows its first line, and the reader shows it whole.
const FIELDS = [{ name: 'body', kind: 'text' }];
const INPUT_TYPES = { text: 'text', integer: 'number', boolean: 'checkbox', timestamp: 'datetime-local' };
const TEXT = FIELDS.find((field) => field.kind === 'text') ?? null;
const $ = (id) => document.getElementById(id);
const say = (id, text) => { $(id).textContent = text; };
const inputs = [];
let rows = [];
let selected = null;
let busy = false;
const dateOf = (value, full) => new Intl.DateTimeFormat(undefined, full ? { month: 'long', day: 'numeric', year: 'numeric' } : { month: 'short', day: 'numeric' }).format(new Date(value));
function valueOf(field, input) {
if (field.kind === 'boolean') return input.checked;
if (input.value === '') return field.kind === 'text' ? '' : null;
if (field.kind === 'integer') return Number(input.value);
return field.kind === 'timestamp' ? new Date(input.value).toISOString() : input.value;
}
const shown = (field, value) => (field.kind === 'boolean' ? (value ? 'yes' : 'no') : field.kind === 'timestamp' && value ? dateOf(value, true) : String(value ?? ''));
function setBusy(value) {
busy = value;
for (const input of inputs) input[input.type === 'checkbox' ? 'disabled' : 'readOnly'] = value;
$('delete-row').disabled = value;
$('save').disabled = value;
}
async function act(work) {
setBusy(true);
say('status', '');
try {
await work();
} catch (error) {
say('status', error.message);
} finally {
setBusy(false);
}
}
function signedOut(message = `Sign in to save your ${PLURAL} and come back to them anywhere.`) {
$('workspace').hidden = true;
$('welcome').hidden = false;
$('sign-in').hidden = false;
say('who', message);
}
async function api(path, options) {
const response = await fetch(path, options);
if (response.status === 401) {
signedOut(`Please sign in to open your ${PLURAL}.`);
throw new Error('Please sign in again. Your unsaved text is still here.');
}
if (!response.ok) throw new Error(response.status === 404 ? `This ${SINGULAR} no longer exists. Reload the page to see your ${PLURAL}.` : 'That did not work. Please try again.');
return response.status === 204 ? null : response.json();
}
function renderList() {
const list = $('row-list');
say('count', rows.length);
list.replaceChildren();
$('empty').hidden = rows.length > 0;
for (const row of rows) {
const entry = $('row-template').content.firstElementChild.cloneNode(true);
const button = entry.querySelector('button');
button.setAttribute('aria-current', String(row.id === selected));
entry.querySelector('.excerpt').textContent = TEXT ? String(row[TEXT.name] ?? '').split('\n')[0] : FIELDS.map((field) => `${field.name}: ${shown(field, row[field.name])}`).join(', ');
entry.querySelector('.row-date').textContent = dateOf(row.created_at);
button.addEventListener('click', () => busy || showRow(row.id));
list.append(entry);
}
}
function showRow(id) {
const row = rows.find((held) => held.id === id);
if (!row) return compose();
selected = id;
$('reader').hidden = false;
$('composer').hidden = true;
say('row-date', dateOf(row.created_at, true));
const others = FIELDS.filter((field) => field !== TEXT).map((field) => `${field.name}: ${shown(field, row[field.name])}`);
say('reader-body', [TEXT ? String(row[TEXT.name] ?? '') : '', others.join('\n')].filter(Boolean).join('\n\n'));
say('status', '');
renderList();
}
function compose() {
if (busy) return;
selected = null;
renderList();
$('reader').hidden = true;
$('composer').hidden = false;
$('cancel').hidden = rows.length === 0;
say('status', '');
inputs[0]?.focus();
}
const clearInputs = () => inputs.forEach((input) => (input.type === 'checkbox' ? (input.checked = false) : (input.value = '')));
for (const field of FIELDS) {
const input = document.createElement(field === TEXT ? 'textarea' : 'input');
if (field === TEXT) {
input.maxLength = 20000;
input.placeholder = "What's on your mind?";
input.addEventListener('keydown', (event) => {
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
event.preventDefault();
$('composer').requestSubmit();
}
});
} else input.type = INPUT_TYPES[field.kind];
input.name = field.name;
input.required = field.kind !== 'boolean';
input.addEventListener('input', () => input.setCustomValidity(''));
if (FIELDS.length === 1) input.setAttribute('aria-labelledby', 'composer-title');
const label = document.createElement('label');
label.append(FIELDS.length === 1 ? '' : field.name, input);
$('fields').append(label);
inputs.push(input);
}
$('new-row').addEventListener('click', compose);
$('cancel').addEventListener('click', () => {
if (busy) return;
clearInputs();
if (rows.length) showRow(rows[0].id);
});
$('composer').addEventListener('submit', (event) => {
event.preventDefault();
const row = Object.fromEntries(FIELDS.map((field, index) => [field.name, valueOf(field, inputs[index])]));
const text = TEXT && inputs[FIELDS.indexOf(TEXT)];
if (text && !String(row[TEXT.name]).trim()) {
text.setCustomValidity(`Enter a ${SINGULAR} before saving.`);
return text.reportValidity();
}
if (!busy) act(async () => {
const added = await api(ROUTE, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(row) });
rows.unshift(added);
clearInputs();
busy = false;
showRow(added.id);
$('new-row').focus();
});
});
$('delete-row').addEventListener('click', async () => {
const dialog = $('confirm-dialog');
if (busy || !selected) return;
say('confirm-message', `Delete this ${SINGULAR}?`);
dialog.returnValue = '';
dialog.showModal();
await new Promise((resolve) => dialog.addEventListener('close', resolve, { once: true }));
if (dialog.returnValue !== 'confirm') return;
const index = rows.findIndex((held) => held.id === selected);
await act(async () => {
await api(`${ROUTE}/${encodeURIComponent(selected)}`, { method: 'DELETE' });
rows.splice(index, 1);
busy = false;
if (rows.length) showRow(rows[Math.min(index, rows.length - 1)].id);
else {
clearInputs();
compose();
}
});
});
async function start() {
// The page's words that name the rows, from the rows' names.
say('list-title', `Your ${PLURAL}`);
say('new-row-label', `New ${SINGULAR}`);
say('composer-title', `Enter a ${SINGULAR.charAt(0).toUpperCase()}${SINGULAR.slice(1)}`);
say('save', `Save ${SINGULAR}`);
say('private', `Your ${PLURAL} are private to your account.`);
say('empty', `Your ${PLURAL} will appear here.`);
$('delete-row').setAttribute('aria-label', `Delete this ${SINGULAR}`);
try {
const response = await fetch('/__account/me');
if (response.status === 404) {
return say('who', "Sign-in is unavailable at this address. For a local run, start with --sign-in and the application's hostname. Otherwise sign in at the application's deployed address.");
}
const user = response.status === 200 ? (await response.json()).user : null;
if (!user) return signedOut();
rows = await api(ROUTE);
$('welcome').hidden = true;
$('workspace').hidden = false;
$('sign-out').hidden = false;
if (rows.length) showRow(rows[0].id);
else compose();
} catch {
$('welcome').hidden = false;
say('who', `Your ${PLURAL} could not be opened. Please reload to try again.`);
}
}
start();
client/index.html #
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>A little space for your ideas</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<div class="page">
<header class="hero">
<div>
<h1>A little space for your ideas.</h1>
</div>
<svg class="illustration" viewBox="0 0 280 180" role="img" aria-label="A folded sheet of paper and a blue pencil">
<defs><pattern id="grain" width="5" height="5" patternUnits="userSpaceOnUse"><circle cx="1" cy="2" r=".6" fill="#1749dd" opacity=".2"/></pattern></defs>
<path d="M45 140 190 159 227 143 87 126Z" fill="#d7e2ff"/>
<path d="m54 125 35-98 78 17 69-18-39 110-72 24Z" fill="#faf8f1" stroke="#1749dd" stroke-width="2.8" stroke-linejoin="round"/>
<path d="m54 125 71 35-14-41Z" fill="#bdcefa" stroke="#1749dd" stroke-width="2.2"/>
<path d="m54 125 57-6 86 17-72 24Z" fill="url(#grain)"/>
<g transform="rotate(39 207 102)">
<rect x="197" y="36" width="20" height="114" rx="3" fill="#1749dd"/>
<path d="M197 48h20M204 53v88" fill="none" stroke="#a5bdff" stroke-width="3"/>
<path d="m197 150 10 25 10-25" fill="#e9d8b6" stroke="#1749dd" stroke-width="2"/>
<path d="m203 164 4 11 4-11" fill="#1749dd"/>
<path d="M197 44v-8a10 10 0 0 1 20 0v8" fill="#e9edff" stroke="#1749dd" stroke-width="2"/>
</g>
<path d="m42 37-12-8m29-9-5-14M30 61H15" stroke="#1749dd" stroke-width="4" stroke-linecap="round"/>
</svg>
</header>
<section id="welcome" class="welcome" aria-label="Sign in">
<h2>Your thoughts, kept for you.</h2>
<p id="who">Reading who is signed in.</p>
<p class="welcome-action"><a id="sign-in" href="/__account/signin" hidden>Sign in</a></p>
</section>
<main id="workspace" class="workspace" hidden>
<aside class="sidebar">
<div class="list-heading"><h2><span id="list-title"></span> <span id="count"></span></h2><button id="new-row" class="primary" type="button"><span aria-hidden="true">+</span> <span id="new-row-label"></span></button></div>
<p id="empty" class="empty-list" hidden></p>
<div class="row-list" id="row-list"></div>
</aside>
<section class="detail" id="detail">
<article id="reader">
<div class="reader-toolbar"><p id="row-date" class="date"></p><button id="delete-row" class="delete-row" type="button"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16M9 7V4h6v3M6 7l1 14h10l1-14M10 11v6M14 11v6"/></svg></button></div>
<div id="reader-body" class="reader-body"></div>
</article>
<form id="composer" hidden>
<h3 id="composer-title" class="composer-title"></h3>
<div id="fields" class="fields"></div>
<div class="compose-actions"><button type="submit" class="primary" id="save"></button><button id="cancel" type="button" class="quiet">Cancel</button><span class="shortcut">Ctrl / ⌘ + Enter to save</span></div>
</form>
<p class="status" id="status" role="status" aria-live="polite"></p>
</section>
</main>
<footer><span id="private"></span><a id="sign-out" href="/__account/signout" hidden>Sign out</a></footer>
</div>
<dialog id="confirm-dialog" aria-labelledby="confirm-message">
<form method="dialog"><p id="confirm-message"></p><div class="confirm-actions"><button class="quiet" value="cancel" autofocus>Cancel</button><button class="primary" value="confirm">Delete</button></div></form>
</dialog>
<template id="row-template"><div class="row-entry"><button type="button" class="row-item"><span class="excerpt"></span><span class="row-date"></span></button></div></template>
<script src="/app.js"></script>
</body>
</html>
client/styles.css #
/* client/styles.css */
:root{font-family:Arial,Helvetica,sans-serif;color:#20201e;background:#f8f5ed;font-synthesis:none;--blue:#1749dd;--line:#e7e6e1;--muted:#777a7e}
*{box-sizing:border-box}
dialog{border:1px solid #d5d6d3;border-radius:14px;padding:26px;max-width:360px;color:#20201e;background:#fffefc;box-shadow:0 15px 70px #0002}
dialog::backdrop{background:#18243740}
dialog p{font-size:17px;line-height:1.5;margin:0 0 20px}
.confirm-actions{display:flex;justify-content:flex-end;gap:10px}
body{margin:0;background:radial-gradient(ellipse at 87% 0,#fffdf7,transparent 65%);min-height:100vh}
button,a,textarea{-webkit-tap-highlight-color:transparent}
button{font:inherit;cursor:pointer}
button:focus-visible,a:focus-visible,textarea:focus-visible,input:focus-visible{outline:3px solid #779cff;outline-offset:4px}
[hidden]{display:none!important}
.page{max-width:1480px;margin:auto;padding:36px 48px 18px}
.hero{display:flex;justify-content:space-between;align-items:center;min-height:213px;padding:0 22px 24px;gap:30px}
h1{font:500 clamp(32px,3.6vw,53px)/1.13 Georgia,'Times New Roman',serif;letter-spacing:-1.5px;margin:23px 0 0}
.illustration{width:236px;flex-shrink:0;height:166px}
.workspace{display:grid;grid-template-columns:36% 64%;height:clamp(430px,65vh,660px);background:#fffefc;border:1px solid #d5d6d3;border-radius:17px;overflow:hidden;box-shadow:0 10px 45px #30332205}
.sidebar{border-right:1px solid var(--line);display:flex;flex-direction:column;min-width:0;min-height:0;padding:25px 13px 16px 22px}
.list-heading{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:0 10px 20px 6px}
h2{font:500 27px Georgia,serif;margin:0;white-space:nowrap}
#count{font:12px Arial,sans-serif;color:#8b8d90;vertical-align:middle;margin-left:4px}
.primary,.welcome-action a{background:var(--blue);border:1px solid var(--blue);border-radius:8px;padding:11px 16px;color:white;font-size:14px;font-weight:600;white-space:nowrap;box-shadow:0 2px 3px #1749dd10;transition:background .15s}
.primary:hover,.welcome-action a:hover{background:#103bb9}
.primary span[aria-hidden]{font-size:19px;line-height:12px;margin-right:4px;font-weight:400}
.row-list{overflow-y:scroll;scrollbar-color:#b9bdc5 #f2f2ef;scrollbar-width:thin;min-height:0;padding-right:9px;flex:1}
.row-entry{position:relative;border-bottom:1px solid var(--line)}
.row-item{display:block;width:100%;text-align:left;border:0;background:transparent;padding:17px 18px 15px;position:relative;color:#2d3034;min-height:79px;border-radius:0}
.reader-toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:30px;gap:15px}
.reader-toolbar .date{margin:0}
.delete-row{width:34px;height:34px;display:grid;place-items:center;background:none;border:0;border-radius:6px;color:#858b95;flex-shrink:0}
.delete-row:hover{color:#b33338;background:#fff0ef}
.delete-row svg{width:15px;height:15px}
.empty-list{font-size:14px;line-height:1.6;color:#858a94;padding:18px}
.row-item:hover{background:#f4f6fa}
.row-item[aria-current="true"]{background:#eaf0ff;border-radius:8px;border-bottom-color:transparent}
.row-item[aria-current="true"]:before{content:"";position:absolute;left:0;top:10px;bottom:10px;width:3px;border-radius:3px;background:var(--blue)}
.excerpt{font-size:16px;line-height:1.4;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:block}
.row-date{font-size:12px;color:var(--muted);display:block;margin-top:7px}
.detail{padding:37px 45px;overflow-y:auto;min-width:0;position:relative;display:flex;flex-direction:column}
#reader{flex:1;animation:appear .18s ease}
.date{font-size:13px;color:var(--muted);margin:0 0 32px;letter-spacing:.1px}
.reader-body{font-size:clamp(20px,1.8vw,26px);line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere;max-width:660px}
#composer{display:flex;flex-direction:column;flex:1;min-height:280px}
.composer-title{font:500 30px Georgia,serif;margin:0 0 20px}
.fields{display:flex;flex-direction:column;gap:14px;flex:1}
.fields label{display:grid;gap:6px;font-size:14px;color:#4d5157}
.fields label:only-child{display:flex;flex-direction:column;flex:1}
.fields input{font:16px Arial,sans-serif;padding:10px 12px;border:1px solid #d7dce5;border-radius:8px;background:white;color:#20201e}
.fields input[type=checkbox]{justify-self:start;width:18px;height:18px}
textarea{display:block;resize:vertical;flex:1;min-height:180px;width:100%;padding:18px;border:1px solid #d7dce5;border-radius:10px;background:white;font:20px/1.6 Arial,sans-serif;color:#20201e}
textarea::placeholder{color:#999da7}
.compose-actions{display:flex;align-items:center;gap:13px;margin-top:18px;flex-wrap:wrap}
.quiet{background:none;border:0;padding:10px;color:#666c75;font-size:14px}
.shortcut{color:#969aa2;font-size:11px;margin-left:auto}
.status{color:#3156a3;font-size:13px;min-height:16px;margin:15px 0 0}
footer{display:flex;justify-content:space-between;gap:15px;color:#8c8c89;font-size:11px;padding:14px 4px}
#sign-out{color:#777d87;font-size:11px;text-decoration:underline;text-underline-offset:3px}
.welcome{background:#fffefc;border:1px solid #d5d6d3;border-radius:17px;padding:50px;text-align:center;min-height:300px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:16px}
.welcome h2{white-space:normal;font-size:32px}.welcome p{color:#727781;margin:0 0 12px;font-size:16px}
.welcome-action{margin:0}.welcome a{text-decoration:none}.primary:disabled,.delete-row:disabled{opacity:.5;cursor:wait}
@keyframes appear{from{opacity:.5;transform:translateY(3px)}to{opacity:1;transform:none}}
@media(min-width:1600px){.page{padding-top:48px}.hero{min-height:235px}.workspace{height:630px}}
@media(max-width:1000px){.page{padding:24px}.hero{padding:0 7px 22px;min-height:185px}.illustration{width:175px}.workspace{grid-template-columns:39% 61%}.detail{padding:30px}.sidebar{padding-left:12px}.list-heading{flex-wrap:wrap}.shortcut{display:none}}
@media(max-width:640px){.page{padding:18px 12px}.hero{min-height:155px;gap:8px}h1{font-size:29px;margin-top:19px;letter-spacing:-.8px}.illustration{width:95px;height:120px}.workspace{grid-template-columns:1fr;height:auto}.sidebar{border-right:0;border-bottom:1px solid var(--line);height:280px;padding:18px 12px 12px}.list-heading{flex-wrap:nowrap;padding-bottom:12px}h2{font-size:25px}.row-item{padding:12px 16px;min-height:65px}.detail{min-height:320px;padding:26px 22px}.reader-body{font-size:21px}.date{margin-bottom:22px}footer{font-size:10px;align-items:center}#sign-out{font-size:10px}}
@media(prefers-reduced-motion:reduce){*{animation:none!important;transition:none!important}}
manifest.json #
{
"manifest_version": 1,
"services": [{ "kind": "database" }, { "kind": "accounts" }],
"health": "/health",
"region": "usa",
"egress": [],
"audience": { "kind": "public" },
"packages": []
}
migrations/0001_notes.sql #
-- migrations/0001_notes.sql: each row is kept for the user who added it, its owner, with the time it was added.
CREATE TABLE "notes" (
id bigserial PRIMARY KEY,
owner text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
body text NOT NULL CHECK (char_length(btrim(body)) BETWEEN 1 AND 20000)
);
CREATE INDEX ON "notes" (owner, created_at DESC, id DESC);
package.json #
{
"name": "notes-app",
"private": true,
"type": "module",
"scripts": {
"start": "node src/main.mjs",
"test": "node --test"
},
"dependencies": {
"@turnzero/account": "file:lib/account",
"@turnzero/database": "file:lib/database",
"pg": "^8.22.0"
},
"devDependencies": {
"@electric-sql/pglite": "0.5.8"
}
}
src/db.mjs #
// src/db.mjs
import { fileURLToPath } from 'node:url';
import pg from 'pg';
import { bootWalk, createFailoverPool, migrationsFrom } from '@turnzero/database';
const MIGRATIONS = fileURLToPath(new URL('../migrations/', import.meta.url));
const HEALTH_READ_MS = 2_000;
// The live pool, which only the process entry opens: the package's failover
// pool over a pg pool. APP_DATABASE_CONNECTION_LIMIT sets its maximum.
// The platform supplies it; the turnzero command's provision writes it for
// a local run. The pool uses one connection where the setting is absent.
export function openLivePool() {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
const limit = process.env.APP_DATABASE_CONNECTION_LIMIT ?? '';
const max = /^[1-9][0-9]*$/.test(limit) ? Number(limit) : 1;
return createFailoverPool({
// settings is { max, connectionTimeoutMillis }: the maximum and the five-second connect limit.
connect: (settings) => new pg.Pool({ connectionString: url, ...settings }),
max,
onConnectionLoss: (error) => console.warn('database session ended:', error.message),
});
}
// The migrations through the package's boot walk: a lost connection retried
// every second for up to 120 seconds, and any other failure ends the start.
export function migrate(pool) {
return bootWalk(pool, migrationsFrom(MIGRATIONS), {
onRetry: (error, attempt) => {
if (attempt === 1) console.warn('database unreachable at start; retrying:', error.message);
},
});
}
// The data layer over any pool with the pg.Pool shape: the live one, or a test double's.
// Each row belongs to the signed-in user who added it, its owner, and is listed to that user
// alone, newest first; only its owner can delete it.
export function createDataLayer(pool) {
return {
// One read over the connection, bounded so a probe never waits on a lost database.
async reachable() {
let timer;
const late = new Promise((resolve) => { timer = setTimeout(resolve, HEALTH_READ_MS, 'late'); });
try {
return (await Promise.race([pool.query('SELECT 1'), late])) !== 'late';
} catch {
return false;
} finally {
clearTimeout(timer);
}
},
async addNote(owner, body) {
const { rows } = await pool.query('INSERT INTO "notes" (owner, body) VALUES ($1, $2) RETURNING id, body, created_at', [owner, body]);
return rows[0];
},
async listNotes(owner) {
const { rows } = await pool.query('SELECT id, body, created_at FROM "notes" WHERE owner = $1 ORDER BY created_at DESC, id DESC', [owner]);
return rows;
},
// True where the row was the owner's and is gone; false where no row of the owner's has the id.
async deleteNote(owner, id) {
const { rowCount } = await pool.query('DELETE FROM "notes" WHERE owner = $1 AND id = $2', [owner, id]);
return rowCount === 1;
},
};
}
src/main.mjs #
// src/main.mjs, the process entry the start script runs
import { createDataLayer, migrate, openLivePool } from './db.mjs';
import { createUserReader, openLiveAccounts } from './session.mjs';
import { createAppServer } from './server.mjs';
const pool = openLivePool();
const applied = await migrate(pool);
console.log(applied.length > 0 ? `migrations applied at this start: ${applied.join(', ')}` : 'migrations: none pending at this start');
const port = Number(process.env.PORT ?? 8080);
const server = createAppServer({ db: createDataLayer(pool), userIdOf: createUserReader(openLiveAccounts()) });
server.listen(port, () => console.log(`listening on ${port}`));
src/server.mjs #
// 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' });
}
});
}
src/session.mjs #
// src/session.mjs: the signed-in user who sent a request, as the guide Add
// sign-in to your app shows it.
import { makeVerifyClient } from '@turnzero/account';
// The cookie a signed-in browser sends with each request to the application's address.
const SESSION_COOKIE = '__Host-turnzero_cloud_realm';
// The live client, which only the process entry opens. A deployed copy
// receives all three settings. A local run has no TURNZERO_CLOUD_REALM_KEYS,
// so the client is built without keys there and verifies through the
// platform's route. Where the credential is not set, the start stops and
// says which line writes it.
export function openLiveAccounts() {
const keys = process.env.TURNZERO_CLOUD_REALM_KEYS;
if (!process.env.TURNZERO_CLOUD_APP_TOKEN) throw new Error('TURNZERO_CLOUD_APP_TOKEN is not set, so no session can be verified. Run the provision line again, then start the app again.');
return makeVerifyClient({
baseUrl: process.env.TURNZERO_CLOUD_API,
credential: process.env.TURNZERO_CLOUD_APP_TOKEN,
...(keys ? { realmKeys: keys } : {}),
});
}
// The session token: the cookie's value from a browser, or the bearer from a
// native app or a local run.
export function sessionOf(request) {
const auth = request.headers.authorization ?? '';
if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length);
for (const part of (request.headers.cookie ?? '').split(';')) {
// Spaces and tabs come off a pair and nothing else, so a name is read as it stands.
let from = 0;
let to = part.length;
while (from < to && (part.charCodeAt(from) === 0x20 || part.charCodeAt(from) === 0x09)) from += 1;
while (to > from && (part.charCodeAt(to - 1) === 0x20 || part.charCodeAt(to - 1) === 0x09)) to -= 1;
const pair = part.slice(from, to);
const at = pair.indexOf('=');
if (at > 0 && pair.slice(0, at) === SESSION_COOKIE) return pair.slice(at + 1);
}
return null;
}
// The reader of a request's user: the signed-in user's id, or null with no
// live session. The token is verified by the Account package's client, with
// the x-turnzero-cloud-session header the serving router sets on each
// request it forwards.
export function createUserReader(accounts) {
return async (request) => {
const verdict = await accounts.verifySession(sessionOf(request), {
sessionHeader: request.headers['x-turnzero-cloud-session'] ?? null,
});
return 'user' in verdict ? verdict.user.id : null;
};
}
test/app.test.mjs #
// 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/<id> 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;
}
});