autologin-mcp 1.1.0 → 1.3.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.
package/README.md CHANGED
@@ -152,7 +152,7 @@ No. It goes from the local credentials file straight into the page, through the
152
152
  No. Bridge mode needs no browser setup. Remote debugging enables CDP mode, which also works when the app's Content-Security-Policy blocks the bridge.
153
153
 
154
154
  **Does it support SSO, 2FA or multi-step logins?**
155
- Not yet: it handles username + password forms on the app's own page. Multi-step logins, iframes, SSO hosts and TOTP are on the roadmap.
155
+ It fills username + password forms on the app's own page, including identifier-first logins that ask for the email and then swap in the password field. Single sign-on, passkeys, captchas and a one-time code after the password are recognised and handed to you (`needs_human`) instead of failing or retrying. Filling TOTP codes, logins that move to another document, and iframes are on the roadmap.
156
156
 
157
157
  **Is it free?**
158
158
  Yes, MIT licensed.
@@ -162,7 +162,7 @@ More questions: [FAQ](docs/faq.md).
162
162
  ## Roadmap
163
163
 
164
164
  - [ ] Opt-in auto-login (CDP mode): watch a profile's URL and log in without the agent asking
165
- - [ ] Multi-step logins (username → next → password), iframes, SSO login hosts
165
+ - [ ] Logins that navigate between documents, iframes, SSO login hosts
166
166
  - [ ] TOTP codes
167
167
  - [ ] `doctor` and `test <profile>` commands
168
168
  - [ ] Installers that write the config for Codex CLI, Gemini CLI and Cursor (`print-config` prints it today); a Claude Code plugin
@@ -6,7 +6,16 @@ import { autologinInpage } from '../inpage.js';
6
6
  */
