SurSolver

BlogFriendly Captcha solver API: sitekey, version and token

Friendly Captcha solver API: sitekey, version and token

· Updated · 9 min read

By the end of this post you will be able to read the sitekey and widget generation off a page that uses Friendly Captcha, create a task with the correct scriptUrl, and submit the returned token in the field the site expects, with the widget script kept out of the way. The overview of the captcha itself is on the Friendly Captcha solver page; this post goes deep on the request, the two widget generations and the injection step.

What the solve returns

Friendly Captcha does not show an image or a checkbox. The visitor's browser computes a cryptographic proof-of-work puzzle in the background and the widget turns the result into a token. So the thing you buy from a solver is that token: a single string.

The solution of a finished task contains token. userAgent is a required task input, not a result key; submit with the same value you supplied. There is no puzzle and no challenge payload to relay anywhere.

The site checks the token on its own server. Treat a token as bound to the sitekey and the site it was created for, and as single-use: put it into the request that submits the form right away, and never reuse it.

Widget generation 1 and generation 2

The widget exists in two generations. They load different script files, write the token into differently named fields and produce differently shaped tokens, so you have to know which one the page runs before you place anything.

v1 v2
Script file widget.module.min.js or widget.min.js, under friendly-challenge@X.Y.Z/ site.min.js, under @friendlycaptcha/sdk@X.Y.Z/
Default token field frc-captcha-solution frc-captcha-response
Sitekey visible in data-sitekey and the puzzle?sitekey= request data-sitekey, or the page source and network traffic

A v1 token in the v2 field, or the other way round, fails. The version in X.Y.Z is the client version sent in the x-frc-client request header of the widget's own requests.

Find the sitekey and script URLs

Open the page in your browser, then open DevTools.

  1. In the Elements panel, search for data-sitekey. The widget element carries the sitekey in that attribute.
  2. In the Network tab, look for the widget script. widget.module.min.js or widget.min.js means v1, site.min.js means v2. Copy the full script URL.
  3. On v1 you can also filter for puzzle?sitekey= and read the sitekey from that request. Open any widget request and read the x-frc-client header for the version number.
  4. Copy the page URL from the address bar, including the exact path of the form. That is websiteURL.

The Friendly Captcha widget div with its data-sitekey attribute, selected in the DevTools Elements panel on the official friendly-challenge 0.9.17 demo page

Copy the widget script URL from the live page and send it as the required scriptUrl. A URL typed from memory or taken from an old cache can point at a different SDK build. The script URL identifies the widget generation — widget.module.min.js or widget.min.js is v1, site.min.js is v2 — so the solver knows which puzzle format to produce; the task has no separate version field, and no fallback-script field.

If you are unsure which of the two widgets a site runs, identify the captcha and extract its parameters walks through the DevTools routine for every type.

Send the first request

The default task name is FriendlyCaptchaTokenProxyLess. It requires websiteURL, websiteKey and one scriptUrl: the full public HTTP(S) URL of the widget script the page loads. Send userAgent in the task and replay with the same value.

snippet.powershell
$body = @{
  clientKey = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
  task = @{
    type = 'FriendlyCaptchaTokenProxyLess'
    websiteURL = 'https://example.com/signup'
    websiteKey = 'FCMGD8BOO9CFF3RA'
    scriptUrl = 'https://example.com/assets/site.min.js'
  }
} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri 'https://api.sursolver.com/createTask' -ContentType 'application/json' -Body $body

An accepted task answers with an id and idle:

snippet.json
{ "errorId": 0, "taskId": "tsk_9c1f4e2a7b0d5e3f81a62c47", "status": "idle" }

Poll getTaskResult with your clientKey and the taskId every 3 seconds. While the task is queued or being solved the answer is {"errorId":0,"status":"processing"}; when it finishes it is status: "ready" with the solution. Every parameter is listed by the public catalog (GET /v1/task-types) and the API reference.

Two rules matter in code:

  • API errors come back as HTTP 200 with errorId: 1 and an errorCode such as ERROR_FAILED or ERROR_ZERO_BALANCE. Branch on errorId, and stop polling on the first one: a failed task does not change again.
  • A non-200 status or a body without errorId is a transport failure, not an answer about your task.

