Joel Stevick

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.

Runs in: Demo Worker, the private Worker behind the DEMO service binding, demo/src/. New to Cloudflare? How these fit together
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

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo/src/app.ts The demo Worker: json, about, sha256, randomKey and signedIn.

json()

function · lines 71–75View on GitHub

A JSON Response with a status, a body and optional extra headers.

Called by adminDemo() Consent and the archive adminDemos() Consent and the archive ask(): ASK 1 Validate the question ask(): ASK 1–2, then JSON or server-sent events Worker router ask(): ASK 2 Reserve a question authorize() The consent page challenge() Token exchange (RFC 8693) createApp(): fetch Worker router createDemo() Demo accounts and sessions docsStoreRoute() Token exchange (RFC 8693) grantsRoute() Listing and disconnecting apps healthRoute() Daily health oauthError() Token exchange (RFC 8693) oauthRoute(): RESOURCE Token validation and limits openDemo() Demo accounts and sessions remove() Removing a file route(): the visitor's routes Worker router serveMcp() Token validation and limits serversFor(): RESOURCE Token validation and limits session() Demo accounts and sessions tokenExchange() Token exchange (RFC 8693) tooMany Token validation and limits upload(): INGEST 1 Validate the upload upload(): INGEST 2 Claim the file name upload(): INGEST 3 Check the limits upload(): INGEST 5 Store the chunks upload(): INGEST 7 Notify and reply whichDemos() Demo accounts and sessions

/** A JSON response with the given status, body and any extra headers. */export function json(status: number, body: unknown, extra: Record<string, string> = {}): Response {  return new Response(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.

about()

function · lines 76–84View on GitHub

The X-Demo-* headers the site reads to record an event. The site removes them before the response reaches the browser.

Called by ask(): ASK 1–2, then JSON or server-sent events Worker router decided() The consent page grantsRoute() Listing and disconnecting apps remove() Removing a file upload(): INGEST 7 Notify and reply

/** 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. */export function about(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.

sha256()

async function · lines 96–104View on GitHub

The hex SHA-256 of a text.

Called by signedIn() anonymousAllowed() Token validation and limits createDemo() Demo accounts and sessions cursorFor() search_documents docsStoreRoute() Token exchange (RFC 8693) offsetOf() search_documents openDemo() Demo accounts and sessions tokenExchange() Token exchange (RFC 8693)

/** The hex SHA-256 of a text. Only a key's hash is stored, so the table alone signs no one in. */export async function sha256(text: string): Promise<string> {  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().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.

  // The digest's bytes as two-digit hex, joined into one string.  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')}

As 64 hex characters Query time

WhatEach of the 32 digest bytes becomes two lower-case hex digits, and the digits are joined into one string.

WhyThe hex string is one fixed text form, so the hash compares equal in SQL (WHERE key_hash = ?) and works with the UNIQUE constraint on key_hash.

64 hex characters

randomKey()

function · lines 105–112View on GitHub

A URL-safe string of random bytes, used for keys, ids and chunk-id prefixes.

Called by ask(): ASK 1–2, then JSON or server-sent events Worker router createDemo() Demo accounts and sessions openDemo() Demo accounts and sessions upload(): INGEST 4 Chunk each page

/** A random URL-safe string of `bytes` random bytes, for demo keys, ids and upload prefixes. */function randomKey(bytes: number): string {  const raw = crypto.getRandomValues(new Uint8Array(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.  return btoa(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.

32 bytes → 43 characters12 bytes → 16 characters

signedIn()

async function · lines 113–123View on GitHub

The visitor's live demo account, found by the hash of the forwarded access key.

Called by authorize() The consent page route(): the visitor's routes Worker routerCalls sha256()

/** The demo whose key the cookie holds, looked up by the key's hash and nothing else. */export async function signedIn(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 === '') return null  return 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(await sha256(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