/** A scenario's browser profile, using Playwright's storageState and context option shapes. */ export type BrowserCookie = { name: string; value: string; domain: string; path: string; expires: number; httpOnly: boolean; secure: boolean; sameSite: 'Strict' | 'Lax' | 'None'; partitionKey?: string; _crHasCrossSiteAncestor?: boolean }; export type BrowserIndexedDB = { name: string; version: number; stores: { name: string; autoIncrement: boolean; keyPath?: string; keyPathArray?: string[]; records: { key?: unknown; keyEncoded?: unknown; value?: unknown; valueEncoded?: unknown }[]; indexes: { name: string; keyPath?: string; keyPathArray?: string[]; multiEntry: boolean; unique: boolean }[]; }[] }; export type BrowserStorageState = { cookies: BrowserCookie[]; origins: { origin: string; localStorage: { name: string; value: string }[]; indexedDB?: BrowserIndexedDB[] }[] }; /** Profile subset of Playwright 1.61.1 BrowserContextOptions; no execution options. */ export type BrowserContext = { permissions?: string[]; geolocation?: { latitude: number; longitude: number; accuracy?: number }; locale?: string; timezoneId?: string; userAgent?: string; viewport?: { width: number; height: number } | null; deviceScaleFactor?: number; isMobile?: boolean; hasTouch?: boolean; colorScheme?: 'light' | 'dark' | 'no-preference' | null; reducedMotion?: 'reduce' | 'no-preference' | null; extraHTTPHeaders?: Record; offline?: boolean; }; export type BrowserState = { storageState: BrowserStorageState; context: BrowserContext }; export function assertBrowserName(name: string): void { if (!/^[a-z0-9](?:[a-z0-9]|-(?!-)){0,23}$/.test(name) || name.endsWith('-')) throw new Error('browser name: 1–24 lowercase letters, digits or single hyphens, starting and ending with a letter or digit'); } function object(value: unknown, keys: string[]): Record { if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !keys.includes(k))) throw new Error(`browser state: an object with only ${keys.join(', ')}`); return value as Record; } const host = (value: string): boolean => value !== 'localhost' && !value.endsWith('.localhost') && !/^\d+(?:\.\d+){3}$/.test(value) && /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z][a-z0-9-]*$/.test(value) && value.length <= 253 && value.split('.').every(l => l.length <= 63); export function browserOrigin(value: string): string { let url: URL; try { url = new URL(value); } catch { throw new Error('browser origin: an absolute http or https vendor origin'); } if (!['http:', 'https:'].includes(url.protocol) || url.origin !== value || !host(url.hostname)) throw new Error('browser origin: a canonical http or https vendor origin, never a local twin URL'); return value; } /** Refuse unknown keys at every level; the accepted object is never reshaped. */ export function validateBrowserStorageState(value: unknown): BrowserStorageState { const state = object(value, ['cookies', 'origins']); if (!Array.isArray(state.cookies) || !Array.isArray(state.origins)) throw new Error('browser state: cookies and origins are arrays'); const cookies = new Set(); for (const raw of state.cookies) { const c = object(raw, ['name', 'value', 'domain', 'path', 'expires', 'httpOnly', 'secure', 'sameSite', 'partitionKey', '_crHasCrossSiteAncestor']); if (typeof c.name !== 'string' || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(c.name) || typeof c.value !== 'string' || /[\x00-\x1f\x7f;]/.test(c.value)) throw new Error('browser cookie: a cookie name and wire-safe string value'); if (/[^\u0000-\u00ff]/.test(c.value)) throw new Error('browser cookie: value characters must be U+00FF or below for Set-Cookie'); if (typeof c.domain !== 'string' || !host(c.domain.replace(/^\./, ''))) throw new Error('browser cookie: a real vendor domain, optionally prefixed by a dot'); if (typeof c.path !== 'string' || !c.path.startsWith('/') || /[\x00-\x20\x7f;\u0100-\uffff]/.test(c.path)) throw new Error('browser cookie: an absolute wire-safe cookie path'); if (typeof c.expires !== 'number' || !Number.isFinite(c.expires) || (c.expires < 0 && c.expires !== -1)) throw new Error('browser cookie: expires is Unix seconds, or -1 for a session'); if (typeof c.httpOnly !== 'boolean' || typeof c.secure !== 'boolean' || (typeof c.sameSite !== 'string' || !['Strict', 'Lax', 'None'].includes(c.sameSite))) throw new Error('browser cookie: httpOnly and secure are booleans; sameSite is Strict, Lax or None'); if (c.partitionKey !== undefined && (typeof c.partitionKey !== 'string' || !c.partitionKey || /[\x00-\x20\x7f]/.test(c.partitionKey))) throw new Error('browser cookie: partitionKey is a nonempty string'); if (c._crHasCrossSiteAncestor !== undefined && typeof c._crHasCrossSiteAncestor !== 'boolean') throw new Error('browser cookie: _crHasCrossSiteAncestor is a boolean'); const key = JSON.stringify([c.name, c.domain, c.path, c.partitionKey]); if (cookies.has(key)) throw new Error('browser state: duplicate cookie'); cookies.add(key); } const origins = new Set(); for (const raw of state.origins) { const o = object(raw, ['origin', 'localStorage', 'indexedDB']); if (typeof o.origin !== 'string') throw new Error('browser state: origin is a string'); browserOrigin(o.origin); if (origins.has(o.origin)) throw new Error('browser state: duplicate origin'); origins.add(o.origin); if (!Array.isArray(o.localStorage)) throw new Error('browser state: localStorage is an array'); if (o.indexedDB !== undefined) { if (!Array.isArray(o.indexedDB)) throw new Error('browser storage: indexedDB is an array'); const keyPath = (item: Record): void => { if (item.keyPath !== undefined && typeof item.keyPath !== 'string') throw new Error('browser IndexedDB: keyPath is a string'); if (item.keyPathArray !== undefined && (!Array.isArray(item.keyPathArray) || item.keyPathArray.some(k => typeof k !== 'string'))) throw new Error('browser IndexedDB: keyPathArray contains strings'); }; for (const rawDB of o.indexedDB) { const db = object(rawDB, ['name', 'version', 'stores']); if (typeof db.name !== 'string' || typeof db.version !== 'number' || !Number.isSafeInteger(db.version) || db.version < 1 || !Array.isArray(db.stores)) throw new Error('browser IndexedDB: a name, positive integer version and stores array'); for (const rawStore of db.stores) { const store = object(rawStore, ['name', 'autoIncrement', 'keyPath', 'keyPathArray', 'records', 'indexes']); if (typeof store.name !== 'string' || typeof store.autoIncrement !== 'boolean' || !Array.isArray(store.records) || !Array.isArray(store.indexes)) throw new Error('browser IndexedDB: a store name, autoIncrement boolean, records and indexes arrays'); keyPath(store); for (const record of store.records) object(record, ['key', 'keyEncoded', 'value', 'valueEncoded']); for (const rawIndex of store.indexes) { const index = object(rawIndex, ['name', 'keyPath', 'keyPathArray', 'multiEntry', 'unique']); if (typeof index.name !== 'string' || typeof index.multiEntry !== 'boolean' || typeof index.unique !== 'boolean') throw new Error('browser IndexedDB: an index name, multiEntry and unique booleans'); keyPath(index); } } } } const names = new Set(); for (const rawEntry of o.localStorage) { const entry = object(rawEntry, ['name', 'value']); if (typeof entry.name !== 'string' || typeof entry.value !== 'string' || names.has(entry.name)) throw new Error('browser storage: unique string names and string values'); names.add(entry.name); } } return value as BrowserStorageState; } export function validateBrowserContext(value: unknown): BrowserContext { const context = object(value, ['permissions', 'geolocation', 'locale', 'timezoneId', 'userAgent', 'viewport', 'deviceScaleFactor', 'isMobile', 'hasTouch', 'colorScheme', 'reducedMotion', 'extraHTTPHeaders', 'offline']); const finite = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n); if (context.permissions !== undefined && (!Array.isArray(context.permissions) || context.permissions.some(p => typeof p !== 'string'))) throw new Error('browser context: permissions is an array of strings'); for (const key of ['locale', 'timezoneId', 'userAgent']) { if (context[key] !== undefined && typeof context[key] !== 'string') throw new Error(`browser context: ${key} is a string`); } if (context.locale !== undefined) new Headers({ 'accept-language': context.locale as string }); if (context.userAgent !== undefined) new Headers({ 'user-agent': context.userAgent as string }); for (const key of ['isMobile', 'hasTouch', 'offline']) { if (context[key] !== undefined && typeof context[key] !== 'boolean') throw new Error(`browser context: ${key} is a boolean`); } if (context.deviceScaleFactor !== undefined && !finite(context.deviceScaleFactor)) throw new Error('browser context: deviceScaleFactor is a finite number'); if (context.geolocation !== undefined) { const geo = object(context.geolocation, ['latitude', 'longitude', 'accuracy']); if (!finite(geo.latitude) || geo.latitude < -90 || geo.latitude > 90 || !finite(geo.longitude) || geo.longitude < -180 || geo.longitude > 180 || (geo.accuracy !== undefined && (!finite(geo.accuracy) || geo.accuracy < 0))) throw new Error('browser context: geolocation has latitude [-90, 90], longitude [-180, 180] and optional nonnegative accuracy'); } if (context.viewport !== undefined && context.viewport !== null) { const viewport = object(context.viewport, ['width', 'height']); if (!finite(viewport.width) || !Number.isInteger(viewport.width) || !finite(viewport.height) || !Number.isInteger(viewport.height)) throw new Error('browser context: viewport has integer width and height, or is null'); } if (context.viewport === null && (context.deviceScaleFactor !== undefined || context.isMobile === true)) throw new Error('browser context: null viewport does not support deviceScaleFactor or isMobile'); for (const [key, values] of [['colorScheme', ['light', 'dark', 'no-preference']], ['reducedMotion', ['reduce', 'no-preference']]] as const) { if (context[key] !== undefined && context[key] !== null && (typeof context[key] !== 'string' || !(values as readonly string[]).includes(context[key]))) throw new Error(`browser context: ${key} is ${values.join(', ')} or null`); } if (context.extraHTTPHeaders !== undefined) { const headers = context.extraHTTPHeaders; if (!headers || typeof headers !== 'object' || Array.isArray(headers) || Object.values(headers).some(v => typeof v !== 'string')) throw new Error('browser context: extraHTTPHeaders maps header names to strings'); // Validate wire values without normalizing the profile's names or values. new Headers(headers as Record); } return value as BrowserContext; } /** A browser's profile, `{ storageState, context? }`: a missing context reads as `{}`. */ export function validateBrowserState(value: unknown): BrowserState { const profile = object(value, ['storageState', 'context']); return { storageState: validateBrowserStorageState(profile.storageState), context: validateBrowserContext(profile.context === undefined ? {} : profile.context) }; } /** The profile's language header, with Playwright's locale supplying its default. */ export function browserAcceptLanguage(context: BrowserContext): string | undefined { for (const [name, value] of Object.entries(context.extraHTTPHeaders ?? {})) { if (name.toLowerCase() === 'accept-language') return value; } return context.locale; } export function cookieMatchesHost(cookie: BrowserCookie, hostname: string): boolean { const domain = cookie.domain.replace(/^\./, ''); return hostname === domain || (cookie.domain.startsWith('.') && hostname.endsWith(`.${domain}`)); }