Notes app with sign-in, as functions #
On this page
A notes app with sign-in. Each user keeps private notes in PostgreSQL, and the app runs as functions.
Sign-up is open to anyone. Each signed-in person can read, add and delete only their own notes.
Use server-sign-in to run the same notes app on an application server.
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 functions-sign-in
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. Account tools such as read_rate_card keep their shorter names. The copied AGENTS.md instructions below use the names listed by the MCP connection.
Follow these calls to deploy the example. To adapt it, read Deploy from a chat.
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.
Without a shell, use exact version 8.22.0 for pg: replace "^8.22.0" with "8.22.0" in package.json's dependencies. This version is published, so no registry lookup is needed for this sample. Only the direct dependency is pinned. Keeping a range also builds, but without a lockfile the build resolves it again each time.
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.
GET /__account/me returns JSON for the signed-in user. Read an email from user.addresses, whose entries hold email and verified. The list can hold more than one address; this sample has one at user.addresses[0].email.
{
"contract_version": 1,
"user": {
"id": "0b6f1d2e-5c3a-4e7f-9a81-2d4c6e8f0a1b",
"realm": "c41a7e90-3b2d-4f6a-8e15-7d9b0c2a4e6f",
"addresses": [{ "email": "person@example.com", "verified": true }],
"routes": ["email"],
"standing": "active"
},
"session": { "expires": "2026-12-23T16:00:00.000Z" }
}
For a new application, make these calls in order.
- Call
tzcloud_create_applicationwithnameandkind: "serverless", withoutsize. Keep the returnedapplication.id. - Call
tzcloud_read_librarywithentry: "account". Put the entry's name and current version in the manifest'spackageslist. Keep the database and accounts services in the manifest. - Call
tzcloud_submit_manifestwithapplicationand the completemanifestobject. - Call
read_rate_cardand explain the expected usage charges before deploying. Follow the manifest answer's cost guidance. - Call
tzcloud_deploy_fileswithapplication,environment: "production", and the completefileslist ofpathandcontent. Omit the library copy underlib/account/. Keep the example's ownlib/modules. Usepgversion8.22.0. - If the deploy is still running, call
tzcloud_read_statuswithapplicationandwait_seconds: 45until it ends. Read the outcome and stop if the deploy failed.
Check it works #
Call tzcloud_check_deploy with application. Use that ID and the production environment for the following checks. Read the sign-in settings with tzcloud_read_app_sign_in. Ask the person to open the deployed application's address and sign in there.
- Call
tzcloud_request_routefor/and expect 200 with the page. Read/api/noteswithouttest_end_userand expect 401sign_in_required. - Follow Test sign-in with test end users for credentials and for which production writes need the owner's confirmation on an app with real users. For this new example with no real users, call
tzcloud_add_test_end_userswith two unused labels and keep both IDs. Pass one ID astest_end_useron each signed-in call. - As the first user, read
/api/notesand expect 200 with a JSON list. Calltzcloud_write_routewithmethod: "POST",path: "/api/notes",headers: {"content-type":"application/json"}, and a JSONbodycontaining{"body":"example check"}. Expect 201 and keep the note ID. Read the list again to find the note. - As the second user, read the list and confirm the first user's note is absent. Send
DELETE /api/notes/<id>withtzcloud_write_routeas the second user and expect 404not_found. As the first user, delete the note, expect 204, and read the list to confirm it's gone. - Remove both test users with
tzcloud_add_test_end_users,remove: true, and their IDs inend_users. Calltzcloud_read_logswithsource: "pool". Report the results, cleanup, and any test data left.
The first user makes five signed-in calls. To repeat a check after reaching that user's default hourly limit, wait for the limit to reset.
Report separately whether browser sign-in and sign-out, page behavior, and the local tests were checked. The route checks above verify the deployed API.
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 |
functions/api/notes.js |
Text |
lib/db.js |
Text |
lib/notes.js |
Text |
lib/session.js |
Text |
manifest.json |
Text |
migrations/0001_notes.sql |
Text |
package.json |
Text |
test/notes.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 `functions-sign-in` template: a notes app with sign-in, each user's own notes in the platform's database, served as a serverless application with functions. The `server-sign-in` template is the same app on a server. This file describes the template the service started from: keep it current as the service changes.
## Where you build
- Edit the page's files under `client/`. A file's path below `client/` is its path on the site; `/` serves `client/index.html`.
- Each file under `functions/` is one function. `functions/api/notes.js` handles `/api/notes` and the paths beneath it: each request reads the signed-in user, and keeps, lists, and deletes that user's own rows.
- Put shared code under `lib/`, which serves no path. `lib/notes.js` holds the routes, `lib/session.js` the signed-in user, and `lib/db.js` the database.
- Put each database schema change in a new file under `migrations/`. The platform applies these files before a deployed version serves.
## 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 deploy: the `deploy` skill gives each step and the line to run, in this order: `tzcloud_submit_manifest`, `tzcloud_deploy_command`.
- Sign-in: on the deployed application's own address.
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 here. Use the deployed address. For local sign-in with a server app, provision it, then use turnzero run with a port and --sign-in followed by the app's hostname.");
}
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}}
functions/api/notes.js #
// functions/api/notes.js: this file answers /api/notes and the paths beneath
// it. A function is a module whose default export has fetch(request) and
// returns a Response.
import { notesStore } from '../../lib/db.js';
import { createNotesApi } from '../../lib/notes.js';
import { createUserReader, openLiveAccounts } from '../../lib/session.js';
export default { fetch: createNotesApi({ db: notesStore, userIdOf: createUserReader(openLiveAccounts) }) };
lib/db.js #
// lib/db.js: each user's notes in the application's database.
import pg from 'pg';
// One connection for this worker, opened at its first query and kept while
// the worker lives. The platform supplies APP_DATABASE_URL, and the turnzero
// command's provision writes it for a local run. The platform applies the
// files under migrations/ before a version serves, so the table stands when a
// function first reads it.
let pool;
async function query(text, values) {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
pool ??= new pg.Pool({ connectionString: url, max: 1, connectionTimeoutMillis: 5000 }).on('error', (error) => console.error(error.message));
return pool.query(text, values);
}
// The data layer over any query function with pg's 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(run) {
return {
async addNote(owner, body) {
const { rows } = await run('INSERT INTO "notes" (owner, body) VALUES ($1, $2) RETURNING id, body, created_at', [owner, body]);
return rows[0];
},
async listNotes(owner) {
const { rows } = await run('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 run('DELETE FROM "notes" WHERE owner = $1 AND id = $2', [owner, id]);
return rowCount === 1;
},
};
}
export const notesStore = createDataLayer(query);
lib/notes.js #
// 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' });
}
};
}
lib/session.js #
// lib/session.js: the signed-in user who sent a request, as the guide Add
// sign-in to your app shows it, read in a function.
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, opened at the first request. A deployed function receives
// the platform's address and the application's credential; where it also
// receives the realm's keys, the client verifies with them, and otherwise
// through the platform's route.
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.');
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 test.
export function sessionOf(request) {
const auth = request.headers.get('authorization') ?? '';
if (auth.startsWith('Bearer ')) return auth.slice('Bearer '.length);
for (const part of (request.headers.get('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. accountsOf is called at the first request, so a
// module that only imports this file opens nothing.
export function createUserReader(accountsOf) {
let accounts;
return async (request) => {
accounts ??= accountsOf();
const verdict = await accounts.verifySession(sessionOf(request), {
sessionHeader: request.headers.get('x-turnzero-cloud-session'),
});
return 'user' in verdict ? verdict.user.id : null;
};
}
manifest.json #
{
"manifest_version": 1,
"services": [{ "kind": "database" }, { "kind": "accounts" }],
"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": "functions-sign-in",
"private": true,
"type": "module",
"scripts": {
"test": "node --test"
},
"dependencies": {
"@turnzero/account": "file:lib/account",
"pg": "^8.22.0"
}
}
test/notes.test.mjs #
// 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);
}
});