autologin-mcp 1.0.1 → 1.2.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
@@ -62,6 +62,8 @@ npx autologin-mcp add
62
62
 
63
63
  Upgrade with `npx autologin-mcp@latest install`, remove with `npx autologin-mcp uninstall`. Step-by-step guide: [Getting started](docs/getting-started.md).
64
64
 
65
+ Another agent? `npx autologin-mcp print-config --client codex` (or `gemini`, `cursor`, `vscode`, `claude-desktop`, `hermes`) prints its configuration. See [Agents and browser tools](docs/clients.md).
66
+
65
67
  ## Features
66
68
 
67
69
  - **Logs in when the agent needs it.** The agent calls `login` when the page shows a login form, a "session expired" message, a 401/403 or a redirect to a login URL, then carries on with its task.
@@ -72,6 +74,7 @@ Upgrade with `npx autologin-mcp@latest install`, remove with `npx autologin-mcp
72
74
  - **No account lockouts.** Three failed logins in five minutes pause the profile until you check the credentials.
73
75
  - **Several accounts and apps.** One global credentials file outside your projects, with as many profiles as you need.
74
76
  - **One command to install.** `npx autologin-mcp install` registers the MCP server, the skill and the guard hook in Claude Code.
77
+ - **Other agents and CI.** `print-config` prints the setup for Codex CLI, Gemini CLI, Cursor, VS Code, Claude Desktop and Hermes Agent, and `add --password-stdin` creates profiles in scripts and CI.
75
78
 
76
79
  ## Why
77
80
 
@@ -87,7 +90,7 @@ The full documentation is in [`docs/`](docs/README.md) and on the [website](http
87
90
 
88
91
  ### How it works
89
92
 
90
- - **Bridge mode (default, zero setup).** `login` returns a one-time loader script containing only a 60-second URL on `127.0.0.1`. The agent runs it in the tab with the JavaScript tool it already has (`javascript_tool`, `browser_evaluate` or `evaluate_script`). The page then fetches the credentials from your machine, and they are released only if the page's browser-set `Origin` header belongs to the profile's site.
93
+ - **Bridge mode (default, zero setup).** `login` returns a one-time loader script containing only a 60-second URL on `127.0.0.1`. The agent runs it in the tab with the JavaScript tool it already has (`javascript_tool`, `browser_evaluate`, `evaluate_script` or Puppeteer's `page.evaluate`). The page then fetches the credentials from your machine, and they are released only if the page's browser-set `Origin` header belongs to the profile's site.
91
94
  - **CDP mode (automatic when Chrome remote debugging is on).** autologin-mcp connects to Chrome over the DevTools Protocol and fills the tab itself; the agent runs nothing.
92
95
  - The filler works with React, Vue and Angular forms, waits for the outcome, and returns `success`, `submitted`, or `failed` with the page's error message.
93
96
 
@@ -115,9 +118,9 @@ A profile only fills pages whose host matches its root URL (`example.com`, `*.ex
115
118
  | Tool | What the agent gets back |
116
119
  |---|---|
117
120
  | `list_profiles` | Profile name, root URL and username for each profile. Never passwords. |
118
- | `login({ url?, profile? })` | Bridge mode: `run_in_page` with a one-time `script`/`function` to run in the tab. CDP mode: the result directly (`success`, `submitted`, `failed`, `no_login_form`, `rate_limited`, …). |
121
+ | `login({ url?, profile? })` | Bridge mode: `run_in_page` with a one-time loader to run in the tab, as `script`, `function` or `expression` for the agent's browser tool. CDP mode: the result directly (`success`, `submitted`, `failed`, `no_login_form`, `rate_limited`, …). |
119
122
  | `login_status({ profile? })` | The latest outcome per profile, for when the agent's JavaScript call was cut off. |
120
- | `open_config` | Opens the credentials file in your editor. The content is never returned. |
123
+ | `open_config` | Opens the credentials file in your editor, or returns its path where there is no desktop. The content is never returned. |
121
124
 
122
125
  More: [MCP tools](docs/mcp-tools.md) and [CLI reference](docs/cli.md).
123
126
 
@@ -132,7 +135,8 @@ A Claude Code guard hook and deny rules block the agent from reading the credent
132
135
  | Claude Code + Claude in Chrome | Supported and tested end to end |
133
136
  | Claude Code + Playwright MCP | Supported (`browser_evaluate`, or CDP with a shared browser) |
134
137
  | Claude Code + chrome-devtools-mcp | Supported (`evaluate_script`, or CDP with a shared browser) |
135
- | Other MCP clients | The stdio server runs; installer, skill and guard hook are Claude Code only |
138
+ | Puppeteer-based browser tools | Supported (`expression` with `page.evaluate`, or CDP with a shared browser) |
139
+ | Codex CLI, Gemini CLI, Cursor, VS Code, Claude Desktop, Hermes Agent | The stdio server runs, and `print-config` prints the setup; installer, skill and guard hook are Claude Code only. Not tested yet |
136
140
 
137
141
  More: [Agents and browser tools](docs/clients.md) and [Troubleshooting](docs/troubleshooting.md).
138
142
 
@@ -148,7 +152,7 @@ No. It goes from the local credentials file straight into the page, through the
148
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.
149
153
 
150
154
  **Does it support SSO, 2FA or multi-step logins?**
151
- 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 handles 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. Logins that move to another document, iframes, SSO hosts and TOTP are on the roadmap.
152
156
 
153
157
  **Is it free?**
154
158
  Yes, MIT licensed.
@@ -158,10 +162,10 @@ More questions: [FAQ](docs/faq.md).
158
162
  ## Roadmap
159
163
 
160
164
  - [ ] Opt-in auto-login (CDP mode): watch a profile's URL and log in without the agent asking
161
- - [ ] Multi-step logins (username → next → password), iframes, SSO login hosts
165
+ - [ ] Logins that navigate between documents, iframes, SSO login hosts
162
166
  - [ ] TOTP codes
