Running it · Creating a demo account and loading its session · stage 10 of 10
Demo accounts and sessions
A visitor's demo account is one row in D1's demos table, one per verified email address; the code calls it a demo. It owns the visitor's files, chunks and questions. The row holds the account's id, which also names its Vectorize namespace (the account's own partition of the vector index), and the SHA-256 of its access key, the random string the browser keeps in the demo cookie. At sign-up the site calls createDemo, which creates the row or gives the address's existing account a new access key; for an engagement it calls openDemo, which gives that engagement's account a new access key. Either way the site receives the plaintext key once. When the page loads, start() requests GET /api/demo/session. session() returns the account's files, the questions it has left, its limits, whether the idle purge cleared its documents, and up to 20 earlier checked answers. The page draws all of these.
Browser: the visitor's page: demo.html and its module scriptDemo Worker: the private Worker behind the DEMO service binding, demo/src/New to Cloudflare? How these fit together
demo/src/app.ts136 / 136 lines on this page explainedlines 124-259 of 1124; the rest are on other stage pages
demo.html26 / 26 lines on this page explainedlines 179-204 of 505; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own
POST /internal/demos: creates the demo account for a visitor's identity, or gives the live account that identity already has a new access key, and returns the new key once.
/** Creates the demo for a visitor's identity, or finds the one it already has, and gives it a fresh key. */asyncfunctioncreateDemo(request: Request, env: Env): Promise<Response> {
Doc comment and signature Site request
WhatRuns when the site calls POST /internal/demos at sign-up. route() dispatches here before any key check (app.ts:1073).
WhyThe site's proxies never forward an /internal path (the page's proxy forwards only session, files, ask and grants), so a browser cannot reach this route. Only the site's own server code, which holds the DEMO service binding, can create a demo account.
// The visitor's identity, sent by the site: now `email:` + a hash of their address, or an older demo's card fingerprint.// It is unique, so one demo per email; the column keeps its card-era name.const fingerprint = typeof body.fingerprint === 'string' ? body.fingerprint : ''if (fingerprint === '') returnjson(400, { error: 'no card fingerprint' })
The visitor's identity Site request
Whatfingerprint must be a non-empty string, or the call answers 400. It is "email:" plus a hash of the verified address, or, for an account made before email sign-up, a Stripe card fingerprint.
Whycard_fingerprint is NOT NULL UNIQUE in schema.sql, so the identity alone decides which account row is used, and each verified address has one demo account. The column and the error text keep their names from the card era.
// Company, contact and engagement id are optional text, each cut to 300 characters.consttext = (key: string) => (typeof body[key] === 'string' ? (body[key] asstring).slice(0, 300) : null)
Optional text fields Site request
Whattext(key) returns body[key] cut to 300 characters when it is a string, and null otherwise. It reads engagement_id, company and contact.
WhyThe values are stored and shown on the site's admin pages, so the cut limits what one call can write. contact has the form "Name <address>", which about() parses for the X-Demo-Email header.
// The key goes back to the site for the visitor's cookie; only its hash is stored.const key = randomKey(32)const hash = awaitsha256(key)
A fresh key, stored only as its hash Site request
WhatrandomKey(32) draws 32 bytes from crypto.getRandomValues and encodes them as 43 unpadded base64url characters. sha256 turns the key into 64 hex digits.
WhyOnly the hash is written, so reading the demos table signs no one in. The plaintext key goes back once, to the site, which puts it in the visitor's HttpOnly cookie. functions/_lib/demo.ts accepts exactly this 43-character format.
// The demo's row, under a fresh random id: 16 base64url characters, lower-cased, with - and _ made x.await env.DB.prepare(// One demo per identity: the same one again re-keys its existing demo instead of making another, unless that one was purged.`INSERT INTO demos (id, key_hash, engagement_id, card_fingerprint, company, contact) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (card_fingerprint) DO UPDATE SET key_hash = excluded.key_hash WHERE demos.purged_at IS NULL`, ).bind(randomKey(12).toLowerCase().replace(/[^a-z0-9]/g, 'x'), hash, text('engagement_id'), fingerprint, text('company'), text('contact')).run()
Insert, or give the live account a new key Site request
WhatOne INSERT … ON CONFLICT (card_fingerprint) DO UPDATE SET key_hash = excluded.key_hash WHERE demos.purged_at IS NULL. A new identity gets a row under a new id. A known identity keeps its row, and only its key_hash changes.
WhyAn upsert decides between insert and update in a single statement, so two sign-ups for one address can never create two demo accounts. When it gives an existing account a new key, the statement discards the new id, company, contact and engagement_id, and the old cookie stops working. The id also names the account's Vectorize namespace, so it must be stable and use a safe alphabet. As the comment says, it is 16 base64url characters (randomKey(12)), lower-cased, with - and _ replaced by x.
id: 16 characters of [a-z0-9]conflict target: card_fingerprintupdate only while purged_at IS NULL
// The row is read back to learn whether this key landed: on a new demo, or as a re-key of the identity's live one.const demo = await env.DB.prepare('SELECT id, key_hash, purged_at FROM demos WHERE card_fingerprint = ?') .bind(fingerprint).first<{ id: string; key_hash: string | null; purged_at: string | null }>()
Read the row back Site request
WhatSelects id, key_hash and purged_at by card_fingerprint.
WhyWhen the DO UPDATE's WHERE is false (a purged row), the statement changes nothing and raises no error. Reading the row back and comparing key_hash is the only way to learn whether this key was stored.
// The identity's row is purged, or our key did not land on it: its demo has expired.if (demo === null || demo.purged_at !== null || demo.key_hash !== hash) returnjson(200, { expired: true })returnjson(200, { key, id: demo.id })}
Expired, or the key and id Site request
WhatIf the row is missing, purged, or holds a different key_hash, the answer is 200 { expired: true }; otherwise 200 { key, id }.
Whypurged_at belongs to an older 14-day rule (schema.sql), and no code at this commit sets it. The expired answer therefore covers legacy rows, and a concurrent sign-up for the same identity that gave the row a new key between the two statements. The current idle purge deletes documents but keeps the account and its key.
/** Of the engagement ids given, those with a demo that is not purged. */asyncfunctionwhichDemos(request: Request, env: Env): Promise<Response> {// The site's request body; a body that is not JSON reads as empty.const body = (await request.json().catch(() => ({}))) as { engagement_ids?: unknown }
Doc comment, signature and body Site request
WhatRuns on the site's POST /internal/demos/which. A body that is not JSON is read as {}, as in createDemo.
WhyThe site uses the answer to decide which of a signed-in client's engagements can open a demo account. The Worker answers only that question and never sees the site's session.
// Only strings, at most 100, so the IN list below stays within D1's limit on bound values.const ids = Array.isArray(body.engagement_ids) ? body.engagement_ids.filter((id): id is string => typeof id === 'string').slice(0, 100) : []if (ids.length === 0) returnjson(200, { engagement_ids: [] })
Strings only, at most 100 Site request
Whatengagement_ids is filtered to strings and cut to 100. An empty list answers { engagement_ids: [] } without a query.
WhyEach id becomes one bound parameter, and the cut keeps the IN list within D1's limit on bound parameters, as the source comment says. Returning early for an empty list also avoids an invalid IN ().
// An engagement with several demos is listed once.const rows = await env.DB.prepare(`SELECT DISTINCT engagement_id FROM demos WHERE purged_at IS NULL AND engagement_id IN (${ids.map(() => '?').join(', ')})`, ).bind(...ids).all<{ engagement_id: string }>()
One IN query with placeholders Site request
WhatSELECT DISTINCT engagement_id … WHERE purged_at IS NULL AND engagement_id IN (?, ?, …), with one placeholder per id and the ids bound in order.
WhyOnly the placeholders are built into the SQL text and the values are bound, so an id can never change the statement. DISTINCT lists an engagement once even when it has several demo accounts.
POST /internal/demos/open: gives an engagement's newest live demo account a new access key and returns it, so the site can sign the engagement's client in.
/** Gives the engagement's latest live demo a fresh key, as createDemo does for a returning card. */asyncfunctionopenDemo(request: Request, env: Env): Promise<Response> {// The engagement whose demo to open, as the site sent it.const body = (await request.json().catch(() => ({}))) as { engagement_id?: unknown }const engagement = typeof body.engagement_id === 'string' ? body.engagement_id : ''
Doc comment, signature and the engagement id Site request
WhatRuns on the site's POST /internal/demos/open. engagement_id is read from the body, and any value that is not a string becomes ''.
WhyThe site decides who may open an engagement's demo account. This route trusts its caller because only the site holds the DEMO service binding.
// The engagement's newest live demo is re-keyed in one statement; if it has none, no row changes.const demo = await env.DB.prepare(`UPDATE demos SET key_hash = ? WHERE id = ( SELECT id FROM demos WHERE engagement_id = ? AND purged_at IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1 ) RETURNING id`, ).bind(awaitsha256(key), engagement).first<{ id: string }>()
Pick the account and give it a new key in one statement Site request
WhatUPDATE demos SET key_hash = ? WHERE id = (SELECT id … WHERE engagement_id = ? AND purged_at IS NULL ORDER BY created_at DESC, rowid DESC LIMIT 1) RETURNING id.
WhySelecting the account and changing its key in one statement leaves no window in which another request could change which account is newest. rowid breaks ties between accounts created in the same second, since datetime('now') has one-second resolution. RETURNING gives the id without a second query, and returns no row when nothing matched.
// No engagement id given, or no live demo for it: nothing to open.if (engagement === '' || demo === null) returnjson(404, { error: 'no demo' })returnjson(200, { key, id: demo.id })}
404, or the key and id Site request
WhatAn empty engagement id or no matching account answers 404 { error: 'no demo' }; otherwise 200 { key, id }.
WhyThe empty-id check comes after the UPDATE, so an empty id still runs the UPDATE. That statement can match only an account stored with engagement_id '' (NULL never equals ''), which would get a new key and then be reported as 404.
The maximum number of earlier answers the session returns.
/** * How many earlier answers the page is given back when it loads (`history` in the session). * Ten is the demo's whole allowance of questions; the cap only matters for a demo whose count * was reset, and keeps the page from drawing an unbounded list. */exportconstHISTORY = 20
At most 20 earlier answers Module load
WhatHISTORY = 20 is the LIMIT of session()'s questions query.
WhyEvery history row is a question that was reserved and not refunded. The one refund (app.ts:805) records the question without an answer, so it never enters the history. The canary's demo account, whose count is reset (health.ts:228), has no key, so no browser loads its session. An account that a browser can open therefore has at most 10 rows of history, and 20 is a safety bound for a count changed outside this code.
One earlier answer, in the shape of a successful ask's body.
/** One earlier answer as the page draws it: the same shape as the body of a successful ask. */exportinterfaceAsked {question: stringanswer: string/** Present only for a list answer, as in an ask's body. */items?: string[]sources: unknown[]}
The same shape as an ask's reply Type only
Whatquestion, answer, items (for a list answer only) and sources.
WhyAn earlier answer has the fields of the ask's done event, so render() in demo.html draws it with the same addProse, addItem and addSources calls that draw a streamed answer. sources is typed unknown[] because the Worker passes the stored JSON through without reading it.
/** * A recorded answer read back into the shape the page draws, the reverse of `asText`: the lines * that start with "- " are the list's items, the other lines its lead-in (or the whole prose). * A prose answer is one paragraph with no such lines, so it comes back as it was shown. */exportfunctionfromText(text: string): { answer: string; items?: string[] } {
Doc comment and signature Site request
WhatThe doc comment gives the format: lines that start with "- " are list items, and every other line belongs to the lead-in or to the whole prose.
Whyquestions.answer is one text column, written by asText at ASK 8, so the site's admin pages and the golden-set export can read it as plain text. The page needs the parts separated to draw a list as bullets.
// List items are the lines that start with "- ", without that marker; everything else is the lead-in.const lines = text.split('\n')const items = lines.filter((line) => line.startsWith('- ')).map((line) => line.slice(2))const answer = lines.filter((line) => !line.startsWith('- ')).join('\n').trim()
Items and lead-in Site request
WhatSplits the text on newlines. Lines that start with "- " lose the marker and become items; the other lines are joined with newlines and trimmed.
WhyThe prose units (the answer's sentences and lead-ins) are joined with spaces before asText is called (app.ts:847), so a prose answer has no newline and no "- " line, and it comes back unchanged.
/** * The page's state when it loads: the files, the questions left, and the earlier answers. * * `history` is every question this demo was shown an answer to, newest first, read from the * `questions` table the ask records into (ASK 8). Only answers that passed the check * (`checked = 1`) are given back: a refused or failed question showed the visitor only the * fallback line, so there is no answer to show again. The sources are the ones recorded with the * answer, passages included, so "Show the passage" works on an earlier answer as it did when it * was asked; a question kept with consent (keep = 1) keeps them after the idle purge too. */asyncfunctionsession(demo: Demo, env: Env): Promise<Response> {
What the session returns, and why only checked answers Site request
WhatThe doc comment lists what session returns: the files, the questions left, and earlier answers from the questions table, newest first. Only answers with checked = 1 are returned, with their recorded sources and passages. The function runs when the page loads, after route() has found the demo account by its access key.
WhyA refused or failed question showed the visitor only a fallback line, so there is no answer to draw again. As the comment says, the passages outlive the idle purge only for kept questions (keep = 1). The purge deletes questions with keep = 0 together with the documents (app.ts:900), and in this repository mayRecord always returns false, so every question has keep = 0.
// The files in upload order, each with the page numbers that had no text.const files = await env.DB.prepare('SELECT name, pages, skipped FROM files WHERE demo_id = ? ORDER BY rowid') .bind(demo.id).all<{ name: string; pages: number; skipped: string }>()
The files, in upload order Site request
WhatSelects each file's name, pages and skipped pages for this account, ordered by rowid.
Whyrowid follows insertion order, so the list matches the order in which the visitor added the files. skipped is the JSON list of pages with no extractable text, which the page shows with each file.
// The answers that passed the check, newest first, at most HISTORY of them.const asked = await env.DB.prepare('SELECT question, answer, sources FROM questions WHERE demo_id = ? AND checked = 1 AND answer IS NOT NULL ORDER BY asked_at DESC, rowid DESC LIMIT ?') .bind(demo.id, HISTORY).all<{ question: string; answer: string; sources: string }>()
The checked answers, newest first Site request
WhatSELECT question, answer, sources FROM questions WHERE demo_id = ? AND checked = 1 AND answer IS NOT NULL ORDER BY asked_at DESC, rowid DESC LIMIT 20.
Whychecked = 1 includes answers that stopped partway (fallback 'stopped'). Each sentence shown had passed the check, so those sentences are drawn again, without the stopped line. Questions asked through the MCP server are in the same table, so they appear here too. rowid DESC orders two answers recorded in the same second.
// Each recorded answer is split back into prose and list items, and its sources parsed from the stored JSON.consthistory: Asked[] = asked.results.map((row) => ({ question: row.question, ...fromText(row.answer), sources: JSON.parse(row.sources) asunknown[] }))
Back into the ask's shape Site request
WhatEach row becomes an Asked: the question, fromText(answer), and the parsed sources JSON.
WhyThe stored sources hold each cited chunk's text as passage, so "Show the passage" works on a redrawn answer without a read of the chunks table.
// What the page draws: the files, the questions left, the limits, whether idleness cleared the// documents, and the earlier answers.returnjson(200, {files: files.results.map((file) => ({ name: file.name, pages: file.pages, skipped: JSON.parse(file.skipped) asnumber[] })),left: LIMITS.asks - demo.asks_used,limits: LIMITS,cleared: demo.cleared_at !== null, history, })}
The session body Site request
What200 with files (skipped parsed), left = LIMITS.asks − asks_used, limits (the whole LIMITS object), cleared (cleared_at is set) and history.
Whyleft comes from the row signedIn read, so it counts every question reserved, from the page or from the MCP server. cleared tells the page that the idle purge deleted its documents. The next upload sets cleared_at back to NULL (app.ts:309).
Runs once when the page loads. It requests the session and shows either the sign-up box or the visitor's demo account: their files, the questions left and earlier answers.
WhatRequests GET /api/demo/session. A network failure becomes null, and a body that is not JSON becomes {}.
WhyThe demo cookie is HttpOnly, so the page's script cannot read whether it holds a key, and requesting GET /api/demo/session is the only way to learn whether the visitor is signed in. The browser sends the cookie with this same-origin request, and the proxy turns it into X-Demo-Key.
if (!response || !response.ok) { $("signed-out").hidden = false;// Returning visitors verify their email again to open their existing demo.if (/(?:^|; )(?:registered|signed_in)=1(?:;|$)/.test(document.cookie)) $("try-it").textContent = "Verify your email to try it"; $("expired").hidden = !(body.expired || params.has("expired"));if (params.has("unavailable")) { $("expired").textContent = "The demo is not available right now. Please try again later."; $("expired").hidden = false; }return; }
Signed out: the sign-up box In the browser
WhatAny failure shows #signed-out. When a registered=1 or signed_in=1 cookie is present, the button reads "Verify your email to try it". The expired line shows when the Worker reported expired (a key was sent but matches no live demo account) or the URL has ?expired. ?unavailable replaces that line's text with a not-available message and shows it.
Whyregistered and signed_in are the site's readable hint cookies. The site sets them outside this repository, as it does the ?expired and ?unavailable query parameters. A 503 from the proxy (no DEMO binding) or a 500 also lands here, without the expired line.
$("signed-in").hidden = false; body.files.forEach(listFile);// Every earlier answer, newest first, collapsed to its question (see render). (body.history ?? []).forEach((asked) =>render(asked.question, asked, true)); $("cleared").hidden = !body.cleared; left = body.left;showLeft();if (left <= 0) showOffer();showConnect(); }
Signed in: draw the account's view In the browser
WhatShows #signed-in, lists each file (listFile), draws each earlier answer collapsed (render with earlier = true), shows the cleared notice, sets left, shows the offer when no question is left, and calls showConnect.
WhyThe history arrives newest first and render appends earlier answers in that order, so the newest is on top. After a reload the PDFs are no longer in this tab (the opened map is empty), so a redrawn source names its file without a link.