puppeteer-extra-plugin-recaptcha: Write a Provider Function

puppeteer-extra-plugin-recaptcha - puppeteer-extra-plugin-recaptcha: Write a Provider Function

The plugin puppeteer-extra-plugin-recaptcha can use CapSkip as its solver without a hosts file edit or a certificate, because it accepts a provider function. You write about 45 lines that call solver.recaptcha() from the capskip package and hand the token back in the shape the plugin expects. After that, page.solveRecaptchas() finds the widget, calls your function, types the token into the page and runs the page callback. The solving happens in the CapSkip Puppeteer solver on a Windows PC you own, for a flat license, so a retry costs no fee.

What you need

  • A Windows PC with CapSkip installed, following the setup guide. CapSkip answers on 127.0.0.1:8080 on my PC, and I kept every task away from it. Every solve below ran against a stand-in of mine that speaks in.php and res.php, so each time and refusal is the stand-in’s rule, not CapSkip behavior.
  • Node.js 22.12.0 at the least, because puppeteer 25.18.1 declares that in its engines field. The capskip package 1.8.0 asks for 18, puppeteer-extra 3.3.6 for 8 and the plugin for 9.11.2. On 20.11.1, npm only warned, and puppeteer-extra then printed Puppeteer is missing, because requiring Puppeteer 25 failed with ERR_REQUIRE_ESM.
  • The packages from the first command below: puppeteer-extra-plugin-recaptcha 3.6.8, puppeteer-extra 3.3.6, puppeteer 25.18.1 (Chrome 157.0.8103.78) and capskip 1.8.0.
  • A page with a reCAPTCHA you may automate. My test page loaded the real reCAPTCHA script with the v2 test key from the reCAPTCHA FAQ, and that script talks to Google by itself, as on any page. I sent no token to Google and called no verification endpoint. The tokens came from my stand-in and went only to it.
  • An address for CapSkip, which you choose in the connection settings section of the setup guide. In Local mode CapSkip answers on 127.0.0.1 and nowhere else; Server mode also answers other machines.

The plugin is old: the npm registry shows 3.6.8 as published on 2023-03-01, with nothing newer. On Puppeteer 25.18.1 and Chrome 157 it still loaded and raised no warning in my runs.

# In PowerShell, in a new empty folder
npm init -y
npm install puppeteer puppeteer-extra puppeteer-extra-plugin-recaptcha capskip

Why the built-in provider cannot reach CapSkip

The plugin ships one provider. It is a small client on the https module of Node.js with the address of its own service written into the file, so no option moves it to 127.0.0.1:8080. CapSkip has a route for tools like that: pick a service in the Service Emulator setting and add a hosts file entry, and the app answers on port 443 with a certificate under a root certificate it installs in Windows. That edits system files and the trust store, so I did not run it. Per the Node.js command line docs, Node.js trusts its bundled roots plus the PEM file named by NODE_EXTRA_CA_CERTS, read only at process start. The same docs list a flag called use-system-ca, written with two leading hyphens and added in v23.8.0, and a NODE_USE_SYSTEM_CA variable, added in v24.6.0 and v22.19.0, which add the system store, the Windows one here. I tested none of these. A provider function needs none of it.

Step 1: write the provider function

The plugin calls the function as fn(captchas, token, opts), with the plugin itself as this. It reads two things back: result.solutions, one entry for each captcha it can type into the page, and an optional result.error. The fields of each captcha that matter, from the plugin source and from what it gave my function:

Field of a found captchaWhat it holdsWhat the function does with it
captcha._vendorrecaptcha or hcaptchaPicks the capskip method
captcha.idThe name the plugin gives the widget, cut from its iframe nameCopied into the solution, so the plugin finds the widget again
captcha.sitekeyThe key of the widgetFirst argument of the call
captcha.urlThe full page address, query string includedSecond argument of the call
captcha.isEnterpriseTrue when the iframe address has an enterprise pathThe enterprise option
captcha.isInvisibleTrue for size=invisible in the iframe addressThe invisible option
captcha._typecheckbox, invisible or scoreA score widget goes out as version v3
captcha.sThe data-s value, or nullSent only when present
captcha.actionThe action of a v3 widget, if the page set oneSent for score widgets only

A solution carries the captcha id and the token as solution.text. The hCaptcha half of the plugin types only solutions whose solution.hasSolution is true, so set it. Save the next block as capskip-provider.js. If CapSkip runs on another machine, change host to that machine.

// capskip-provider.js: a provider function for puppeteer-extra-plugin-recaptcha.
const { CapSkip } = require("capskip");

