import { BrowserCookieJar } from './browser-cookie-jar.ts'; import { assertBrowserName, browserOrigin, validateBrowserState, validateBrowserContext, browserAcceptLanguage, type BrowserState, type BrowserContext } from './browser-state.ts'; import { nodeBuiltin } from './serve-http.ts'; import { worldNow } from './world-clock.ts'; export { cookieMatchesHost } from './browser-state.ts'; export type SeedBrowser = { fetch(input: string | URL | Request, init?: RequestInit): Promise; storage(origin: string): { set(key: string, value: string): Promise; remove(key: string): Promise }; context(options: BrowserContext): Promise; state(): Promise; }; /** Undo the request's path mount before its answer reaches a vendor-addressed client. */ function vendorResponse(response: Response, vendor: URL, twin: URL, mount: string): Response { if (!mount) return response; const pathAtVendor = (path: string): string => path === mount ? '/' : path.startsWith(`${mount}/`) ? path.slice(mount.length) : path; const urlAtVendor = (value: string): string => { if (!value.trim()) return value; let at: URL; try { at = new URL(value, twin); } catch { return value; } if (at.origin !== twin.origin && at.origin !== vendor.origin) return value; const path = pathAtVendor(at.pathname); if (path === at.pathname) return value; const tail = `${path}${at.search}${at.hash}`; return /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(value.trim()) ? `${vendor.origin}${tail}` : tail; }; const headers = new Headers(response.headers); let changed = false; const cookies = response.headers.getSetCookie(); const mapped = cookies.map(cookie => cookie.replace(/(;\s*path\s*=)([^;]*)/gi, (attribute, lead: string, path: string) => { const at = pathAtVendor(path.trim()); return at === path.trim() ? attribute : `${lead}${at}`; })); if (mapped.some((cookie, i) => cookie !== cookies[i])) { headers.delete('set-cookie'); for (const cookie of mapped) headers.append('set-cookie', cookie); changed = true; } for (const name of ['location', 'content-location']) { const value = headers.get(name); if (value === null) continue; const at = urlAtVendor(value); if (at !== value) { headers.set(name, at); changed = true; } } const refresh = headers.get('refresh'); if (refresh !== null) { const parts = /^(\s*\d+(?:\.\d+)?\s*[;,]\s*(?:url\s*=\s*)?)(?:"([^"]*)"|'([^']*)'|([^"']*?))(\s*)$/i.exec(refresh); if (parts) { const value = parts[2] ?? parts[3] ?? parts[4]!; const at = urlAtVendor(value); if (at !== value) { const quote = parts[2] !== undefined ? '"' : parts[3] !== undefined ? "'" : ''; headers.set('refresh', `${parts[1]}${quote}${at}${quote}${parts[5]}`); changed = true; } } } return changed ? new Response(response.body, { status: response.status, statusText: response.statusText, headers }) : response; } /** The one password of an address in this World (ADR 0033 §5): `worldSecret('_world', /_world, * 'password:
')`, retained World state, so a seed signs a person up with it and a twin keeps only its hash. A * seed reads it beside `browser(name)`; it is never a literal in a committed file. */ export async function password(address: string): Promise { const { worldStateFile } = await import('./world-store.ts'); const data = worldStateFile('data'); if (!process.env.VOLTER_WORLD || !data) throw new Error('password(address) runs in a World seed, with its data directory'); const { worldSecret } = await import('./derived-core.ts'); return worldSecret('_world', nodeBuiltin('path').join(data, '_world'), `password:${address}`); } /** A seed's named browser. Every state write goes through the World's single HTTP loader. */ export async function browser(name: string): Promise { assertBrowserName(name); const door = process.env.VOLTER_WORLD_BROWSER_DOOR; const token = process.env.VOLTER_WORLD_BROWSER_TOKEN; if (!process.env.VOLTER_WORLD || !door || !token) throw new Error('browser(name) runs in a World seed, with its browsers door and credential'); const require = nodeBuiltin('module').createRequire(import.meta.url); const routing = require('../vendor-hosts.cjs') as typeof import('../vendor-hosts.cjs'); const { packs } = require('../pack-facts.cjs').packFacts() as { packs: Record }; const resolve = async (url: URL): Promise<{ vendor: string; origin: string } | null> => { const map = routing.twinOrigins(process.env); const declared = routing.resolveTwinHost(url.hostname, map, url.pathname); if (declared) return declared; const claimed: Record> = {}; for (const [vendor, facts] of Object.entries(packs)) { const origin = map[vendor] ?? process.env[`${routing.twinEnvStem(vendor)}_TWIN_URL`]; if (!origin || !facts.hostsClaimed) continue; map[vendor] = origin; const headers = new Headers({ 'x-volter-read-only': '1' }); if (process.env.VOLTER_TWINS_KEY) headers.set('x-twins-key', process.env.VOLTER_TWINS_KEY); // the hosts a twin claims, read at its door: a failure to read them is named, never taken as no claim (ADR 0036 §8) let listed: { hosts?: unknown }; try { const answer = await fetch(`${origin}${facts.hostsClaimed.door}`, { headers }); if (!answer.ok) throw new Error(`answered ${answer.status} ${(await answer.text()).slice(0, 200)}`); listed = await answer.json() as { hosts?: unknown }; } catch (error) { throw new Error(`${vendor}'s claimed hosts could not be read at ${origin}${facts.hostsClaimed.door}: ${error instanceof Error ? error.message : String(error)}`); } claimed[vendor] = new Set(Array.isArray(listed?.hosts) ? listed.hosts.map(h => String(h).toLowerCase()) : []); } return routing.resolveTwinHost(url.hostname, map, url.pathname, claimed); }; const initial = await fetch(`${door}/${name}`, { headers: { 'x-volter-token': token } }); if (!initial.ok && initial.status !== 404) throw new Error(`browser ${name}: ${initial.status} ${await initial.text()}`); const stored = validateBrowserState(initial.ok ? await initial.json() : { storageState: { cookies: [], origins: [] } }); const jar = new BrowserCookieJar(stored.storageState.cookies); const origins = structuredClone(stored.storageState.origins); let context = structuredClone(stored.context); let queue: Promise = Promise.resolve(); const serial = (fn: () => Promise): Promise => { const next = queue.then(fn); queue = next.then(() => undefined, () => undefined); return next; }; const snapshot = (): BrowserState => { const now = new Date(worldNow()).getTime(); const cookies = jar.snapshot(now); return validateBrowserState({ storageState: { cookies, origins: structuredClone(origins) }, context: structuredClone(context) }); }; const save = async (): Promise => { const response = await fetch(`${door}/${name}`, { method: 'PUT', headers: { 'content-type': 'application/json', 'x-volter-token': token }, body: JSON.stringify(snapshot()) }); if (!response.ok) throw new Error(`browser ${name}: ${response.status} ${await response.text()}`); }; if (initial.status === 404) await save(); return { state: () => serial(async () => snapshot()), context: options => serial(async () => { const next = structuredClone(validateBrowserContext(options)); if (JSON.stringify(next) === JSON.stringify(context)) return; const previous = context; context = next; try { await save(); } catch (error) { context = previous; throw error; } }), storage(origin) { browserOrigin(origin); const change = (key: string, value?: string): Promise => serial(async () => { if (typeof key !== 'string' || (value !== undefined && typeof value !== 'string')) throw new Error('browser storage: string keys and values'); const before = JSON.stringify(origins); let entry = origins.find(o => o.origin === origin); if (!entry && value !== undefined) { entry = { origin, localStorage: [] }; origins.push(entry); } if (entry) { entry.localStorage = entry.localStorage.filter(v => v.name !== key); if (value !== undefined) entry.localStorage.push({ name: key, value }); } if (JSON.stringify(origins) !== before) await save(); }); return { set: (key, value) => change(key, value), remove: key => change(key) }; }, fetch: (input, init) => serial(async () => { const request = new Request(input, init); let url = new URL(request.url); let method = request.method; let body: ArrayBuffer | undefined = request.body ? await request.arrayBuffer() : undefined; const headers = new Headers(request.headers); if (headers.has('cookie')) throw new Error('browser.fetch carries its own cookie jar'); for (let redirects = 0; ; redirects++) { if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error('browser.fetch takes an http or https vendor URL'); const target = await resolve(url); if (!target || target.vendor === 'app') throw new Error(`browser ${name}: no twin in this World serves ${url.hostname}${url.pathname}`); const at = new URL(target.origin); const mount = at.pathname.replace(/\/+$/, ''); at.pathname = `${mount}${url.pathname}`; at.search = url.search; const sent = new Headers(headers); const language = browserAcceptLanguage(context); if (language !== undefined) sent.set('accept-language', language); const cookies = jar.header(url, new Date(worldNow()).getTime()); if (cookies) sent.set('cookie', cookies); sent.set('host', mount ? at.host : url.host); sent.set('x-volter-twin-original-host', url.host); sent.set('x-forwarded-host', url.host); sent.set('x-forwarded-proto', url.protocol.slice(0, -1)); if (process.env.VOLTER_TWINS_KEY) sent.set('x-twins-key', process.env.VOLTER_TWINS_KEY); const before = JSON.stringify(snapshot()); const response = vendorResponse(await fetch(at, { method, headers: sent, body, redirect: 'manual', signal: request.signal }), url, at, mount); for (const cookie of response.headers.getSetCookie()) jar.set(cookie, url, new Date(worldNow()).getTime()); if (JSON.stringify(snapshot()) !== before) await save(); const location = response.headers.get('location'); if (!location || ![301, 302, 303, 307, 308].includes(response.status) || request.redirect === 'manual') return response; if (request.redirect === 'error') throw new Error('browser.fetch refused a redirect'); if (redirects >= 20) throw new Error('browser.fetch exceeded the fetch redirect limit'); await response.body?.cancel(); const next = new URL(location, url); if (next.origin !== url.origin) { headers.delete('authorization'); headers.delete('proxy-authorization'); } if ((response.status === 303 && method !== 'HEAD') || ([301, 302].includes(response.status) && method === 'POST')) { method = 'GET'; body = undefined; for (const key of ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location']) headers.delete(key); } url = next; } }), }; }