ravensight-playtest 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -234,17 +234,18 @@ export function insertUnderHeading(markdown, heading, line) {
234
234
  }
235
235
 
236
236
  /**
237
- * Ask the one question.
237
+ * The check's request, or null when there is no brief to check: what
238
+ * {@link checkBriefChoice} sends, and what the run's budget reserve sizes
239
+ * during play (./budgetReserve.js), so the two are the same request.
238
240
  *
239
241
  * @param {Object} args
240
242
  * @param {string} args.briefText the brief as the persona was shown it
241
243
  * @param {string} args.actionText the numbered action list the report step was given
242
244
  * @param {Array<Object>} args.records transcript observation and action lines
243
245
  * @param {{data: string, mediaType: string}|null} [args.frame] the last screen, as the model is shown it
244
- * @returns {Promise<{choice: string, result: string, shown: string}|null>} null
245
- * when the brief names no choice, or the check could not be made
246
+ * @returns {{system: string, messages: Array<Object>}|null}
246
247
  */
247
- export async function checkBriefChoice({ client, jobId, runId, briefText, actionText, records, frame = null, ledger = null, transcript = null, log = () => {} }) {
248
+ export function choiceCheckRequest({ briefText, actionText, records, frame = null }) {
248
249
  const brief = String(briefText == null ? '' : briefText).trim();
249
250
  if (!brief || brief === '(none)' || brief === 'null') return null;
250
251
  const screens = screensForCheck(records);
@@ -265,6 +266,24 @@ export async function checkBriefChoice({ client, jobId, runId, briefText, action
265
266
  'Your one line:'
266
267
  ].join('\n')
267
268
  });
269
+ return { system: CHOICE_CHECK_SYSTEM, messages: [{ role: 'user', content }] };
270
+ }
271
+
272
+ /**
273
+ * Ask the one question.
274
+ *
275
+ * @param {Object} args
276
+ * @param {string} args.briefText the brief as the persona was shown it
277
+ * @param {string} args.actionText the numbered action list the report step was given
278
+ * @param {Array<Object>} args.records transcript observation and action lines
279
+ * @param {{data: string, mediaType: string}|null} [args.frame] the last screen, as the model is shown it
280
+ * @returns {Promise<{choice: string, result: string, shown: string}|null>} null
281
+ * when the brief names no choice, or the check could not be made
282
+ */
283
+ export async function checkBriefChoice({ client, jobId, runId, briefText, actionText, records, frame = null, ledger = null, transcript = null, log = () => {} }) {
284
+ const request = choiceCheckRequest({ briefText, actionText, records, frame });
285
+ if (!request) return null;
286
+ const brief = String(briefText).trim();
268
287
  let answer;
269
288
  const askedAt = Date.now();
270
289
  try {
@@ -273,8 +292,8 @@ export async function checkBriefChoice({ client, jobId, runId, briefText, action
273
292
  jobId,
274
293
  runId,
275
294
  step: STEPS.personaAct,
276
- system: CHOICE_CHECK_SYSTEM,
277
- messages: [{ role: 'user', content }],
295
+ system: request.system,
296
+ messages: request.messages,
278
297
  maxTokens: CHOICE_CHECK_MAX_TOKENS,
279
298
  escalate: false,
280
299
  maxAttempts: 1
@@ -309,4 +328,4 @@ export async function checkBriefChoice({ client, jobId, runId, briefText, action
309
328
  return check;
310
329
  }
311
330
 
312
- export default { checkBriefChoice, choiceNamedInBrief, parseChoiceAnswer, choiceLine, choiceFromMarkdown, writeChoiceIntoMarkdown, screensForCheck, visibleText };
331
+ export default { checkBriefChoice, choiceCheckRequest, choiceNamedInBrief, parseChoiceAnswer, choiceLine, choiceFromMarkdown, writeChoiceIntoMarkdown, screensForCheck, visibleText };
@@ -16,6 +16,9 @@ import { recordingLimits, recordingViewport, recordingDirectory, recordingMetada
16
16
  import path from 'node:path';
17
17
  import { gameRefusal, runnerGone } from '../gameRefusal.js';
18
18
  import { createAvoidGuard } from '../avoid.js';
19
+ import { classifyRequest, createSafetyCounts, networkRules } from '../livesite/network.js';
20
+ import { hostResolverRules, ravensightHosts } from '../livesite/resolver.js';
21
+ import { LiveSiteError, MASKED_EMAIL, MASKED_PASSWORD, maskSecretsInit, outcomeMessage, performSignIn } from '../livesite/browser.js';
19
22
  import {
20
23
  DEFAULT_DRAG_MS, DOUBLE_CLICK_GAP_MS, KEY_REPEAT_DELAY_MS, KEY_REPEAT_INTERVAL_MS, MAX_DRAG_MS, MAX_HOLD_MS,
21
24
  dragPath, mouseButton, sequenceEvents, webKeyName, wheelNotches
@@ -1208,6 +1211,22 @@ export function tapSdkEvents(request, log) {
1208
1211
 
1209
1212
  export const CHECK_PLAYTEST_IDENTITY = Object.freeze({ token: 'check', runId: null, jobId: null, persona: 'check' });
1210
1213
 
1214
+ /**
1215
+ * Chromium's arguments. A recorded run is muted; a live site run can resolve
1216
+ * only the names its rules allow (../livesite/resolver.js), because the route
1217
+ * never sees a redirect's next hop or a WebSocket.
1218
+ *
1219
+ * @param {{video: boolean, liveSite: Object|null}} args
1220
+ * @returns {Array<string>}
1221
+ */
1222
+ export function browserLaunchArgs({ video, liveSite }) {
1223
+ const args = video ? ['--mute-audio'] : [];
1224
+ if (liveSite) {
1225
+ args.push(`--host-resolver-rules=${hostResolverRules({ startHost: liveSite.startHost, local: liveSite.local, addresses: liveSite.addresses || [], ravensightHosts: ravensightHosts(liveSite.ravensightOrigins || []) })}`);
1226
+ }
1227
+ return args;
1228
+ }
1229
+
1211
1230
  /**
1212
1231
  * @param {Object} opts
1213
1232
  * @param {(specifier: string) => Promise<any>} [opts.importer] test seam
@@ -1412,7 +1431,7 @@ export async function needsFrame(page, text) {
1412
1431
  try { return (await page.evaluate(pageHasLargeCanvas, LARGE_CANVAS_SHARE)) === true; } catch { return false; }
1413
1432
  }
1414
1433
 
1415
- export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true } = {}) {
1434
+ export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null } = {}) {
1416
1435
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1417
1436
  // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
1418
1437
  let avoidGuard = createAvoidGuard([]);
@@ -1498,6 +1517,65 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
1498
1517
  let soundTest = null;
1499
1518
  // Inputs the page did not take that are the runner's limit, for the notes.
1500
1519
  const inputLimits = [];
1520
+ // A live URL playtest (../livesite/): the network rules every request is held to, what they kept
1521
+ // from the site, the sign-in's outcome (never a value), and a session header for the start host.
1522
+ const liveRules = liveSite ? networkRules({ startUrl: liveSite.startUrl, local: liveSite.local, extraOrigins: liveSite.ravensightOrigins || [] }) : null;
1523
+ const liveSafety = createSafetyCounts();
1524
+ let liveSignIn = null;
1525
+ const sessionHeader = liveSite && liveSite.signIn && liveSite.signIn.kind === 'header' ? liveSite.signIn.credential().header : null;
1526
+
1527
+ /**
1528
+ * The one route of a live site run (CONTRACT.md 6.1), for the sign-in
1529
+ * context and the play context. In the play context a request it lets
1530
+ * through falls back to the build guard below, so a top-level navigation off
1531
+ * the start address is still answered 204 and noted for the persona.
1532
+ *
1533
+ * @param {any} route
1534
+ * @param {{onBlocked?: (host: string) => void, play?: boolean}} hooks
1535
+ */
1536
+ function liveRoute(route, { onBlocked = null, play = false } = {}) {
1537
+ const request = route.request();
1538
+ const decision = classifyRequest(liveRules, { url: request.url(), method: request.method() });
1539
+ if (decision.action === 'ingest') {
1540
+ const headers = { ...request.headers() };
1541
+ if (decision.playtestHeader && playtest && playtest.token) headers['x-ravensight-playtest'] = String(playtest.token);
1542
+ return route.continue({ headers });
1543
+ }
1544
+ if (decision.action === 'refuse') {
1545
+ liveSafety.refuse(decision.path);
1546
+ return route.fulfill({ status: 403, contentType: 'application/json', body: '{"error":"sandbox_refused"}' });
1547
+ }
1548
+ if (decision.action === 'block') {
1549
+ liveSafety.block(decision.host);
1550
+ if (onBlocked) onBlocked(decision.host);
1551
+ const topLevel = request.isNavigationRequest() ? isTopLevel(request) : false;
1552
+ if (topLevel !== false) {
1553
+ if (play && guardArmed) recordOffSite(request.url(), topLevel === null ? 'new window' : 'navigation');
1554
+ return route.fulfill({ status: 204, body: '' });
1555
+ }
1556
+ return route.abort('blockedbyclient');
1557
+ }
1558
+ const overrides = decision.startHost && sessionHeader ? { headers: { ...request.headers(), [sessionHeader.name.toLowerCase()]: sessionHeader.value } } : undefined;
1559
+ return play ? route.fallback(overrides) : route.continue(overrides);
1560
+ }
1561
+
1562
+ /** The live route and the page's playtest identity on the sign-in context. */
1563
+ async function prepareSignInContext(signInContext, { onBlocked }) {
1564
+ await signInContext.route('**/*', route => liveRoute(route, { onBlocked }));
1565
+ // A redirect hop is not routed: a top-level one off the site's hosts is still the sign-in leaving them.
1566
+ signInContext.on('request', request => {
1567
+ try {
1568
+ if (!request.isNavigationRequest() || !request.redirectedFrom()) return;
1569
+ const decision = classifyRequest(liveRules, { url: request.url(), method: request.method() });
1570
+ if (decision.action === 'block') { liveSafety.block(decision.host); onBlocked(decision.host); }
1571
+ } catch {
1572
+ // A request that cannot be read is not a sign-in leaving the site.
1573
+ }
1574
+ });
1575
+ if (playtest && playtest.token) {
1576
+ await signInContext.addInitScript(injectPlaytestIdentity, { token: playtest.token, runId: playtest.runId || null, jobId: playtest.jobId || null, persona: playtest.persona || null });
1577
+ }
1578
+ }
1501
1579
 
1502
1580
  /** @param {string} candidate */
1503
1581
  function onBuild(candidate) {
@@ -2805,10 +2883,25 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2805
2883
  try {
2806
2884
  const playwright = await loadPlaywright(importer);
2807
2885
  await mkdir(runDir, { recursive: true });
2808
- browser = await playwright.chromium.launch({ headless, ...(videoRequested ? { args: ['--mute-audio'] } : {}) });
2886
+ const launchArgs = browserLaunchArgs({ video: videoRequested, liveSite });
2887
+ browser = await playwright.chromium.launch({ headless, ...(launchArgs.length ? { args: launchArgs } : {}) });
2888
+ const contextBase = { viewport, ...(touch ? { hasTouch: true, isMobile: true, deviceScaleFactor: 1, userAgent: PHONE_USER_AGENT } : {}) };
2889
+ // A live site's sign-in happens first, in a context of its own with no recording of any kind; the
2890
+ // recorded context starts from its cookies and storage, so it never shows the form being filled.
2891
+ let storageState = null;
2892
+ if (liveSite && liveSite.signIn && liveSite.signIn.method !== 'none') {
2893
+ try {
2894
+ const signed = await performSignIn({ browser, contextOptions: contextBase, prepareContext: prepareSignInContext, liveSite, rules: liveRules, ...(liveSite.timing || {}) });
2895
+ liveSignIn = signed.outcome;
2896
+ storageState = signed.storageState;
2897
+ } catch (error) {
2898
+ if (error && error.liveSite) liveSignIn = error.signIn;
2899
+ throw error;
2900
+ }
2901
+ }
2809
2902
  context = await browser.newContext({
2810
- viewport,
2811
- ...(touch ? { hasTouch: true, isMobile: true, deviceScaleFactor: 1, userAgent: PHONE_USER_AGENT } : {}),
2903
+ ...contextBase,
2904
+ ...(storageState ? { storageState } : {}),
2812
2905
  ...(videoRequested ? { recordVideo: { dir: captureDirectory, size: viewport }, permissions: [] } : {})
2813
2906
  });
2814
2907
  // The playtest identity goes in as an init script, not as
@@ -2823,6 +2916,11 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2823
2916
  persona: playtest.persona || null
2824
2917
  });
2825
2918
  }
2919
+ // A live site's test account never shows as page text: its email reads "test account" and its password six dots.
2920
+ if (liveSite && liveSite.signIn && liveSite.signIn.method === 'password') {
2921
+ const { email, password } = liveSite.signIn.credential();
2922
+ await context.addInitScript(maskSecretsInit, { email, password, emailLabel: MASKED_EMAIL, passwordLabel: MASKED_PASSWORD });
2923
+ }
2826
2924
  // any-game hook: the sound probe goes in before the time gate, so its sampler keeps real time. It only listens; it is read once the self test has passed.
2827
2925
  if (typeof context.addInitScript === 'function') await context.addInitScript(soundProbeInit);
2828
2926
  // One token per document: set again by every new document, kept by
@@ -2856,6 +2954,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2856
2954
  return route.fulfill({ status: 204, body: '' });
2857
2955
  });
2858
2956
  }
2957
+ // Registered after the build guard, so it decides first and hands what it allows back to the guard.
2958
+ if (liveSite && typeof context.route === 'function') await context.route('**/*', route => liveRoute(route, { play: true }));
2859
2959
  captureStartedAt = videoRequested ? now() : null;
2860
2960
  page = await context.newPage();
2861
2961
  // A new window that did get a document (one on the build, or a blank
@@ -2977,7 +3077,14 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
2977
3077
  }
2978
3078
  });
2979
3079
 
2980
- const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
3080
+ let response;
3081
+ try {
3082
+ response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
3083
+ } catch (error) {
3084
+ if (!liveSite) throw error;
3085
+ throw new LiveSiteError('site_unreachable', outcomeMessage('site_unreachable', { url, detail: String((error && error.message) || error).split('\n')[0].replace(/^page\.goto:\s*/, '').slice(0, 160) }));
3086
+ }
3087
+ if (liveSite && response && response.status() >= 500) throw new LiveSiteError('site_unreachable', outcomeMessage('site_unreachable', { url, detail: `it answered ${response.status()}` }));
2981
3088
  // A 404 is not something to guess around: the build is not there, and
2982
3089
  // guessing URLs is exactly what spec 03 forbids.
2983
3090
  if (response && response.status() >= 400) {
@@ -3152,6 +3259,12 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3152
3259
  /** The brief's avoid lines for this run (../avoid.js): an input on a control they name is refused before the page. */
3153
3260
  setAvoid(lines) { avoidGuard = createAvoidGuard(lines); },
3154
3261
 
3262
+ /** A live site run's sign-in outcome (`{ method, ok, code, seconds }`, never a value), or null. */
3263
+ signInOutcome() { return liveSignIn ? { ...liveSignIn } : null; },
3264
+
3265
+ /** A live site run's blocked hosts and refused Ravensight paths, or null for any other run. */
3266
+ liveSiteSafety() { return liveSite ? liveSafety.toJSON() : null; },
3267
+
3155
3268
  /** The controls an input was refused on because the brief asks to stay out of them, by name. */
3156
3269
  avoidedControls() { return avoidGuard.list(); },
3157
3270
 
@@ -0,0 +1,316 @@
1
+ import { classifyRequest } from './network.js';
2
+ import { addSecret } from '../redaction.js';
3
+
4
+ /**
5
+ * The browser half of a live URL playtest (CONTRACT.md 6.2 and 6.3): the
6
+ * scripted sign-in in a context of its own, and the masking every played
7
+ * page gets. Nothing here writes a file or a log line: the sign-in context has
8
+ * no video, no tracing, no screenshot and no step log, and the outcome it
9
+ * answers carries a code and a host, never a value.
10
+ */
11
+
12
+ /** How long the sign-in waits for a signed-in page after submitting. */
13
+ export const SIGN_IN_TIMEOUT_MS = 30000;
14
+ /** How long it waits for the sign-in form to appear. */
15
+ export const FIELD_WAIT_MS = 10000;
16
+ /** How long the site's start page may take to answer. */
17
+ export const LOAD_TIMEOUT_MS = 30000;
18
+
19
+ /** What a masked email and password read as on screen. */
20
+ export const MASKED_EMAIL = 'test account';
21
+ export const MASKED_PASSWORD = '••••••';
22
+
23
+ /**
24
+ * A live site run that could not start: the sign-in failed or the site did
25
+ * not load. Its message is the plain sentence the report and the run's reason
26
+ * carry; `code` is the contract's outcome code.
27
+ */
28
+ export class LiveSiteError extends Error {
29
+ constructor(code, message, signIn = null) {
30
+ super(message);
31
+ this.name = 'LiveSiteError';
32
+ this.code = code;
33
+ this.liveSite = true;
34
+ this.plainReason = true;
35
+ this.signIn = signIn;
36
+ }
37
+ }
38
+
39
+ /** The plain sentence for each outcome: what happened and what to change. */
40
+ export function outcomeMessage(code, { url = '', host = '', detail = '' } = {}) {
41
+ switch (code) {
42
+ case 'sign_in_fields_not_found':
43
+ return `Sign in failed: no email and password fields were found on ${url}. Pass --sign-in-url with the page that has the sign-in form, or --sign-in-selectors naming its fields. Nothing was played.`;
44
+ case 'sign_in_refused':
45
+ return 'Sign in failed: the site kept its sign-in form after the test account\'s email and password were sent, so it did not accept them. Check the test account signs in by hand, and that --login-password-env names the variable that holds its password. Nothing was played.';
46
+ case 'sign_in_timeout':
47
+ return 'Sign in failed: the site showed no signed-in page within 30 seconds, twice. Pass --sign-in-selectors with a "signedIn" selector that only the signed-in page shows, such as {"signedIn": "text=Sign out"}. Nothing was played.';
48
+ case 'sign_in_left_verified_hosts':
49
+ return `Sign in failed: signing in went to ${host || 'another host'}, which is not the site's own host (an outside sign-in service). Sign in with a test user's session instead: --session-cookie-env or --session-header-env. Nothing was played.`;
50
+ case 'session_expired':
51
+ return 'Sign in failed: the test user\'s session has expired. Paste a fresh one and run this again. Nothing was played.';
52
+ case 'site_unreachable':
53
+ return `The site did not load: ${url}${detail ? ` (${detail})` : ''}. Check it is up and reachable from this machine, then run this again. Nothing was played.`;
54
+ default:
55
+ return 'Signed in.';
56
+ }
57
+ }
58
+
59
+ /** The first line of an error, without the call log Playwright appends. */
60
+ function shortError(error) {
61
+ return String((error && error.message) || error || '').split('\n')[0].replace(/^page\.goto:\s*/, '').slice(0, 160);
62
+ }
63
+
64
+ /**
65
+ * Load an address the way the sign-in and the play context do. A failed load
66
+ * or a server error is `site_unreachable`.
67
+ *
68
+ * @returns {Promise<{ok: boolean, detail?: string}>}
69
+ */
70
+ export async function loadSite(page, url, timeout = LOAD_TIMEOUT_MS) {
71
+ try {
72
+ const response = await page.goto(url, { waitUntil: 'domcontentloaded', timeout });
73
+ if (response && response.status() >= 500) return { ok: false, detail: `it answered ${response.status()}` };
74
+ return { ok: true };
75
+ } catch (error) {
76
+ return { ok: false, detail: shortError(error) };
77
+ }
78
+ }
79
+
80
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
81
+
82
+ async function firstVisible(page, selectors) {
83
+ for (const selector of selectors) {
84
+ try {
85
+ const locator = typeof selector === 'string' ? page.locator(selector) : selector(page);
86
+ const visible = locator.filter({ visible: true }).first();
87
+ if (await visible.count() > 0) return visible;
88
+ } catch {
89
+ // A selector this page cannot parse is skipped.
90
+ }
91
+ }
92
+ return null;
93
+ }
94
+
95
+ const EMAIL_SELECTORS = Object.freeze([
96
+ 'input[type=email]',
97
+ 'input[autocomplete=username]', 'input[autocomplete=email]',
98
+ 'input[name*=email i]', 'input[id*=email i]',
99
+ 'input[name*=user i]:not([type=password]):not([type=hidden])', 'input[id*=user i]:not([type=password]):not([type=hidden])',
100
+ 'input[name*=login i]:not([type=password]):not([type=hidden])', 'input[id*=login i]:not([type=password]):not([type=hidden])',
101
+ page => page.getByLabel(/email|user|login/i)
102
+ ]);
103
+
104
+ /** The email and password fields, waited for up to `waitMs`. */
105
+ async function findFields(page, selectors, waitMs) {
106
+ const deadline = Date.now() + waitMs;
107
+ for (;;) {
108
+ const password = await firstVisible(page, selectors.password ? [selectors.password] : ['input[type=password]']);
109
+ const email = await firstVisible(page, selectors.email ? [selectors.email] : EMAIL_SELECTORS);
110
+ if (password && email) return { email, password };
111
+ if (Date.now() >= deadline) return null;
112
+ await sleep(250);
113
+ }
114
+ }
115
+
116
+ async function passwordVisible(page, selectors) {
117
+ return Boolean(await firstVisible(page, selectors.password ? [selectors.password] : ['input[type=password]']));
118
+ }
119
+
120
+ const ERROR_SELECTORS = Object.freeze(['[role=alert]', '[aria-live=assertive]', '[aria-invalid=true]', '.error', '.errors', '.alert-danger', '.invalid-feedback', '.form-error']);
121
+ const ERROR_TEXT = /(invalid|incorrect|wrong|unknown|not recognised|not recognized|does not match|did not match)[^.\n]{0,40}(email|password|credentials|user|login|account)|(email|password|credentials|login)[^.\n]{0,40}(invalid|incorrect|wrong|does not match|did not match)|(sign.?in|log.?in) failed|try again/i;
122
+
123
+ /** Whether the page shows a sign-in error near its form. */
124
+ async function errorShown(page) {
125
+ for (const selector of ERROR_SELECTORS) {
126
+ try {
127
+ const shown = page.locator(selector).filter({ visible: true });
128
+ const count = await shown.count();
129
+ for (let i = 0; i < Math.min(count, 5); i += 1) {
130
+ const text = (await shown.nth(i).innerText({ timeout: 500 }).catch(() => '')).trim();
131
+ if (text || selector === '[aria-invalid=true]') return true;
132
+ }
133
+ } catch {
134
+ // Not on this page.
135
+ }
136
+ }
137
+ const body = await page.locator('body').innerText({ timeout: 1000 }).catch(() => '');
138
+ return ERROR_TEXT.test(body);
139
+ }
140
+
141
+ function pathOf(url) {
142
+ try { return new URL(url).pathname; } catch { return ''; }
143
+ }
144
+
145
+ /**
146
+ * Wait for the signed-in page after a submit. Answers `signed_in`,
147
+ * `sign_in_refused`, `sign_in_left_verified_hosts` (with the host), or
148
+ * `stuck` when no signal came in time.
149
+ */
150
+ async function waitForSignedIn(page, { selectors, pathBefore, timeoutMs, watch, rules }) {
151
+ const deadline = Date.now() + timeoutMs;
152
+ for (;;) {
153
+ const current = page.url();
154
+ // An error page (a navigation that never reached a server) is neither the site nor a success.
155
+ const onWeb = /^https?:/.test(current);
156
+ const landed = classifyRequest(rules, { url: current, method: 'GET' });
157
+ if (onWeb && landed.action === 'block') return { code: 'sign_in_left_verified_hosts', host: landed.host };
158
+ // Success first: a signed-in page may itself load things from other hosts, which are blocked and are no failure.
159
+ if (onWeb && selectors.signedIn && await firstVisible(page, [selectors.signedIn])) return { code: 'signed_in' };
160
+ const formShown = await passwordVisible(page, selectors);
161
+ if (onWeb && !formShown && pathOf(current) !== pathBefore) return { code: 'signed_in' };
162
+ // Anything the route blocked since the submit, with no signed-in page: the sign-in went to another host
163
+ // (a redirect, or the form posting by script to a company-wide sign-in service).
164
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
165
+ if (formShown && await errorShown(page)) {
166
+ // A blocked call can be what made the page show its error: name the host, not a refusal.
167
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
168
+ return { code: 'sign_in_refused' };
169
+ }
170
+ if (Date.now() >= deadline) {
171
+ if (watch.blocked) return { code: 'sign_in_left_verified_hosts', host: watch.blocked };
172
+ return formShown && pathOf(page.url()) === pathBefore ? { code: 'sign_in_refused' } : { code: 'stuck' };
173
+ }
174
+ await sleep(250);
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The scripted sign-in, in a context of its own with no recording of any
180
+ * kind. Answers the storage state the recorded play context starts from, or
181
+ * throws a LiveSiteError. The credential is read once and dropped when this
182
+ * returns.
183
+ *
184
+ * @param {Object} args
185
+ * @param {any} args.browser
186
+ * @param {Object} args.contextOptions viewport, touch and so on; never recordVideo
187
+ * @param {(context: any, hooks: {onBlocked: (host: string) => void}) => Promise<void>} args.prepareContext installs the route and the page's playtest identity
188
+ * @param {Object} args.liveSite from ./options.js
189
+ * @param {Object} args.rules from ./network.js networkRules
190
+ * @returns {Promise<{storageState: Object, outcome: Object}>}
191
+ */
192
+ export async function performSignIn({ browser, contextOptions = {}, prepareContext, liveSite, rules, timeoutMs = SIGN_IN_TIMEOUT_MS, fieldWaitMs = FIELD_WAIT_MS, loadTimeoutMs = LOAD_TIMEOUT_MS, now = () => Date.now() }) {
193
+ const started = now();
194
+ const { method, kind, selectors: given } = liveSite.signIn;
195
+ const selectors = given || { email: null, password: null, submit: null, signedIn: null };
196
+ const outcome = (code, extra = {}) => ({ method, ...(kind ? { kind } : {}), ok: code === 'signed_in', code, seconds: Math.round((now() - started) / 100) / 10, ...extra });
197
+ const fail = (code, details = {}) => {
198
+ const result = outcome(code, details.host ? { blockedHost: details.host } : {});
199
+ throw new LiveSiteError(code, outcomeMessage(code, details), result);
200
+ };
201
+ // Everything after a submit that the route blocks is the sign-in leaving the site's hosts.
202
+ const watch = { armed: false, blocked: null };
203
+ let credential = liveSite.signIn.credential();
204
+ const context = await browser.newContext({ ...contextOptions });
205
+ try {
206
+ await prepareContext(context, { onBlocked: host => { if (watch.armed && !watch.blocked) watch.blocked = host; } });
207
+ if (kind === 'cookie') {
208
+ const secure = new URL(liveSite.startUrl).protocol === 'https:';
209
+ await context.addCookies(credential.cookies.map(cookie => ({ name: cookie.name, value: cookie.value, domain: liveSite.startHost, path: '/', secure, httpOnly: true, sameSite: 'Lax' })));
210
+ }
211
+ const page = await context.newPage();
212
+ if (method === 'session') {
213
+ const loaded = await loadSite(page, liveSite.startUrl, loadTimeoutMs);
214
+ if (!loaded.ok) fail('site_unreachable', { url: liveSite.startUrl, detail: loaded.detail });
215
+ } else {
216
+ let lastStuck = false;
217
+ for (let attempt = 1; attempt <= 2; attempt += 1) {
218
+ watch.armed = false;
219
+ watch.blocked = null;
220
+ const loaded = await loadSite(page, liveSite.signIn.signInUrl, loadTimeoutMs);
221
+ if (!loaded.ok) fail('site_unreachable', { url: liveSite.signIn.signInUrl, detail: loaded.detail });
222
+ const landed = classifyRequest(rules, { url: page.url(), method: 'GET' });
223
+ if (landed.action === 'block') fail('sign_in_left_verified_hosts', { host: landed.host });
224
+ const fields = await findFields(page, selectors, fieldWaitMs);
225
+ if (!fields) {
226
+ // The form was there the first time: a page without it now is a sign-in that went somewhere this step cannot see.
227
+ if (lastStuck) fail('sign_in_timeout');
228
+ fail('sign_in_fields_not_found', { url: liveSite.signIn.signInUrl });
229
+ }
230
+ await fields.email.fill(credential.email);
231
+ await fields.password.fill(credential.password);
232
+ const pathBefore = pathOf(page.url());
233
+ watch.armed = true;
234
+ if (selectors.submit) await page.locator(selectors.submit).filter({ visible: true }).first().click({ timeout: 10000 });
235
+ else await fields.password.press('Enter');
236
+ const result = await waitForSignedIn(page, { selectors, pathBefore, timeoutMs, watch, rules });
237
+ if (result.code === 'signed_in') break;
238
+ if (result.code !== 'stuck') fail(result.code, { host: result.host });
239
+ if (attempt === 2) fail('sign_in_timeout');
240
+ lastStuck = true;
241
+ }
242
+ }
243
+ const storageState = await context.storageState();
244
+ // The cookies the sign-in left are the test account's session: a credential too, so a page that
245
+ // prints one never puts it in a file or a model request (../redaction.js).
246
+ for (const cookie of storageState.cookies || []) addSecret(cookie.value);
247
+ return { storageState, outcome: outcome('signed_in') };
248
+ } finally {
249
+ credential = null;
250
+ await context.close().catch(() => {});
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Runs in every played page, before its own scripts: any text node, input
256
+ * value or readable attribute holding the test account's email (any case) is
257
+ * rewritten to "test account", and the password to six dots, and kept so by a
258
+ * MutationObserver and the input value setters, so the screen, the video and
259
+ * the page text the playtester reads never show them. Text drawn into a canvas
260
+ * or an image is not rewritten. Serialised by Playwright: it must not close
261
+ * over anything.
262
+ *
263
+ * @param {{email?: string|null, password?: string|null, emailLabel: string, passwordLabel: string}} secrets
264
+ */
265
+ export function maskSecretsInit(secrets) {
266
+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
267
+ const rules = [];
268
+ if (secrets.email) rules.push([new RegExp(escape(secrets.email), 'gi'), secrets.emailLabel]);
269
+ if (secrets.password) rules.push([new RegExp(escape(secrets.password), 'g'), secrets.passwordLabel]);
270
+ if (rules.length === 0) return;
271
+ const has = text => typeof text === 'string' && text.length > 0 && rules.some(([pattern]) => { pattern.lastIndex = 0; return pattern.test(text); });
272
+ const fix = text => rules.reduce((out, [pattern, label]) => out.replace(pattern, label), text);
273
+ const SKIP = new Set(['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEMPLATE']);
274
+ const ATTRIBUTES = ['value', 'title', 'aria-label', 'aria-description', 'aria-valuetext', 'placeholder', 'alt'];
275
+ for (const proto of [globalThis.HTMLInputElement && HTMLInputElement.prototype, globalThis.HTMLTextAreaElement && HTMLTextAreaElement.prototype]) {
276
+ const descriptor = proto && Object.getOwnPropertyDescriptor(proto, 'value');
277
+ if (!descriptor || !descriptor.set) continue;
278
+ Object.defineProperty(proto, 'value', { ...descriptor, set(value) { descriptor.set.call(this, has(value) ? fix(value) : value); } });
279
+ }
280
+ function maskNode(node) {
281
+ if (!node) return;
282
+ if (node.nodeType === 3) {
283
+ if (node.parentNode && SKIP.has(node.parentNode.nodeName)) return;
284
+ if (has(node.data)) node.data = fix(node.data);
285
+ return;
286
+ }
287
+ if (node.nodeType !== 1 || SKIP.has(node.nodeName)) return;
288
+ for (const name of ATTRIBUTES) {
289
+ const value = node.getAttribute(name);
290
+ if (has(value)) node.setAttribute(name, fix(value));
291
+ }
292
+ if ((node.nodeName === 'INPUT' || node.nodeName === 'TEXTAREA') && has(node.value)) node.value = node.value;
293
+ if (node.shadowRoot) walk(node.shadowRoot);
294
+ }
295
+ function walk(root) {
296
+ if (!root) return;
297
+ if (root.nodeType === 1 || root.nodeType === 3) maskNode(root);
298
+ if (typeof root.querySelectorAll !== 'function' && root.nodeType !== 9 && root.nodeType !== 11) return;
299
+ const walker = document.createTreeWalker(root, 5 /* SHOW_ELEMENT | SHOW_TEXT */);
300
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) maskNode(node);
301
+ }
302
+ const observer = new MutationObserver(records => {
303
+ for (const record of records) {
304
+ if (record.type === 'childList') record.addedNodes.forEach(walk);
305
+ else maskNode(record.target);
306
+ }
307
+ });
308
+ observer.observe(document, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ATTRIBUTES });
309
+ const sweep = event => maskNode(event && event.target);
310
+ document.addEventListener('input', sweep, true);
311
+ document.addEventListener('change', sweep, true);
312
+ document.addEventListener('DOMContentLoaded', () => walk(document), { once: true });
313
+ walk(document);
314
+ }
315
+
316
+ export default { performSignIn, maskSecretsInit, loadSite, outcomeMessage, LiveSiteError, MASKED_EMAIL, MASKED_PASSWORD };