// Local mode. For CapSkip on another machine, use its address as the host.
const solver = new CapSkip({ host: "127.0.0.1", port: 8080 });

// Turn what the plugin found into options for the capskip package.
function recaptchaOptions(c) {
  const options = { enterprise: c.isEnterprise ? 1 : 0 };
  if (c._type === "score") {
    options.version = "v3"; // a hidden widget with no challenge frame
    if (c.action) options.action = c.action;
  } else {
    if (c.isInvisible) options.invisible = 1;
    if (c.s) options["data-s"] = c.s;
  }
  return options;
}

async function solveOne(c) {
  const solution = { _vendor: c._vendor, id: c.id, provider: "capskip", requestAt: new Date() };
  try {
    const result = c._vendor === "hcaptcha"
      ? await solver.hcaptcha(c.sitekey, c.url)
      : await solver.recaptcha(c.sitekey, c.url, recaptchaOptions(c));
    if (!result.code) throw new Error("CapSkip answered with an empty token");
    solution.providerCaptchaId = result.captchaId;
    solution.text = result.code;
    solution.hasSolution = true; // the hCaptcha part of the plugin reads it
  } catch (err) {
    solution.error = `${err.name}: ${err.message}`;
  }
  solution.responseAt = new Date();
  solution.duration = (solution.responseAt - solution.requestAt) / 1000;
  return solution;
}

// The plugin calls this as fn(captchas, token, opts), with the plugin as this.
async function capskipProvider(captchas) {
  const all = await Promise.all(captchas.map(solveOne));
  // Hand back only the solved ones: the plugin types every solution it gets into the page.
  return { solutions: all.filter((s) => s.hasSolution), error: all.find((s) => s.error)?.error };
}

module.exports = { capskipProvider, solver };

A v2 task that carries an action is refused before any request, with ValidationException, so the function sends the action for score widgets only. The recaptcha method takes no user agent either, so the headless user agent never reaches CapSkip. On a hand-made page with an enterprise widget, an invisible widget with an open challenge frame, a score widget with an action and a widget with a data-s value, the function sent enterprise 1, invisible 1, version v3 with the action, and the data-s value. A hand-made hCaptcha entry went out as the hcaptcha method. I wrote that page, so the enterprise and v3 scripts of Google stay untested.

Step 2: plug it in and solve

Save this as signup.js beside the first file. Set SIGNUP_URL to your own page and the submit selector to your own button.

// signup.js: puppeteer-extra, the reCAPTCHA plugin and CapSkip as its provider.
const puppeteer = require("puppeteer-extra");
const RecaptchaPlugin = require("puppeteer-extra-plugin-recaptcha");
const { capskipProvider } = require("./capskip-provider");

const SIGNUP_URL = "https://example.com/signup"; // a page with a reCAPTCHA you may automate
const SIZE = 2; // tabs at once: keep it at or below Max. Threads for reCAPTCHA in CapSkip

puppeteer.use(RecaptchaPlugin({
  provider: { fn: capskipProvider },
  visualFeedback: false,
  throwOnError: true,
}));

async function signUp(browser, url) {
  const page = await browser.newPage();
  try {
    await page.goto(url);
    const { captchas, solved } = await page.solveRecaptchas(); // throws on an error
    const entered = solved.filter((s) => s.isSolved).length;
    // An empty result is not an error to the plugin, so check the counts yourself.
    if (captchas.length === 0 || entered < captchas.length) {
      throw new Error(`found ${captchas.length} captchas, entered ${entered}`);
    }
    await Promise.all([page.waitForNavigation(), page.click("button[type=submit]")]);
    return await page.evaluate(() => document.body.innerText);
  } finally {
    await page.close();
  }
}

(async () => {
  const urls = process.argv.length > 2 ? process.argv.slice(2) : [SIGNUP_URL];
  const browser = await puppeteer.launch(); // headless, the default
  try {
    for (let i = 0; i < urls.length; i += SIZE) {
      const batch = urls.slice(i, i + SIZE);
      const results = await Promise.allSettled(batch.map((u) => signUp(browser, u)));
      results.forEach((r, j) => {
        console.log(batch[j], r.status === "fulfilled" ? r.value : `FAIL ${r.reason.message}`);
      });
    }
  } finally {
    await browser.close();
  }
})();
# PowerShell, in the same folder: one page, the address in SIGNUP_URL
node signup.js
# or several pages, SIZE at a time
node signup.js https://example.com/signup?a=1 https://example.com/signup?a=2

