import { assertBrowserName } from './browser-state.ts'; // THE ONE HTTP ADAPTATION (runtime contract R12b): most packs' serve path is the same // ~20 lines of glue — the keyless GET /twin manifest door, the body read, a header map, // the dispatch into `handleTwinRequest` with the WORLD instant, and a JSON // response. That glue is a MECHANISM, so it lives here once; a pack's differences are // VALUES (its manifest, its header threading, its static handler options, its extra // response headers). A pack whose wire genuinely exceeds this shape (SSE streaming, // multipart adaptation, raw-bytes responses) writes its own fetch instead — openai is // that reference; this adapter is the reference for everyone else. // // Workerd-clean by construction: no Bun APIs, no fs, no clock but worldNow() — the same // closure serves under Bun.serve locally and mounted in-process on Cloudflare. import { runWithCorrelationId } from './actions.ts'; import { runWithRequestTrace } from './trace-context.ts'; import { isReadOnlyRequest, runAsReadOnlyRequest, type ReadOnlyRequestError } from './request-scope.ts'; import { worldNow } from './world-clock.ts'; /** The header a host sets when it mounts a twin under a path (a served World's wire: * `///`), the reverse-proxy convention; with it the host sets * `x-forwarded-host` and `x-forwarded-proto` to where the World is reached. */ export const TWIN_PREFIX_HEADER = 'x-forwarded-prefix'; /** Where this twin is reached for this request: the request's origin plus the path a host mounted * the twin under. A pack mints every live URL it hands back (an upload target, a file link, a * callback) from this, never from the bare origin, so the URL works behind a served World. */ export function twinPublicBase(request: Request): string { const prefix = request.headers.get(TWIN_PREFIX_HEADER); if (!prefix || !/^\/[A-Za-z0-9._~\/-]*$/.test(prefix)) { // a twin reached at its vendor's host through the World's proxy, which ends the caller's TLS and forwards the // request in the clear: the scheme the caller used is the one its links carry (a page's form posting to // http://accounts.google.com from an https page is one a browser warns about), the host the request's own // A twin reached at its own listener (a loopback or an address: the injector's route, a direct client) is that // listener, whatever scheme a caller's forwarded headers claim const proto = request.headers.get('x-forwarded-proto'); const own = new URL(request.url); // the World's proxy forwards by fetch, which replaces the Host with the twin's own address, so it names the host the // caller asked in x-volter-twin-original-host (redirect-proxy.ts); with its forwarded scheme beside it, that host is // where the caller is, and the page's links carry it (a Checkout page at checkout.stripe.com posts to it) const asked = request.headers.get('x-volter-twin-original-host'); if (asked && /^[A-Za-z0-9.-]+(:\d+)?$/.test(asked) && (proto === 'https' || proto === 'http')) return `${proto}://${asked}`; const listener = own.hostname === 'localhost' || own.hostname.endsWith('.localhost') || /^[\d.]+$/.test(own.hostname) || own.hostname.startsWith('['); return !listener && (proto === 'https' || proto === 'http') ? `${proto}://${own.host}` : own.origin; } // the host that mounted the twin says where it is reached: a local World forwards to the twin's // own port, so the request's own origin is not the public one const host = request.headers.get('x-forwarded-host'); const proto = request.headers.get('x-forwarded-proto'); const origin = host && /^[A-Za-z0-9.-]+(:\d+)?$/.test(host) && (proto === 'http' || proto === 'https') ? `${proto}://${host}` : new URL(request.url).origin; return `${origin}${prefix.replace(/\/+$/, '')}`; } /** Where a World shows a hostname its twins answer (a Workers Custom Domain, an R2 public domain): the address a person * opens it at, from the World's sites template. `{host}` stands for the hostname as it is, where the host's names nest * (`http://{host}.--.localhost:`); `{site}` for the hostname as one DNS label, its dots as hyphens, * where one wildcard certificate covers the host's names (`https://{site}----.volterdev.com`). A World that * routes its sites to a browser sends the template on every request it forwards to a twin. */ export const TWIN_SITES_HEADER = 'x-volter-world-sites'; /** The real host of the page whose hosted-site session owns this request, including a /_host/ request. */ export const TWIN_SITE_HEADER = 'x-volter-world-site'; /** A hostname as one DNS label: its dots as hyphens (`www.volter.ai` is `www-volter-ai`). */ export const siteLabel = (hostname: string): string => hostname.toLowerCase().replace(/\./g, '-'); /** The address a sites template gives `hostname`, or null where the template is not one or the name makes no address * (a label over 63 characters). */ export function siteUrlOf(template: string, hostname: string, browser?: string): string | null { const host = hostname.toLowerCase(); if (browser) { try { assertBrowserName(browser); } catch { return null; } } const label = `${browser ? `${browser}--` : ''}${siteLabel(host)}`; if (!/^[a-z0-9.-]+$/.test(host)) return null; // a one-label site is never an IDN's (`xn--…` would be read as punycode, and is no address) const filled = /^https?:\/\/\{host\}\.[A-Za-z0-9.-]+(:\d+)?$/.test(template) ? template.replace('{host}', browser ? label : host) : /^https?:\/\/\{site\}--[A-Za-z0-9.-]+(:\d+)?$/.test(template) && !host.startsWith('xn--') ? template.replace('{site}', label) : null; try { return filled && new URL(filled).hostname.split('.').every((l) => l.length > 0 && l.length <= 63) ? filled : null; } catch { return null; } } /** Where a page links a hostname the twin answers: the World's address for it when the World shows sites, else the * hostname itself (reached through the World's proxy, or the vendor). A pack's screen links a site from this, as it * mints its own URLs from twinPublicBase. */ export function twinSiteUrl(request: Request, hostname: string): string { const at = request.headers.get(TWIN_SITES_HEADER); let browser = request.headers.get('x-volter-world-browser') ?? undefined; if (browser) { try { assertBrowserName(browser); } catch { browser = undefined; } } return (at ? siteUrlOf(at, hostname, browser) : null) ?? `https://${hostname.toLowerCase()}`; } /** A URL on the page's vendor: hosted sites keep it on the page's origin, with another of the vendor's hosts under * /_host/. The World checks that target's vendor and applies the page's session; a pack supplies only its own * vendor URLs. Without hosted-site headers (the local proxy or a path-mounted page), the URL is unchanged. */ export function twinVendorUrl(request: Request, vendorUrl: string): string { const site = request.headers.get(TWIN_SITE_HEADER); if (!site || !request.headers.has(TWIN_SITES_HEADER)) return vendorUrl; let target: URL; try { target = new URL(vendorUrl); } catch { return vendorUrl; } if (target.protocol !== 'https:' || target.username || target.password || target.port) return vendorUrl; const forwarded = request.headers.get('x-forwarded-host'); const proto = request.headers.get('x-forwarded-proto'); const origin = forwarded && /^[A-Za-z0-9.-]+(:\d+)?$/.test(forwarded) && (proto === 'https' || proto === 'http') ? `${proto}://${forwarded}` : new URL(request.url).origin; const prefix = target.hostname === site.toLowerCase() ? '' : `/_host/${target.hostname}`; return `${origin}${prefix}${target.pathname}${target.search}${target.hash}`; } /** A twin's BYTE-STREAM door: a pack whose clients speak a TCP protocol (SMTP, the MySQL wire) serves * it over whatever carries the bytes — a local listener's socket, or a WebSocket to a hosted World. * The pack owns framing and protocol; the host owns the transport. `open` greets through the sink; * `data` hands the connection bytes in arrival order; `settled` resolves when every byte handed so * far has been answered; `close` is the peer going away. A connection whose work can fall behind its bytes (a live * ingest writing segments) says how many bytes wait in `backlog`, and a listener that can pause its transport does so * past a high-water mark until `settled` (serve-http.ts, `serveStream`). */ export type TwinStreamSink = { write(bytes: Uint8Array): void; end(): void }; export type TwinStreamConnection = { data(chunk: Uint8Array): void; settled(): Promise; close(): void; backlog?(): number }; export type TwinStream = (sink: TwinStreamSink, peer: string) => TwinStreamConnection; /** The request scopes a pack wrapped in `withRequestScopes` enforces, advertised on its `GET /twin` as * `requestScopes`: `read` — a request carrying `x-volter-read-only: 1` (request-scope.ts) has every * write it attempts refused at the kernel's write seam, whatever operation it names. A World's doors * forward a read-scope request that is not a GET only to a twin that advertises it. */ export const TWIN_REQUEST_SCOPES: readonly string[] = ['read']; /** `GET /twin`'s body with the request scopes this seam enforces. */ function advertised(manifest: unknown): unknown { return manifest !== null && typeof manifest === 'object' && !Array.isArray(manifest) ? { ...(manifest as Record), requestScopes: [...TWIN_REQUEST_SCOPES] } : manifest; } /** The answer to a read-only request's write when the twin names no vendor-shaped one (rule D3). */ function readOnlyRefusal(error: ReadOnlyRequestError): Response { return Response.json({ error: 'read_only', message: error.message }, { status: 405 }); } /** * THE READ SCOPE for a pack that writes its own fetch (the derived packs, the byte-wire packs): a * request carrying the read-only marker, or an instance mounted read-only, runs with the kernel's * write seam refusing its writes, and a * refused write answers `refuse` (the vendor's own read-only error; a generic 405 without one) — * whatever the handler made of the refusal. `GET /twin` advertises `requestScopes`. Everything else * passes through untouched; the wrapped fetch keeps its own properties (a derived fetch's `owners`). */ export function withRequestScopes Promise>( fetch: F, opts: { readOnly?: boolean; refuse?: (request: Request, error: ReadOnlyRequestError) => Response | Promise } = {}, ): F { const scoped = async (request: Request): Promise => { const url = new URL(request.url); if (request.method === 'GET' && (url.pathname.replace(/\/+$/, '') || '/') === '/twin') { const answer = await fetch(request); if (!answer.ok || !(answer.headers.get('content-type') ?? '').includes('json')) return answer; const headers = new Headers(answer.headers); headers.delete('content-length'); return new Response(JSON.stringify(advertised(await answer.json())), { status: answer.status, headers }); } // the request's W3C traceparent follows every entry the fetch writes, as through the kernel's own adapters // (a custom fetch never entered it, so the timeline's trace filter missed its entries) return runWithRequestTrace(request, async () => { if (!opts.readOnly && !isReadOnlyRequest(request)) return fetch(request); const out = await runAsReadOnlyRequest(() => fetch(request)); if (!out.refused) return out.value; return opts.refuse ? await opts.refuse(request, out.refused) : readOnlyRefusal(out.refused); }); }; return Object.assign(scoped, fetch); } export type TwinFetchHandlerResult = { status: number; body: unknown; headers?: Record; }; /** The common handler request shape. Extra vendor fields ride `handlerOptions` (static, * per instance) and `extras` (derived per request); handlers ignore keys they don't * declare, so the union is safe to pass wholesale. */ export type TwinFetchHandlerRequest = { method: string; path: string; body: string; headers: Record; readOnly: boolean; occurredAt: string; root?: string; } & Record; export interface TwinFetchAdapterConfig { root?: string; readOnly?: boolean; /** The keyless GET /twin body — a value (stateful packs: statefulTwinManifest(...)) or * a thunk (generative packs build theirs around the scenario engine). */ manifest: unknown | (() => unknown); /** GET /twin/scenario body (thunk) — scenario-carrying packs only. */ scenarioStatus?: () => unknown; /** Per-request vendor extras (header threading: stripe-version, notion-version, …). */ extras?: (request: Request, url: URL) => Record; /** Static per-instance handler options (e.g. rateLimitPerSecond). */ handlerOptions?: Record; /** Extra response headers on every non-door reply (e.g. stripe's request-id, and * postmark's `connection: close` Bun-socket workaround — inert under workerd). */ responseHeaders?: Record; } export function createTwinFetchFromHandler( handler: (request: TwinFetchHandlerRequest) => TwinFetchHandlerResult | Promise, config: TwinFetchAdapterConfig, ): (request: Request) => Promise { const readOnly = config.readOnly ?? false; return async function twinFetch(request: Request): Promise { const url = new URL(request.url); const cleanPath = url.pathname.replace(/\/+$/, '') || '/'; if (request.method === 'GET' && cleanPath === '/twin') { const manifest = typeof config.manifest === 'function' ? (config.manifest as () => unknown)() : config.manifest; return Response.json(manifest); } if (request.method === 'GET' && cleanPath === '/twin/scenario' && config.scenarioStatus !== undefined) { return Response.json(config.scenarioStatus()); } const body = request.method === 'GET' || request.method === 'HEAD' ? '' : await request.text(); const headers: Record = {}; request.headers.forEach((value, key) => { headers[key] = value; }); // FIXED FIELDS WIN: handlerOptions/extras spread FIRST, so no config — // and via extras, no WIRE INPUT — can override method/path/body/readOnly or the // world instant. A client-settable occurredAt would be a direct R9 hole. // D3 — the wire's request id becomes the correlation of every action this handler appends. const requestId = request.headers.get('x-twins-request-id') ?? undefined; const invoke = (asReadOnly = readOnly) => handler({ ...config.handlerOptions, ...config.extras?.(request, url), method: request.method, path: url.pathname + (url.search || ''), body, headers, readOnly: asReadOnly, occurredAt: worldNow(), ...(config.root !== undefined ? { root: config.root } : {}), }); // a read-only request is, to the handler, a request to a read-only twin: the pack refuses its // writes in the vendor's own shape (D3), and the kernel's write seam refuses any it misses const scoped = readOnly || isReadOnlyRequest(request); const run = (asReadOnly = scoped) => (requestId ? runWithCorrelationId(requestId, () => invoke(asReadOnly)) : invoke(asReadOnly)); // W3C trace context: a valid incoming traceparent scopes the handler, so its entries record it const result = await runWithRequestTrace(request, () => (isReadOnlyRequest(request) ? readScoped(run) : run())); // A null/undefined body is an EMPTY reply (`JSON.stringify(null)` would serve the // four bytes "null") — and so is the estate's own 204 idiom, `body: ''` with a // null-body status: workerd THROWS on any body with 204/205/304, where // Bun silently serves '""' — either way a wire break on exactly one lane. const nullBodyStatus = result.status === 204 || result.status === 205 || result.status === 304; if (result.body === null || result.body === undefined || (nullBodyStatus && result.body === '')) { return new Response(null, { status: result.status, headers: { ...config.responseHeaders, ...result.headers } }); } return new Response(JSON.stringify(result.body), { status: result.status, headers: { 'content-type': 'application/json', ...config.responseHeaders, ...result.headers }, }); }; } /** A read-only request through the handler seam: the handler runs once, with its writes refused at * the kernel's write seam; a write it attempted answers 405 (rule D3). The handler is never asked * twice (a second run would repeat whatever it did before its first write: a rate-limit slot, a * vendor call). The seam enforces the marker for whoever sends it, but does not advertise * `requestScopes`: a pack opts in to being handed a World's read-token requests by wrapping its * fetch in `withRequestScopes`, once it has made sure nothing it does on a read escapes the seam. */ async function readScoped(run: (asReadOnly?: boolean) => TwinFetchHandlerResult | Promise): Promise { const out = await runAsReadOnlyRequest(() => run()); if (!out.refused) return out.value; return { status: 405, body: { error: 'read_only', message: out.refused.message } }; } /** A twin's answer at a World's place with its cookies kept to the twin: every cookie it sets is scoped to the twin's * base path there (`Path=/` and no Path become `Path=`, which RFC 6265's path-match gives the twin's root * `` and every path under it and no sibling; a path under the vendor's root, `Path=/x`, becomes `/x`), * so one twin's sign-in never reaches a sibling twin served from the same pages origin (architecture, "A page at a * World's place"). A `__Host-` cookie, which a browser takes only at `Path=/`, is left as set. An answer off a place, at * a prefix the World never sends (outside `/[A-Za-z0-9._~/-]*`, which twinPublicBase refuses too), or setting no cookie * is the answer as it is. */ export function placedCookies(request: Request, response: Response): Response { const prefix = request.headers.get(TWIN_PREFIX_HEADER)?.replace(/\/+$/, ''); if (!prefix || !/^\/[A-Za-z0-9._~\/-]*$/.test(prefix)) return response; const cookies = response.headers.getSetCookie?.() ?? []; if (!cookies.length || response.status < 200) return response; const scoped = cookies.map((cookie) => { if (/^\s*__Host-/i.test(cookie)) return cookie; const path = /;\s*path=([^;]*)/i.exec(cookie)?.[1]?.trim(); // already scoped (a lane's answer its vendor passes on): as it is if (path !== undefined && (path === prefix || path.startsWith(`${prefix}/`))) return cookie; const at = !path || path === '/' ? prefix : `${prefix}${path.startsWith('/') ? path : `/${path}`}`.replace(/\/+$/, ''); return path === undefined ? `${cookie}; Path=${at}` : cookie.replace(/(;\s*)path=[^;]*/i, `$1Path=${at}`); }); const headers = new Headers(response.headers); headers.delete('set-cookie'); for (const cookie of scoped) headers.append('set-cookie', cookie); return new Response(response.body, { status: response.status, statusText: response.statusText, headers }); }