@monkeytestai/monkeytester 0.7.2-beta.5 → 0.7.2-beta.7

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/auth/browser.d.ts.map +1 -1
  3. package/dist/auth/browser.js +22 -1
  4. package/dist/auth/browser.js.map +1 -1
  5. package/dist/auth/contract.d.ts +42 -2
  6. package/dist/auth/contract.d.ts.map +1 -1
  7. package/dist/auth/contract.js +6 -0
  8. package/dist/auth/contract.js.map +1 -1
  9. package/dist/auth/egress.d.ts +6 -1
  10. package/dist/auth/egress.d.ts.map +1 -1
  11. package/dist/auth/egress.js +30 -3
  12. package/dist/auth/egress.js.map +1 -1
  13. package/dist/auth/establish.d.ts +3 -1
  14. package/dist/auth/establish.d.ts.map +1 -1
  15. package/dist/auth/establish.js +384 -60
  16. package/dist/auth/establish.js.map +1 -1
  17. package/dist/auth/fence.d.ts +9 -3
  18. package/dist/auth/fence.d.ts.map +1 -1
  19. package/dist/auth/fence.js +274 -51
  20. package/dist/auth/fence.js.map +1 -1
  21. package/dist/auth/origins.d.ts +7 -0
  22. package/dist/auth/origins.d.ts.map +1 -1
  23. package/dist/auth/origins.js +65 -10
  24. package/dist/auth/origins.js.map +1 -1
  25. package/dist/auth/proof.d.ts.map +1 -1
  26. package/dist/auth/proof.js +12 -7
  27. package/dist/auth/proof.js.map +1 -1
  28. package/dist/auth/redact.d.ts +19 -0
  29. package/dist/auth/redact.d.ts.map +1 -1
  30. package/dist/auth/redact.js +45 -5
  31. package/dist/auth/redact.js.map +1 -1
  32. package/dist/auth/report.d.ts +6 -1
  33. package/dist/auth/report.d.ts.map +1 -1
  34. package/dist/auth/report.js +15 -0
  35. package/dist/auth/report.js.map +1 -1
  36. package/dist/auth/sessionFile.js +5 -0
  37. package/dist/auth/sessionFile.js.map +1 -1
  38. package/dist/outcome.d.ts.map +1 -1
  39. package/dist/outcome.js +2 -0
  40. package/dist/outcome.js.map +1 -1
  41. package/dist/types.d.ts +7 -1
  42. package/dist/types.d.ts.map +1 -1
  43. package/package.json +1 -1
@@ -7,12 +7,12 @@
7
7
  */
8
8
  import { blockUnroutableEgress } from './browser.js';
9
9
  import { launchFencedBrowser } from './egress.js';
10
- import { loginProved } from './proof.js';
11
- import { installLoginFence } from './fence.js';
12
- import { acceptSessionMaterial, assertSessionBound, originAllowed, policyFrom } from './origins.js';
13
- import { assertPublicSafe, redactError, storageContainsSecret } from './redact.js';
10
+ import { loginProved, passwordFieldVisible } from './proof.js';
11
+ import { emptyFenceState, installLoginFence } from './fence.js';
12
+ import { acceptSessionMaterial, assertSessionBound, originAllowed, policyFrom, sameSiteUrl } from './origins.js';
13
+ import { assertPublicSafe, credentialStorageNeedles, redactError, storageContainsSecret } from './redact.js';
14
14
  import { publicMetadata } from './report.js';
15
- import { rememberSecrets, withSensitiveSinks } from './secrets.js';
15
+ import { activeNeedles, rememberSecrets, withSensitiveSinks } from './secrets.js';
16
16
  const MIN_PASSWORD = 8;