Set SIGNUP_URL first, because the example.com default prints a FAIL line saying found 0 captchas. Addresses after the file name replace it, and the script visits each. Against my stand-in site it printed the page address and then accepted, on Node.js 24.22.0 and 25.2.1. The stand-in site accepts a token its CapSkip issued, once. Eighteen runs took 5.9 to 7.9 seconds in total, with the stand-in ready after 2 seconds. The solve call itself returned after 3.8 seconds, because the SDK polls at 0, 0.25, 0.75, 1.75 and 3.75 seconds, and the stand-in was ready between the fourth poll and the fifth.

The call wraps three page methods that you can also run one by one, with the same result: findRecaptchas, getRecaptchaSolutions and enterRecaptchaSolutions. It returns this:

Key of the resultHoldsIn the run above
result.captchasThe widgets the plugin will solveOne checkbox widget
result.filteredWidgets it found and skipped, each with filteredReasonEmpty
result.solutionsWhat your function returnedOne entry, the token, the duration and a providerCaptchaId
result.solvedWhat it typed, with isSolved, responseElement and responseCallbackisSolved and responseElement true, responseCallback false because this page has no callback
result.errorA string when your function reports one, otherwise nothingNothing

Headless or headful made no difference: the default headless mode, the shell mode and headless set to false all got the form accepted. With visualFeedback on, the plugin put a CSS filter on the widget iframe, so I set it to false.

Options, failures and retries

What the options filter

Three options decide which widgets reach your function, and a fourth decides how errors come back. A skipped widget lands in result.filtered with the option named in filteredReason, and no task goes to CapSkip.

Option, default falseSkipsWhat I saw
solveInViewportOnlyCheckbox widgets outside the viewport (source: invisible ones are not tested)A widget below a 3000 pixel spacer: solved with false, skipped with true and no task sent
solveScoreBasedHidden widgets with no challenge frame, the shape of v3On the hand-made page: skipped by default, and with true the function got it with its action
solveInactiveChallengesInvisible widgets whose challenge popup is not activeWith the real script it never skipped one, see below
throwOnErrorNothing. It makes the plugin throw instead of returning an error stringSee the failure cases

An invisible v2 widget is a trap. With the real reCAPTCHA script and the test key, the plugin usually called the widget score based and skipped it when it looked straight after the page load: in 50 of 60 runs on Node.js 24.22.0 and 55 of 60 on 25.2.1, with the rest passing it as an invisible widget. After a 2 second wait it called the widget invisible, with an active challenge, in 10 of 10 runs on each version, and waiting for the challenge frame, as below, passed 30 of 30 on each. The plugin decides from whether that frame exists yet, and it appears a moment after the script runs. The page callback then submits the form, so the script waits for a result element instead of clicking. Make two edits in signUp, which passed three runs on each Node.js version:

// Edit 1: right after page.goto(url) and before page.solveRecaptchas()
await page.waitForSelector('iframe[src*="/recaptcha/api2/bframe"]'); // the challenge frame

// Edit 2: instead of the Promise.all line that clicks the button
await page.waitForSelector("#verdict"); // use your own success element: the page callback submitted the form

When your function fails

The plugin sets no timer around your function, so a silent CapSkip holds page.solveRecaptchas() until the capskip package gives up. The package default is 300 seconds (source), and the setup guide gives the reCAPTCHA row a Row Timeout of 250 seconds, so CapSkip should end a stuck solve first. With the recaptchaTimeout option at 5 and a stand-in that never answered, TimeoutException came after 7.80 seconds, and with 12 after 12.81 seconds, because the package checks its clock only after each wait (Node.js 24.22.0).

What the plugin does with a failure depends on what your function returns. I ran several shapes with throwOnError off and on. A provider error also prints a warning line to the console.

What the function doesthrowOnError falsethrowOnError true
Throws, or returns undefined, or returns no solutions keyresult.error holds the text, nothing typedThe call throws, nothing typed
Returns an empty solutions array and no errorNo error and nothing typed: solved is emptyDoes not throw either
Returns a solution that has an error and no textTypes the word undefined into the response field, runs the callback with undefined and reports isSolved trueThrows before it types
The function above: solved ones only, error text for the restTypes the solved ones, and result.error holds the first failure: three of four widgets were filledThrows before it types, so the solved tokens of that call are lost: on the hand-made page, with one of four widgets failing, three tokens were wasted

The thrown message starts with Error: Error:, because the plugin wraps its own error text again. The empty array row is why signup.js compares the counts itself, and the third row is why the function drops failed solutions before it returns. ERROR_CAPTCHA_UNSOLVABLE and ERROR_GOOGLEKEY, simulated by the stand-in, came out as ApiException text in result.error. A solution with an error and no text, or with an unknown id, gave an object, so the text ended in [object Object].