163
167
  - [ ] `doctor` and `test <profile>` commands
164
- - [ ] Installers for Codex CLI, Gemini CLI and Cursor; a Claude Code plugin
168
+ - [ ] Installers that write the config for Codex CLI, Gemini CLI and Cursor (`print-config` prints it today); a Claude Code plugin
165
169
 
166
170
  ## Development
167
171
 
@@ -17,13 +17,75 @@ export async function bridgeLogin(inpage, creds, timing) {
17
17
  };
18
18
  try {
19
19
  const startedAt = Date.now();
20
+ // Same rules as the CDP engine (identifierSettleMs): an identifier step with a Next button counts once it
21
+ // has stayed for the settle time; with a Log in / Sign in button, only after the whole detect time.
22
+ 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.';
23
+ const settleMs = Math.min(timing.detectTimeoutMs, Math.max(4 * timing.pollMs, timing.detectTimeoutMs / 2));
24
+ let identifierSince = null;
20
25
  let detected = inpage('detect', { selectors: creds.selectors });
21
- while (!detected.found && !detected.error && Date.now() - startedAt < timing.detectTimeoutMs) {
26
+ for (;;) {
27
+ if (detected.found || detected.error)
28
+ break;
29
+ const now = Date.now();
30
+ if (detected.step === 'identifier') {
31
+ identifierSince ??= now;
32
+ if (detected.nextButton && now - identifierSince >= settleMs)
33
+ break;
34
+ }
35
+ else {
36
+ identifierSince = null;
37
+ }
38
+ if (now - startedAt >= timing.detectTimeoutMs)
39
+ break;
22
40
  await sleep(timing.pollMs);
23
41
  detected = inpage('detect', { selectors: creds.selectors });
24
42
  }
25
- if (!detected.found)
26
- return finish('no_login_form', { hint: detected.error ?? 'No visible password field was found on the page.' });
43
+ if (!detected.found) {
44
+ if (detected.step !== 'identifier' || !detected.hasUsername) {
45
+ return finish('no_login_form', { hint: detected.error ?? 'No visible password field was found on the page.' });
46
+ }
47
+ // Identifier-first login: send the username, then wait for the password step.
48
+ // A message already on the page (say "Your session has expired") is not an answer to the username.
49
+ const beforeStep = inpage('state', { successSelector: creds.successSelector });
50
+ const stepField = document.querySelector(`[${ATTR}="username"]`);
51
+ window.addEventListener('beforeunload', onLeave, { once: true });
52
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(stepField, creds.username);
53
+ stepField.dispatchEvent(new Event('input', { bubbles: true }));
54
+ stepField.dispatchEvent(new Event('change', { bubbles: true }));
55
+ if (inpage('submit', {}) === 'none') {
56
+ for (const type of ['keydown', 'keypress', 'keyup']) {
57
+ stepField.dispatchEvent(new KeyboardEvent(type, { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true }));
58
+ }
59
+ }
60
+ const stepStart = Date.now();
61
+ let next = inpage('detect', { selectors: creds.selectors });
62
+ while (!next.found) {
63
+ if (leaving)
64
+ return finish('submitted', { reason: 'username_step_navigated', hint: NAVIGATED_HINT });
65
+ const current = inpage('state', { successSelector: creds.successSelector });
66
+ const newError = current.errorText !== null && current.errorText !== beforeStep.errorText;
67
+ if (newError && Date.now() - stepStart >= timing.earlyFailAfterMs)
68
+ return finish('failed', { reason: 'identifier_rejected', hint: scrub(current.errorText) });
69
+ if (Date.now() - stepStart >= timing.detectTimeoutMs) {
70
+ // No password was sent, so this is not a failed login (and does not count toward the rate limit).
71
+ return finish('needs_human', {
72
+ reason: 'password_step_timeout',
73
+ 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.',
74
+ });
75
+ }
76
+ await new Promise((resolve) => {
77
+ const timer = setTimeout(resolve, timing.pollMs);
78
+ wake = () => {
79
+ clearTimeout(timer);
80
+ resolve();
81
+ };
82
+ });
83
+ if (leaving)
84
+ return finish('submitted', { reason: 'username_step_navigated', hint: NAVIGATED_HINT });
85
+ next = inpage('detect', { selectors: creds.selectors });
86
+ }
87
+ detected = next;
88
+ }
27
89
  const before = inpage('state', { successSelector: creds.successSelector });
28
90
  const fill = (role, value) => {
29
91
  const field = document.querySelector(`[${ATTR}="${role}"]`);
@@ -128,5 +190,11 @@ export function agentFunction(base, token) {
128
190
  "s.onerror = () => done({ status: 'error', hint: 'The page blocked the autologin-mcp bridge (Content-Security-Policy?) or the MCP server stopped' }); " +
129
191
  '(document.head || document.documentElement).append(s); })');
130
192
  }
131
- /** Expression form, for REPL-style tools such as Claude in Chrome's javascript_tool. */
193
+ /** Expression form with top-level await, for REPL-style tools such as Claude in Chrome's javascript_tool. */
132
194
  export const agentScript = (fn) => `await (${fn})()`;
195
+ /**
196
+ * Expression form without top-level await: it evaluates to a Promise of the result, for tools that
197
+ * evaluate a plain script and wait for its value (Puppeteer page.evaluate, CDP Runtime.evaluate with awaitPromise).
198
+ * There, `await (...)()` fails with "await is not defined".
199
+ */
200
+ export const agentExpression = (fn) => `(${fn})()`;
@@ -2,7 +2,7 @@ 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 { agentFunction, agentScript, fillerScript } from './filler.js';
5
+ import { agentExpression, agentFunction, agentScript, fillerScript } from './filler.js';
6
6
  export const BRIDGE_TIMING = { detectTimeoutMs: 5_000, verifyTimeoutMs: 10_000, pollMs: 250, earlyFailAfterMs: 1_500 };
7
7
  const TOKEN_PATH = /^\/v1\/(filler|credentials|result)\/([A-Za-z0-9_-]{16,})(?:\.js)?$/;
8
8
  const MAX_BODY = 8_192;
@@ -33,7 +33,7 @@ export class BridgeServer {
33
33
  this.ttlMs = options.ttlMs ?? 60_000;
34
34
  this.timing = options.timing ?? BRIDGE_TIMING;
35
35
  this.now = options.now ?? Date.now;
36
- this.reuseWaitMs = options.reuseWaitMs ?? 15_000;
36
+ this.reuseWaitMs = options.reuseWaitMs ?? 25_000;
37
37
  this.releases = new FailureLimiter(options.maxReleases ?? 20, 5 * 60_000, this.now);
38
38
  }
39
39
  /** The first run's result, waiting for it (up to reuseWaitMs) when it is still in progress. */
@@ -65,7 +65,7 @@ export class BridgeServer {
65
65
  const token = randomBytes(24).toString('base64url');
66
66
  this.tickets.set(token, { profile, expiresAt: now + this.ttlMs, released: false, result: null, waiters: [] });
67
67
  const fn = agentFunction(base, token);
68
- return { profile: profile.name, expiresInSeconds: Math.round(this.ttlMs / 1000), function: fn, script: agentScript(fn) };
68
+ return { profile: profile.name, expiresInSeconds: Math.round(this.ttlMs / 1000), function: fn, script: agentScript(fn), expression: agentExpression(fn) };
69
69
  }
70
70
  async handle(req, res) {
71
71
  const { base } = await this.listen();
package/dist/cli.js CHANGED
@@ -3,6 +3,7 @@ import { existsSync } from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
+ import { clientConfig, CLIENTS } from './clients.js';
6
7
  import { createExec } from './exec.js';
7
8
  import { install, uninstall } from './installer.js';
8
9
  import { openDetached, openInEditor } from './opener.js';
@@ -23,18 +24,24 @@ Usage:
23
24
  (--package: what npx runs, e.g. a local .tgz to test a build)
24
25
  npx autologin-mcp uninstall [-y] [--dry-run] [--purge]
25
26
  Undo install (--purge also deletes your credentials file)
26
- npx autologin-mcp add [name] [--url <root-url>] [--username <user>]
27
+ npx autologin-mcp add [name] [--url <root-url>] [--username <user>] [-y]
27
28
  Add or replace a login profile (the password is asked hidden)
29
+ npx autologin-mcp add <name> --url <root-url> --username <user> --password-stdin [-y]
30
+ Same, with the password piped in (scripts, CI)
28
31
  npx autologin-mcp list List profiles (passwords are never shown)
29
32
  npx autologin-mcp remove <name> [-y] Delete a profile
30
33
  npx autologin-mcp edit Open the credentials file in $VISUAL / $EDITOR or the default editor
34
+ npx autologin-mcp print-config [--client <name>] [--package <spec>]
35
+ Print the MCP server config for another agent: json (default),
36
+ claude-desktop, cursor, vscode, gemini, codex or hermes
31
37
  npx autologin-mcp --version | --help
32
38
 
33
39
  Credentials file: ~/.autologin-mcp/credentials.env (override the folder with AUTOLOGIN_HOME).
34
40
  Run add/edit in a separate terminal, never inside an AI chat.
35
41
  `;
42
+ export const NO_PASSWORD_FLAG = '--password is not supported: it would leave the password in your shell history and the process list. Pipe it in with --password-stdin instead.';
36
43
  export function parseArgs(argv) {
37
- const flags = { yes: false, dryRun: false, purge: false, help: false, version: false };
44
+ const flags = { yes: false, dryRun: false, purge: false, help: false, version: false, passwordStdin: false };
38
45
  const positionals = [];
39
46
  for (let i = 0; i < argv.length; i += 1) {
40
47
  const arg = argv[i];
@@ -49,7 +56,11 @@ export function parseArgs(argv) {
49
56
  flags.help = true;
50
57
  else if (name === '-v' || name === '--version')
51
58
  flags.version = true;
52
- else if (name === '--url' || name === '--username' || name === '--package') {
59
+ else if (name === '--password-stdin')
60
+ flags.passwordStdin = true;
61
+ else if (name === '--password')
62
+ throw new Error(NO_PASSWORD_FLAG);
63
+ else if (name === '--url' || name === '--username' || name === '--package' || name === '--client') {
53
64
  const value = inline ?? argv[++i];
54
65
  if (value === undefined)
55
66
  throw new Error(`${name} needs a value`);
@@ -86,21 +97,79 @@ async function confirmAction(ctx, yes, question) {
86
97
  function credentialsFile(ctx) {
87
98
  return credentialsPath(resolveConfigDir(ctx.env, ctx.home));
88
99
  }
100
+ const invalidName = (name) => PROFILE_NAME_RE.test(name) && !name.toUpperCase().startsWith(SETTINGS_PREFIX)
101
+ ? null
102
+ : `Invalid profile name "${name}": use letters, digits and _ (not starting with ${SETTINGS_PREFIX.toLowerCase()}).`;
103
+ /** Writes the profile, replacing an existing one with the same name. Returns an error message or null. */
104
+ async function saveProfile(ctx, file, profile, exists) {
105
+ let block;
106
+ try {
107
+ block = renderProfile(profile);
108
+ }
109
+ catch (error) {
110
+ return error.message;
111
+ }
112
+ const current = (await readText(file)) ?? ENV_TEMPLATE;
113
+ const base = exists ? removeProfile(current, profile.name).text : current;
114
+ await writeSecureFile(file, appendBlock(base, block));
115
+ line(ctx.stdout, `✓ Saved profile "${profile.name}" (${profile.url}) to ${file}`);
116
+ line(ctx.stdout, ' The password is stored only in this file and is never shown to the AI.');
117
+ return null;
118
+ }
119
+ async function readAll(stream) {
120
+ const chunks = [];
121
+ for await (const chunk of stream)
122
+ chunks.push(Buffer.from(chunk));
123
+ return Buffer.concat(chunks).toString('utf8');
124
+ }
125
+ export const STDIN_EXAMPLE = `printf '%s' "$PASSWORD" | npx autologin-mcp add staging --url staging.example.com --username qa@example.com --password-stdin`;
126
+ /** `add --password-stdin`: no questions, for scripts and CI (like `docker login --password-stdin`). */
127
+ async function addFromStdin(ctx, args, file, fail) {
128
+ const name = args.positionals[0]?.toLowerCase();
129
+ const { url, username } = args.flags;
130
+ if (name === undefined || url === undefined || username === undefined) {
131
+ return fail(`--password-stdin needs the profile name, --url and --username, for example:\n ${STDIN_EXAMPLE}`);
132
+ }
133
+ if (ctx.stdin.isTTY === true)
134
+ return fail('--password-stdin reads the password from a pipe, not from the keyboard. Leave it out to type the password hidden.');
135
+ const nameError = invalidName(name);
136
+ if (nameError !== null)
137
+ return fail(nameError);
138
+ const parsed = parseRootUrl(url);
139
+ if (!parsed.ok)
140
+ return fail(parsed.error);
141
+ if (username === '')
142
+ return fail('A username is required.');
143
+ // One trailing newline (from echo or a here-string) is not part of the password.
144
+ const password = (await readAll(ctx.stdin)).replace(/\r?\n$/, '');
145
+ if (password === '')
146
+ return fail('A password is required: nothing was piped in.');
147
+ if (/[\r\n]/.test(password))
148
+ return fail('The password must be a single line.');
149
+ const store = await loadStore(file);
150
+ const exists = store.profiles.some((p) => p.name === name);
151
+ if (exists && !args.flags.yes)
152
+ return fail(`Profile "${name}" already exists. Add -y to replace it.`);
153
+ const error = await saveProfile(ctx, file, { name, url: parsed.normalized, username, password }, exists);
154
+ return error === null ? 0 : fail(error);
155
+ }
89
156
  async function addCommand(ctx, args) {
90
157
  const file = credentialsFile(ctx);
91
- const prompter = ctx.prompter(ctx.stdin, ctx.stdout);
92
158
  const fail = (text) => {
93
159
  line(ctx.stderr, text);
94
160
  return 1;
95
161
  };
162
+ if (args.flags.passwordStdin)
163
+ return addFromStdin(ctx, args, file, fail);
164
+ const prompter = ctx.prompter(ctx.stdin, ctx.stdout);
96
165
  try {
97
166
  const store = await loadStore(file);
98
167
  const name = (args.positionals[0] ?? (await prompter.ask('Profile name (e.g. staging): '))).toLowerCase();
99
- if (!PROFILE_NAME_RE.test(name) || name.toUpperCase().startsWith(SETTINGS_PREFIX)) {
100
- return fail(`Invalid profile name "${name}": use letters, digits and _ (not starting with ${SETTINGS_PREFIX.toLowerCase()}).`);
101
- }
168
+ const nameError = invalidName(name);
169
+ if (nameError !== null)
170
+ return fail(nameError);
102
171
  const exists = store.profiles.some((p) => p.name === name);
103
- if (exists && !(await prompter.confirm(`Profile "${name}" already exists. Replace it?`, false)))
172
+ if (exists && !args.flags.yes && !(await prompter.confirm(`Profile "${name}" already exists. Replace it?`, false)))
104
173
  return fail('Cancelled.');
105
174
  const urlInput = args.flags.url ?? (await prompter.ask('Root URL (e.g. example.com or localhost:3000): '));
106
175
  const parsed = parseRootUrl(urlInput);
@@ -116,19 +185,8 @@ async function addCommand(ctx, args) {
116
185
  return fail('A password is required.');
117
186
  if ((await prompter.askHidden('Repeat the password: ')) !== password)
118
187
  return fail('The passwords do not match.');
119
- let block;
120
- try {
121
- block = renderProfile({ name, url: parsed.normalized, username, password });
122
- }
123
- catch (error) {
124
- return fail(error.message);
125
- }
126
- const current = (await readText(file)) ?? ENV_TEMPLATE;
127
- const base = exists ? removeProfile(current, name).text : current;
128
- await writeSecureFile(file, appendBlock(base, block));
129
- line(ctx.stdout, `✓ Saved profile "${name}" (${parsed.normalized}) to ${file}`);
130
- line(ctx.stdout, ' The password is stored only in this file and is never shown to the AI.');
131
- return 0;
188
+ const error = await saveProfile(ctx, file, { name, url: parsed.normalized, username, password }, exists);
189
+ return error === null ? 0 : fail(error);
132
190
  }
133
191
  catch (error) {
134
192
  if (error instanceof InputClosedError)
@@ -187,10 +245,49 @@ async function editCommand(ctx) {
187
245
  const editor = ctx.env.VISUAL?.trim() || ctx.env.EDITOR?.trim();
188
246
  if (editor)
189
247
  return openInEditor(file, editor, ctx.spawn);
190
- await openDetached(file, ctx.platform, ctx.spawn);
248
+ try {
249
+ await openDetached(file, ctx.platform, { spawn: ctx.spawn, env: ctx.env });
250
+ }
251
+ catch (error) {
252
+ line(ctx.stderr, `Could not open an editor (${error.message}).`);
253
+ line(ctx.stderr, `Set one for this command, e.g. EDITOR=nano npx autologin-mcp edit, or open ${file} yourself.`);
254
+ line(ctx.stderr, 'To add a profile without an editor: npx autologin-mcp add');
255
+ return 1;
256
+ }
191
257
  line(ctx.stdout, `Opened ${file} in your default editor.`);
192
258
  return 0;
193
259
  }
260
+ /** `~/...` for a path inside the home folder, for messages. */
261
+ function displayPath(target, home) {
262
+ const rel = path.relative(home, target);
263
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel) ? `~/${rel.split(path.sep).join('/')}` : target;
264
+ }
265
+ /** Prints the MCP server entry for a client other than Claude Code: the config on stdout, the notes on stderr. */
266
+ function printConfigCommand(ctx, args) {
267
+ const id = (args.flags.client ?? 'json').toLowerCase();
268
+ const config = clientConfig(id, packageSpec(args.flags.package));
269
+ if (config === null) {
270
+ line(ctx.stderr, `Unknown client "${id}". Choose one of: ${CLIENTS.join(', ')}.`);
271
+ line(ctx.stderr, 'For Claude Code, run "npx autologin-mcp install": it also adds the skill and the guard hook.');
272
+ return 1;
273
+ }
274
+ ctx.stdout.write(config.snippet);
275
+ const dir = displayPath(resolveConfigDir(ctx.env, ctx.home), ctx.home);
276
+ line(ctx.stderr);
277
+ line(ctx.stderr, `Add this to ${config.where}.`);
278
+ if (config.command)
279
+ line(ctx.stderr, `Or run: ${config.command}`);
280
+ if (config.note)
281
+ line(ctx.stderr, config.note);
282
+ line(ctx.stderr, 'Then add a login profile in a terminal, never in the AI chat: npx autologin-mcp add');
283
+ line(ctx.stderr, '');
284
+ line(ctx.stderr, `! Only Claude Code has the guard hook that keeps the agent out of ${dir}.`);
285
+ line(ctx.stderr, ` ${config.name === 'your MCP client' ? 'Your client' : config.name} gets the server's instruction not to read that folder, but nothing enforces it;`);
286
+ line(ctx.stderr, " deny the folder in the client's permission settings if it has them.");
287
+ line(ctx.stderr, ` Tested with Claude Code; reports for other clients: ${ISSUES_URL}`);
288
+ return 0;
289
+ }
290
+ export const ISSUES_URL = 'https://github.com/olgaysezgin/autologin-mcp/issues';
194
291
  /**
195
292
  * A local path (e.g. ./autologin-mcp-1.0.0.tgz) becomes an absolute `file:` spec:
196
293
  * npx would try to execute a bare path instead of installing it.
@@ -267,6 +364,8 @@ export async function main(argv, overrides = {}) {
267
364
  return await removeCommand(ctx, args);
268
365
  case 'edit':
269
366
  return await editCommand(ctx);
367
+ case 'print-config':
368
+ return printConfigCommand(ctx, args);
270
369
  default:
271
370
  line(ctx.stderr, `Unknown command "${args.command}".\n`);
272
371
  line(ctx.stderr, USAGE);
@@ -0,0 +1,61 @@
1
+ import { SERVER_NAME } from './installer.js';
2
+ export const CLIENTS = ['json', 'claude-desktop', 'cursor', 'vscode', 'gemini', 'codex', 'hermes'];
3
+ /** Quotes a word for POSIX shells when it needs it. */
4
+ export function shellQuote(word) {
5
+ return /^[\w@%+=:,./-]+$/.test(word) ? word : `'${word.replaceAll("'", `'\\''`)}'`;
6
+ }
7
+ const json = (value) => `${JSON.stringify(value, null, 2)}\n`;
8
+ const list = (items) => `[${items.map((item) => JSON.stringify(item)).join(', ')}]`;
9
+ export function clientConfig(id, packageSpec) {
10
+ const args = ['-y', packageSpec];
11
+ const server = { command: 'npx', args };
12
+ const npx = `npx ${args.map(shellQuote).join(' ')}`;
13
+ switch (id) {
14
+ case 'json':
15
+ return { name: 'your MCP client', where: "your client's MCP configuration (the common mcpServers format)", snippet: json({ mcpServers: { [SERVER_NAME]: server } }) };
16
+ case 'claude-desktop':
17
+ return {
18
+ name: 'Claude Desktop',
19
+ where: 'claude_desktop_config.json (Settings > Developer > Edit Config): ~/Library/Application Support/Claude/ on macOS, %APPDATA%\\Claude\\ on Windows',
20
+ snippet: json({ mcpServers: { [SERVER_NAME]: server } }),
21
+ note: 'Quit and restart Claude Desktop after saving.',
22
+ };
23
+ case 'cursor':
24
+ return {
25
+ name: 'Cursor',
26
+ where: '~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project)',
27
+ snippet: json({ mcpServers: { [SERVER_NAME]: { type: 'stdio', ...server } } }),
28
+ };
29
+ case 'vscode':
30
+ return {
31
+ name: 'VS Code',
32
+ where: '.vscode/mcp.json (one workspace) or your user mcp.json (command "MCP: Open User Configuration")',
33
+ snippet: json({ servers: { [SERVER_NAME]: { type: 'stdio', ...server } } }),
34
+ command: `code --add-mcp ${shellQuote(JSON.stringify({ name: SERVER_NAME, type: 'stdio', ...server }))}`,
35
+ };
36
+ case 'gemini':
37
+ return {
38
+ name: 'Gemini CLI',
39
+ where: '~/.gemini/settings.json (all projects) or .gemini/settings.json (one project)',
40
+ snippet: json({ mcpServers: { [SERVER_NAME]: server } }),
41
+ command: `gemini mcp add -s user ${SERVER_NAME} npx -- ${args.map(shellQuote).join(' ')}`,
42
+ };
43
+ case 'codex':
44
+ return {
45
+ name: 'Codex CLI',
46
+ where: '~/.codex/config.toml',
47
+ snippet: `[mcp_servers.${SERVER_NAME}]\ncommand = "npx"\nargs = ${list(args)}\n`,
48
+ command: `codex mcp add ${SERVER_NAME} -- ${npx}`,
49
+ };
50
+ case 'hermes':
51
+ return {
52
+ name: 'Hermes Agent',
53
+ where: '~/.hermes/config.yaml (merge it into an existing mcp_servers: block)',
54
+ snippet: `mcp_servers:\n ${SERVER_NAME}:\n command: "npx"\n args: ${list(args)}\n`,
55
+ command: `hermes mcp add ${SERVER_NAME} --command npx --args ${args.map(shellQuote).join(' ')}`,
56
+ note: 'In a running session, /reload-mcp loads it.',
57
+ };
58
+ default:
59
+ return null;
60
+ }
61
+ }
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).
@@ -84,7 +94,7 @@ export function autologinInpage(action, arg) {
84
94
  button.click();
85
95
  return 'clicked';
86
96
  }
87
- const form = tagged('password')?.form;
97
+ const form = (tagged('password') ?? tagged('username'))?.form;
88
98
  if (form) {
89
99
  form.requestSubmit();
90
100
  return 'submitted';
@@ -109,8 +119,59 @@ export function autologinInpage(action, arg) {
109
119
  }
110
120
  else {
111
121
  const el = Array.from(document.querySelectorAll('input[type="password"]')).find(usable);
112
- if (!el)
122
+ if (!el) {
123
+ // Identifier-first login: a username step before the password one. Only the heuristic path
124
+ // does this: an explicit password selector means the caller expects that field to exist.
125
+ const textLike = (el) => usable(el) && ['text', 'email', 'tel'].includes(el.type);
126
+ // A login identifier says so: autocomplete="username", or a name / id that is exactly a login word.
127
+ // `type="email"` alone is not enough: invite, share and newsletter fields are email fields too.
128
+ const loginField = (el) => (el.getAttribute('autocomplete') ?? '').toLowerCase().split(/\s+/).includes('username') ||
129
+ [el.name, el.id].some((word) => LOGIN_FIELD.test(word));
130
+ // Controls a person types into or picks from. Hidden fields, checkboxes and buttons do not count.
131
+ const NOT_TYPED = ['hidden', 'checkbox', 'radio', 'submit', 'button', 'image', 'reset'];
132
+ const typedControls = (controls) => controls.filter((el) => (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement) &&
133
+ visible(el) &&
134
+ !el.disabled &&
135
+ !(el instanceof HTMLInputElement && NOT_TYPED.includes(el.type))).length;
136
+ const BUTTONS = 'button, [role="button"], input[type="button"], input[type="submit"]';
137
+ // A button after the field that means "continue", and not, say, "Subscribe" or "Invite".
138
+ 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;
139
+ // A username step is a form, or a small container, whose only typed field is the username: not a signup,
140
+ // checkout or invite form with more fields, and never a button far away (a header "Sign in" next to a
141
+ // footer newsletter field).
142
+ const buttonFor = (field) => {
143
+ if (selectors.submit)
144
+ return find(selectors.submit);
145
+ const form = field.form;
146
+ if (form !== null) {
147
+ // form.elements also holds controls outside the element that point at it with form="…".
148
+ if (typedControls(Array.from(form.elements)) !== 1)
149
+ return null;
150
+ return continueButton([...Array.from(form.querySelectorAll(BUTTONS)), ...Array.from(form.elements)], field);
151
+ }
152
+ let node = field.parentElement;
153
+ for (let depth = 0; depth < 3 && node !== null && node !== document.documentElement; depth += 1, node = node.parentElement) {
154
+ if (typedControls(Array.from(node.querySelectorAll('input, textarea, select'))) !== 1)
155
+ return null;
156
+ const button = continueButton(Array.from(node.querySelectorAll(BUTTONS)), field);
157
+ if (button !== null)
158
+ return button;
159
+ }
160
+ return null;
161
+ };
162
+ const candidates = selectors.username
163
+ ? [find(selectors.username)].filter(textLike)
164
+ : Array.from(document.querySelectorAll('input')).filter((el) => textLike(el) && loginField(el));
165
+ for (const field of candidates) {
166
+ const button = buttonFor(field);
167
+ if (!visible(button))
168
+ continue;
169
+ field.setAttribute(ATTR, 'username');
170
+ button.setAttribute(ATTR, 'submit');
171
+ return { found: false, hasUsername: true, hasSubmit: true, step: 'identifier', nextButton: NEXT_TEXT.test(label(button)) };
172
+ }
113
173
  return { found: false, hasUsername: false, hasSubmit: false };
174
+ }
114
175
  password = el;
115
176
  }
116
177
  let username = null;
@@ -1,5 +1,12 @@
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
+ 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
10
  export const realClock = {
4
11
  now: () => Date.now(),
5
12
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
@@ -13,14 +20,24 @@ async function attempt(fn) {
13
20
  return null;
14
21
  }
15
22
  }
16
- async function typeInto(page, role, value) {
23
+ /** Types into a tagged field; `beforeInsert` runs between focusing it and typing (the site check). */
24
+ async function typeInto(page, role, value, beforeInsert) {
17
25
  await page.run('clear', { role });
18
26
  const field = await page.element(selectorFor(role));
19
27
  if (field === null)
20
28
  throw new Error(`The ${role} field disappeared before it could be filled.`);
21
29
  await field.focus();
30
+ beforeInsert();
22
31
  await page.insertText(value);
23
32
  }
33
+ /** Thrown when the tab left the profile's site right before something would be typed. */
34
+ class LeftSiteError extends Error {
35
+ result;
36
+ constructor(result) {
37
+ super(result.hint);
38
+ this.result = result;
39
+ }
40
+ }
24
41
  async function submitForm(page, hasSubmit) {
25
42
  if (hasSubmit) {
26
43
  try {
@@ -41,24 +58,92 @@ async function submitForm(page, hasSubmit) {
41
58
  */
42
59
  export async function performLogin(page, profile, timing = DEFAULT_TIMING, clock = realClock) {
43
60
  const base = { profile: profile.name };
61
+ // The tab can leave the profile's site while we wait (a redirect, or the username step sending it to a
62
+ // single sign-on host). Nothing is typed into a page of another site: the site is checked before each
63
+ // step and again right between focusing a field and typing into it.
64
+ const leftSite = () => {
65
+ const url = page.url();
66
+ if (matchesUrl(profile.root, url))
67
+ return null;
68
+ return {
69
+ status: 'needs_human',
70
+ ...base,
71
+ url,
72
+ reason: 'left_profile_site',
73
+ hint: `The login moved to ${hostOf(url)}, which is not part of profile "${profile.name}" (${profile.url}), so nothing was typed there. ` +
74
+ '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).',
75
+ };
76
+ };
77
+ const onSite = () => {
78
+ const away = leftSite();
79
+ if (away !== null)
80
+ throw new LeftSiteError(away);
81
+ };
44
82
  const detect = () => attempt(() => page.run('detect', { selectors: profile.selectors }));
45
83
  const state = () => attempt(() => page.run('state', { successSelector: profile.selectors.success }));
46
84
  const clearPassword = () => attempt(() => page.run('clear', { role: 'password' }));
47
85
  try {
48
86
  const detectStart = clock.now();
87
+ const settleMs = identifierSettleMs(timing);
88
+ let identifierSince = null;
49
89
  let detected = await detect();
50
- while (!detected?.found && !detected?.error && clock.now() - detectStart < timing.detectTimeoutMs) {
90
+ // Wait for a password field. An identifier step (username + Next) counts only once it has stayed for
91
+ // the settle time; with a Log in / Sign in button, only after the whole detect time, since a one-page
92
+ // form may still be rendering its password field.
93
+ for (;;) {
94
+ if (detected?.found || detected?.error)
95
+ break;
96
+ const now = clock.now();
97
+ if (detected?.step === 'identifier') {
98
+ identifierSince ??= now;
99
+ if (detected.nextButton && now - identifierSince >= settleMs)
100
+ break;
101
+ }
102
+ else {
103
+ identifierSince = null;
104
+ }
105
+ if (now - detectStart >= timing.detectTimeoutMs)
106
+ break;
51
107
  await clock.sleep(timing.pollMs);
52
108
  detected = await detect();
53
109
  }
54
110
  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.' };
111
+ if (detected?.step !== 'identifier' || !detected.hasUsername) {
112
+ return { status: 'no_login_form', ...base, url: page.url(), hint: detected?.error ?? 'No visible password field was found on the page.' };
113
+ }
114
+ // Identifier-first login: send the username, then wait for the page to ask for the password.
115
+ // A message already on the page (say "Your session has expired") is not an answer to the username.
116
+ onSite();
117
+ const beforeStep = await state();
118
+ await page.bringToFront().catch(() => undefined);
119
+ await typeInto(page, 'username', profile.username, onSite);
120
+ await submitForm(page, detected.hasSubmit);
121
+ const stepStart = clock.now();
122
+ let next = await detect();
123
+ while (!next?.found) {
124
+ onSite(); // a message on a single sign-on host is not a rejection of the username
125
+ const current = await state();
126
+ const newError = current?.errorText != null && current.errorText !== beforeStep?.errorText;
127
+ if (newError && clock.now() - stepStart >= timing.earlyFailAfterMs) {
128
+ return { status: 'failed', ...base, url: page.url(), reason: 'identifier_rejected', hint: current.errorText };
129
+ }
130
+ if (clock.now() - stepStart >= timing.detectTimeoutMs)
131
+ break;
132
+ await clock.sleep(timing.pollMs);
133
+ next = await detect();
134
+ }
135
+ if (!next?.found) {
136
+ // No password was sent, so this is not a failed login (and does not count toward the rate limit).
137
+ return { status: 'needs_human', ...base, url: page.url(), reason: 'password_step_timeout', hint: PASSWORD_STEP_HINT };
138
+ }
139
+ detected = next;
56
140
  }
141
+ onSite();
57
142
  const before = await state();
58
143
  await page.bringToFront().catch(() => undefined);
59
144
  if (detected.hasUsername)
60
- await typeInto(page, 'username', profile.username);
61
- await typeInto(page, 'password', profile.password);
145
+ await typeInto(page, 'username', profile.username, onSite);
146
+ await typeInto(page, 'password', profile.password, onSite);
62
147
  await submitForm(page, detected.hasSubmit);
63
148
  const submittedAt = clock.now();
64
149
  let goneStreak = 0;
@@ -95,6 +180,8 @@ export async function performLogin(page, profile, timing = DEFAULT_TIMING, clock
95
180
  };
96
181
  }
97
182
  catch (error) {
183
+ if (error instanceof LeftSiteError)
184
+ return error.result;
98
185
  await clearPassword();
99
186
  return { status: 'error', ...base, url: page.url(), hint: error instanceof Error ? error.message : String(error) };
100
187
  }
package/dist/opener.js CHANGED
@@ -6,15 +6,39 @@ export function guiOpenCommand(file, platform) {
6
6
  return ['notepad.exe', [file]];
7
7
  return ['xdg-open', [file]];
8
8
  }
9
- /** Opens a file in the desktop's default text editor without waiting for it. */
10
- export function openDetached(file, platform, spawn = nodeSpawn) {
9
+ /** macOS and Windows always have a desktop; elsewhere a window needs X11 or Wayland (not over SSH, in CI or in a container). */
10
+ export function hasDesktop(platform, env) {
11
+ if (platform === 'darwin' || platform === 'win32')
12
+ return true;
13
+ return Boolean(env.DISPLAY?.trim() || env.WAYLAND_DISPLAY?.trim());
14
+ }
15
+ /**
16
+ * Opens a file in the desktop's default text editor without waiting for the editor.
17
+ * Rejects when there is no desktop, when the opener is missing, or when it exits with an error
18
+ * within `settleMs` (xdg-open without a display, `open` with no GUI session).
19
+ */
20
+ export function openDetached(file, platform, options = {}) {
21
+ const { spawn = nodeSpawn, env = process.env, settleMs = 1_500 } = options;
22
+ if (!hasDesktop(platform, env))
23
+ return Promise.reject(new Error('there is no desktop session here (DISPLAY and WAYLAND_DISPLAY are not set)'));
11
24
  const [command, args] = guiOpenCommand(file, platform);
12
25
  return new Promise((resolve, reject) => {
13
26
  const child = spawn(command, args, { detached: true, stdio: 'ignore' });
27
+ let timer;
14
28
  child.once('error', reject);
29
+ child.once('exit', (code) => {
30
+ clearTimeout(timer);
31
+ if (code === 0)
32
+ resolve();
33
+ else
34
+ reject(new Error(`${command} exited with ${code === null ? 'a signal' : `code ${code}`}`));
35
+ });
15
36
  child.once('spawn', () => {
16
- child.unref();
17
- resolve();
37
+ timer = setTimeout(() => {
38
+ child.removeAllListeners('exit');
39
+ child.unref();
40
+ resolve();
41
+ }, settleMs);
18
42
  });
19
43
  });
20
44
  }
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/serve.js CHANGED
@@ -40,7 +40,7 @@ export function createDefaultDeps(options = {}) {
40
40
  bridge,
41
41
  openConfig: async () => {
42
42
  const created = await ensureEnvFile(file);
43
- await openDetached(file, platform, options.spawn);
43
+ await openDetached(file, platform, { spawn: options.spawn, env });
44
44
  return { created };
45
45
  },
46
46
  limiter,
package/dist/server.js CHANGED
@@ -6,13 +6,15 @@ import { hostOf, matchesUrl } from './store/match.js';
6
6
  import { isUsable } from './store/profiles.js';
7
7
  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
8
  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
- 'Tools that take a function (Playwright MCP browser_evaluate, chrome-devtools-mcp evaluate_script) take `function` instead. ' +
9
+ 'Tools that take a function (Playwright MCP browser_evaluate, chrome-devtools-mcp evaluate_script) take `function` instead; ' +
10
+ 'tools that evaluate a plain script without top-level await (Puppeteer page.evaluate) take `expression`. ' +
10
11
  'The value it returns is the login result (success, submitted, failed, ...). It works once, within the expiry, and only on a page of this profile\'s site. ' +
11
12
  'If the call itself fails or returns nothing (the page navigated, the browser tool lost the tab), call `login_status` to get the result the page reported.';
12
13
  export const INSTRUCTIONS = [
13
14
  "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.",
14
15
  '- 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`.',
15
16
  `- If \`login\` returns \`run_in_page\`: ${RUN_IN_PAGE_HINT} On \`submitted\`, check the page to confirm you are logged in.`,
17
+ '- On `needs_human`, the page wants something only a person can do (single sign-on, a passkey or a second factor): tell the user the hint and do not retry.',
16
18
  '- `list_profiles` shows which apps (root URLs) and usernames are configured; `login_status` shows the latest login outcome per profile.',
17
19
  '- 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.',
18
20
  `- If no profile matches: ${ADD_HINT}`,
@@ -87,6 +89,7 @@ async function loginViaBridge(deps, usable, args) {
87
89
  expires_in_s: ticket.expiresInSeconds,
88
90
  script: ticket.script,
89
91
  function: ticket.function,
92
+ expression: ticket.expression,
90
93
  };
91
94
  }
92
95
  export async function runLogin(deps, store, args) {
@@ -178,7 +181,13 @@ export function createServer(deps) {
178
181
  });
179
182
  }
180
183
  catch (error) {
181
- return reply({ file: deps.configFile, opened: false, hint: `Could not open an editor (${message(error)}). Ask the user to run "npx autologin-mcp edit".` }, true);
184
+ // No desktop (SSH, CI, a container) is a normal situation, not a tool error: tell the agent where the file is.
185
+ return reply({
186
+ file: deps.configFile,
187
+ opened: false,
188
+ hint: `Could not open an editor here (${message(error)}). Ask the user to run "npx autologin-mcp add" in a separate terminal (never in this chat), ` +
189
+ 'or to open this file in a text editor there. Do not read this file.',
190
+ });
182
191
  }
183
192
  });
