import { randomUUID } from 'node:crypto'; import { z } from 'zod'; import type { CdpConnection } from './browserAutomation.js'; import { browserIdentity, decodeEvaluation, resolveBrowserReference, } from './browserObservation.js'; import { buildLocatorExpression } from './browserLocator.js'; export const probeSchema = z .object({ name: z.string().min(1).max(80), selector: z.string().min(1).max(1000).optional(), elementRef: z.string().min(1).optional(), frameId: z.string().optional(), field: z.enum([ 'text', 'value', 'valueAsNumber', 'checked', 'selected', 'disabled', 'visible', 'attribute', 'x', 'y', 'width', 'height', 'currentTime', 'duration', 'paused', 'muted', 'playbackRate', 'readyState', 'seeking', 'ended', ]), attribute: z.string().max(100).optional(), }) .refine( (p) => Boolean(p.selector) !== Boolean(p.elementRef), 'provide exactly one selector or elementRef', ) .refine( (p) => p.field !== 'attribute' || Boolean( p.attribute && /^(aria-[\w-]+|data-[\w-]+|role|title|alt|min|max|step)$/.test( p.attribute, ), ), 'attribute must be an explicit aria/data or semantic attribute', ); export const probesSchema = z .array(probeSchema) .min(1) .max(8) .refine( (p) => new Set(p.map((i) => i.name)).size === p.length, 'probe names must be unique', ); export const assertionSchema = z.object({ probe: z.string(), operator: z.enum(['equals', 'approx', 'advances', 'preserved', 'relation']), expected: z .union([z.string().max(1000), z.number().finite(), z.boolean()]) .optional(), other: z.string().optional(), scale: z.number().finite().default(1), offset: z.number().finite().default(0), tolerance: z.number().finite().nonnegative().default(0), minIncrease: z.number().finite().positive().default(0.1), }); export const verificationSchema = z .object({ probes: probesSchema, assertions: z.array(assertionSchema).min(1).max(12), baselineId: z.string().optional(), mode: z.enum(['eventually', 'throughout']).default('eventually'), durationMs: z.number().int().min(100).max(30_000).default(2000), intervalMs: z.number().int().min(50).max(5000).default(200), }) .superRefine((v, ctx) => { const names = new Set(v.probes.map((p) => p.name)); for (const a of v.assertions) { if ( !names.has(a.probe) || (a.operator === 'relation' && (!a.other || !names.has(a.other))) ) ctx.addIssue({ code: 'custom', message: 'assertion references an unknown probe', }); if (['equals', 'approx'].includes(a.operator) && a.expected === undefined) ctx.addIssue({ code: 'custom', message: 'equals/approx require expected', }); if (a.operator === 'approx' && typeof a.expected !== 'number') ctx.addIssue({ code: 'custom', message: 'approx requires numeric expected', }); if (a.operator === 'preserved' && !v.baselineId) ctx.addIssue({ code: 'custom', message: 'preserved requires baselineId from probe', }); } if (v.durationMs / v.intervalMs > 150 || v.intervalMs > v.durationMs) ctx.addIssue({ code: 'custom', message: 'sampling requires 1..150 intervals', }); }); type Probe = z.infer; type Assertion = z.infer; type Values = Record; const baselines = new Map< string, { owner: string; values: Values; probes: Probe[]; document: string; frames: Array<[string, string]>; mediaSources: Array<[string, string]>; expires: number; } >(); export async function sampleBrowser( cdp: CdpConnection, owner: string, probes: Probe[], signal?: AbortSignal, documents = new Map(), mediaSources?: Map, ): Promise { const values: Values = Object.create(null); const sampledFrames = new Set(); let lastFrame: string | undefined; for (const probe of probes) { if (signal?.aborted) throw signal.reason; const locator = probe.elementRef ? await resolveBrowserReference( cdp, owner, { by: 'ref', value: probe.elementRef, frameId: probe.frameId }, signal, ) : undefined; const identity = await browserIdentity( cdp, signal, locator?.frameId ?? probe.frameId, ); const known = documents.get(identity.frameId); if (known && known !== identity.documentEpoch) throw new Error('probe_frame_document_changed'); documents.set(identity.frameId, identity.documentEpoch); lastFrame = identity.frameId; sampledFrames.add(identity.frameId); const target = `(() => { const matches=${buildLocatorExpression(locator, probe.selector)}; if(matches.length!==1) throw new Error('probe_requires_exactly_one_element'); return matches[0]; })()`; // Read the value and its media identity from the same DOM node in one // evaluation. Re-resolving the selector for identity can pair two videos. const trackMedia = probe.field === 'currentTime' && mediaSources !== undefined; const mediaResult = trackMedia ? `if(e.seeking) throw new Error('media_seek_during_verification'); const ids=globalThis.__minimalMediaIdentitiesV2 ??= new WeakMap(); if(!ids.has(e)) ids.set(e,${JSON.stringify(randomUUID())}); return {value,mediaKey:JSON.stringify([ids.get(e),e.currentSrc])};` : 'return value;'; const expression = `(() => { const e=${target}; const field=${JSON.stringify(probe.field)}; if(e.matches('input[type=password]')||/password|cc-|one-time-code/i.test(e.getAttribute('autocomplete')||'')) throw new Error('sensitive_probe_denied'); if(['currentTime','duration','paused','muted','playbackRate','readyState','seeking','ended'].includes(field) && !(e instanceof HTMLMediaElement)) throw new Error('probe_requires_media_element'); const r=e.getBoundingClientRect(); let value; if(field==='attribute') value=e.getAttribute(${JSON.stringify(probe.attribute)}); else if(field==='text') value=e.textContent; else if(field==='visible'){const s=getComputedStyle(e);value=!!(r.width&&r.height)&&s.display!=='none'&&s.visibility!=='hidden'&&s.visibility!=='collapse';} else if(['x','y','width','height'].includes(field)) value=r[field]; else value=e[field]; if(!['string','number','boolean'].includes(typeof value)) throw new Error('probe_value_unavailable'); if(typeof value==='string'&&value.length>1000) throw new Error('probe_value_too_large'); if(typeof value==='number'&&!Number.isFinite(value)) throw new Error('probe_value_nonfinite'); ${mediaResult} })()`; const reading = decodeEvaluation( await cdp.evaluateInFrame(identity.frameId, expression, signal), ); let value = reading; if (trackMedia) { const sample = reading as { value?: unknown; mediaKey?: unknown } | null; const mediaKey = sample?.mediaKey; value = sample?.value; if (typeof mediaKey !== 'string') throw new Error('media_identity_unavailable'); const prior = mediaSources!.get(probe.name); if (prior && prior !== mediaKey) throw new Error('media_source_changed_during_verification'); mediaSources!.set(probe.name, mediaKey); } if ( identity.documentEpoch !== (await browserIdentity(cdp, signal, identity.frameId)).documentEpoch ) throw new Error('probe_frame_document_changed'); if (!['string', 'number', 'boolean'].includes(typeof value)) throw new Error('probe_value_unavailable'); values[probe.name] = value as Values[string]; } // Looking up a later probe can let an earlier child frame navigate even // when the top document is unchanged. Never combine those epochs as proof. for (const frameId of sampledFrames) { if (frameId !== lastFrame && (await browserIdentity(cdp, signal, frameId)).documentEpoch !== documents.get(frameId)) throw new Error('probe_frame_document_changed'); } return values; } export async function captureBrowserBaseline( cdp: CdpConnection, owner: string, probes: Probe[], signal?: AbortSignal, ) { const before = await browserIdentity(cdp, signal); const documents = new Map(); const mediaSources = new Map(); const values = await sampleBrowser(cdp, owner, probes, signal, documents, mediaSources); if ( JSON.stringify(before) !== JSON.stringify(await browserIdentity(cdp, signal)) ) throw new Error('probe_document_changed'); for (const [id, item] of baselines) if (item.expires < Date.now()) baselines.delete(id); while (baselines.size >= 128) baselines.delete(baselines.keys().next().value!); const baselineId = randomUUID(); baselines.set(baselineId, { owner, values: { ...values }, probes: structuredClone(probes), document: JSON.stringify(before), frames: [...documents], mediaSources: [...mediaSources], expires: Date.now() + 15 * 60_000, }); return { baselineId, capturedAt: new Date().toISOString(), identity: before, values, }; } export function evaluateBrowserAssertion( assertion: Assertion, values: Values, first: Values, previous: Values, baseline?: Values, ): boolean { const value = values[assertion.probe]; switch (assertion.operator) { case 'equals': return value === assertion.expected; case 'preserved': if (!baseline || !(assertion.probe in baseline)) throw new Error('baseline_value_unavailable'); return value === baseline[assertion.probe]; case 'approx': return ( typeof value === 'number' && typeof assertion.expected === 'number' && Math.abs(value - assertion.expected) <= assertion.tolerance ); case 'relation': { const other = values[assertion.other!]; return ( typeof value === 'number' && typeof other === 'number' && Math.abs(value - (other * assertion.scale + assertion.offset)) <= assertion.tolerance ); } case 'advances': { const initial = first[assertion.probe], prior = previous[assertion.probe]; return ( typeof value === 'number' && typeof initial === 'number' && typeof prior === 'number' && value + assertion.tolerance >= prior && value - initial >= assertion.minIncrease ); } } } async function pause(ms: number, signal?: AbortSignal) { if (signal?.aborted) throw signal.reason; await new Promise((resolve, reject) => { const cleanup = () => signal?.removeEventListener('abort', abort); const timer = setTimeout(() => { cleanup(); resolve(); }, ms); const abort = () => { clearTimeout(timer); cleanup(); reject(signal?.reason ?? new Error('cancelled')); }; signal?.addEventListener('abort', abort, { once: true }); }); } export async function verifyBrowser( cdp: CdpConnection, owner: string, input: z.infer, signal?: AbortSignal, ) { const verificationId = randomUUID(); const startedAt = new Date().toISOString(); const start = performance.now(); const samples: Array<{ elapsedMs: number; values: Values; checks: boolean[]; }> = []; let status: 'passed' | 'failed' | 'inconclusive' | 'cancelled' = 'inconclusive'; let reason: string | undefined; let identity: Awaited> | undefined; try { identity = await browserIdentity(cdp, signal); const baseline = input.baselineId ? baselines.get(input.baselineId) : undefined; if ( input.baselineId && (!baseline || baseline.owner !== owner || baseline.expires < Date.now() || baseline.document !== JSON.stringify(identity) || JSON.stringify(baseline.probes) !== JSON.stringify(input.probes)) ) throw new Error('baseline_expired_or_incompatible'); let all = true; // Temporal checks always run for the whole bounded window, not until the // first apparently successful sample. A backwards clock invalidates it. let backwards = false; const temporal = input.assertions.some((a) => a.operator === 'advances'); const documents = new Map(baseline?.frames); const mediaSources = new Map(baseline?.mediaSources); while (samples.length < 151) { const samplingStart = performance.now(); const values = await sampleBrowser( cdp, owner, input.probes, signal, documents, mediaSources, ); if ( performance.now() - samplingStart > Math.max(1000, input.intervalMs * 3) ) throw new Error('sampling_skew_exceeds_budget'); if ( JSON.stringify(identity) !== JSON.stringify(await browserIdentity(cdp, signal)) ) throw new Error('verification_document_changed'); const first = samples[0]?.values ?? values; const previous = samples.at(-1)?.values ?? values; for (const a of input.assertions.filter((a) => a.operator === 'advances')) if ( typeof values[a.probe] === 'number' && typeof previous[a.probe] === 'number' && Number(values[a.probe]) + a.tolerance < Number(previous[a.probe]) ) backwards = true; const checks = input.assertions.map((a) => evaluateBrowserAssertion(a, values, first, previous, baseline?.values), ); // Progress cannot hold at t=0. Non-temporal throughout assertions must. all &&= checks.every( (pass, index) => pass || input.assertions[index]!.operator === 'advances', ); const elapsedMs = performance.now() - start; // Setup (CDP attachment, initial sampling) is not an observed interval. const observedMs = elapsedMs - (samples[0]?.elapsedMs ?? elapsedMs); if ( samples.length && elapsedMs - samples.at(-1)!.elapsedMs > Math.max(1000, input.intervalMs * 4) ) throw new Error('sampling_gap_exceeds_budget'); samples.push({ elapsedMs, values, checks }); if (!temporal && input.mode === 'eventually' && checks.every(Boolean)) { status = 'passed'; break; } if (input.mode === 'throughout' && !all) { status = 'failed'; break; } if (observedMs >= input.durationMs) { if (samples.length < 2) throw new Error('insufficient_temporal_samples'); status = samples.length >= 2 && !backwards && checks.every(Boolean) && (input.mode !== 'throughout' || all) ? 'passed' : 'failed'; break; } await pause( Math.min(input.intervalMs, Math.ceil(input.durationMs - observedMs)), signal, ); } if (status === 'inconclusive') reason = 'sample_limit_before_window_complete'; } catch (error) { status = signal?.aborted ? 'cancelled' : 'inconclusive'; reason = error instanceof Error ? error.message : String(error); } return { schemaVersion: 2, verificationId, status, reason, startedAt, identity, durationMs: performance.now() - start, contract: input, samples, scope: 'observed_window_only', }; }