diff --git a/CHANGELOG.md b/CHANGELOG.md index 3faae96..c1f9609 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,19 +5,18 @@ All notable changes to this project will be documented in this file. ## [Unreleased] ### Added -- **Turn pushed edits into tracked changes** ([#66](https://github.com/aloth/olcli/pull/66)) - `suggestChanges(projectId, path, edits)` makes edits that reached Overleaf as plain text, through git, `olcli push` or a sync, show up as tracked changes, as if they had been typed in Reviewing mode. Each edit is given as the old and new text with some text around it; olcli finds the new text, undoes the edit without tracking and redoes it with tracking (`meta.tc` on the update, as the editor sends it). The text ends up as it was, so a git clone that pushed the edit has nothing new to pull. An edit whose new text is not on Overleaf yet is reported as `not-pushed` and left alone. sharejs-text-ot docs only; history-ot docs are refused. Thanks to @fredericosantos -- **MCP tool `suggest_changes` (experimental)** - turns edits that are already on Overleaf as plain text into suggestions collaborators can accept or reject, for projects with track changes, by calling `suggestChanges`. Like the other write tools it asks the user first: the dialog lists each edit with its location and the suggested deletion and insertion, or why it is left alone. If no edit can become a suggestion it asks nothing and writes nothing, and it refuses to write when the document changed after the preview. Clients without elicitation get the preview only, since there is no olcli command for this yet. sharejs-text-ot documents only; returns one result per edit +- **Turn pushed edits into suggestions (experimental)** ([#66](https://github.com/aloth/olcli/pull/66), [#70](https://github.com/aloth/olcli/pull/70)) - `suggestChanges(projectId, path, edits)` makes edits that reached Overleaf as plain text, through git, `olcli push` or a sync, show up as tracked changes that collaborators can accept or reject, as if they had been typed in Reviewing mode. Each edit is given as the old and new text with some text around it; olcli finds the new text, undoes the edit without tracking and redoes it with tracking. The text ends up as it was, so a git clone that pushed the edit has nothing new to pull. Each edit gets a result: `done`, `not-pushed` (the new text is not on Overleaf yet), `not-found`, `already-tracked` (running it again sends nothing), `unchanged`, `invalid` or `not-tracked` (the document was read again and no tracked change was found). `planSuggestions` reports the results without writing, and `expectedVersion` refuses to write when the document changed since. Review-only access is refused with `SuggestionPermissionError` before anything is written. Limits: sharejs-text-ot documents only (history-ot documents are refused), and collaborators who have the document open see the old text for about 0.2 seconds. Documented in docs/LIBRARY.md. Thanks to @fredericosantos for the idea and the first implementation +- **MCP tool `suggest_changes` (experimental)** ([#70](https://github.com/aloth/olcli/pull/70)) - lets an agent turn edits that are already on Overleaf into suggestions, for projects with track changes. Like the other write tools it asks first: the dialog lists each edit with its location and the suggested deletion and insertion, or why it is left alone. If no edit can become a suggestion it asks nothing and writes nothing, and it refuses to write when the document changed after the preview. Clients without elicitation get the preview only. Returns one result per edit ### Fixed -- **`suggestChanges` no longer hangs on an edit with nothing to search for** - an edit whose `before`, `inserted` and `after` were all empty, such as a pure deletion given without surrounding text, made the search loop forever. Such an edit is now reported as `invalid` and nothing is sent -- **`suggestChanges` no longer tracks the same edit twice** - running it again for an edit that is already a tracked change added a second tracked change, and the tracked deletion held the old text twice. An edit whose new or old text is already tracked at that place is now reported as `already-tracked` and nothing is sent, also when the same edit appears twice in one call -- **`suggestChanges` checks its result** - after writing, the document is read again, and an edit without a tracked change at the expected place is reported as `not-tracked` instead of `done` -- **`suggestChanges` names the missing permission** - with review-only access the untracked undo is refused, and the call failed with "applyOtUpdate did not return an acknowledgement". It now throws `SuggestionPermissionError`, which says that the account needs edit access to the project, and nothing is written. When Overleaf reports the access level up front, the check happens before anything is sent -- **`suggestChanges` sends a tracked-change id seed in Overleaf's format** - the seed in `meta.tc` was 18 random hex digits; it now starts with the current time in seconds like the seeds the Overleaf editor generates, so the ids of the new tracked changes carry a meaningful timestamp +- **Password sign-in on overleaf.com says why it fails** - overleaf.com requires a captcha for password sign-in and answers a form post without one with HTTP 400, so `olcli auth --email`, and every command that signs in with `OVERLEAF_EMAIL` and `OVERLEAF_PASSWORD`, failed with only "Password login failed. HTTP 400". olcli now recognizes Overleaf's captcha rejection (`errorReason: "cannot_verify_user_not_robot"`), or, when the answer gives no reason, a login page with reCAPTCHA switched on for login, and stops with " requires a captcha for password sign-in, which olcli cannot complete. Sign in with `olcli auth --browser`, or paste a session cookie with `olcli auth --cookie`." The CLI, the MCP server and the git remote helper print the same message; library code gets a `CaptchaRequiredError`. A wrong password keeps its old message, and the exit status is unchanged. On a terminal, `olcli auth --email` then asks "Sign in in the browser instead? [Y/n]" and runs the same flow as `olcli auth --browser` on yes; scripts, CI and the other commands never get a question +- **The progress spinner no longer hangs on a terminal without a width** - a terminal that reports a width of 0, such as a pseudo-terminal opened without a window size, made the spinner try to clear an endless number of lines on every frame, so a command printed control codes forever instead of finishing. Such a terminal now gets the plain output used for pipes and logs ### Changed -- **`suggestChanges` reports `unchanged`** for an edit whose `inserted` equals `deleted`, instead of `not-pushed`. `SuggestionResult` gains `already-tracked`, `unchanged`, `invalid` and `not-tracked`; existing values keep their meaning. `hint` is now optional -- **`suggestChanges` is marked experimental** - sharejs-text-ot documents only (history-ot documents are refused), and collaborators who have the document open see the old text for about 0.2 seconds while an edit is undone and redone. `planSuggestions` reports what it would do without writing, and an `expectedVersion` option refuses to write when the document changed since. Documented in docs/LIBRARY.md +- **Password sign-in is documented as self-hosted only** - `olcli --help`, `olcli auth --help`, the README, docs/CONFIGURATION.md, docs/MCP.md and SKILL.md say that `--email` and `OVERLEAF_EMAIL`/`OVERLEAF_PASSWORD` work only on self-hosted servers without reCAPTCHA and point to `olcli auth --browser` for overleaf.com. `olcli auth status` warns when password credentials would be used on overleaf.com, and its JSON output gains a `warnings` array + +### Documentation +- **Contributing without an issue first** - CONTRIBUTING.md now welcomes pull requests at any time; for a larger change a draft pull request works as well as an issue. A pull request that does what it says is merged as it is, and remaining findings are fixed in a follow-up ## [0.17.0] - 2026-11-15 diff --git a/README.md b/README.md index c69f74e..731f038 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ olcli auth status # instance, account, where the credential comes fr **Get your session cookie:** sign in to Overleaf in a browser, open the developer tools (F12), then Application (Chrome, Edge) or Storage (Firefox), Cookies, and copy the value of `overleaf_session2` (`overleaf.sid` on most self-hosted instances). A value on the command line also works but lands in your shell history. -Self-hosted instances without reCAPTCHA also accept `olcli auth --email you@example.com`, which prompts for the password. Scripts can set `OVERLEAF_SESSION`, or `OVERLEAF_EMAIL` and `OVERLEAF_PASSWORD`, and skip `olcli auth` entirely. +Self-hosted instances without reCAPTCHA also accept `olcli auth --email you@example.com`, which prompts for the password. overleaf.com requires a captcha for password sign-in, which olcli cannot complete, so use `olcli auth --browser` or `olcli auth --cookie` there; on a terminal, a refused password sign-in offers the browser sign-in instead. Scripts can set `OVERLEAF_SESSION`, or on self-hosted instances without reCAPTCHA `OVERLEAF_EMAIL` and `OVERLEAF_PASSWORD`, and skip `olcli auth` entirely. ### Self-hosted Overleaf diff --git a/SKILL.md b/SKILL.md index 02b9639..46dbea1 100644 --- a/SKILL.md +++ b/SKILL.md @@ -65,9 +65,11 @@ reports each. Environment variables cannot be unset by a child process, so `OVERLEAF_SESSION` and `OVERLEAF_EMAIL`/`OVERLEAF_PASSWORD` are reported rather than silently ignored — they outrank anything on disk. -For unattended use, prefer `OVERLEAF_EMAIL`/`OVERLEAF_PASSWORD` over -`olcli auth --password`: every command reads them, and nothing is written to -disk or to shell history. +For unattended use on a self-hosted instance without reCAPTCHA, prefer +`OVERLEAF_EMAIL`/`OVERLEAF_PASSWORD` over `olcli auth --password`: every +command reads them, and nothing is written to disk or to shell history. +overleaf.com requires a captcha for password sign-in, which olcli cannot +complete; use `olcli auth --browser` or `OVERLEAF_SESSION` there. ### Self-hosted Overleaf diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 10d61ac..f42282b 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -27,14 +27,14 @@ Everything is stored in plaintext, so it is worth knowing what is on disk: ### Password login -Self-hosted instances without reCAPTCHA accept a password login: +Self-hosted instances without reCAPTCHA accept a password login. overleaf.com does not: it requires a captcha for password sign-in, which olcli cannot complete, and olcli says so instead of a bare HTTP 400. Use `olcli auth --browser` or `olcli auth --cookie` there. On a terminal, `olcli auth --email` offers the browser sign-in when the captcha refuses the password; `olcli auth status` warns when password credentials would be used on overleaf.com. ```bash olcli auth --email "you@example.com" # prompts for the password, so it stays out of your shell history ``` -The password is **not stored** unless you pass `--save-password`. A session cookie is saved either way and is what later commands use; the password only buys an automatic re-login once that cookie expires. For scripts, set `OVERLEAF_EMAIL` and `OVERLEAF_PASSWORD`: every command reads them, so a scripted run never needs `olcli auth` at all. +The password is **not stored** unless you pass `--save-password`. A session cookie is saved either way and is what later commands use; the password only buys an automatic re-login once that cookie expires. For scripts on such an instance, set `OVERLEAF_EMAIL` and `OVERLEAF_PASSWORD`: every command reads them, so a scripted run never needs `olcli auth` at all. ## Self-hosted Overleaf @@ -62,7 +62,7 @@ olcli reads these. The MCP server and the git remote helper read the same sessio | Variable | Purpose | |---|---| | `OVERLEAF_SESSION` | Session cookie value | -| `OVERLEAF_EMAIL`, `OVERLEAF_PASSWORD` | Password login, used when no session cookie is set or it is rejected | +| `OVERLEAF_EMAIL`, `OVERLEAF_PASSWORD` | Password login, used when no session cookie is set or it is rejected. Self-hosted instances without reCAPTCHA only; overleaf.com requires a captcha (use `olcli auth --browser`) | | `OVERLEAF_BASE_URL` | Instance URL, like `--base-url` (default: `https://www.overleaf.com`) | | `OVERLEAF_COOKIE_NAME` | Session cookie name, like `--cookie-name` (default: `overleaf_session2`; self-hosted instances often use `overleaf.sid`) | | `OVERLEAF_TIMEOUT` | HTTP timeout in milliseconds, like `--timeout` | diff --git a/docs/MCP.md b/docs/MCP.md index fe157e7..c3386df 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -101,7 +101,7 @@ Every tool declares MCP tool annotations. Read-only tools set `readOnlyHint`. To The MCP server reads credentials in this order: 1. **`OVERLEAF_SESSION` environment variable** — set in your MCP config (recommended) -2. **`OVERLEAF_EMAIL` + `OVERLEAF_PASSWORD` environment variables** — for password login (self-hosted) +2. **`OVERLEAF_EMAIL` + `OVERLEAF_PASSWORD` environment variables** - for password login on self-hosted instances without reCAPTCHA. overleaf.com requires a captcha for password sign-in, which olcli cannot complete; the tools then fail with a message that says so. Use `OVERLEAF_SESSION` or run `olcli auth --browser` once instead 3. **`.olauth` file in cwd** — written by `olcli auth --save-local` 4. **Stored config** — written by `olcli auth` (including saved password credentials) diff --git a/src/auth-fallback.ts b/src/auth-fallback.ts new file mode 100644 index 0000000..6247408 --- /dev/null +++ b/src/auth-fallback.ts @@ -0,0 +1,81 @@ +/** + * What `olcli auth` does when a password sign-in is refused because the + * instance requires a captcha: on a terminal, offer the browser sign-in + * instead; everywhere else, only report it. + * + * Kept apart from cli.ts so the decision can be tested without a terminal, + * a browser or the network. + */ + +import { CaptchaRequiredError } from './errors.js'; + +export interface BrowserFallbackDeps { + /** True when a person is at the terminal (see `canOfferBrowserSignIn`). */ + interactive: boolean; + /** Throws with a reason when `auth --browser` cannot run here (no browser, old Node). */ + checkBrowser: () => void; + /** Asks the question; resolves to true for yes. */ + ask: (question: string) => Promise; + /** Runs the same flow as `olcli auth --browser`. */ + runBrowser: () => Promise; +} + +/** + * - `browser`: the user said yes and the browser sign-in ran + * - `declined`: the user said no + * - `unavailable`: interactive, but `auth --browser` cannot run here; `reason` says why + * - `not-offered`: not a captcha error, or nobody to ask + */ +export type BrowserFallbackOutcome = + | { outcome: 'browser' } + | { outcome: 'declined' } + | { outcome: 'unavailable'; reason: string } + | { outcome: 'not-offered' }; + +export const BROWSER_FALLBACK_QUESTION = 'Sign in in the browser instead?'; + +/** + * True when stdin and stdout are both terminals and no CI system is driving + * the run. Only then can a question be answered by a person. + */ +export function canOfferBrowserSignIn( + streams: { stdin: { isTTY?: boolean }; stdout: { isTTY?: boolean } } = { stdin: process.stdin, stdout: process.stdout }, + env: NodeJS.ProcessEnv = process.env, +): boolean { + const ci = env.CI !== undefined && env.CI !== '' && env.CI !== '0' && env.CI.toLowerCase() !== 'false'; + return Boolean(streams.stdin.isTTY) && Boolean(streams.stdout.isTTY) && !ci; +} + +export async function offerBrowserSignIn(error: unknown, deps: BrowserFallbackDeps): Promise { + if (!(error instanceof CaptchaRequiredError) || !deps.interactive) return { outcome: 'not-offered' }; + try { + deps.checkBrowser(); + } catch (reason) { + return { outcome: 'unavailable', reason: reason instanceof Error ? reason.message : String(reason) }; + } + if (!(await deps.ask(BROWSER_FALLBACK_QUESTION))) return { outcome: 'declined' }; + await deps.runBrowser(); + return { outcome: 'browser' }; +} + +/** Hosts where password sign-in is known to need a captcha. */ +const CAPTCHA_HOSTS = new Set(['www.overleaf.com', 'overleaf.com']); + +/** + * Warnings for `auth status` about the credential that would be used. + * Password credentials on overleaf.com cannot sign in, because Overleaf + * requires a captcha for password sign-in there. Self-hosted instances are + * not judged: whether they have reCAPTCHA switched on is only known after a + * sign-in attempt. + */ +export function passwordSignInWarnings(usesPassword: boolean, baseUrl: string): string[] { + if (!usesPassword) return []; + let host: string; + try { + host = new URL(baseUrl).hostname.toLowerCase(); + } catch { + return []; + } + if (!CAPTCHA_HOSTS.has(host)) return []; + return ['overleaf.com requires a captcha for password sign-in, which olcli cannot complete. Sign in with: olcli auth --browser']; +} diff --git a/src/cli.ts b/src/cli.ts index baf5472..dc3c42f 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -10,7 +10,7 @@ import { Command } from 'commander'; import chalk from 'chalk'; import type { Ora } from 'ora'; import { colorDisabled, createSpinner as ora, icon } from './term.js'; -import { ProjectOwnerOnlyError, formatError } from './errors.js'; +import { CaptchaRequiredError, ProjectOwnerOnlyError, formatError } from './errors.js'; import { writeFileSync, readFileSync, existsSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs'; import { join, dirname, basename } from 'node:path'; import { tmpdir } from 'node:os'; @@ -70,7 +70,8 @@ import { maskSecret, type PasswordCredentials } from './config.js'; -import { promptHidden, PromptCancelled, NotATerminal } from './prompt.js'; +import { promptHidden, promptYesNo, PromptCancelled, NotATerminal } from './prompt.js'; +import { canOfferBrowserSignIn, offerBrowserSignIn, passwordSignInWarnings } from './auth-fallback.js'; import { BrowserSignInAborted, browserSignIn, chromiumLauncher, findBrowser, requireWebSocket } from './browser-auth.js'; // NO_COLOR (no-color.org) and --no-color. chalk handles --no-color and a @@ -93,7 +94,9 @@ program Environment: OVERLEAF_SESSION session cookie (instead of olcli auth) OVERLEAF_EMAIL, OVERLEAF_PASSWORD - password login when no session cookie works + password login when no session cookie works; + self-hosted servers without reCAPTCHA only + (overleaf.com: olcli auth --browser) OVERLEAF_BASE_URL instance URL, like --base-url OVERLEAF_COOKIE_NAME session cookie name, like --cookie-name OVERLEAF_TIMEOUT HTTP timeout in milliseconds, like --timeout @@ -261,7 +264,7 @@ const authCmd = program .command('auth') .description('Authenticate with Overleaf using a session cookie or email/password') .option('--cookie [session]', 'Session cookie; omit the value to be prompted, "-" reads stdin') - .option('--email ', 'Account email for password login') + .option('--email ', 'Account email for password login (self-hosted servers without reCAPTCHA)') .option('--password ', 'Account password (omit to be prompted; see warning below)') .option('--save-password', 'Persist the password in the config file, in plaintext') .option('--no-save-password', 'Do not persist the password (the default; kept for existing scripts)') @@ -284,13 +287,18 @@ instances). Then either: pbpaste | olcli auth --cookie - reads the cookie from stdin A value given on the command line works too, but lands in your shell history. +Password sign-in (--email) works only on self-hosted servers without +reCAPTCHA. overleaf.com requires a captcha for it, which olcli cannot +complete; use --browser or --cookie there. + The password is not stored unless you ask for it with --save-password. A session cookie is stored either way, and that is what later commands use; the password only buys an automatic re-login once the cookie expires. Passing --password puts the password in your shell history. Omit it to be prompted instead, or set OVERLEAF_EMAIL and OVERLEAF_PASSWORD, which every -command reads without needing 'auth' at all.`) +command reads without needing 'auth' at all (self-hosted servers without +reCAPTCHA only).`) .action(async (options) => { if (options.browser) { if (options.cookie || options.email || options.password) { @@ -316,7 +324,7 @@ command reads without needing 'auth' at all.`) console.log(chalk.cyan(' olcli auth --cookie')); console.log(chalk.dim(' (or pipe it: pbpaste | olcli auth --cookie -)')); console.log(); - console.log('Or log in with email/password:'); + console.log('Or log in with email/password (self-hosted servers without reCAPTCHA):'); console.log(chalk.cyan(' olcli auth --email "you@example.com"')); console.log(chalk.dim(' (prompts for the password, so it stays out of your shell history)')); console.log(); @@ -383,8 +391,8 @@ command reads without needing 'auth' at all.`) } catch (error: any) { if (error instanceof NotATerminal) { console.error(chalk.red('No terminal available to prompt for a password.')); - console.error('Set OVERLEAF_EMAIL and OVERLEAF_PASSWORD instead — every command reads them,'); - console.error("so a scripted run does not need 'olcli auth' at all."); + console.error('Set OVERLEAF_EMAIL and OVERLEAF_PASSWORD instead - every command reads them,'); + console.error("so a scripted run does not need 'olcli auth' at all (self-hosted servers without reCAPTCHA only)."); process.exit(1); } if (error instanceof PromptCancelled) { @@ -448,6 +456,20 @@ command reads without needing 'auth' at all.`) printNextSteps(projects); } catch (error: any) { + if (error instanceof CaptchaRequiredError) { + const [first, ...rest] = formatError(error, { verbose: Boolean(program.opts().verbose) }); + spinner.fail(first); + for (const line of rest) console.error(chalk.dim(` ${line}`)); + const offer = await offerBrowserSignIn(error, { + interactive: canOfferBrowserSignIn(), + checkBrowser: () => { requireWebSocket(); findBrowser(); }, + ask: (question) => promptYesNo(question, true).catch(() => false), + runBrowser: () => authWithBrowser({ saveLocal: options.saveLocal }), + }); + if (offer.outcome === 'browser') return; + if (offer.outcome === 'unavailable') console.error(chalk.dim(` Browser sign-in is not available here: ${offer.reason}`)); + process.exit(1); + } failWith(spinner, error); } }); @@ -555,6 +577,7 @@ async function authStatus(options: { json?: boolean }): Promise { configFile: string; passwordStored: boolean; signedIn: boolean; + warnings: string[]; projects?: number; error?: string; } = { @@ -566,6 +589,7 @@ async function authStatus(options: { json?: boolean }): Promise { configFile: getConfigPath(), passwordStored: stored.password, signedIn: false, + warnings: passwordSignInWarnings(Boolean(password), baseUrl), }; const print = (): void => { @@ -585,6 +609,9 @@ async function authStatus(options: { json?: boolean }): Promise { if (report.signedIn) { row('Session', chalk.green(`valid, ${report.projects} project(s)`)); } + for (const warning of report.warnings) { + row('Warning', chalk.yellow(warning)); + } }; let failure: unknown; diff --git a/src/client.ts b/src/client.ts index 167f865..468931f 100644 --- a/src/client.ts +++ b/src/client.ts @@ -40,7 +40,7 @@ import { } from './tracked-changes.js'; import { planEntityMove, type MovePlan } from './move-plan.js'; import { matchProject } from './project-match.js'; -import { HttpStatusError, ProjectOwnerOnlyError, SessionExpiredError, httpError, isAuthStatus } from './errors.js'; +import { CaptchaRequiredError, HttpStatusError, ProjectOwnerOnlyError, SessionExpiredError, httpError, isAuthStatus } from './errors.js'; // Read version from package.json const __dirname = dirname(fileURLToPath(import.meta.url)); @@ -292,6 +292,57 @@ export interface SuggestionPlan { } /** Thrown when the account may review but not edit: turning an edit into a suggestion first writes untracked. */ +/** + * The `errorReason` Overleaf answers a login post with when its reCAPTCHA + * check fails (HTTP 400, JSON). Sent before the credentials are checked, so + * it also means nothing is known about the password. + */ +export const CAPTCHA_ERROR_REASON = 'cannot_verify_user_not_robot'; + +function parseJsonObject(text: string): Record | undefined { + try { + const parsed = JSON.parse(text); + return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined; + } catch { + return undefined; + } +} + +/** True when a login response body says the reCAPTCHA check failed. */ +export function isCaptchaRejection(body: string): boolean { + return parseJsonObject(body)?.errorReason === CAPTCHA_ERROR_REASON; +} + +/** + * True when a login response body is JSON that gives a reason of its own + * (`errorReason` or `message`), such as a wrong password. Such an answer is + * not second-guessed with the login page markers. + */ +function hasLoginMessage(body: string): boolean { + const parsed = parseJsonObject(body); + return Boolean(parsed && (parsed.errorReason || parsed.message)); +} + +/** + * True when an Overleaf login page has reCAPTCHA switched on for login: + * `recaptchaDisabled.login === false` in the `ol-ExposedSettings` meta data, + * or, on releases without that setting, the reCAPTCHA script or widget on the + * page. Self-hosted instances without reCAPTCHA have neither. + */ +export function loginPageRequiresCaptcha(html: string): boolean { + const $ = cheerio.load(html); + const settingsText = $('meta[name="ol-ExposedSettings"]').attr('content'); + if (settingsText) { + const settings = parseJsonObject(settingsText); + const disabled = settings?.recaptchaDisabled as { login?: unknown } | undefined; + if (disabled && typeof disabled === 'object' && typeof disabled.login === 'boolean') { + return !disabled.login && Boolean(settings?.recaptchaSiteKey || settings?.recaptchaSiteKeyV3 || settings?.recaptchaEnterpriseSiteKey); + } + } + const scriptSources = $('script[src]').toArray().map(el => $(el).attr('src') ?? ''); + return scriptSources.some(src => /\/recaptcha\/(api|enterprise)\.js/.test(src)) || $('.g-recaptcha').length > 0; +} + export class SuggestionPermissionError extends Error { constructor(path: string, detail?: string) { super(`${path}: this account needs edit access to the project to turn edits into suggestions; review-only access cannot do it, because the edit is first undone without tracking. Nothing was changed${detail ? ` (${detail})` : ''}`); @@ -558,12 +609,19 @@ export class OverleafClient { bootstrapClient.applySetCookieHeaders(loginResponse.headers['set-cookie'] as string[] | undefined); if (![302, 303].includes(loginResponse.status)) { - const loginFailure = typeof loginResponse.body === 'string' - ? OverleafClient.isLoginPage(cheerio.load(loginResponse.body)) - : false; + const responseText = typeof loginResponse.body === 'string' ? loginResponse.body : ''; + if (isCaptchaRejection(responseText)) { + throw new CaptchaRequiredError(new URL(baseUrl).host, loginResponse.status); + } + const loginFailure = responseText ? OverleafClient.isLoginPage(cheerio.load(responseText)) : false; if (loginFailure) { throw new Error('Password login failed. Email or password may be incorrect.'); } + // An answer that does not say why: if the login page asked for a + // captcha, that is the most likely reason. + if (!hasLoginMessage(responseText) && loginPageRequiresCaptcha(loginHtml)) { + throw new CaptchaRequiredError(new URL(baseUrl).host, loginResponse.status); + } throw new HttpStatusError('Password login failed', loginResponse.status); } diff --git a/src/errors.ts b/src/errors.ts index 86f2423..321b757 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -69,6 +69,33 @@ export class ProjectOwnerOnlyError extends Error { } } +/** + * Password sign-in was refused because the instance requires a reCAPTCHA + * token, which olcli cannot produce. overleaf.com has reCAPTCHA switched on + * for its login form and answers a form post without a token with HTTP 400 + * and `errorReason: "cannot_verify_user_not_robot"`, before it looks at the + * email and password. Retrying cannot help; only a browser sign-in or a + * session cookie can. + */ +export class CaptchaRequiredError extends Error { + readonly status?: number; + /** Host of the instance, like `www.overleaf.com`. */ + readonly host: string; + + constructor(host: string, status?: number) { + super(captchaRequiredMessage(host)); + this.name = 'CaptchaRequiredError'; + this.host = host; + this.status = status; + } +} + +/** The message of a CaptchaRequiredError for `host`. */ +export function captchaRequiredMessage(host: string): string { + return `${host} requires a captcha for password sign-in, which olcli cannot complete. ` + + `Sign in with \`${AUTH_COMMAND} --browser\`, or paste a session cookie with \`${AUTH_COMMAND} --cookie\`.`; +} + /** HTTP statuses that mean "this session is not allowed", not "this request is wrong". */ export function isAuthStatus(status: number): boolean { return status === 401 || status === 403; @@ -116,6 +143,11 @@ export function formatError(error: unknown, options: FormatErrorOptions = {}): s return [error.message, `${error.detail}.${verboseHint}`]; } + if (error instanceof CaptchaRequiredError) { + if (error.status === undefined) return [error.message]; + return [error.message, `Overleaf answered HTTP ${error.status}.`]; + } + if (error instanceof ProjectOwnerOnlyError) { if (error.status === undefined) return [error.message]; return [ diff --git a/src/index.ts b/src/index.ts index 73a738f..76bd8e8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,6 +52,9 @@ export { type CommentStatus, } from './client.js'; +// Password sign-in refused because the instance requires a captcha +export { CaptchaRequiredError } from './errors.js'; + // Tracked changes: kinds, authors and the ShareJS op format export { type TrackedChangeKind, diff --git a/src/prompt.ts b/src/prompt.ts index 2c1cc82..bc2daec 100644 --- a/src/prompt.ts +++ b/src/prompt.ts @@ -169,3 +169,43 @@ export function promptHidden(label: string): Promise { stdout.write(label); }); } + +/** + * Read a yes/no answer for a `[Y/n]` or `[y/N]` question. An empty answer + * takes the default; anything that is not a recognizable yes or no counts as + * no, so a stray keystroke never starts something the user did not ask for. + */ +export function parseYesNo(answer: string, defaultYes: boolean): boolean { + const text = answer.trim().toLowerCase(); + if (text === '') return defaultYes; + return text === 'y' || text === 'yes'; +} + +/** + * Ask a yes/no question on the terminal and read one visible line. + * + * Throws `NotATerminal` when stdin is not a terminal, like `promptHidden`, and + * `PromptCancelled` on Ctrl+C or Ctrl+D. + */ +export async function promptYesNo(question: string, defaultYes = true): Promise { + if (!stdin.isTTY) { + throw new NotATerminal('stdin is not a terminal, so a question cannot be asked'); + } + const { createInterface } = await import('node:readline'); + const rl = createInterface({ input: stdin, output: stdout, terminal: true }); + try { + const answer = await new Promise((resolve, reject) => { + let answered = false; + rl.once('SIGINT', () => reject(new PromptCancelled())); + rl.once('close', () => { if (!answered) reject(new PromptCancelled()); }); + rl.question(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `, (line) => { + answered = true; + resolve(line); + }); + }); + return parseYesNo(answer, defaultYes); + } finally { + rl.close(); + stdin.pause(); + } +} diff --git a/src/term.ts b/src/term.ts index dc8157e..edee11c 100644 --- a/src/term.ts +++ b/src/term.ts @@ -22,6 +22,11 @@ export function isInteractive(stream: { isTTY?: boolean } = process.stdout, env: return Boolean(stream.isTTY) && env.TERM !== 'dumb'; } +/** False when a terminal reports a width of 0 or less; an unknown width is fine. */ +export function hasUsableWidth(stream: { columns?: number } = process.stderr): boolean { + return stream.columns === undefined || stream.columns > 0; +} + /** `fancy` on an interactive stdout, `plain` otherwise. */ export function icon(fancy: string, plain: string): string { return isInteractive() ? fancy : plain; @@ -33,8 +38,12 @@ export function icon(fancy: string, plain: string): string { * rather than a glyph. On a terminal it is ora unchanged. */ export function createSpinner(text: string): Ora { - const spinner = oraFactory({ text }); - if (isInteractive(process.stderr)) return spinner; + // A terminal that reports a width of 0 (a pty opened without a window size) + // makes ora count Infinity lines to clear on every frame, which never + // finishes. Treat it like a non-terminal: no animation, plain words. + const animate = isInteractive(process.stderr) && hasUsableWidth(process.stderr); + const spinner = oraFactory(animate ? { text } : { text, isEnabled: false }); + if (animate) return spinner; const plain = (symbol: string) => (message?: string): Ora => spinner.stopAndPersist({ symbol, text: message }); spinner.succeed = plain('ok:'); spinner.fail = plain('error:'); diff --git a/test/auth-fallback.test.ts b/test/auth-fallback.test.ts new file mode 100644 index 0000000..798849f --- /dev/null +++ b/test/auth-fallback.test.ts @@ -0,0 +1,102 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + BROWSER_FALLBACK_QUESTION, + canOfferBrowserSignIn, + offerBrowserSignIn, + passwordSignInWarnings, + type BrowserFallbackDeps, +} from '../src/auth-fallback.js'; +import { CaptchaRequiredError, HttpStatusError, formatError, formatErrorText } from '../src/errors.js'; +import { parseYesNo } from '../src/prompt.js'; + +function deps(overrides: Partial & { answer?: boolean } = {}) { + const calls = { asked: [] as string[], browser: 0 }; + const d: BrowserFallbackDeps = { + interactive: true, + checkBrowser: () => {}, + ask: async (question) => { calls.asked.push(question); return overrides.answer ?? true; }, + runBrowser: async () => { calls.browser += 1; }, + ...overrides, + }; + return { d, calls }; +} + +const captcha = new CaptchaRequiredError('www.overleaf.com', 400); + +test('browser fallback: interactive and yes runs the browser sign-in', async () => { + const { d, calls } = deps({ answer: true }); + assert.deepEqual(await offerBrowserSignIn(captcha, d), { outcome: 'browser' }); + assert.deepEqual(calls.asked, [BROWSER_FALLBACK_QUESTION]); + assert.equal(calls.browser, 1); +}); + +test('browser fallback: no leaves it at the message', async () => { + const { d, calls } = deps({ answer: false }); + assert.deepEqual(await offerBrowserSignIn(captcha, d), { outcome: 'declined' }); + assert.equal(calls.browser, 0); +}); + +test('browser fallback: never asks when not interactive', async () => { + const { d, calls } = deps({ interactive: false }); + assert.deepEqual(await offerBrowserSignIn(captcha, d), { outcome: 'not-offered' }); + assert.deepEqual(calls.asked, []); + assert.equal(calls.browser, 0); +}); + +test('browser fallback: other errors are not answered with a browser offer', async () => { + const { d, calls } = deps(); + assert.deepEqual(await offerBrowserSignIn(new HttpStatusError('Password login failed', 400), d), { outcome: 'not-offered' }); + assert.deepEqual(await offerBrowserSignIn(new Error('Password login failed. Email or password may be incorrect.'), d), { outcome: 'not-offered' }); + assert.deepEqual(calls.asked, []); +}); + +test('browser fallback: no browser or old Node means no question, only the reason', async () => { + const { d, calls } = deps({ checkBrowser: () => { throw new Error('No Chrome, Edge, Chromium or Brave found.'); } }); + assert.deepEqual(await offerBrowserSignIn(captcha, d), { outcome: 'unavailable', reason: 'No Chrome, Edge, Chromium or Brave found.' }); + assert.deepEqual(calls.asked, []); + assert.equal(calls.browser, 0); +}); + +test('canOfferBrowserSignIn: needs a TTY on stdin and stdout and no CI', () => { + const tty = { isTTY: true }; + const pipe = { isTTY: false }; + assert.equal(canOfferBrowserSignIn({ stdin: tty, stdout: tty }, {}), true); + assert.equal(canOfferBrowserSignIn({ stdin: pipe, stdout: tty }, {}), false); + assert.equal(canOfferBrowserSignIn({ stdin: tty, stdout: pipe }, {}), false); + assert.equal(canOfferBrowserSignIn({ stdin: tty, stdout: tty }, { CI: 'true' }), false); + assert.equal(canOfferBrowserSignIn({ stdin: tty, stdout: tty }, { CI: '1' }), false); + assert.equal(canOfferBrowserSignIn({ stdin: tty, stdout: tty }, { CI: 'false' }), true); +}); + +test('parseYesNo: empty takes the default, only y/yes is yes', () => { + assert.equal(parseYesNo('', true), true); + assert.equal(parseYesNo(' ', false), false); + assert.equal(parseYesNo('Y', false), true); + assert.equal(parseYesNo('yes', false), true); + assert.equal(parseYesNo('n', true), false); + assert.equal(parseYesNo('nope', true), false); + assert.equal(parseYesNo('x', true), false); +}); + +test('auth status warning: password credentials on overleaf.com warn, self-hosted does not', () => { + for (const url of ['https://www.overleaf.com', 'https://www.overleaf.com/', 'https://overleaf.com']) { + const warnings = passwordSignInWarnings(true, url); + assert.equal(warnings.length, 1, url); + assert.match(warnings[0], /overleaf\.com requires a captcha for password sign-in/); + assert.match(warnings[0], /olcli auth --browser/); + } + assert.deepEqual(passwordSignInWarnings(true, 'https://latex.example.org'), []); + assert.deepEqual(passwordSignInWarnings(true, 'http://127.0.0.1:8080'), []); + assert.deepEqual(passwordSignInWarnings(false, 'https://www.overleaf.com'), []); + assert.deepEqual(passwordSignInWarnings(true, 'not a url'), []); +}); + +test('CaptchaRequiredError: one message for CLI, MCP and the remote helper', () => { + const lines = formatError(captcha); + assert.equal(lines[0], 'www.overleaf.com requires a captcha for password sign-in, which olcli cannot complete. Sign in with `olcli auth --browser`, or paste a session cookie with `olcli auth --cookie`.'); + assert.equal(lines[1], 'Overleaf answered HTTP 400.'); + assert.doesNotMatch(lines.join('\n'), /--verbose/, 'the request log would not explain more'); + assert.equal(formatErrorText(captcha, { verbose: true }), lines.join('\n')); + assert.deepEqual(formatError(new CaptchaRequiredError('latex.example.org')), [new CaptchaRequiredError('latex.example.org').message]); +}); diff --git a/test/cli-offline.test.ts b/test/cli-offline.test.ts index caf708a..ab8d243 100644 --- a/test/cli-offline.test.ts +++ b/test/cli-offline.test.ts @@ -422,3 +422,116 @@ test('pull keeps non-ASCII letters in the directory name and reuses a pre-0.16 d await live.close(); } }); + +/** A login page with reCAPTCHA on for login, and the answer overleaf.com gives a form post without a captcha token. */ +async function captchaOverleaf(): Promise { + const requests: string[] = []; + const settings = JSON.stringify({ recaptchaSiteKey: 'site-key', recaptchaDisabled: { login: false } }).replace(/"/g, '"'); + const server = createServer((req: IncomingMessage, res: ServerResponse) => { + requests.push(`${req.method} ${req.url}`); + req.resume(); + if (req.method === 'GET' && req.url === '/login') { + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(`
`); + return; + } + if (req.method === 'POST' && req.url === '/login') { + res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' }); + res.end(JSON.stringify({ errorReason: 'cannot_verify_user_not_robot', message: { text: 'Sorry, we could not verify that you are not a robot.' } })); + return; + } + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('not found'); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + assert(address && typeof address === 'object'); + return { + baseUrl: `http://127.0.0.1:${address.port}`, + requests, + close: () => new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))), + }; +} + +const CAPTCHA_MESSAGE = /requires a captcha for password sign-in, which olcli cannot complete\. Sign in with `olcli auth --browser`, or paste a session cookie with `olcli auth --cookie`\./; + +test('auth with a password refused by reCAPTCHA names the browser sign-in and never prompts without a terminal', async () => { + const mock = await captchaOverleaf(); + try { + const env = { ...freshHome(), OVERLEAF_BASE_URL: mock.baseUrl }; + // --password *** used here because a hidden prompt needs a terminal; this is the scripted case. + const result = await olcli(['auth', '--email', 'me@example.com', '--password', 'pw'], { env }); + assert.equal(result.status, 1, result.stdout + result.stderr); + assert.match(result.stdout + result.stderr, CAPTCHA_MESSAGE); + assert.doesNotMatch(result.stdout + result.stderr, /\[Y\/n\]/); + assert.equal(mock.requests.filter((r) => r === 'POST /login').length, 1); + } finally { + await mock.close(); + } +}); + +test('commands that fall back to OVERLEAF_EMAIL/OVERLEAF_PASSWORD report the captcha, without a question', async () => { + const mock = await captchaOverleaf(); + try { + const env = { ...freshHome(), OVERLEAF_BASE_URL: mock.baseUrl, OVERLEAF_EMAIL: 'me@example.com', OVERLEAF_PASSWORD: 'pw' }; + const result = await olcli(['list'], { env }); + assert.equal(result.status, 1, result.stdout + result.stderr); + assert.match(result.stdout + result.stderr, CAPTCHA_MESSAGE); + assert.doesNotMatch(result.stdout + result.stderr, /\[Y\/n\]/); + } finally { + await mock.close(); + } +}); + +test('remote helper with password credentials refused by reCAPTCHA prints the captcha message', async () => { + const mock = await captchaOverleaf(); + try { + const result = await run( + 'remote-helper.ts', + ['origin', `${mock.baseUrl}/project/${PROJECT_ID}`], + { input: 'capabilities\n\nimport refs/heads/main\n\n', env: { ...freshHome(), GIT_DIR: join(home, 'captcha.git'), OVERLEAF_EMAIL: 'me@example.com', OVERLEAF_PASSWORD: 'pw' } }, + ); + assert.equal(result.status, 1, result.stderr); + assert.match(result.stderr, /^fatal: .*requires a captcha for password sign-in/m); + assert.match(result.stderr, CAPTCHA_MESSAGE); + } finally { + await mock.close(); + } +}); + +test('auth status warns about password credentials on overleaf.com, not on a self-hosted URL', async () => { + // overleaf.com: the warning comes from the URL alone. The sign-in attempt is + // pointed at a dead proxy so the test never reaches the network. + const env = { + ...freshHome(), + OVERLEAF_BASE_URL: 'https://www.overleaf.com', + OVERLEAF_EMAIL: 'me@example.com', + OVERLEAF_PASSWORD: 'pw', + HTTPS_PROXY: 'http://127.0.0.1:9', + OVERLEAF_TIMEOUT: '2000', + }; + const text = await olcli(['auth', 'status'], { env }); + assert.equal(text.status, 1, text.stdout + text.stderr); + assert.match(text.stdout, /Warning\s+overleaf\.com requires a captcha for password sign-in, which olcli cannot complete\. Sign in with: olcli auth --browser/); + const json = await olcli(['auth', 'status', '--json'], { env }); + const parsed = JSON.parse(json.stdout); + assert.equal(parsed.credentialSource, 'OVERLEAF_EMAIL/OVERLEAF_PASSWORD'); + assert.equal(parsed.warnings.length, 1); + assert.match(parsed.warnings[0], /overleaf\.com requires a captcha/); + + const mock = await captchaOverleaf(); + try { + const selfHosted = { ...freshHome(), OVERLEAF_BASE_URL: mock.baseUrl, OVERLEAF_EMAIL: 'me@example.com', OVERLEAF_PASSWORD: 'pw' }; + const result = await olcli(['auth', 'status', '--json'], { env: selfHosted }); + const report = JSON.parse(result.stdout); + assert.deepEqual(report.warnings, []); + assert.match(report.error, /requires a captcha for password sign-in/); + const plain = await olcli(['auth', 'status'], { env: selfHosted }); + assert.doesNotMatch(plain.stdout, /Warning/); + } finally { + await mock.close(); + } + + const cookie = await olcli(['auth', 'status', '--json'], { env: { ...freshHome(), OVERLEAF_BASE_URL: 'https://www.overleaf.com', OVERLEAF_SESSION: 'x', HTTPS_PROXY: 'http://127.0.0.1:9', OVERLEAF_TIMEOUT: '2000' } }); + assert.deepEqual(JSON.parse(cookie.stdout).warnings, []); +}); diff --git a/test/client.test.ts b/test/client.test.ts index 968d931..6f3787d 100644 --- a/test/client.test.ts +++ b/test/client.test.ts @@ -1,7 +1,8 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; -import { MAX_RETRY_AFTER_MS, OverleafClient, resolveCommentConcurrency, retryDelayMs } from '../src/client.js'; +import { MAX_RETRY_AFTER_MS, OverleafClient, isCaptchaRejection, loginPageRequiresCaptcha, resolveCommentConcurrency, retryDelayMs } from '../src/client.js'; +import { CaptchaRequiredError, HttpStatusError } from '../src/errors.js'; interface CapturedRequest { method?: string; @@ -427,3 +428,157 @@ test('a 429 with Retry-After: 3600 waits at most 60 seconds, not an hour', async await new Promise(resolve => server.close(resolve)); } }); + +// ─── Password sign-in refused by reCAPTCHA ─── +// +// Shapes measured against www.overleaf.com: the login page carries +// `recaptchaDisabled: { login: false }` and a site key in ol-ExposedSettings +// and loads recaptcha/api.js; a form post without a captcha token is answered +// with HTTP 400, JSON, `errorReason: "cannot_verify_user_not_robot"`, before +// the credentials are checked. + +const CAPTCHA_SETTINGS = JSON.stringify({ isOverleaf: true, recaptchaSiteKey: 'site-key', recaptchaDisabled: { login: false, passwordReset: false, register: false, addEmail: false } }); +const NO_CAPTCHA_SETTINGS = JSON.stringify({ isOverleaf: false, recaptchaDisabled: { login: true, passwordReset: true, register: true, addEmail: true } }); +const CAPTCHA_REJECTION = { errorReason: 'cannot_verify_user_not_robot', message: { text: 'Sorry, we could not verify that you are not a robot. Please check that Google reCAPTCHA is not being blocked by an ad blocker or firewall.' } }; + +function loginPageHtml(options: { settings?: string; script?: boolean }): string { + const attr = (v: string) => v.replace(/&/g, '&').replace(/"/g, '"'); + return '' + + (options.settings ? `` : '') + + '' + + (options.script ? '' : '') + + '
'; +} + +async function withLoginServer( + page: string, + answer: { status: number; contentType: string; body: string }, + run: (baseUrl: string, posts: string[]) => Promise +): Promise { + const posts: string[] = []; + const server = createServer(async (req: IncomingMessage, res: ServerResponse) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + if (req.method === 'GET' && req.url === '/login') { + res.writeHead(200, { 'Content-Type': 'text/html', 'Set-Cookie': 'overleaf_session2=anon; Path=/' }); + res.end(page); + return; + } + if (req.method === 'POST' && req.url === '/login') { + posts.push(Buffer.concat(chunks).toString('utf-8')); + res.writeHead(answer.status, { 'Content-Type': answer.contentType }); + res.end(answer.body); + return; + } + res.writeHead(404); + res.end(); + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + assert(address && typeof address === 'object'); + try { + await run(`http://127.0.0.1:${address.port}`, posts); + } finally { + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } +} + +test('password login: the measured reCAPTCHA rejection becomes CaptchaRequiredError', async () => { + await withLoginServer( + loginPageHtml({ settings: CAPTCHA_SETTINGS, script: true }), + { status: 400, contentType: 'application/json; charset=utf-8', body: JSON.stringify(CAPTCHA_REJECTION) }, + async (baseUrl, posts) => { + const host = new URL(baseUrl).host; + await assert.rejects( + () => OverleafClient.fromPasswordLogin('me@example.com', 'right-password', baseUrl), + (error: unknown) => { + assert.ok(error instanceof CaptchaRequiredError); + assert.equal(error.status, 400); + assert.equal(error.message, `${host} requires a captcha for password sign-in, which olcli cannot complete. Sign in with \`olcli auth --browser\`, or paste a session cookie with \`olcli auth --cookie\`.`); + return true; + } + ); + assert.equal(posts.length, 1, 'exactly one sign-in attempt'); + } + ); +}); + +test('password login: the captcha rejection is recognized even when the page shows no markers', async () => { + await withLoginServer( + loginPageHtml({}), + { status: 400, contentType: 'application/json', body: JSON.stringify(CAPTCHA_REJECTION) }, + async (baseUrl) => { + await assert.rejects(() => OverleafClient.fromPasswordLogin('me@example.com', 'pw', baseUrl), CaptchaRequiredError); + } + ); +}); + +test('password login: a bare 400 on a login page with reCAPTCHA on for login is a captcha error', async () => { + for (const page of [loginPageHtml({ settings: CAPTCHA_SETTINGS }), loginPageHtml({ script: true })]) { + await withLoginServer(page, { status: 400, contentType: 'text/plain', body: 'Bad Request' }, async (baseUrl) => { + await assert.rejects(() => OverleafClient.fromPasswordLogin('me@example.com', 'pw', baseUrl), CaptchaRequiredError); + }); + } +}); + +test('password login: without reCAPTCHA a bare 400 keeps the generic HTTP error', async () => { + await withLoginServer( + loginPageHtml({ settings: NO_CAPTCHA_SETTINGS }), + { status: 400, contentType: 'text/plain', body: 'Bad Request' }, + async (baseUrl) => { + await assert.rejects( + () => OverleafClient.fromPasswordLogin('me@example.com', 'pw', baseUrl), + (error: unknown) => { + assert.ok(!(error instanceof CaptchaRequiredError)); + assert.ok(error instanceof HttpStatusError); + assert.equal(error.status, 400); + assert.equal(error.action, 'Password login failed'); + return true; + } + ); + } + ); +}); + +test('password login: a wrong password keeps its old message, also on a page with reCAPTCHA', async () => { + // A JSON answer with a reason of its own is not second-guessed with page markers. + await withLoginServer( + loginPageHtml({ settings: CAPTCHA_SETTINGS, script: true }), + { status: 401, contentType: 'application/json', body: JSON.stringify({ message: { type: 'error', text: 'Your email or password is incorrect.' } }) }, + async (baseUrl) => { + await assert.rejects( + () => OverleafClient.fromPasswordLogin('me@example.com', 'wrong', baseUrl), + (error: unknown) => { + assert.ok(!(error instanceof CaptchaRequiredError)); + assert.ok(error instanceof HttpStatusError); + assert.equal(error.message, 'Password login failed (HTTP 401)'); + return true; + } + ); + } + ); + // An HTML login form as the answer is the old "may be incorrect" case. + await withLoginServer( + loginPageHtml({ settings: NO_CAPTCHA_SETTINGS }), + { status: 200, contentType: 'text/html', body: loginPageHtml({}) }, + async (baseUrl) => { + await assert.rejects( + () => OverleafClient.fromPasswordLogin('me@example.com', 'wrong', baseUrl), + /^Error: Password login failed\. Email or password may be incorrect\.$/ + ); + } + ); +}); + +test('loginPageRequiresCaptcha and isCaptchaRejection read the measured shapes', () => { + assert.equal(loginPageRequiresCaptcha(loginPageHtml({ settings: CAPTCHA_SETTINGS })), true); + assert.equal(loginPageRequiresCaptcha(loginPageHtml({ script: true })), true); + assert.equal(loginPageRequiresCaptcha(loginPageHtml({ settings: NO_CAPTCHA_SETTINGS })), false); + // recaptchaDisabled.login is the authority when present, even with the script on the page. + assert.equal(loginPageRequiresCaptcha(loginPageHtml({ settings: NO_CAPTCHA_SETTINGS, script: true })), false); + assert.equal(loginPageRequiresCaptcha(loginPageHtml({})), false); + assert.equal(isCaptchaRejection(JSON.stringify(CAPTCHA_REJECTION)), true); + assert.equal(isCaptchaRejection(JSON.stringify({ message: { text: 'Your email or password is incorrect.' } })), false); + assert.equal(isCaptchaRejection(''), false); + assert.equal(isCaptchaRejection(''), false); +}); diff --git a/test/help.test.ts b/test/help.test.ts index 6847935..669a150 100644 --- a/test/help.test.ts +++ b/test/help.test.ts @@ -5,7 +5,7 @@ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { colorDisabled, icon, isInteractive } from '../src/term.js'; +import { colorDisabled, hasUsableWidth, icon, isInteractive } from '../src/term.js'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); const SNAPSHOT = join(ROOT, 'test', 'snapshots', 'root-help.txt'); @@ -88,3 +88,9 @@ test('spinner results use words, not symbols, when stderr is not a terminal', () assert.equal(result.status, 1); assert.doesNotMatch(result.stderr + result.stdout, /[\u2714\u2716\u26a0\u2139]/); }); + +test('a terminal that reports a width of 0 gets no spinner animation', () => { + assert.equal(hasUsableWidth({ columns: 0 }), false); + assert.equal(hasUsableWidth({ columns: 80 }), true); + assert.equal(hasUsableWidth({}), true); +}); diff --git a/test/mcp.test.ts b/test/mcp.test.ts index b2a1dc7..bf1781b 100644 --- a/test/mcp.test.ts +++ b/test/mcp.test.ts @@ -727,3 +727,12 @@ test('every registered tool is documented in SKILL.md and docs/MCP.md', async () assert.deepEqual(missing, [], `${doc} does not mention: ${missing.join(', ')}`); } }); + +test('a password sign-in refused by reCAPTCHA reaches the agent as the captcha message', async () => { + const { CaptchaRequiredError } = await import('../src/errors.js'); + const h = await connect(async () => { throw new CaptchaRequiredError('www.overleaf.com', 400); }); + const result = await h.call('list_projects', {}); + assert.equal(result.isError, true); + assert.match(result.text[0], /^Error: www\.overleaf\.com requires a captcha for password sign-in, which olcli cannot complete\. Sign in with `olcli auth --browser`, or paste a session cookie with `olcli auth --cookie`\./); + await h.close(); +}); diff --git a/test/snapshots/root-help.txt b/test/snapshots/root-help.txt index f65f344..fe74b52 100644 --- a/test/snapshots/root-help.txt +++ b/test/snapshots/root-help.txt @@ -52,7 +52,9 @@ Help: Environment: OVERLEAF_SESSION session cookie (instead of olcli auth) OVERLEAF_EMAIL, OVERLEAF_PASSWORD - password login when no session cookie works + password login when no session cookie works; + self-hosted servers without reCAPTCHA only + (overleaf.com: olcli auth --browser) OVERLEAF_BASE_URL instance URL, like --base-url OVERLEAF_COOKIE_NAME session cookie name, like --cookie-name OVERLEAF_TIMEOUT HTTP timeout in milliseconds, like --timeout