Results stay readable for 30 minutes from creation, so store the token if you cannot use it at once. The task lifecycle and errors guides have the full list.

Use the proxy variant only when needed

Start with the proxyless name. Send the page URL, sitekey and widget script URL as scriptUrl; no caller proxy is needed.

If the site refuses tokens that were solved without a proxy, switch the type to FriendlyCaptchaToken and pass your own proxy in task.proxy. That name requires proxy details: a request without them is rejected with ERROR_INVALID_REQUEST. A four-part string is always read as user:password:host:port, so convert strings written in another order before you send them:

snippet.json
{
  "type": "FriendlyCaptchaToken",
  "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36",
  "websiteURL": "https://example.com/signup",
  "websiteKey": "FCMGD8BOO9CFF3RA",
  "scriptUrl": "https://example.com/assets/site.min.js",
  "proxy": "user:password:203.0.113.10:8000"
}

The formats and the split proxyType / proxyAddress / proxyPort fields are on the proxies guide; the thinking behind choosing a proxy is in proxies for captcha solving.

Block the widget script

This is the step that most often decides whether a token is accepted. Load the page in your automated browser with the request for the Friendly Captcha widget script aborted, then set the token. If the widget script is running while you inject the token, the token is likely to be rejected.

In Playwright you do this with page.route() before page.goto(). Match on the part of the script URL you copied from the Network tab, for example friendly-challenge on v1 or @friendlycaptcha/sdk on v2; a regular expression avoids trouble with query strings. If the site hosts the file itself, match its own path instead.

Inject the token

Check the widget element before you assume a field name:

  • The default field is frc-captcha-solution on v1 and frc-captcha-response on v2.
  • If the element has a data-solution-field-name attribute, use that name instead.
  • If it has a data-callback attribute, call that function with the token, for example doneCallback(token), instead of or in addition to filling the field.

The Friendly Captcha widget div with data-solution-field-name and data-callback attributes, selected in the DevTools Elements panel on a local demo page running the official friendly-challenge 0.9.17 widget script

Because the widget script is blocked, the hidden field may not exist yet, so create it in the widget's form when it is missing. Submit the parent form afterwards. A form that posts through JavaScript usually wants the data-callback route instead; how to submit a captcha token covers both.

Run it with Playwright

The generated script has constants at the top for CLIENT_KEY, TARGET_URL, SUBMIT_SELECTOR and SUCCESS_SELECTOR; SITE_KEY and SCRIPT_URL are optional overrides.

friendlycaptcha-playwright.js
// friendlycaptcha-playwright.js - solve FriendlyCaptcha on the live page and submit the form
// with the token.
// Install: npm install playwright && npx playwright install chromium
// Run: node friendlycaptcha-playwright.js

const { chromium } = require('playwright');
const { setTimeout: sleep } = require('node:timers/promises');

// Your SurSolver API key.
const CLIENT_KEY = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// The page that renders the widget, with its path and query string.
const TARGET_URL = 'https://example.com/page';
// Optional, read from the page when empty: data-sitekey on the .frc-captcha element.
const SITE_KEY = '';
// Optional, read from the page when empty: the widget script URL (widget.min.js or
// widget.module.min.js for v1, site.min.js for v2).
const SCRIPT_URL = '';
// The User-Agent the solve runs with; send the result with this same user agent.
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36';
// The control that submits the form.
const SUBMIT_SELECTOR = '.PASTE_SUBMIT_SELECTOR';
// A selector that matches only after the site accepted the result.
const SUCCESS_SELECTOR = '.PASTE_ACCEPTED_SELECTOR';

const API = 'https://api.sursolver.com';
const POLL_ATTEMPTS = 60;

