import { isRecord } from '@void/deploy-core'; import { usageLimitResponse } from '@void/edge'; import { isProjectId } from '@voidcloud/api/id'; import { readUsageSigningKey, signUsageEvent } from '@voidcloud/api/usage-auth'; import { WorkerEntrypoint } from 'cloudflare:workers'; import { PLATFORM_DISABLED_KEY, PLATFORM_DISABLED_VALUE } from './platform-lifecycle.ts'; import type { Env } from './types.ts'; /** * Identity the API sets on a tenant's Browser Run service binding. Cloudflare * fixes `props` at upload time, so tenant code cannot claim another project. */ export type BrowserRunProps = Readonly<{ projectId: string }>; /** * Quick Actions that only spend browser time. `json` (and the `json` snapshot * format) also runs Workers AI on the platform account, outside AI metering. */ const QUICK_ACTIONS: ReadonlySet = new Set([ 'screenshot', 'pdf', 'content', 'scrape', 'links', 'snapshot', 'markdown', 'accessibilityTree', ]); /** Inline HTML, including base64 fonts, stays well below this. */ export const BROWSER_OPTIONS_MAX_BYTES = 8 * 1024 * 1024; export const BROWSER_SESSIONS_UNAVAILABLE = 'Browser Sessions (Puppeteer, Playwright, CDP and scripts) are not available on Void platform deploys. Use quickAction(), or deploy with `void deploy --platform cloudflare` to use your own Browser Run binding.'; /** The `blob2` request type of Browser Run rows in the requests dataset. */ export const BROWSER_REQUEST_TYPE = 'browser'; export function browserBlockKey(projectId: string): string { return `browser-block:${projectId}`; } /** * The Quick Actions a project may run in 10 seconds, published by the API from * its plan or its own override: `0` (unlimited), `1` or `300`. */ export function browserRateKey(projectId: string): string { return `browser-rate:${projectId}`; } /** A call refused before it reached Browser Run; `browser_quick_action` logs the rest. */ function logLimited(projectId: string, action: string, reason: string): void { console.log(JSON.stringify({ event: 'browser_quick_action_limited', projectId, action, reason })); } /** The `BrowserRunErrorResponse` shape native Quick Actions return. */ function browserError(status: number, message: string): Response { return Response.json({ success: false, errors: [{ message }] }, { status }); } /** Seconds in one window of the proxy's `BROWSER_RATE_LIMIT` and `BROWSER_RATE_LIMIT_FREE` bindings. */ export const BROWSER_RATE_LIMIT_PERIOD_SECONDS = 10; /** * Browser time the native binding reports on Quick Action responses below 500, * or `null` when the header is missing or malformed. */ export function browserMsUsed(response: Response): number | null { const value = response.headers.get('x-browser-ms-used'); if (value === null || !/^\d+$/.test(value)) { return null; } const ms = Number(value); return Number.isSafeInteger(ms) ? ms : null; } /** * Report one Quick Action to the requests dataset, in the column layout of * dispatch's `recordRequest`. The request count and response bytes are zero, so * request and bandwidth totals ignore the row; `double4` holds the browser time. * Usage pages read it; the limit is enforced from the queue event below. */ function recordBrowserUsage( env: Env, data: { projectId: string; action: string; status: number; durationMs: number; browserMs: number; }, ): void { try { env.ANALYTICS?.writeDataPoint({ indexes: [data.projectId], blobs: [data.projectId, BROWSER_REQUEST_TYPE, data.action, String(data.status), '', ''], doubles: [0, 0, data.durationMs, data.browserMs], }); } catch (error) { console.error(JSON.stringify({ event: 'browser_usage_unreported', ...data }), error); } } async function enqueueBrowserUsage( env: Env, signingKey: string, projectId: string, action: string, browserMs: number, ): Promise { const callId = crypto.randomUUID(); try { if (!env.USAGE_QUEUE) { throw new Error('usage queue binding is unavailable'); } // The consumer resolves the owner and slug from PostgreSQL; these are hints. await env.USAGE_QUEUE.send( await signUsageEvent(signingKey, 'proxy-browser', `browser:${callId}`, { projectId, userId: '', slug: '', requests: 0, responseBytes: 0, browserCallId: callId, browserMs, }), ); } catch (error) { console.error( JSON.stringify({ event: 'browser_usage_unrecorded', projectId, action, browserMs }), error, ); } } /** * Run one Quick Action for a project with the platform's Browser Run binding. * Returns the native `Response`, or a `BrowserRunErrorResponse`/usage-limit 429 * the caller handles like any other Browser Run failure. */ export async function runBrowserQuickAction( env: Env, waitUntil: (promise: Promise) => void, projectId: unknown, action: unknown, options: unknown, ): Promise { if (typeof projectId !== 'string' || !isProjectId(projectId)) { return browserError(403, 'This Browser Run binding has no valid project identity.'); } if (typeof action !== 'string' || !QUICK_ACTIONS.has(action)) { return browserError( 400, action === 'json' ? 'The json Quick Action is not available on Void platform deploys. Use void/ai to extract structured data.' : `Unsupported Browser Run Quick Action: ${String(action)}.`, ); } if (!isRecord(options)) { return browserError(400, 'Browser Run Quick Action options must be an object.'); } if (action === 'snapshot' && Array.isArray(options.formats) && options.formats.includes('json')) { return browserError(400, 'The json snapshot format is not available on Void platform deploys.'); } // Only the default browser is metered in browser time; other backends are billed differently. if (options.browser !== undefined) { return browserError( 400, 'Alternate browser backends are not available on Void platform deploys. Remove the browser option, or deploy with `void deploy --platform cloudflare`.', ); } let serializedOptions: string; try { // Values such as BigInt cross RPC but are not valid Quick Action input. serializedOptions = JSON.stringify(options); } catch { return browserError(400, 'Browser Run Quick Action options must be JSON-serializable.'); } if (new TextEncoder().encode(serializedOptions).byteLength > BROWSER_OPTIONS_MAX_BYTES) { return browserError(413, 'Browser Run Quick Action options must not exceed 8 MiB.'); } if ( env.PLATFORM_TRAFFIC_STATE === 'staging' || env.PLATFORM_TRAFFIC_STATE === 'sandbox-drain' || (env.PLATFORM_INSTALLATION_ID && (await env.ROUTING.get(PLATFORM_DISABLED_KEY)) === PLATFORM_DISABLED_VALUE) ) { return browserError(503, 'Platform disabled'); } if (!env.BROWSER) { return browserError(501, 'This Void platform does not enable Browser Run.'); } if (await env.ROUTING.get(browserBlockKey(projectId), { cacheTtl: 60 })) { logLimited(projectId, action, 'monthly_quota'); return usageLimitResponse({ code: 'usage_limit', resource: 'browser', reason: 'monthly_quota', message: 'Browser Run usage limit exceeded', }); } // The Quick Action rates Cloudflare gives an account, applied per project: Workers // Free (1 per 10 seconds) or Workers Paid (300). The standard rate applies until the // API publishes one. The bindings count per location and are approximate. const rate = await env.ROUTING.get(browserRateKey(projectId), { cacheTtl: 60 }); const rateLimit = rate === '0' ? undefined : rate === '1' ? // An installation without the Free binding still limits the project. (env.BROWSER_RATE_LIMIT_FREE ?? env.BROWSER_RATE_LIMIT) : env.BROWSER_RATE_LIMIT; if (rateLimit && !(await rateLimit.limit({ key: projectId })).success) { logLimited(projectId, action, 'rate_limit'); return usageLimitResponse({ code: 'usage_limit', resource: 'browser', reason: 'rate_limit', message: 'Browser Run rate limit exceeded', retryAt: new Date(Date.now() + BROWSER_RATE_LIMIT_PERIOD_SECONDS * 1000).toISOString(), }); } // Fail closed before spending browser time that could not be billed. const signingKey = await readUsageSigningKey(env.ROUTING); if (!signingKey) { return browserError( 503, 'Usage metering is not initialized. Check the platform API /health endpoint.', ); } const startedAt = Date.now(); const response = await env.BROWSER.quickAction(action, options); const reportedMs = browserMsUsed(response); const browserMs = reportedMs ?? 0; const durationMs = Date.now() - startedAt; if (reportedMs === null && response.status < 500) { // Billing depends on this header; its absence means the call ran unmetered. console.warn( JSON.stringify({ event: 'browser_usage_header_missing', projectId, action, status: response.status, durationMs, }), ); } console.log( JSON.stringify({ event: 'browser_quick_action', projectId, action, status: response.status, browserMs, durationMs, }), ); if (browserMs > 0) { recordBrowserUsage(env, { projectId, action, status: response.status, durationMs, browserMs }); waitUntil(enqueueBrowserUsage(env, signingKey, projectId, action, browserMs)); } return response; } function sessionsUnavailable(): never { throw new Error(BROWSER_SESSIONS_UNAVAILABLE); } /** * Tenant Browser Run binding on Void platforms. Its Quick Actions match the * native binding; Browser Sessions are refused because their concurrency is * billed to, and their session APIs list, the whole platform account. */ export class BrowserRun extends WorkerEntrypoint { async quickAction(action: unknown, options: unknown): Promise { return runBrowserQuickAction( this.env, (promise) => this.ctx.waitUntil(promise), this.ctx.props?.projectId, action, options, ); } /** `@cloudflare/puppeteer` and `@cloudflare/playwright` acquire sessions here. */ override async fetch(): Promise { return browserError(501, BROWSER_SESSIONS_UNAVAILABLE); } acquire(): never { return sessionsUnavailable(); } launch(): never { return sessionsUnavailable(); } connectSession(): never { return sessionsUnavailable(); } getLiveView(): never { return sessionsUnavailable(); } listSessions(): never { return sessionsUnavailable(); } history(): never { return sessionsUnavailable(); } limits(): never { return sessionsUnavailable(); } getSession(): never { return sessionsUnavailable(); } closeSession(): never { return sessionsUnavailable(); } script(): never { return sessionsUnavailable(); } }