7
7
  export async function bridgeLogin(inpage, creds, timing) {
8
8
  const ATTR = 'data-autologin-mcp';
9
- const scrub = (text) => text.split(creds.password).join('[REDACTED]');
9
+ let secret = 'password' in creds ? { username: creds.username, password: creds.password } : null;
10
+ const credentials = async () => (secret ??= await creds.load());
11
+ const scrub = (text) => (secret === null ? text : text.split(secret.password).join('[REDACTED]'));
12
+ // Same words as NEEDS_HUMAN_HINTS in src/login/engine.ts (this function runs in the page and cannot import).
13
+ const NEEDS_HUMAN_HINTS = {
14
+ sso: "This page signs in through single sign-on (another provider), so a human has to finish this login. autologin-mcp only fills the app's own username and password form.",
15
+ passkey: "This page asks for a passkey or security key, which needs the user's device, so a human has to finish this login.",
16
+ captcha: 'This page shows a captcha. A human has to solve it; autologin-mcp does not.',
17
+ mfa_required: 'The page now asks for a one-time code (a second factor) after the password, so a human has to enter it.',
18
+ };
10
19
  const finish = (status, extra = {}) => ({ status, url: location.href, ...extra });
11
20
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
21
  let leaving = false;
@@ -17,13 +26,82 @@ export async function bridgeLogin(inpage, creds, timing) {
17
26
  };
18
27
  try {
19
28
  const startedAt = Date.now();
29
+ // Same rules as the CDP engine (identifierSettleMs): an identifier step with a Next button counts once it
30
+ // has stayed for the settle time; with a Log in / Sign in button, only after the whole detect time.
31
+ const NAVIGATED_HINT = 'Only the username was sent: the page navigated after the username step. Call login again on the next page; if it asks for single sign-on, a passkey or a code, a human has to finish.';
32
+ const settleMs = Math.min(timing.detectTimeoutMs, Math.max(4 * timing.pollMs, timing.detectTimeoutMs / 2));
33
+ let identifierSince = null;
20
34
  let detected = inpage('detect', { selectors: creds.selectors });
21
- while (!detected.found && !detected.error && Date.now() - startedAt < timing.detectTimeoutMs) {
35
+ for (;;) {
36
+ if (detected.found || detected.error)
37
+ break;
38
+ const now = Date.now();
39
+ if (detected.step === 'identifier') {
40
+ identifierSince ??= now;
41
+ if (detected.nextButton && now - identifierSince >= settleMs)
42
+ break;
43
+ }
44
+ else {
45
+ identifierSince = null;
46
+ }
47
+ if (now - startedAt >= timing.detectTimeoutMs)
48
+ break;
22
49
  await sleep(timing.pollMs);
23
50
  detected = inpage('detect', { selectors: creds.selectors });
24
51
  }
25
- if (!detected.found)
26
- return finish('no_login_form', { hint: detected.error ?? 'No visible password field was found on the page.' });
52
+ if (!detected.found) {
53
+ if (detected.step !== 'identifier' || !detected.hasUsername) {
54
+ if (detected.blocker)
55
+ return finish('needs_human', { reason: detected.blocker, hint: NEEDS_HUMAN_HINTS[detected.blocker] });
56
+ return finish('no_login_form', { hint: detected.error ?? 'No visible password field was found on the page.' });
57
+ }
58
+ // Identifier-first login: send the username, then wait for the password step.
59
+ // A message already on the page (say "Your session has expired") is not an answer to the username.
60
+ const beforeStep = inpage('state', { successSelector: creds.successSelector });
61
+ const { username } = await credentials();
62
+ // The page may have re-rendered while the credentials were on their way: tag the step again.
63
+ inpage('detect', { selectors: creds.selectors });
64
+ const stepField = document.querySelector(`[${ATTR}="username"]`);
65
+ if (stepField === null)
66
+ return finish('no_login_form', { hint: 'The username step went away while the credentials were on their way; nothing was typed.' });
67
+ window.addEventListener('beforeunload', onLeave, { once: true });
68
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(stepField, username);
69
+ stepField.dispatchEvent(new Event('input', { bubbles: true }));
70
+ stepField.dispatchEvent(new Event('change', { bubbles: true }));
71
+ if (inpage('submit', {}) === 'none') {
72
+ for (const type of ['keydown', 'keypress', 'keyup']) {
73
+ stepField.dispatchEvent(new KeyboardEvent(type, { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }));
74
+ }
75
+ }
76
+ const stepStart = Date.now();
77
+ let next = inpage('detect', { selectors: creds.selectors });
78
+ while (!next.found) {
79
+ if (leaving)
80
+ return finish('submitted', { reason: 'username_step_navigated', hint: NAVIGATED_HINT });
81
+ const current = inpage('state', { successSelector: creds.successSelector });
82
+ const newError = current.errorText !== null && current.errorText !== beforeStep.errorText;
83
+ if (newError && Date.now() - stepStart >= timing.earlyFailAfterMs)
84
+ return finish('failed', { reason: 'identifier_rejected', hint: scrub(current.errorText) });
85
+ if (Date.now() - stepStart >= timing.detectTimeoutMs) {
86
+ // No password was sent, so this is not a failed login (and does not count toward the rate limit).
87
+ return finish('needs_human', {
88
+ reason: 'password_step_timeout',
89
+ hint: 'The page did not ask for a password after the username step. It may use single sign-on, a passkey or a second factor, so a human has to finish this login.',
90
+ });
91
+ }
92
+ await new Promise((resolve) => {
93
+ const timer = setTimeout(resolve, timing.pollMs);
94
+ wake = () => {
95
+ clearTimeout(timer);
96
+ resolve();
97
+ };
98
+ });
99
+ if (leaving)
100
+ return finish('submitted', { reason: 'username_step_navigated', hint: NAVIGATED_HINT });
101
+ next = inpage('detect', { selectors: creds.selectors });
102
+ }
103
+ detected = next;
104
+ }
27
105
  const before = inpage('state', { successSelector: creds.successSelector });
28
106
  const fill = (role, value) => {
29
107
  const field = document.querySelector(`[${ATTR}="${role}"]`);
@@ -33,9 +111,15 @@ export async function bridgeLogin(inpage, creds, timing) {
33
111
  field.dispatchEvent(new Event('input', { bubbles: true }));
34
112
  field.dispatchEvent(new Event('change', { bubbles: true }));
35
113
  };
114
+ const { username, password } = await credentials();
115
+ // The page may have re-rendered while the credentials were on their way: tag the form again.
116
+ const again = inpage('detect', { selectors: creds.selectors });
117
+ if (!again.found)
118
+ return finish('no_login_form', { hint: 'The login form went away while the credentials were on their way; nothing was typed.' });
119
+ detected = again;
36
120
  if (detected.hasUsername)
37
- fill('username', creds.username);
38
- fill('password', creds.password);
121
+ fill('username', username);
122
+ fill('password', password);
39
123
  window.addEventListener('beforeunload', onLeave, { once: true });
40
124
  if (inpage('submit', {}) === 'none') {
41
125
  const field = document.querySelector(`[${ATTR}="password"]`);
@@ -61,6 +145,8 @@ export async function bridgeLogin(inpage, creds, timing) {
61
145
  last = current;
62
146
  if (current.success)
63
147
  return finish('success');
148
+ if (current.codeVisible && !current.passwordVisible)
149
+ return finish('needs_human', { reason: 'mfa_required', hint: NEEDS_HUMAN_HINTS.mfa_required });
64
150
  if (!current.passwordVisible) {
65
151
  goneStreak += 1;
66
152
  if (goneStreak >= 2)
@@ -95,7 +181,7 @@ export const REUSED_NOTE = 'This one-time script already ran; this is the outcom
95
181
  * A re-run of a used script gets the first run's outcome instead of credentials.
96
182
  * `noForm` is merged into a `no_login_form` outcome, typically "the previous login already went through".
97
183
  */
98
- export function fillerScript(base, token, timing, noForm = null) {
184
+ export function fillerScript(base, token, timing, noForm = null, hints = { selectors: {} }) {
99
185
  return [
100
186
  '(() => {',
101
187
  `const inpage = ${autologinInpage.toString()};`,
@@ -106,8 +192,16 @@ export function fillerScript(base, token, timing, noForm = null) {
106
192
  "const explain = (result) => (noForm !== null && result.status === 'no_login_form' ? Object.assign({}, result, noForm) : result);",
107
193
  "const done = (detail) => window.dispatchEvent(new CustomEvent('autologin-mcp:' + token, { detail }));",
108
194
  "const report = (result) => { fetch(base + '/v1/result/' + token, { method: 'POST', body: JSON.stringify(result), keepalive: true }).catch(() => {}); return result; };",
109
- "fetch(base + '/v1/credentials/' + token, { method: 'POST' })",
110
- ` .then(async (res) => { const body = await res.json(); if (res.ok) return report(explain(await login(inpage, body, ${JSON.stringify(timing)}))); return body.result ? Object.assign({}, body.result, { note: ${JSON.stringify(REUSED_NOTE)} }) : body; })`,
195
+ // The credentials are fetched only when the page is about to type them (see LazyBridgeCredentials).
196
+ 'let refused = null;',
197
+ "const load = () => fetch(base + '/v1/credentials/' + token, { method: 'POST' }).then(async (res) => {",
198
+ ' const body = await res.json();',
199
+ ' if (res.ok) return { username: body.username, password: body.password };',
200
+ ` refused = body.result ? Object.assign({}, body.result, { note: ${JSON.stringify(REUSED_NOTE)} }) : body;`,
201
+ " throw new Error(refused.hint || refused.status || 'credentials refused');",
202
+ '});',
203
+ `login(inpage, Object.assign(${JSON.stringify(hints)}, { load }), ${JSON.stringify(timing)})`,
204
+ ' .then((result) => (refused !== null ? refused : report(explain(result))))',
111
205
  " .then(done, (error) => done({ status: 'error', url: location.href, hint: 'autologin-mcp bridge: ' + (error && error.message ? error.message : String(error)) }));",
112
206
  '})();',
113
207
  ].join('\n');
@@ -2,8 +2,9 @@ import { randomBytes } from 'node:crypto';
2
2
  import http from 'node:http';
3
3
  import { FailureLimiter } from '../ratelimit.js';
4
4
  import { matchesUrl } from '../store/match.js';
5
- import { agentExpression, agentFunction, agentScript, fillerScript } from './filler.js';
5
+ import { agentExpression, agentFunction, agentScript, fillerScript, REUSED_NOTE } from './filler.js';
6
6
  export const BRIDGE_TIMING = { detectTimeoutMs: 5_000, verifyTimeoutMs: 10_000, pollMs: 250, earlyFailAfterMs: 1_500 };
7
+ const REUSED_UNKNOWN = { status: 'expired', hint: 'This login script was already used and its outcome is unknown; call login_status, or login again.' };
7
8
  const TOKEN_PATH = /^\/v1\/(filler|credentials|result)\/([A-Za-z0-9_-]{16,})(?:\.js)?$/;
8
9
  const MAX_BODY = 8_192;
9
10
  async function readBody(req) {
@@ -33,7 +34,7 @@ export class BridgeServer {
33
34
  this.ttlMs = options.ttlMs ?? 60_000;
34
35
  this.timing = options.timing ?? BRIDGE_TIMING;
35
36
  this.now = options.now ?? Date.now;
36
- this.reuseWaitMs = options.reuseWaitMs ?? 15_000;
37
+ this.reuseWaitMs = options.reuseWaitMs ?? 25_000;
37
38
  this.releases = new FailureLimiter(options.maxReleases ?? 20, 5 * 60_000, this.now);
38
39
  }
39
40
  /** The first run's result, waiting for it (up to reuseWaitMs) when it is still in progress. */
@@ -63,7 +64,7 @@ export class BridgeServer {
63
64
  if (ticket.expiresAt <= now)
64
65
  this.tickets.delete(token);
65
66
  const token = randomBytes(24).toString('base64url');
66
- this.tickets.set(token, { profile, expiresAt: now + this.ttlMs, released: false, result: null, waiters: [] });
67
+ this.tickets.set(token, { profile, expiresAt: now + this.ttlMs, started: false, released: false, result: null, waiters: [] });
67
68
  const fn = agentFunction(base, token);
68
69
  return { profile: profile.name, expiresInSeconds: Math.round(this.ttlMs / 1000), function: fn, script: agentScript(fn), expression: agentExpression(fn) };
69
70
  }
@@ -100,9 +101,20 @@ export class BridgeServer {
100
101
  hint: `This page (${origin ?? 'unknown origin'}) is not part of profile "${profile.name}" (${profile.url}); nothing was filled.`,
101
102
  };
102
103
  if (kind === 'filler') {
103
- const script = allowed
104
- ? fillerScript(base, token, this.timing, this.options.noFormContext?.(profile.name) ?? null)
105
- : `window.dispatchEvent(new CustomEvent(${JSON.stringify(`autologin-mcp:${token}`)}, { detail: ${JSON.stringify(mismatch)} }));`;
104
+ const answer = (detail) => `window.dispatchEvent(new CustomEvent(${JSON.stringify(`autologin-mcp:${token}`)}, { detail: ${JSON.stringify(detail)} }));`;
105
+ if (!allowed)
106
+ return send(200, answer(mismatch), 'text/javascript');
107
+ // One run per script, also when the first run found no form and never asked for the credentials:
108
+ // a re-run (a browser tool retrying after losing the tab) only gets the first run's outcome.
109
+ if (ticket.started) {
110
+ const first = await this.firstRunResult(ticket);
111
+ return send(200, answer(first === null ? REUSED_UNKNOWN : { ...first, note: REUSED_NOTE }), 'text/javascript');
112
+ }
113
+ ticket.started = true;
114
+ const script = fillerScript(base, token, this.timing, this.options.noFormContext?.(profile.name) ?? null, {
115
+ selectors: { username: profile.selectors.username, password: profile.selectors.password, submit: profile.selectors.submit },
116
+ successSelector: profile.selectors.success,
117
+ });
106
118
  return send(200, script, 'text/javascript');
107
119
  }
108
120
  if (req.method !== 'POST')
@@ -113,9 +125,7 @@ export class BridgeServer {
113
125
  if (ticket.released) {
114
126
  // A browser tool may re-run the script (e.g. after losing the tab mid-call): answer with the first run's outcome.
115
127
  const first = await this.firstRunResult(ticket);
116
- return first === null
117
- ? send(410, { status: 'expired', hint: 'This login script was already used and its outcome is unknown; call login_status, or login again.' })
118
- : send(409, { status: 'already_used', result: first });
128
+ return first === null ? send(410, REUSED_UNKNOWN) : send(409, { status: 'already_used', result: first });
119
129
  }
120
130
  if (this.releases.isBlocked(profile.name)) {
121
131
  return send(429, { status: 'rate_limited', hint: 'Too many logins for this profile in the last 5 minutes.' });
package/dist/inpage.js CHANGED
@@ -6,6 +6,14 @@ export const FIELD_ATTR = 'data-autologin-mcp';
6
6
  export function autologinInpage(action, arg) {
7
7
  const ATTR = 'data-autologin-mcp';
8
8
  const SUBMIT_TEXT = /^(log ?-?in|sign ?-?in|login|signin|submit|continue|giri[sş]( yap)?|oturum a[cç]|anmelden|connexion|entrar|iniciar sesi[oó]n)$/i;
9
+ // The button that moves an identifier-first page to its password step: Next / Continue, or a
10
+ // Log in / Sign in button (which may also belong to a one-page form still rendering its password field).
11
+ // "Submit" is deliberately absent: a comment or contact form has a username field and a Submit
12
+ // button, and typing a login there is worse than reporting that no login form was found.
13
+ const NEXT_TEXT = /^(continue|next|weiter|suivant|siguiente|continuar|devam( et)?|ileri)$/i;
14
+ const IDENTIFIER_TEXT = /^(log ?-?in|sign ?-?in|login|signin|giri[sş]( yap)?|oturum a[cç]|anmelden|connexion|entrar|iniciar sesi[oó]n)$/i;
15
+ // Field names and ids of login identifiers (Google, Microsoft "loginfmt", Okta "identifier", most in-house forms).
16
+ const LOGIN_FIELD = /^(user(_?name|_?id)?|login(_?(id|name))?|loginfmt|identifier|e-?mail|mail|email_?address|account(_?name)?)$/i;
9
17
  // Most specific first. Labels and field wrappers (e.g. MUI's red "Password *" label) are skipped below.
10
18
  const ERROR_SELECTORS = [
11
19
  '[role="alert"]',
@@ -40,6 +48,8 @@ export function autologinInpage(action, arg) {
40
48
  const tagged = (role) => document.querySelector(`[${ATTR}="${role}"]`);
41
49
  const precedes = (a, b) => (a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING) !== 0;
42
50
  const text = (el) => el.textContent.replace(/\s+/g, ' ').trim();
51
+ /** What a button says: an input's value, or an element's text. */
52
+ const label = (el) => (el instanceof HTMLInputElement ? el.value.trim() : text(el));
43
53
  if (action === 'state') {
44
54
  const findError = () => {
45
55
  // 1. The message an invalid field points to (aria-errormessage / aria-describedby).
@@ -62,11 +72,19 @@ export function autologinInpage(action, arg) {
62
72
  return null;
63
73
  };
64
74
  const errorText = findError();
75
+ // A field for a one-time code (an authenticator app, SMS or email code): a second factor.
76
+ // Only clear names: a bare "code" or "securityCode" is as likely a promo code or a card's CVV after login.
77
+ // The last part of a name counts: Devise's user[otp_attempt], django-two-factor's token-otp_token.
78
+ const CODE_FIELD = /(^|[[-])(otp|totp|one[-_]?time[-_]?(code|password)|verification[-_]?code|(otp|totp|mfa|2fa|two[-_]?factor)[-_]?(code|token|attempt))\]?$/i;
79
+ const codeVisible = Array.from(document.querySelectorAll('input')).some((el) => usable(el) &&
80
+ el.type !== 'password' &&
81
+ ((el.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/).includes('one-time-code') || [el.name, el.id].some((word) => CODE_FIELD.test(word))));
65
82
  return {
66
83
  ready: document.readyState !== 'loading',
67
84
  passwordVisible: Array.from(document.querySelectorAll('input[type="password"]')).some(visible),
68
85
  success: visible(find(arg.successSelector)),
69
86
  errorText: errorText === null ? null : errorText.slice(0, 200),
87
+ ...(codeVisible ? { codeVisible: true } : {}),
70
88
  };
71
89
  }
72
90
  if (action === 'clear') {
@@ -84,7 +102,7 @@ export function autologinInpage(action, arg) {
84
102
  button.click();
85
103
  return 'clicked';
86
104
  }
87
- const form = tagged('password')?.form;
105
+ const form = (tagged('password') ?? tagged('username'))?.form;
88
106
  if (form) {
89
107
  form.requestSubmit();
90
108
  return 'submitted';
@@ -109,8 +127,81 @@ export function autologinInpage(action, arg) {
109
127
  }
110
128
  else {
111
129
  const el = Array.from(document.querySelectorAll('input[type="password"]')).find(usable);
112
- if (!el)
113
- return { found: false, hasUsername: false, hasSubmit: false };
130
+ if (!el) {
131
+ // Identifier-first login: a username step before the password one. Only the heuristic path
132
+ // does this: an explicit password selector means the caller expects that field to exist.
133
+ const textLike = (el) => usable(el) && ['text', 'email', 'tel'].includes(el.type);
134
+ // A login identifier says so: autocomplete="username", or a name / id that is exactly a login word.
135
+ // `type="email"` alone is not enough: invite, share and newsletter fields are email fields too.
136
+ const loginField = (el) => (el.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/).includes('username') ||
137
+ [el.name, el.id].some((word) => LOGIN_FIELD.test(word));
138
+ // Controls a person types into or picks from. Hidden fields, checkboxes and buttons do not count.
139
+ const NOT_TYPED = ['hidden', 'checkbox', 'radio', 'submit', 'button', 'image', 'reset'];
140
+ const typedControls = (controls) => controls.filter((el) => (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) &&
141
+ visible(el) &&
142
+ !el.disabled &&
143
+ !(el instanceof HTMLInputElement && NOT_TYPED.includes(el.type))).length;
144
+ const BUTTONS = 'button, [role="button"], input[type="button"], input[type="submit"]';
145
+ // A button after the field that means "continue", and not, say, "Subscribe" or "Invite".
146
+ const continueButton = (buttons, field) => buttons.find((el) => visible(el) && !el.disabled && precedes(field, el) && (NEXT_TEXT.test(label(el)) || IDENTIFIER_TEXT.test(label(el)))) ?? null;
147
+ // A username step is a form, or a small container, whose only typed field is the username: not a signup,
148
+ // checkout or invite form with more fields, and never a button far away (a header "Sign in" next to a
149
+ // footer newsletter field).
150
+ const buttonFor = (field) => {
151
+ if (selectors.submit)
152
+ return find(selectors.submit);
153
+ const form = field.form;
154
+ if (form !== null) {
155
+ // form.elements also holds controls outside the element that point at it with form="…".
156
+ if (typedControls(Array.from(form.elements)) !== 1)
157
+ return null;
158
+ return continueButton([...Array.from(form.querySelectorAll(BUTTONS)), ...Array.from(form.elements)], field);
159
+ }
160
+ let node = field.parentElement;
161
+ for (let depth = 0; depth < 3 && node !== null && node !== document.documentElement; depth += 1, node = node.parentElement) {
162
+ if (typedControls(Array.from(node.querySelectorAll('input, textarea, select'))) !== 1)
163
+ return null;
164
+ const button = continueButton(Array.from(node.querySelectorAll(BUTTONS)), field);
165
+ if (button !== null)
166
+ return button;
167
+ }
168
+ return null;
169
+ };
170
+ const candidates = selectors.username
171
+ ? [find(selectors.username)].filter(textLike)
172
+ : Array.from(document.querySelectorAll('input')).filter((el) => textLike(el) && loginField(el));
173
+ for (const field of candidates) {
174
+ const button = buttonFor(field);
175
+ if (!visible(button))
176
+ continue;
177
+ field.setAttribute(ATTR, 'username');
178
+ button.setAttribute(ATTR, 'submit');
179
+ return { found: false, hasUsername: true, hasSubmit: true, step: 'identifier', nextButton: NEXT_TEXT.test(label(button)) };
180
+ }
181
+ // No form to fill. Does the page want something only a person can do? Only checked here, without a
182
+ // password field or a username step: SSO buttons, passkeys and invisible captchas sit on many normal
183
+ // login pages and block nothing there.
184
+ const CAPTCHA_FRAME = /\/recaptcha\/(api2|enterprise)\/(anchor|bframe)|hcaptcha\.com\/captcha|challenges\.cloudflare\.com/i;
185
+ const SSO_TEXT = /^((sign|log) ?in|login|continue|sign up) (with|using|via) (google|microsoft|apple|github|gitlab|okta|azure( ad)?|facebook|linkedin|slack|saml|sso|single sign-on|your (company|organi[sz]ation)( account)?)$|^(single sign-on|sso|use sso|enterprise sso)$|^(google|microsoft|apple|github|sso) ile (giri[sş] yap|oturum a[cç]|devam et)$/i;
186
+ // Sign-in actions only: "Add a passkey" in a logged-in app's settings is not a login.
187
+ const PASSKEY_TEXT = /^((sign|log) ?in|login|continue) with (a |your )?(passkey|security key|face id|touch id|windows hello)$|^use (a |your )?(passkey|security key|face id|touch id|windows hello)$|^(ge[cç]i[sş] anahtar[ıi]|passkey) ile (giri[sş] yap|oturum a[cç])$/i;
188
+ // A page that also offers email, a username or a password still leads to a form: open it and log in again.
189
+ const FORM_PATH = /^((sign|log) ?in|login|continue|sign up) with (email|e-mail|username|(a |your )?password)$|^use (a |your )?(password|email|username)( instead)?$|^(e-?posta|şifre|parola) ile/i;
190
+ const captcha = Array.from(document.querySelectorAll('iframe')).some((frame) => visible(frame) && CAPTCHA_FRAME.test(frame.src) && !/[?&]size=invisible/.test(frame.src)) ||
191
+ visible(document.querySelector('#challenge-form, #challenge-stage, #cf-challenge-running'));
192
+ const actions = Array.from(document.querySelectorAll(`${BUTTONS}, a`)).filter(visible).map(label);
193
+ const formPath = actions.some((t) => FORM_PATH.test(t));
194
+ const blocker = captcha
195
+ ? 'captcha'
196
+ : formPath
197
+ ? null
198
+ : actions.some((t) => SSO_TEXT.test(t))
199
+ ? 'sso'
200
+ : actions.some((t) => PASSKEY_TEXT.test(t))
201
+ ? 'passkey'
202
+ : null;
203
+ return blocker === null ? { found: false, hasUsername: false, hasSubmit: false } : { found: false, hasUsername: false, hasSubmit: false, blocker };
204
+ }
114
205
  password = el;
115
206
  }
116
207
  let username = null;
@@ -1,5 +1,19 @@
1
1
  import { FIELD_ATTR } from '../inpage.js';
2
+ import { hostOf, matchesUrl } from '../store/match.js';
2
3
  export const DEFAULT_TIMING = { detectTimeoutMs: 5_000, verifyTimeoutMs: 10_000, pollMs: 250, earlyFailAfterMs: 1_500 };
4
+ /**
5
+ * How long an identifier step with a Next / Continue button must stay before the username is sent alone:
6
+ * half the detect time (2.5 s by default), so a one-page form whose password field renders late is not split.
7
+ */
8
+ export const identifierSettleMs = (timing) => Math.min(timing.detectTimeoutMs, Math.max(4 * timing.pollMs, timing.detectTimeoutMs / 2));
9
+ /** Hints for `needs_human`; bridge mode (src/bridge/filler.ts) carries the same words. */
10
+ export const NEEDS_HUMAN_HINTS = {
11
+ sso: 'This page signs in through single sign-on (another provider), so a human has to finish this login. autologin-mcp only fills the app\'s own username and password form.',
12
+ passkey: 'This page asks for a passkey or security key, which needs the user\'s device, so a human has to finish this login.',
13
+ captcha: 'This page shows a captcha. A human has to solve it; autologin-mcp does not.',
14
+ mfa_required: 'The page now asks for a one-time code (a second factor) after the password, so a human has to enter it.',
15
+ };
16
+ export const PASSWORD_STEP_HINT = 'The page did not ask for a password after the username step. It may use single sign-on, a passkey or a second factor, so a human has to finish this login.';
3
17
  export const realClock = {
4
18
  now: () => Date.now(),
5
19
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
@@ -13,14 +27,24 @@ async function attempt(fn) {
13
27
  return null;
14
28
  }
15
29
  }
16
- async function typeInto(page, role, value) {
30
+ /** Types into a tagged field; `beforeInsert` runs between focusing it and typing (the site check). */
31
+ async function typeInto(page, role, value, beforeInsert) {
17
32
  await page.run('clear', { role });
18
33
  const field = await page.element(selectorFor(role));
19
34
  if (field === null)
20
35
  throw new Error(`The ${role} field disappeared before it could be filled.`);
21
36
  await field.focus();
37
+ beforeInsert();
22
38
  await page.insertText(value);
23
39
  }
40
+ /** Thrown when the tab left the profile's site right before something would be typed. */
41
+ class LeftSiteError extends Error {
42
+ result;
43
+ constructor(result) {
44
+ super(result.hint);
45
+ this.result = result;
46
+ }
47
+ }
24
48
  async function submitForm(page, hasSubmit) {
25
49
  if (hasSubmit) {
26
50
  try {
@@ -41,24 +65,94 @@ async function submitForm(page, hasSubmit) {
41
65
  */
42
66
  export async function performLogin(page, profile, timing = DEFAULT_TIMING, clock = realClock) {
43
67
  const base = { profile: profile.name };
68
+ // The tab can leave the profile's site while we wait (a redirect, or the username step sending it to a
69
+ // single sign-on host). Nothing is typed into a page of another site: the site is checked before each
70
+ // step and again right between focusing a field and typing into it.
71
+ const leftSite = () => {
72
+ const url = page.url();
73
+ if (matchesUrl(profile.root, url))
74
+ return null;
75
+ return {
76
+ status: 'needs_human',
77
+ ...base,
78
+ url,
79
+ reason: 'left_profile_site',
80
+ hint: `The login moved to ${hostOf(url)}, which is not part of profile "${profile.name}" (${profile.url}), so nothing was typed there. ` +
81
+ 'If it is single sign-on, a human has to finish this login. If that site belongs to the app, give the profile a root URL that covers it (for example *.example.com).',
82
+ };
83
+ };
84
+ const onSite = () => {
85
+ const away = leftSite();
86
+ if (away !== null)
87
+ throw new LeftSiteError(away);
88
+ };
44
89
  const detect = () => attempt(() => page.run('detect', { selectors: profile.selectors }));
45
90
  const state = () => attempt(() => page.run('state', { successSelector: profile.selectors.success }));
46
91
  const clearPassword = () => attempt(() => page.run('clear', { role: 'password' }));
47
92
  try {
48
93
  const detectStart = clock.now();
94
+ const settleMs = identifierSettleMs(timing);
95
+ let identifierSince = null;
49
96
  let detected = await detect();
50
- while (!detected?.found && !detected?.error && clock.now() - detectStart < timing.detectTimeoutMs) {
97
+ // Wait for a password field. An identifier step (username + Next) counts only once it has stayed for
98
+ // the settle time; with a Log in / Sign in button, only after the whole detect time, since a one-page
99
+ // form may still be rendering its password field.
100
+ for (;;) {
101
+ if (detected?.found || detected?.error)
102
+ break;
103
+ const now = clock.now();
104
+ if (detected?.step === 'identifier') {
105
+ identifierSince ??= now;
106
+ if (detected.nextButton && now - identifierSince >= settleMs)
107
+ break;
108
+ }
109
+ else {
110
+ identifierSince = null;
111
+ }
112
+ if (now - detectStart >= timing.detectTimeoutMs)
113
+ break;
51
114
  await clock.sleep(timing.pollMs);
52
115
  detected = await detect();
53
116
  }
54
117
  if (!detected?.found) {
55
- return { status: 'no_login_form', ...base, url: page.url(), hint: detected?.error ?? 'No visible password field was found on the page.' };
118
+ if (detected?.step !== 'identifier' || !detected.hasUsername) {
119
+ if (detected?.blocker)
120
+ return { status: 'needs_human', ...base, url: page.url(), reason: detected.blocker, hint: NEEDS_HUMAN_HINTS[detected.blocker] };
121
+ return { status: 'no_login_form', ...base, url: page.url(), hint: detected?.error ?? 'No visible password field was found on the page.' };
122
+ }
123
+ // Identifier-first login: send the username, then wait for the page to ask for the password.
124
+ // A message already on the page (say "Your session has expired") is not an answer to the username.
125
+ onSite();
126
+ const beforeStep = await state();
127
+ await page.bringToFront().catch(() => undefined);
128
+ await typeInto(page, 'username', profile.username, onSite);
129
+ await submitForm(page, detected.hasSubmit);
130
+ const stepStart = clock.now();
131
+ let next = await detect();
132
+ while (!next?.found) {
133
+ onSite(); // a message on a single sign-on host is not a rejection of the username
134
+ const current = await state();
135
+ const newError = current?.errorText != null && current.errorText !== beforeStep?.errorText;
136
+ if (newError && clock.now() - stepStart >= timing.earlyFailAfterMs) {
137
+ return { status: 'failed', ...base, url: page.url(), reason: 'identifier_rejected', hint: current.errorText };
138
+ }
139
+ if (clock.now() - stepStart >= timing.detectTimeoutMs)
140
+ break;
141
+ await clock.sleep(timing.pollMs);
142
+ next = await detect();
143
+ }
144
+ if (!next?.found) {
145
+ // No password was sent, so this is not a failed login (and does not count toward the rate limit).
146
+ return { status: 'needs_human', ...base, url: page.url(), reason: 'password_step_timeout', hint: PASSWORD_STEP_HINT };
147
+ }
148
+ detected = next;
56
149
  }
150
+ onSite();
57
151
  const before = await state();
58
152
  await page.bringToFront().catch(() => undefined);
59
153
  if (detected.hasUsername)
60
- await typeInto(page, 'username', profile.username);
61
- await typeInto(page, 'password', profile.password);
154
+ await typeInto(page, 'username', profile.username, onSite);
155
+ await typeInto(page, 'password', profile.password, onSite);
62
156
  await submitForm(page, detected.hasSubmit);
63
157
  const submittedAt = clock.now();
64
158
  let goneStreak = 0;
@@ -70,6 +164,9 @@ export async function performLogin(page, profile, timing = DEFAULT_TIMING, clock
70
164
  last = current;
71
165
  if (current.success)
72
166
  return { status: 'success', ...base, url: page.url() };
167
+ if (current.codeVisible && !current.passwordVisible) {
168
+ return { status: 'needs_human', ...base, url: page.url(), reason: 'mfa_required', hint: NEEDS_HUMAN_HINTS.mfa_required };
169
+ }
73
170
  if (!current.passwordVisible) {
74
171
  goneStreak += 1;
75
172
  if (goneStreak >= 2)
@@ -95,6 +192,8 @@ export async function performLogin(page, profile, timing = DEFAULT_TIMING, clock
95
192
  };
96
193
  }
97
194
  catch (error) {
195
+ if (error instanceof LeftSiteError)
196
+ return error.result;
98
197
  await clearPassword();
99
198
  return { status: 'error', ...base, url: page.url(), hint: error instanceof Error ? error.message : String(error) };
100
199
  }
package/dist/results.js CHANGED
@@ -1,6 +1,12 @@
1
1
  /** How long a login outcome counts as "previous" for a later `no_login_form`. */
2
2
  export const RECENT_MS = 5 * 60_000;
3
3
  const WENT_THROUGH = new Set(['success', 'submitted']);
4
+ /**
5
+ * Bridge mode: the page navigated right after the username step of an identifier-first login. That is
6
+ * `submitted`, but not a login that went through: only the username was sent.
7
+ */
8
+ export const USERNAME_STEP_NAVIGATED = 'username_step_navigated';
9
+ const wentThrough = (login) => WENT_THROUGH.has(login.status) && login.reason !== USERNAME_STEP_NAVIGATED;
4
10
  export function alreadyLoggedInHint(previous) {
5
11
  return (`No login form on this page, and the previous login for this profile (${previous.status} at ${previous.at}) went through: ` +
6
12
  'the tab is most likely already logged in. Look at the page and continue; call login again only if it shows a login form.');
@@ -20,13 +26,23 @@ export class ResultLog {
20
26
  * `no_login_form`) when it is recent. An agent whose result was cut off often just logs in again.
21
27
  */
22
28
  noFormContext(profile) {
29
+ const previous = this.recent(profile);
30
+ if (previous === null)
31
+ return null;
32
+ return wentThrough(previous) ? { previous_login: previous, hint: alreadyLoggedInHint(previous) } : { previous_login: previous };
33
+ }
34
+ /** The profile's latest real login outcome (not an earlier `no_login_form`) when it is recent. */
35
+ recent(profile) {
23
36
  const latest = this.latest.get(profile);
24
37
  const previous = latest?.status === 'no_login_form'
25
38
  ? latest.previous_login
26
- : latest && { status: latest.status, at: latest.at, ...(latest.url === undefined ? {} : { url: latest.url }) };
27
- if (previous === undefined || this.now() - Date.parse(previous.at) > RECENT_MS)
28
- return null;
29
- return WENT_THROUGH.has(previous.status) ? { previous_login: previous, hint: alreadyLoggedInHint(previous) } : { previous_login: previous };
39
+ : latest && {
40
+ status: latest.status,
41
+ at: latest.at,
42
+ ...(latest.url === undefined ? {} : { url: latest.url }),
43
+ ...(latest.reason === undefined ? {} : { reason: latest.reason }),
44
+ };
45
+ return previous === undefined || this.now() - Date.parse(previous.at) > RECENT_MS ? null : previous;
30
46
  }
31
47
  record(profile, result, via) {
32
48
  const context = result.status === 'no_login_form' ? this.noFormContext(profile) : null;
@@ -34,6 +50,7 @@ export class ResultLog {
34
50
  const entry = {
35
51
  profile,
36
52
  status: result.status,
53
+ ...(result.reason === undefined ? {} : { reason: result.reason }),
37
54
  ...(hint === undefined ? {} : { hint }),
38
55
  ...(result.url === undefined ? {} : { url: result.url }),
39
56
  ...(context === null ? {} : { previous_login: context.previous_login }),
package/dist/server.js CHANGED
@@ -4,6 +4,7 @@ import { selectTarget } from './browser/tabs.js';
4
4
  import { createRedactor } from './redact.js';
5
5
  import { hostOf, matchesUrl } from './store/match.js';
6
6
  import { isUsable } from './store/profiles.js';
7
+ import { ssoProvider } from './sso.js';
7
8
  export const ADD_HINT = 'Ask the user to run "npx autologin-mcp add" in a separate terminal (never in this chat), or call open_config so they can edit the credentials file.';
8
9
  export const RUN_IN_PAGE_HINT = 'Run `script` unchanged in the tab that shows the login form, with your browser tool\'s JavaScript evaluation (Claude in Chrome: javascript_tool). ' +
9
10
  'Tools that take a function (Playwright MCP browser_evaluate, chrome-devtools-mcp evaluate_script) take `function` instead; ' +
@@ -14,6 +15,7 @@ export const INSTRUCTIONS = [
14
15
  "autologin-mcp signs the browser tab you are testing into its app with credentials that stay on the user's machine; you never see them.",
15
16
  '- When a page under test shows a login form, a "session expired" message, a 401/403, or redirects to a login URL, call `login`, then continue the task. Pass `url` (the tab URL) and, when several accounts exist for the app, `profile`.',
16
17
  `- If \`login\` returns \`run_in_page\`: ${RUN_IN_PAGE_HINT} On \`submitted\`, check the page to confirm you are logged in.`,
18
+ '- On `needs_human`, the page wants something only a person can do (single sign-on, a passkey, a captcha or a second factor): tell the user the hint and do not retry.',
17
19
  '- `list_profiles` shows which apps (root URLs) and usernames are configured; `login_status` shows the latest login outcome per profile.',
18
20
  '- Never ask the user for a password, never type credentials into a page yourself, never read files under ~/.autologin-mcp, never modify the login script, and do not inspect the login request body in network logs or read password field values.',
19
21
  `- If no profile matches: ${ADD_HINT}`,
@@ -103,6 +105,16 @@ export async function runLogin(deps, store, args) {
103
105
  const usable = store.profiles.filter(isUsable);
104
106
  if (usable.length === 0)
105
107
  return { status: 'no_profile', hint: `No usable profile is configured. ${ADD_HINT}` };
108
+ // A tab on a single sign-on provider is not a profile's site, but "add a profile" would be the wrong advice.
109
+ const provider = args.url === undefined || usable.some((p) => matchesUrl(p.root, args.url)) ? null : ssoProvider(args.url);
110
+ if (provider !== null) {
111
+ return {
112
+ status: 'needs_human',
113
+ url: args.url,
114
+ reason: 'sso',
115
+ hint: `The tab is on ${provider}, a single sign-on provider, so a human has to finish this login. autologin-mcp only fills the app's own username and password form.`,
116
+ };
117
+ }
106
118
  const mode = store.settings.mode ?? 'auto';
107
119
  if (mode !== 'bridge') {
108
120
  const result = await loginViaCdp(deps, usable, args);
package/dist/sso.js ADDED
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Hosts of single sign-on providers. A tab on one of them shows a login that a person has to finish:
3
+ * autologin-mcp only fills the app's own username and password form (#2).
4
+ */
5
+ const SSO_HOSTS = [
6
+ /^accounts\.google\.com$/,
7
+ /^login\.(microsoftonline|microsoft|live)\.com$/,
8
+ /^login\.microsoftonline\.us$/,
9
+ /\.b2clogin\.com$/,
10
+ /\.okta(preview|-emea)?\.com$/,
11
+ /\.auth0\.com$/,
12
+ /\.onelogin\.com$/,
13
+ /^appleid\.apple\.com$/,
14
+ /\.amazoncognito\.com$/,
15
+ /\.pingone\.(com|eu|asia|ca)$/,
16
+ /\.duosecurity\.com$/,
17
+ /\.jumpcloud\.com$/,
18
+ ];
19
+ /** The host of `pageUrl` when it belongs to a known single sign-on provider, else null. */
20
+ export function ssoProvider(pageUrl) {
21
+ let host;
22
+ try {
23
+ host = new URL(pageUrl).hostname;
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ return SSO_HOSTS.some((pattern) => pattern.test(host)) ? host : null;
29
+ }
package/dist/templates.js CHANGED
@@ -37,6 +37,7 @@ The \`autologin\` MCP server fills the login form for you and only tells you the
37
37
  3. \`success\`: continue the task where you left off. \`submitted\`: the page navigated; take a look to confirm you are logged in.
38
38
  4. \`failed\`: tell the user the \`hint\`; do not retry more than once.
39
39
  \`no_login_form\`: the page has no login form. If it carries \`previous_login\` with \`success\` or \`submitted\`, your earlier login went through: continue the task.
40
+ \`needs_human\`: the page wants something only a person can do (single sign-on, a passkey, a captcha, a second factor). Tell the user the \`hint\` and wait; do not retry.
40
41
  5. \`no_profile\` / \`origin_mismatch\`: ask the user to run \`npx autologin-mcp add\` in a separate terminal (never in this chat), or call \`mcp__autologin__open_config\` so they can edit the file.
41
42
  6. \`browser_not_connected\` (only with AUTOLOGIN_MODE=cdp): ask the user to enable chrome://inspect/#remote-debugging in Chrome.
42
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "autologin-mcp",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Auto-login MCP server for AI coding agents (Claude Code, Claude in Chrome, Playwright MCP, chrome-devtools-mcp). Logs your agent into the app under test; credentials stay on your machine and never reach the model.",
5
5
  "type": "module",
6
6
  "bin": {