Running it · Responses, key hashing and sign-in · stage 9 of 10
Shared helpers
Five small functions that the routes call. json builds a JSON response. about returns the headers the site reads to record an event. sha256 and randomKey are the Web Crypto primitives behind access keys and account ids. signedIn finds the visitor's demo account (their row in the demos table) from the access key the site forwards, by the key's hash alone.
demo/src/app.ts42 / 42 lines on this page explainedlines 71-84,96-123 of 1124; 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
/** A JSON response with the given status, body and any extra headers. */exportfunctionjson(status: number, body: unknown, extra: Record<string, string> = {}): Response {returnnewResponse(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json', ...extra } })}
Every JSON reply Query time
WhatSerialises body with JSON.stringify and sets Content-Type: application/json. The extra headers are spread after it, so a caller can override the content type.
WhyMost JSON responses go through this one function, so the content type stays consistent: errors, the session, upload, remove, the JSON ask, and the router's 401 and 404. The routes that answer in other formats build their own Response: the ask's event stream, the golden-set export's NDJSON, and the consent page's HTML and redirects. oauth.ts, mcp.ts, health.ts and token-exchange.ts import json.
/** What the site reads off a demo route's answer (an upload, a removal, a question, a grant) to record the event; it never reaches the browser. */exportfunctionabout(demo: Demo, question?: string): Record<string, string> {// The address is the part of "Name <address>" inside the angle brackets; with none, no email header is sent.const email = /<([^<>]+)>$/.exec(demo.contact ?? '')?.[1] ?? ''
The address from the contact Query time
WhatTakes the account's row and an optional question id. The regular expression /<([^<>]+)>$/ extracts the address from a contact stored as "Name <address>". Without a match, the address is the empty string.
WhyThe contact is one text column, so the address is parsed here instead of being stored twice. The doc comment names the routes whose events the site records from these headers: an upload, a removal, a question and a grant, which covers the Connected apps disconnect and the OAuth consent flow (oauth.ts).
// The demo's id always, then the email and the question's id only when there is one.return { 'X-Demo-Id': demo.id, ...(email ? { 'X-Demo-Email': email } : {}), ...(question ? { 'X-Question-Id': question } : {}) }}
Only the headers that have a value Query time
WhatX-Demo-Id is always set. X-Demo-Email is set only when an address was found, and X-Question-Id only when a question id was given (the ask's stream, and its JSON response when the question was recorded).
WhyBoth site proxies read these headers to attribute their events. functions/api/demo/[[path]].ts records demo_upload, demo_remove, demo_ask and the disconnect's demo_mcp_grant, and functions/_lib/demo-mcp.ts records the consent page's demo_mcp_grant. Each proxy deletes the headers in its INTERNAL list before it responds, so the visitor's id and email never reach the browser in a header.
/** The hex SHA-256 of a text. Only a key's hash is stored, so the table alone signs no one in. */exportasyncfunctionsha256(text: string): Promise<string> {const digest = await crypto.subtle.digest('SHA-256', newTextEncoder().encode(text))
Only a hash is stored Query time
WhatDigests the UTF-8 encoding of the text with Web Crypto's crypto.subtle.digest('SHA-256').
Whydemos.key_hash holds the hash of the cookie's key and never the key, so a copy of the table signs no one in. A fast unsalted hash is enough because the key is 32 random bytes (256 bits), which no one can recover from the hash by guessing. mcp.ts also uses sha256 to hash client addresses and cursor tags, and token-exchange.ts uses it to key exchanged access tokens in KV.
/** A random URL-safe string of `bytes` random bytes, for demo keys, ids and upload prefixes. */functionrandomKey(bytes: number): string {const raw = crypto.getRandomValues(newUint8Array(bytes))
Random bytes Query time
WhatFills a Uint8Array of the requested length with crypto.getRandomValues, the runtime's cryptographically secure random number generator.
WhyAn access key is a bearer credential (whoever holds it is signed in), so it must be unpredictable, which Math.random does not guarantee. Callers request 32 bytes for an access key, 12 for an account id or a question id, and 6 for an upload's chunk-id prefix.
// URL-safe base64 of random bytes, unpadded: a key that fits a cookie and a URL.returnbtoa(String.fromCharCode(...raw)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')}
base64url, unpadded Query time
WhatConverts btoa's base64 to the URL-safe alphabet (+ becomes -, / becomes _) and removes the trailing = padding.
WhyURL-safe base64 (RFC 4648 §5) can appear in a cookie or a URL without escaping. 32 bytes give 43 characters, the exact format the site's cookie check expects (functions/_lib/demo.ts). For an account id, createDemo then lower-cases the 16 characters and replaces any - or _ with x.
/** The demo whose key the cookie holds, looked up by the key's hash and nothing else. */exportasyncfunctionsignedIn(request: Request, env: Env): Promise<Demo | null> {// The key the proxy forwarded from the visitor's cookie.const key = request.headers.get('X-Demo-Key') ?? ''
The forwarded key Query time
WhatReads X-Demo-Key, which the site's proxy sets from the visitor's HttpOnly demo cookie. A missing header becomes the empty string.
WhyBoth site proxies set X-Demo-Key only from a well-formed demo cookie. /api/demo/* builds new headers, and the consent path (functions/_lib/demo-mcp.ts) removes any X-Demo-* header the caller sent, so no other part of the browser's request can name a demo account. oauth.ts imports signedIn so that its consent page identifies the visitor the same way.
// No key forwarded means signed out. Otherwise the key's hash names the demo, and a purged demo signs no one in.if (key === '') returnnullreturn env.DB.prepare('SELECT id, asks_used, files, pages, chars, company, contact, cleared_at FROM demos WHERE key_hash = ? AND purged_at IS NULL') .bind(awaitsha256(key)).first<Demo>()}
Look up by hash, live accounts only Query time
WhatWithout a key it returns null at once. Otherwise one D1 prepared statement selects the Demo columns WHERE key_hash = sha256(key) AND purged_at IS NULL, and .first() returns null when no row matches.
WhyThe key's hash is the only identity, so nothing in the request body or URL can select another account. A key replaced by a newer one (createDemo, openDemo) no longer matches, and an account with purged_at set (the old rule that purged whole accounts) signs no one in. The router turns null into a 401, with expired: true when a key was sent.
table: demosfilter: key_hash = ? AND purged_at IS NULL