One token, one submit: retries and tabs

A reCAPTCHA token is good once, and briefly; see the token expiration guide. The plugin has no retry and no cache. Calling page.solveRecaptchas() twice on one page sent two tasks to my stand-in, the second token replaced the first, and the stand-in site accepted one form post. So solve right before the click, and after a refused form post load the page again and solve again.

Tabs call your function at the same time, and so do the widgets of one page. With SIZE edited to 4, four tabs put four tasks in flight at the stand-in and took 6.2 to 6.6 seconds. With SIZE at 2, as written, no more than 2 ran at once and the same tabs took 10.5 to 11.0 seconds, and with SIZE at 1 they took 18.4 to 19.0. Six tabs with SIZE 3 peaked at 3 (Node.js 24.22.0 and 25.2.1). A page with four widgets sent four tasks at once. The setup guide describes Max. Threads in the reCAPTCHA row of CapSkip as how many tasks it solves at once, with the others waiting up to the Wait Timeout, a queue I did not test. The capskip clock starts at the submit, so a wait counts against it: set SIZE no higher than Max. Threads. For a crawl with a queue and retry limits, see the puppeteer-cluster guide.

Server mode: the plugin on one machine, CapSkip on another

CapSkip can run as a server on a Windows machine you control. Point host in capskip-provider.js at that machine, then switch the mode in the connection settings, a step for which the setup guide says CapSkip must run as administrator. No second machine took part in my tests. Starting Server mode makes CapSkip add a rule that lets every address reach its port. To narrow that, add a Windows Firewall block rule for the addresses you do not expect, because a block rule beats an allow rule. Also turn on API Key Validation in CapSkip, and pass your own key as the apiKey option of the CapSkip constructor.

Common errors

A row marked seen was reproduced against my stand-in. The CapSkip error codes are listed in the API docs on the CapSkip site.

What you seeCauseFix
Please provide a solution provider to the plugin.The plugin got neither provider.fn nor a token (seen)Pass provider: { fn: capskipProvider }
found 0 captchasThe widget is not drawn yet, it sits in an iframe, or it is an invisible widget looked at before its challenge frame exists (see above). The plugin waits up to 10 seconds for a client only when a reCAPTCHA script tag is already on the page (source)Wait for the widget first. For an iframe, the README says to call frame.solveRecaptchas() on each child frame (not tested)
The widget is in result.filteredAn option skipped it (seen)Read filteredReason and change that option
ValidationExceptionThe capskip package refused the options before any request (seen)The message names the option. Do not retry
ERROR_CAPTCHA_UNSOLVABLEThe solve failed (simulated by the stand-in)Load the page and solve again
ERROR_GOOGLEKEYCapSkip did not accept the sitekey (simulated)Check the key the plugin found. A retry fails the same way
ERROR_KEY_DOES_NOT_EXISTAPI Key Validation is on in CapSkip and the client sent the default key (stand-in rule)Pass your own key as apiKey in the CapSkip constructor
TimeoutExceptionNo token before recaptchaTimeout, noticed after the next wait (seen)Look at the CapSkip Monitor, or raise the limit
NetworkException saying connect ECONNREFUSEDNothing listens at that host and port (seen)Start CapSkip, or fix host and port
The response field says undefinedA custom function returned a solution without text (seen)Return only solved entries
A form post the site refusesA token used before, or an older oneSolve once per submit, right before the click

FAQ

Is puppeteer-extra-plugin-recaptcha still maintained?

Its last npm release is 3.6.8 from 2023-03-01 (see the project README). It worked in my runs on Puppeteer 25.18.1 against one page with the real script. If detection breaks, read the sitekey yourself and call solver.recaptcha() directly.

Does the plugin handle reCAPTCHA v3?

It can hand your function a score based widget when solveScoreBased is on, and the function above sends it as version v3. I could not test that against a real v3 page, since I used only the v2 test key. A v3 page usually reads its token from its own script call, not a response field, so the direct route in the reCAPTCHA v3 in Node.js guide is safer.

Does this work with playwright-extra too?

The package lists playwright-extra as an optional peer dependency. I tested only Puppeteer, and the provider function has no Puppeteer code in it.

With puppeteer-extra-plugin-recaptcha the only new part is one provider function, and it hands every widget to a local captcha solver that runs on your own Windows PC and bills nothing per solve. For other CAPTCHA types from Node.js, see the Node.js CAPTCHA solver page, and for the browser side the Puppeteer CAPTCHA solver page.