17
17
  export async function establishFormAuth(input) {
18
18
  const policyResult = policyFrom(input.targetUrl, input.idpOrigins ?? []);
@@ -36,6 +36,7 @@ export async function establishFormAuth(input) {
36
36
  return failure('form', 'not_authorized', policy, true, 'Sign-in is not treated as success without a post-login URL or selector on the target. Nothing was typed. This is not a verified run.');
37
37
  }
38
38
  return withSensitiveSinks(secrets, () => withLoginCaptureOff(async () => {
39
+ const credentialBaseline = [...activeNeedles()];
39
40
  const launched = await launchFencedBrowser({
40
41
  headless: input.headless !== false,
41
42
  policy,
@@ -52,7 +53,7 @@ export async function establishFormAuth(input) {
52
53
  return failure('form', 'target_rejected', policy, true, 'Sign-in could not pin the target. Nothing was typed.');
53
54
  }
54
55
  let context;
55
- const fence = { originRejected: false };
56
+ const fence = emptyFenceState();
56
57
  const onAbort = () => {
57
58
  void context?.close().catch(() => { });
58
59
  void browser.close().catch(() => { });
@@ -81,38 +82,63 @@ export async function establishFormAuth(input) {
81
82
  return failure('form', 'origin_rejected', policy, false);
82
83
  throw redactError(err, secrets);
83
84
  }
85
+ if (fence.credentialLeak)
86
+ return failure('form', 'credential_leak', policy, false, undefined, 'customer-local', fence);
84
87
  if (fence.originRejected || !(await onPolicy(page, policy)))
85
- return failure('form', 'origin_rejected', policy, false);
88
+ return failure('form', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
86
89
  const before = await classifyPage(page, policy, 'before');
87
90
  if (before === 'off')
88
91
  return failure('form', 'origin_rejected', policy, false);
89
92
  if (before === 'mfa' || before === 'sso')
90
93
  return failure('form', 'mfa_required', policy, false);
91
94
  if (before !== 'login') {
92
- return failure('form', 'credentials_rejected', policy, false, 'Our test couldn\'t complete the run because the authorized page has no password field. Nothing was typed. This is not a verified run.');
95
+ return failure('form', 'fields_not_found', policy, false, undefined, 'customer-local', undefined, {
96
+ rejectReason: 'password_field_not_found',
97
+ rejectContext: await rejectContext(page),
98
+ });
93
99
  }
94
100
  if (!(await formPostsToPolicy(page, policy))) {
95
101
  return failure('form', 'origin_rejected', policy, false, 'Our test couldn\'t complete the run because the sign-in form posts off the authorized origin. The password was not typed. This is not a verified run.');
96
102
  }
103
+ let filledField;
97
104
  try {
98
- await fillLogin(page, taken.username, taken.password, timeout);
105
+ const filled = await fillLogin(page, policy, taken.username, taken.password, timeout);
106
+ if (!filled.ok) {
107
+ return failure('form', 'fields_not_found', policy, false, undefined, 'customer-local', fence, {
108
+ rejectReason: filled.reason,
109
+ rejectContext: await rejectContext(page, filled.field),
110
+ });
111
+ }
112
+ filledField = filled.field;
99
113
  }
100
114
  catch (err) {
101
115
  if (input.signal?.aborted)
102
116
  return failure('form', 'not_authorized', policy, false, 'Our test couldn\'t complete the run because sign-in was cancelled. The session was not kept. This is not a verified run.');
117
+ if (fence.credentialLeak)
118
+ return failure('form', 'credential_leak', policy, false, undefined, 'customer-local', fence);
103
119
  if (navigationRejected(err, fence, true))
104
- return failure('form', 'origin_rejected', policy, false);
120
+ return failure('form', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
105
121
  throw redactError(err, secrets);
106
122
  }
123
+ if (fence.credentialLeak)
124
+ return failure('form', 'credential_leak', policy, false, undefined, 'customer-local', fence);
107
125
  if (fence.originRejected)
108
- return failure('form', 'origin_rejected', policy, false);
126
+ return failure('form', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
109
127
  const after = await classifyPage(page, policy, 'after');
128
+ if (fence.credentialLeak)
129
+ return failure('form', 'credential_leak', policy, false, undefined, 'customer-local', fence);
110
130
  if (fence.originRejected || after === 'off')
111
- return failure('form', 'origin_rejected', policy, false);
131
+ return failure('form', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
112
132
  if (after === 'mfa')
113
133
  return failure('form', 'mfa_required', policy, false);
114
- if (after === 'login')
115
- return failure('form', 'credentials_rejected', policy, false);
134
+ const proved = await loginProved(page, policy, input.postLoginUrl, input.postLoginSelector);
135
+ if (after === 'login' && !proved) {
136
+ const errored = await loginErrorText(page);
137
+ return failure('form', 'credentials_rejected', policy, false, undefined, 'customer-local', fence, {
138
+ rejectReason: errored ? 'error_text_detected' : 'still_on_login_page',
139
+ rejectContext: await rejectContext(page, filledField),
140
+ });
141
+ }
116
142
  const state = await snapshot(context);
117
143
  if (input.signal?.aborted) {
118
144
  return failure('form', 'not_authorized', policy, false, 'Our test couldn\'t complete the run because sign-in was cancelled. The session was not kept. This is not a verified run.');
@@ -120,20 +146,33 @@ export async function establishFormAuth(input) {
120
146
  if (input.expiresAt && Date.parse(input.expiresAt) <= Date.now()) {
121
147
  return failure('form', 'expired', policy, false, 'Our test couldn\'t complete the run because the sign-in envelope expired before the browser finished. The session was not kept. This is not a verified run.');
122
148
  }
149
+ const signals = sessionSignals(state);
123
150
  const material = acceptSessionMaterial(state);
124
151
  if (!material.ok) {
125
- return failure('form', 'credentials_rejected', policy, false, `Our test couldn't complete the run. ${material.detail} This is not a verified run.`);
152
+ return failure('form', 'credentials_rejected', policy, false, `Our test couldn't complete the run. ${material.detail} This is not a verified run.`, 'customer-local', fence, {
153
+ rejectReason: 'session_not_detected',
154
+ rejectContext: await rejectContext(page, filledField, signals),
155
+ });
126
156
  }
127
- if (!(await loginProved(page, policy, input.postLoginUrl, input.postLoginSelector))) {
128
- return failure('form', 'credentials_rejected', policy, false, 'Our test couldn\'t complete the run because the target did not show the configured post-login URL or selector. The session was not kept. This is not a verified run.');
157
+ if (!proved) {
158
+ return failure('form', 'credentials_rejected', policy, false, 'Our test couldn\'t complete the run because the target did not show the configured post-login URL or selector. The session was not kept. This is not a verified run.', 'customer-local', fence, {
159
+ rejectReason: 'post_login_url_mismatch',
160
+ rejectContext: await rejectContext(page, filledField, signals),
161
+ });
162
+ }
163
+ if (storageContainsSecret(state, credentialStorageNeedles({
164
+ secrets,
165
+ baseline: credentialBaseline,
166
+ username: taken.username,
167
+ password: taken.password,
168
+ }))) {
169
+ return failure('form', 'storage_unsafe', policy, false, undefined, 'customer-local', fence);
129
170
  }
130
- if (storageContainsSecret(state, secrets))
131
- return failure('form', 'storage_unsafe', policy, false);
132
171
  const bound = assertSessionBound(state, policy);
133
172
  if (!bound.ok)
134
- return failure('form', 'origin_rejected', policy, false, `Our test couldn't complete the run. ${bound.detail} This is not a verified run.`);
173
+ return failure('form', 'origin_rejected', policy, false, `Our test couldn't complete the run. ${bound.detail} This is not a verified run.`, 'customer-local', fence);
135
174
  rememberSecrets(state, [...secrets, ...secretValues(state)]);
136
- return success('form', policy, state, input.custody ?? 'customer-local', false, input.expiresAt);
175
+ return success('form', policy, state, input.custody ?? 'customer-local', false, input.expiresAt, fence);
137
176
  }
138
177
  finally {
139
178
  input.signal?.removeEventListener('abort', onAbort);
@@ -171,7 +210,7 @@ export async function establishManualAuth(input) {
171
210
  return failure('manual', 'target_rejected', policy, true, 'Sign-in could not pin the target. Nothing was typed.');
172
211
  }
173
212
  let context;
174
- const fence = { originRejected: false };
213
+ const fence = emptyFenceState();
175
214
  try {
176
215
  context = await browser.newContext({
177
216
  viewport: { width: 1280, height: 800 },
@@ -186,16 +225,22 @@ export async function establishManualAuth(input) {
186
225
  await page.goto(input.targetUrl, { waitUntil: 'domcontentloaded', timeout });
187
226
  }
188
227
  catch (err) {
228
+ if (fence.credentialLeak)
229
+ return failure('manual', 'credential_leak', policy, false, undefined, 'customer-local', fence);
189
230
  if (navigationRejected(err, fence, await onPolicy(page, policy)))
190
- return failure('manual', 'origin_rejected', policy, false);
231
+ return failure('manual', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
191
232
  throw redactError(err, []);
192
233
  }
234
+ if (fence.credentialLeak)
235
+ return failure('manual', 'credential_leak', policy, false, undefined, 'customer-local', fence);
193
236
  if (fence.originRejected)
194
- return failure('manual', 'origin_rejected', policy, false);
237
+ return failure('manual', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
195
238
  await input.settle(page);
196
239
  await page.waitForLoadState('domcontentloaded', { timeout }).catch(() => { });
240
+ if (fence.credentialLeak)
241
+ return failure('manual', 'credential_leak', policy, false, undefined, 'customer-local', fence);
197
242
  if (fence.originRejected)
198
- return failure('manual', 'origin_rejected', policy, false);
243
+ return failure('manual', 'origin_rejected', policy, false, undefined, 'customer-local', fence);
199
244
  const after = await classifyPage(page, policy, 'after');
200
245
  if (after === 'off')
201
246
  return failure('manual', 'origin_rejected', policy, false);
@@ -214,7 +259,7 @@ export async function establishManualAuth(input) {
214
259
  if (!bound.ok)
215
260
  return failure('manual', 'origin_rejected', policy, false, `Our test couldn't complete the run. ${bound.detail} This is not a verified run.`);
216
261
  rememberSecrets(state, secretValues(state));
217
- return success('manual', policy, state, 'customer-local');
262
+ return success('manual', policy, state, 'customer-local', false, undefined, fence);
218
263
  }
219
264
  finally {
220
265
  await context?.close().catch(() => { });
@@ -238,7 +283,16 @@ export async function establishWithRuntimeProvider(provider, targetUrl, idpOrigi
238
283
  }
239
284
  return success('session', policyResult.policy, opened.storageState, 'in-memory', true);
240
285
  }
241
- function success(mode, policy, storageState, custody, sessionReused = false, expiresAt) {
286
+ function ledgerInput(ledger) {
287
+ if (!ledger || (ledger.thirdPartyRequestCount === 0 && ledger.thirdPartyDeniedCount === 0))
288
+ return {};
289
+ return {
290
+ ...(ledger.thirdPartyOrigins.length ? { thirdPartyOrigins: [...ledger.thirdPartyOrigins] } : {}),
291
+ thirdPartyRequestCount: ledger.thirdPartyRequestCount,
292
+ thirdPartyDeniedCount: ledger.thirdPartyDeniedCount,
293
+ };
294
+ }
295
+ function success(mode, policy, storageState, custody, sessionReused = false, expiresAt, ledger) {
242
296
  const metadata = publicMetadata({
243
297
  mode,
244
298
  outcome: 'authenticated',
@@ -246,6 +300,7 @@ function success(mode, policy, storageState, custody, sessionReused = false, exp
246
300
  custody,
247
301
  sessionReused,
248
302
  ...(expiresAt ? { expiresAt } : {}),
303
+ ...ledgerInput(ledger),
249
304
  });
250
305
  assertPublicSafe(metadata, secretValues(storageState));
251
306
  return {
@@ -257,48 +312,265 @@ function success(mode, policy, storageState, custody, sessionReused = false, exp
257
312
  toJSON: () => ({ ok: true, setup: false, metadata, storageState: { redacted: true } }),
258
313
  };
259
314
  }
260
- function failure(mode, outcome, policy, setup, detail, custody = 'customer-local') {
261
- return { ok: false, setup, metadata: publicMetadata({ mode, outcome, policy, custody, detail }) };
315
+ function failure(mode, outcome, policy, setup, detail, custody = 'customer-local', ledger, reject) {
316
+ const safeReject = reject
317
+ ? { rejectReason: reject.rejectReason, rejectContext: scrubRejectContext(reject.rejectContext) }
318
+ : undefined;
319
+ if (safeReject)
320
+ console.debug(formatRejectDebug(safeReject.rejectReason, safeReject.rejectContext));
321
+ return { ok: false, setup, metadata: publicMetadata({ mode, outcome, policy, custody, detail, ...ledgerInput(ledger), ...safeReject }) };
322
+ }
323
+ /** Debug line. Only tag, type, name, id, path, and session signals. No typed values. */
324
+ export function formatRejectDebug(reason, context) {
325
+ const safe = scrubRejectContext(context);
326
+ return `[monkeytester] auth reject ${reason} ${JSON.stringify(safe)}`;
327
+ }
328
+ function scrubRejectContext(context) {
329
+ const clean = (value) => {
330
+ const lower = value.toLowerCase();
331
+ if (activeNeedles().some(secret => secret.trim().length >= 4 && lower.includes(secret.trim().toLowerCase())))
332
+ return '';
333
+ return value;
334
+ };
335
+ const path = (context.path || '').split('?')[0]?.split('#')[0] || '';
336
+ return {
337
+ ...(context.field ? {
338
+ field: {
339
+ tag: clean(context.field.tag),
340
+ type: clean(context.field.type),
341
+ name: clean(context.field.name),
342
+ id: clean(context.field.id),
343
+ },
344
+ } : {}),
345
+ ...(path ? { path } : {}),
346
+ ...(context.sessionSignals ? { sessionSignals: [...context.sessionSignals] } : {}),
347
+ };
262
348
  }
263
- async function fillLogin(page, username, password, timeout) {
264
- const user = page.locator('input[type="email"], input[autocomplete="username"], input[name="email" i], input[name="username" i], input[type="text"]').first();
265
- const pass = page.locator('input[type="password"]').first();
266
- await user.fill(username, { timeout });
267
- await pass.fill(password, { timeout });
268
- const submit = page.locator('button[type="submit"], input[type="submit"]').first();
269
- if (await submit.count()) {
270
- await Promise.all([
271
- page.waitForLoadState('domcontentloaded', { timeout }).catch(() => { }),
272
- submit.click({ timeout }),
273
- ]);
349
+ function frameOnPolicy(frame, policy) {
350
+ try {
351
+ return originAllowed(new URL(frame.url()), policy);
274
352
  }
275
- else {
276
- await pass.press('Enter');
353
+ catch {
354
+ return false;
277
355
  }
278
- await page.waitForLoadState('domcontentloaded', { timeout }).catch(() => { });
279
356
  }
280
- async function formPostsToPolicy(page, policy) {
281
- const form = page.locator('form').filter({ has: page.locator('input[type="password"]') }).first();
282
- if (!(await form.count()))
357
+ const SEARCH_NAMES = new Set(['q', 's', 'search', 'query']);
358
+ const MIN_USERNAME_SCORE = 40;
359
+ const SCORE_GAP = 15;
360
+ async function loginCandidates(frame) {
361
+ return frame.locator('input, button').evaluateAll(elements => elements.map((el, index) => {
362
+ const input = el;
363
+ const form = input.form ?? el.closest('form');
364
+ const action = form?.getAttribute('action') || '';
365
+ const formRole = form?.getAttribute('role') || '';
366
+ const formIndex = form ? Array.from(document.forms).indexOf(form) : -1;
367
+ let container = formIndex >= 0 ? `form:${formIndex}` : '';
368
+ if (!container) {
369
+ let node = el.parentElement;
370
+ let depth = 0;
371
+ while (node && node !== document.body && depth < 6) {
372
+ if (node.querySelector('input[type="password"]')) {
373
+ container = node.id ? `id:${node.id}` : `tag:${node.tagName.toLowerCase()}:${depth}`;
374
+ break;
375
+ }
376
+ node = node.parentElement;
377
+ depth += 1;
378
+ }
379
+ }
380
+ const labelEl = input.labels && input.labels.length ? input.labels[0] : el.closest('label');
381
+ const box = el.getBoundingClientRect();
382
+ return {
383
+ index,
384
+ tag: el.tagName.toLowerCase(),
385
+ type: (el.getAttribute('type') || (el.tagName === 'BUTTON' ? 'submit' : 'text')).toLowerCase(),
386
+ name: el.getAttribute('name') || '',
387
+ id: el.id || '',
388
+ autocomplete: (el.getAttribute('autocomplete') || '').toLowerCase(),
389
+ role: el.getAttribute('role') || '',
390
+ placeholder: el.getAttribute('placeholder') || '',
391
+ ariaLabel: el.getAttribute('aria-label') || '',
392
+ label: (labelEl?.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 80),
393
+ inSearch: formRole === 'search' || Boolean(el.closest('[role="search"]')) || /(?:^|\/)search(?:\/|$|\?)/i.test(action),
394
+ inChrome: Boolean(el.closest('header, nav')),
395
+ formIndex,
396
+ container,
397
+ visible: !!(box.width || box.height),
398
+ enabled: !input.disabled && !input.readOnly,
399
+ top: box.top,
400
+ };
401
+ }));
402
+ }
403
+ function searchControl(field) {
404
+ if (field.type === 'search' || field.role === 'search' || field.inSearch)
283
405
  return true;
284
- const action = await form.getAttribute('action');
285
- if (!action || action === '#')
406
+ const name = field.name.toLowerCase();
407
+ const id = field.id.toLowerCase();
408
+ return SEARCH_NAMES.has(name) || SEARCH_NAMES.has(id);
409
+ }
410
+ function sameContainer(field, password) {
411
+ if (field.formIndex >= 0 && field.formIndex === password.formIndex)
286
412
  return true;
287
- try {
288
- return originAllowed(new URL(action, page.url()), policy);
413
+ return Boolean(field.container) && field.container === password.container;
414
+ }
415
+ function usernameScore(field, password, submit) {
416
+ if (!field.visible || field.tag !== 'input' || searchControl(field))
417
+ return -1;
418
+ if (field.inChrome && !sameContainer(field, password))
419
+ return -1;
420
+ if (['hidden', 'password', 'submit', 'button', 'checkbox', 'radio', 'file', 'image', 'range', 'color'].includes(field.type))
421
+ return -1;
422
+ if (!sameContainer(field, password))
423
+ return -1;
424
+ let score = 0;
425
+ if (field.type === 'email')
426
+ score += 50;
427
+ if (field.autocomplete === 'username' || field.autocomplete === 'email')
428
+ score += 40;
429
+ const hints = `${field.name} ${field.id} ${field.ariaLabel} ${field.label} ${field.placeholder}`;
430
+ if (/email/i.test(hints))
431
+ score += 30;
432
+ else if (/user|login/i.test(hints))
433
+ score += 25;
434
+ else if (/phone|tel/i.test(hints) || field.type === 'tel')
435
+ score += 20;
436
+ if (field.formIndex >= 0 && field.formIndex === password.formIndex)
437
+ score += 20;
438
+ if (Math.abs(field.top - password.top) < 240)
439
+ score += 10;
440
+ if (submit && Math.abs(field.top - submit.top) < 280)
441
+ score += 6;
442
+ return score;
443
+ }
444
+ function descriptor(field) {
445
+ return { tag: field.tag, type: field.type, name: field.name, id: field.id };
446
+ }
447
+ async function valueStuck(locator, expected, password) {
448
+ return locator.evaluate((el, args) => {
449
+ const input = el;
450
+ if (input.disabled || input.readOnly)
451
+ return false;
452
+ if (input.value !== args.expected)
453
+ return false;
454
+ return !args.password || input.value.length === args.expected.length;
455
+ }, { expected, password }).catch(() => false);
456
+ }
457
+ async function fillLogin(page, policy, username, password, timeout) {
458
+ for (const frame of page.frames()) {
459
+ if (!frameOnPolicy(frame, policy))
460
+ continue;
461
+ const fields = await loginCandidates(frame);
462
+ const passwords = fields.filter(field => field.tag === 'input' && field.type === 'password' && field.visible && field.enabled);
463
+ if (!passwords.length)
464
+ continue;
465
+ if (passwords.length > 1)
466
+ return { ok: false, reason: 'password_field_not_found', field: descriptor(passwords[0]) };
467
+ const pass = passwords[0];
468
+ const submits = fields.filter(field => sameContainer(field, pass)
469
+ && field.visible
470
+ && field.enabled
471
+ && ((field.tag === 'button' && (field.type === 'submit' || field.type === ''))
472
+ || (field.tag === 'input' && field.type === 'submit')));
473
+ const submit = submits.sort((a, b) => Math.abs(a.top - pass.top) - Math.abs(b.top - pass.top))[0];
474
+ const ranked = fields
475
+ .map(field => ({ field, score: usernameScore(field, pass, submit) }))
476
+ .filter(item => item.score >= MIN_USERNAME_SCORE)
477
+ .sort((a, b) => b.score - a.score);
478
+ if (!ranked.length)
479
+ return { ok: false, reason: 'username_field_not_found', field: descriptor(pass) };
480
+ if (ranked.length > 1 && ranked[0].score - ranked[1].score < SCORE_GAP) {
481
+ return { ok: false, reason: 'username_field_not_found', field: descriptor(ranked[0].field) };
482
+ }
483
+ if (!submit)
484
+ return { ok: false, reason: 'submit_not_found', field: descriptor(ranked[0].field) };
485
+ const chosen = ranked[0].field;
486
+ if (!chosen.enabled || !pass.enabled || !submit.enabled) {
487
+ return { ok: false, reason: 'field_not_interactable', field: descriptor(chosen) };
488
+ }
489
+ const controls = frame.locator('input, button');
490
+ const userLoc = controls.nth(chosen.index);
491
+ const passLoc = controls.nth(pass.index);
492
+ try {
493
+ await userLoc.fill(username, { timeout });
494
+ await passLoc.fill(password, { timeout });
495
+ }
496
+ catch {
497
+ return { ok: false, reason: 'field_not_interactable', field: descriptor(chosen) };
498
+ }
499
+ if (!(await valueStuck(userLoc, username, false)) || !(await valueStuck(passLoc, password, true))) {
500
+ return { ok: false, reason: 'field_not_interactable', field: descriptor(chosen) };
501
+ }
502
+ const startUrl = page.url();
503
+ const budget = Math.min(timeout, 5_000);
504
+ await controls.nth(submit.index).click({ timeout });
505
+ const started = Date.now();
506
+ let networkIdle = false;
507
+ const idleDone = page.waitForLoadState('networkidle', { timeout: budget }).then(() => { networkIdle = true; }).catch(() => { });
508
+ while (Date.now() - started < budget) {
509
+ const moved = page.url() !== startUrl;
510
+ const passwordGone = !(await passwordFieldVisible(page));
511
+ if (moved && passwordGone)
512
+ break;
513
+ if (moved && networkIdle)
514
+ break;
515
+ if (!moved && passwordGone && networkIdle)
516
+ break;
517
+ if (networkIdle && Date.now() - started > 800)
518
+ break;
519
+ await page.waitForTimeout(100);
520
+ }
521
+ await idleDone;
522
+ await page.waitForLoadState('domcontentloaded', { timeout }).catch(() => { });
523
+ return { ok: true, field: descriptor(chosen) };
289
524
  }
290
- catch {
291
- return false;
525
+ return { ok: false, reason: 'password_field_not_found' };
526
+ }
527
+ async function formPostsToPolicy(page, policy) {
528
+ for (const frame of page.frames()) {
529
+ if (!frameOnPolicy(frame, policy))
530
+ continue;
531
+ const form = frame.locator('form').filter({ has: frame.locator('input[type="password"]') }).first();
532
+ if (!(await form.count()))
533
+ continue;
534
+ const action = await form.getAttribute('action');
535
+ if (!action || action === '#')
536
+ return true;
537
+ try {
538
+ return originAllowed(new URL(action, frame.url()), policy);
539
+ }
540
+ catch {
541
+ return false;
542
+ }
292
543
  }
544
+ return true;
293
545
  }
294
546
  async function classifyPage(page, policy, phase) {
295
547
  if (!(await onPolicy(page, policy)))
296
548
  return 'off';
297
- const otp = await page.locator('input[autocomplete="one-time-code"], input[name*="otp" i], input[name*="totp" i], input[name*="mfa" i]').count();
298
- const text = await page.locator('body').innerText().catch(() => '');
549
+ let otp = 0;
550
+ let passwords = 0;
551
+ let text = '';
552
+ for (const frame of page.frames()) {
553
+ let frameUrl;
554
+ try {
555
+ frameUrl = new URL(frame.url());
556
+ }
557
+ catch {
558
+ continue;
559
+ }
560
+ if (!sameSiteUrl(frameUrl, policy))
561
+ continue;
562
+ otp += await frame.locator('input[autocomplete="one-time-code"], input[name*="otp" i], input[name*="totp" i], input[name*="mfa" i]').count();
563
+ const fields = frame.locator('input[type="password"]');
564
+ const count = await fields.count();
565
+ for (let i = 0; i < count; i++) {
566
+ if (await fields.nth(i).isVisible().catch(() => false))
567
+ passwords += 1;
568
+ }
569
+ text += `\n${await frame.locator('body').innerText().catch(() => '')}`;
570
+ }
299
571
  if (otp > 0 || /\b(verification code|authenticator app|two-factor|2-step verification|one-time code|enter the code)\b/i.test(text))
300
572
  return 'mfa';
301
- if (await page.locator('input[type="password"]').count())
573
+ if (passwords > 0)
302
574
  return 'login';
303
575
  if (phase === 'before' && /\b(continue with|sign in with|log in with|single sign-on|\bsso\b)\b/i.test(text))
304
576
  return 'sso';
@@ -306,14 +578,68 @@ async function classifyPage(page, policy, phase) {
306
578
  }
307
579
  async function onPolicy(page, policy) {
308
580
  try {
309
- return originAllowed(new URL(page.url()), policy);
581
+ return sameSiteUrl(new URL(page.url()), policy);
310
582
  }
311
583
  catch {
312
584
  return false;
313
585
  }
314
586
  }
587
+ function safePath(page) {
588
+ try {
589
+ return new URL(page.url()).pathname || '/';
590
+ }
591
+ catch {
592
+ return '';
593
+ }
594
+ }
595
+ async function rejectContext(page, field, sessionSignalsFound) {
596
+ return {
597
+ ...(field ? { field } : {}),
598
+ path: safePath(page),
599
+ ...(sessionSignalsFound ? { sessionSignals: sessionSignalsFound } : {}),
600
+ };
601
+ }
602
+ function sessionSignals(state) {
603
+ const signals = [];
604
+ if (state.cookies.some(cookie => cookie.value && !/csrf|xsrf/i.test(cookie.name)))
605
+ signals.push('cookie');
606
+ if (state.origins.some(origin => origin.localStorage.some(item => item.value && !/csrf|xsrf/i.test(item.name))))
607
+ signals.push('localStorage');
608
+ if (state.origins.some(origin => (origin.sessionStorage || []).some(item => item.value && !/csrf|xsrf/i.test(item.name))))
609
+ signals.push('sessionStorage');
610
+ return signals;
611
+ }
612
+ async function loginErrorText(page) {
613
+ const blocks = await page.locator('[role="alert"], form:has(input[type="password"])').allInnerTexts().catch(() => []);
614
+ return blocks.some(text => /\b(invalid credentials|wrong (?:email|password|username)|incorrect password|login failed|sign-in failed|could not sign in)\b/i.test(text));
615
+ }
315
616
  async function snapshot(context) {
316
617
  const raw = await context.storageState();
618
+ const sessionByOrigin = new Map();
619
+ for (const page of context.pages()) {
620
+ const read = await page.evaluate(() => {
621
+ const items = [];
622
+ for (let i = 0; i < sessionStorage.length; i++) {
623
+ const name = sessionStorage.key(i) || '';
624
+ if (!name)
625
+ continue;
626
+ items.push({ name, value: sessionStorage.getItem(name) || '' });
627
+ }
628
+ return { origin: location.origin, items };
629
+ }).catch(() => undefined);
630
+ if (read && read.items.length)
631
+ sessionByOrigin.set(read.origin, read.items);
632
+ }
633
+ const origins = raw.origins.map(origin => ({
634
+ origin: origin.origin,
635
+ localStorage: origin.localStorage.map(item => ({ name: item.name, value: item.value })),
636
+ ...(sessionByOrigin.has(origin.origin) ? { sessionStorage: sessionByOrigin.get(origin.origin) } : {}),
637
+ }));
638
+ for (const [origin, sessionStorage] of sessionByOrigin) {
639
+ if (!origins.some(entry => entry.origin === origin)) {
640
+ origins.push({ origin, localStorage: [], sessionStorage });
641
+ }
642
+ }
317
643
  return {
318
644
  cookies: raw.cookies.map(cookie => ({
319
645
  name: cookie.name,
@@ -325,16 +651,14 @@ async function snapshot(context) {
325
651
  secure: cookie.secure,
326
652
  sameSite: cookie.sameSite === 'Strict' || cookie.sameSite === 'None' ? cookie.sameSite : 'Lax',
327
653
  })),
328
- origins: raw.origins.map(origin => ({
329
- origin: origin.origin,
330
- localStorage: origin.localStorage.map(item => ({ name: item.name, value: item.value })),
331
- })),
654
+ origins,
332
655
  };
333
656
  }
334
657
  function secretValues(state) {
335
658
  return [
336
659
  ...state.cookies.map(cookie => cookie.value),
337
660
  ...state.origins.flatMap(origin => origin.localStorage.map(item => item.value)),
661
+ ...state.origins.flatMap(origin => (origin.sessionStorage || []).map(item => item.value)),
338
662
  ].filter(value => value.length >= 8);
339
663
  }
340
664
  function navigationRejected(err, fence, onOrigin) {