// API errors are HTTP 200 with errorId 1; anything else is a transport failure.
async function call(path, body) {
  const res = await fetch(`${API}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json();
  if (data.errorId !== 0) throw new Error(`${data.errorCode}: ${data.errorDescription}`);
  return data;
}

async function solve(task) {
  const created = await call('/createTask', { clientKey: CLIENT_KEY, task });

  for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {
    const result = await call('/getTaskResult', {
      clientKey: CLIENT_KEY,
      taskId: created.taskId,
    });
    if (result.status === 'ready') return result.solution;
    await sleep(3000);
  }
  throw new Error(`task ${created.taskId} was not ready in ${POLL_ATTEMPTS} polls`);
}

// Optional task fields are sent only when they have a value.
function withoutEmpty(fields) {
  return Object.fromEntries(
    Object.entries(fields).filter(([, value]) => value !== undefined && value !== ''),
  );
}

// A value the page did not show must be pasted into its constant at the top.
function need(name, value) {
  if (value === undefined || value === null || value === '') {
    throw new Error(`Could not read ${name} from the page; fill in the ${name} constant.`);
  }
  return value;
}

// Opens the page once and reads what the solve needs from it.
async function readPage(browser) {
  const page = await browser.newPage({ userAgent: USER_AGENT });
  try {
    await page.goto(TARGET_URL, {
      waitUntil: 'domcontentloaded',
      timeout: 45000,
    });
    // The widget is often added after the page loads; give it a moment to appear.
    await page
      .waitForFunction(
        () =>
          !!document.querySelector('.frc-captcha[data-sitekey]')?.dataset.sitekey,
        undefined,
        { timeout: 10000 },
      )
      .catch(() => undefined);
    const dom = await page.evaluate(() => ({
      websiteKey: document.querySelector('.frc-captcha[data-sitekey]')?.dataset.sitekey,
      scriptUrl: [...document.scripts]
        .map((script) => script.src)
        .find((url) => /(widget|site)(\.module|\.compat)?\.min\.js/.test(url)),
    }));
    return {
      pageUrl: page.url(),
      ...dom,
    };
  } finally {
    await page.close();
  }
}

async function main() {
  const browser = await chromium.launch();
  try {
    const found = await readPage(browser);
    const solution = await solve({
      type: 'FriendlyCaptchaTokenProxyLess',
      websiteURL: found.pageUrl,
      websiteKey: need('websiteKey', SITE_KEY || found.websiteKey),
      scriptUrl: need('scriptUrl', SCRIPT_URL || found.scriptUrl),
      userAgent: USER_AGENT,
    });

    // Submit from a fresh session with the user agent the solve ran with.
    const context = await browser.newContext({ userAgent: USER_AGENT });
    const page = await context.newPage();
    // The widget script must not run again: it would replace the token with its own.
    await context.route(
      (url) => url.href === (SCRIPT_URL || found.scriptUrl),
      (route) => route.abort(),
    );
    await page.goto(found.pageUrl);

    const applied = await page.evaluate(
      ({ token, scriptUrl }) => {
        let filled = false;
        for (const name of ['frc-captcha-response', 'frc-captcha-solution']) {
          for (const field of document.querySelectorAll(`[name="${name}"]`)) {
            field.value = token;
            filled = true;
          }
        }
        if (!filled) {
          // The widget script did not run, so the hidden field does not exist yet.
          const anchor = document.querySelector('.frc-captcha');
          const form = anchor?.closest('form') ?? document.forms[0];
          if (form) {
            const field = document.createElement('input');
            field.type = 'hidden';
            const legacy = /\/widget(\.module)?\.min\.js/.test(scriptUrl ?? '');
            const name = anchor?.dataset.solutionFieldName;
            field.name = name ?? (legacy ? 'frc-captcha-solution' : 'frc-captcha-response');
            field.value = token;
            form.append(field);
            filled = true;
          }
        }
        const callback = document.querySelector('.frc-captcha')?.dataset.callback;
        if (callback && typeof window[callback] === 'function') {
          window[callback](token);
          filled = true;
        }
        return filled;
      },
      { token: solution.token, scriptUrl: SCRIPT_URL || found.scriptUrl },
    );
    if (!applied) {
      throw new Error('The page has no token field or callback; check how it passes the token.');
    }

    await page.click(SUBMIT_SELECTOR);
    await page.locator(SUCCESS_SELECTOR).first().waitFor({ timeout: 15000 });
    console.log('The site accepted the token.');
  } finally {
    await browser.close();
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

What it does: reads the sitekey and the widget script URL off the page, solves a FriendlyCaptchaTokenProxyLess task with both values, aborts that exact script request on a fresh session so the widget cannot run again and overwrite the token, then fills frc-captcha-response and frc-captcha-solution fields, creates the version-correct hidden field inside the widget's form when the blocked script left none behind (naming it from data-solution-field-name when present), calls the data-callback function with the token, and clicks your submit control before waiting for the success selector.

In a local run against a page loading the real v2 SDK, the flow ended with a roughly 6.5 KB token in frc-captcha-response. The last mile — the site's own server checking the token with its secret — cannot be reproduced without that secret, so on your own target the check to make is the protected request succeeding after the submit, compared against the same form in a normal browser session.

Node.js

The plain-HTTP variant skips the page entirely: fill in the constants at the top and run node friendlycaptcha-node.js — Node 18 or newer, no packages. It solves FriendlyCaptchaTokenProxyLess from the page URL, the key and scriptUrl, then posts the form with the token in frc-captcha-response, presenting the task's required userAgent.

friendlycaptcha-node.js
// friendlycaptcha-node.js - solve FriendlyCaptcha and post the token with the form.
// Install: Node.js 18 or newer (no packages).
// Run: node friendlycaptcha-node.js

const { setTimeout: sleep } = require('node:timers/promises');

// Your SurSolver API key.
const CLIENT_KEY = 'sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// The page that renders the widget, with its path and query string.
const TARGET_URL = 'https://example.com/page';
// data-sitekey on the .frc-captcha element.
const SITE_KEY = 'YOUR_SITE_KEY';
// The widget script URL (widget.min.js or widget.module.min.js for v1, site.min.js for v2).
const SCRIPT_URL = 'https://example.com/challenge.js';
// The User-Agent the solve runs with; send the result with this same user agent.
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36';
// Current application session as a Cookie header value; used on form submission.
const SESSION_COOKIES = '';
// Where the page posts the form (the form action, or the request in DevTools, Network).
const FORM_URL = 'https://example.com/submit';
// The form's other fields as a JSON object, such as {"username":"demo"}.
const FORM_FIELDS = undefined;
// Text that appears only in a response the site accepted.
const SUCCESS_TEXT = 'PASTE_ACCEPTED_MARKER';

const API = 'https://api.sursolver.com';
const POLL_ATTEMPTS = 60;

// API errors are HTTP 200 with errorId 1; anything else is a transport failure.
async function call(path, body) {
  const res = await fetch(`${API}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  const data = await res.json();
  if (data.errorId !== 0) throw new Error(`${data.errorCode}: ${data.errorDescription}`);
  return data;
}

async function solve(task) {
  const created = await call('/createTask', { clientKey: CLIENT_KEY, task });

  for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {
    const result = await call('/getTaskResult', {
      clientKey: CLIENT_KEY,
      taskId: created.taskId,
    });
    if (result.status === 'ready') return result.solution;
    await sleep(3000);
  }
  throw new Error(`task ${created.taskId} was not ready in ${POLL_ATTEMPTS} polls`);
}

// Optional task fields are sent only when they have a value.
function withoutEmpty(fields) {
  return Object.fromEntries(
    Object.entries(fields).filter(([, value]) => value !== undefined && value !== ''),
  );
}

async function main() {
  const solution = await solve({
    type: 'FriendlyCaptchaTokenProxyLess',
    websiteURL: TARGET_URL,
    websiteKey: SITE_KEY,
    scriptUrl: SCRIPT_URL,
    userAgent: USER_AGENT,
  });

  // Send the token the way the page does; some sites name it differently or send JSON.
  // The solve ran with USER_AGENT; the submit presents the same one.
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': USER_AGENT,
    ...(SESSION_COOKIES ? { Cookie: SESSION_COOKIES } : {}),
  };
  const body = new URLSearchParams({
    ...(FORM_FIELDS ?? {}),
    ['frc-captcha-response']: solution.token,
  });
  const response = await fetch(FORM_URL, { method: 'POST', headers, body });
  const text = await response.text();
  if (!response.ok || !text.includes(SUCCESS_TEXT)) {
    throw new Error(`The site did not accept the result (HTTP ${response.status}).`);
  }
  console.log('The site accepted the result.');
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Python

pip install requests is the only dependency: the same constants, python friendlycaptcha-python.py, and the form post carries the token under the same field name. The data-callback route above is the one part a plain client cannot perform.

friendlycaptcha-python.py
# friendlycaptcha-python.py - solve FriendlyCaptcha and post the token with the form.
# Install: pip install requests
# Run: python friendlycaptcha-python.py

import time
from urllib.parse import urlsplit

import requests


# Your SurSolver API key.
CLIENT_KEY = "sur_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# The page that renders the widget, with its path and query string.
TARGET_URL = "https://example.com/page"
# data-sitekey on the .frc-captcha element.
SITE_KEY = "YOUR_SITE_KEY"
# The widget script URL (widget.min.js or widget.module.min.js for v1, site.min.js for v2).
SCRIPT_URL = "https://example.com/challenge.js"
# The User-Agent the solve runs with; send the result with this same user agent.
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36"
# Current application session as a Cookie header value; used on form submission.
SESSION_COOKIES = None
# Where the page posts the form (the form action, or the request in DevTools, Network).
FORM_URL = "https://example.com/submit"
# The form's other fields as a JSON object, such as {"username": "demo"}.
FORM_FIELDS = None
# Text that appears only in a response the site accepted.
SUCCESS_TEXT = "PASTE_ACCEPTED_MARKER"


API = "https://api.sursolver.com"
POLL_ATTEMPTS = 60


def call(path, body):
    # API errors are HTTP 200 with errorId 1; anything else is a transport failure.
    response = requests.post(f"{API}{path}", json=body, timeout=30)
    response.raise_for_status()
    data = response.json()
    if data["errorId"] != 0:
        raise RuntimeError(f'{data["errorCode"]}: {data["errorDescription"]}')
    return data


def solve(task):
    created = call("/createTask", {"clientKey": CLIENT_KEY, "task": task})
    for _ in range(POLL_ATTEMPTS):
        result = call("/getTaskResult", {"clientKey": CLIENT_KEY, "taskId": created["taskId"]})
        if result["status"] == "ready":
            return result["solution"]
        time.sleep(3)
    raise TimeoutError(f'task {created["taskId"]} was not ready in {POLL_ATTEMPTS} polls')


def main():
    session = requests.Session()
    if SESSION_COOKIES:
        for part in SESSION_COOKIES.split(";"):
            if "=" in part:
                name, value = part.strip().split("=", 1)
                session.cookies.set(name, value, domain=urlsplit(FORM_URL).hostname, path="/")
    solution = solve({
        "type": "FriendlyCaptchaTokenProxyLess",
        "websiteURL": TARGET_URL,
        "websiteKey": SITE_KEY,
        "scriptUrl": SCRIPT_URL,
        "userAgent": USER_AGENT,
    })

    # The solve ran with USER_AGENT; the submit presents the same one.
    headers = {"User-Agent": USER_AGENT}
    # Send the token the way the page does; some sites name it differently or send JSON.
    response = session.post(
        FORM_URL,
        data={**(FORM_FIELDS or {}), "frc-captcha-response": solution["token"]},
        headers=headers,
        timeout=30,
    )
    session.close()
    if not response.ok or SUCCESS_TEXT not in response.text:
        raise SystemExit(f"The site did not accept the result (HTTP {response.status_code}).")
    print("The site accepted the result.")


if __name__ == "__main__":
    main()

Common failures

Symptom Likely cause Check / fix
Token rejected, widget script still loaded The script ran after the token was set Confirm in the Network tab that the script request was aborted before you set the field
Token rejected, wrong field v1 and v2 field names differ, or data-solution-field-name renames either Detect the generation from the script URL, then match the field name
Task fails or never finishes after a site update Stale or guessed scriptUrl Copy the required scriptUrl from the live page, including its SDK version
Proxy variant rejected before charging Proxy details missing or malformed Check the string is user:password:host:port; ERROR_INVALID_REQUEST names the field it dislikes
Token reused Tokens are single-use Create a new task for each submission

Friendly Captcha is verified on the site's own server, so a rejected token shows up only as your form being refused. Compare with a real browser session, where you can watch which field the widget fills and what the page does with it.

Where to go from here

Create a key, send the request above with your own websiteURL, websiteKey and scriptUrl, and poll until ready; the same generated scripts in Node and Python variants live in the examples hub. Keep the public catalog (GET /v1/task-types) open for the parameter list. If the captcha on your target turns out to be a different proof-of-work widget, the Altcha guide covers the one that has no sitekey.

More articles