184
193
  return server;
package/dist/templates.js CHANGED
@@ -33,10 +33,11 @@ The \`autologin\` MCP server fills the login form for you and only tells you the
33
33
  ## When the app asks you to log in
34
34
 
35
35
  1. Call \`mcp__autologin__login\` with \`url\` = the tab's current URL. Pass \`profile\` when there are several accounts for the same app (see \`mcp__autologin__list_profiles\`).
36
- 2. \`run_in_page\`: run the returned \`script\` **unchanged** in that tab with your JavaScript tool (Claude in Chrome: \`javascript_tool\`; Playwright MCP \`browser_evaluate\` / chrome-devtools-mcp \`evaluate_script\`: pass \`function\`). Its return value is the login result below. It contains a one-time URL, never a password. If that call fails or returns nothing (the page navigated, the browser tool lost the tab), call \`mcp__autologin__login_status\` to get the result the page reported.
36
+ 2. \`run_in_page\`: run the returned \`script\` **unchanged** in that tab with your JavaScript tool (Claude in Chrome: \`javascript_tool\`; Playwright MCP \`browser_evaluate\` / chrome-devtools-mcp \`evaluate_script\`: pass \`function\`; Puppeteer \`page.evaluate\`: pass \`expression\`). Its return value is the login result below. It contains a one-time URL, never a password. If that call fails or returns nothing (the page navigated, the browser tool lost the tab), call \`mcp__autologin__login_status\` to get the result the page reported.
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 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.0.1",
3
+ "version": "1.2.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": {
@@ -40,6 +40,11 @@
40
40
  "claude-in-chrome",
41
41
  "playwright-mcp",
42
42
  "chrome-devtools-mcp",
43
+ "puppeteer",
44
+ "codex",
45
+ "gemini-cli",
46
+ "cursor",
47
+ "hermes-agent",
43
48
  "ai-testing",
44
49
  "session-expired",
45
50
  "test-automation",