Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed errors #12

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
node_modules
.vscode
test.js
test.js
package-lock.json
**/*.DS_Store
5 changes: 5 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.vscode
test.js
package-lock.json
**/*.DS_Store
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,28 @@ A library to solve hcaptcha challenges
## Install

```bash
npm install hcaptcha-solver
npm install @hitthemoney/hcaptcha-solver
```

## Quick Example

```js
const solveCaptcha = require('hcaptcha-solver');
const solveCaptcha = require("@hitthemoney/hcaptcha-solver");

(async () => {
try {
const response = await solveCaptcha('https://captcha-protected-site.com');
console.log(response);
// F0_eyJ0eXAiOiJKV1Q...
const response = await solveCaptcha("https://captcha-protected-site.com", {
siteKey: "site-key"
});
console.log(response);
// F0_eyJ0eXAiOiJKV1Q...
} catch (error) {
console.log(error);
console.log(error);
}
})();
```

## Credits

- Original [Repository](https://github.com/JimmyLaurent/hcaptcha-solver) by [Jimmy Laurent](https://github.com/JimmyLaurent)
- Thanks to [Futei](https://github.com/Futei/SineCaptcha)
253 changes: 141 additions & 112 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,140 +1,169 @@
const request = require('request-promise-native');
const Url = require('url');
const vm = require('vm');
const fetch = require("node-fetch");
const { URL } = require("url");
const vm = require("vm");
const {
randomFromRange,
randomTrueFalse,
delay,
uuid,
getRandomUserAgent
} = require('./src/utils');
randomFromRange,
randomTrueFalse,
delay,
uuid,
getRandomUserAgent,
encodeFormData
} = require("./src/utils");

function getMouseMovements(timestamp) {
let lastMovement = timestamp;
const motionCount = randomFromRange(1000, 10000);
const mouseMovements = [];
for (let i = 0; i < motionCount; i++) {
lastMovement += randomFromRange(0, 10);
mouseMovements.push([randomFromRange(0, 500), randomFromRange(0, 500), lastMovement]);
}
return mouseMovements;
let lastMovement = timestamp;
const motionCount = randomFromRange(1000, 10000); // 100, 1000
const mouseMovements = [];
for (let i = 0; i < motionCount; i++) {
lastMovement += randomFromRange(0, 10);
mouseMovements.push([randomFromRange(0, 500), randomFromRange(0, 500), lastMovement]);
}
return mouseMovements;
}

let hslFile;

async function hsl(req) {
const hsl = await request.get('https://assets.hcaptcha.com/c/500c658/hsl.js');
return new Promise((resolve, reject) => {
const code = `
const hsl = hslFile = hslFile || (await fetch("https://assets.hcaptcha.com/c/3118c3eb/hsl.js").then(res => res.text())); // https://assets.hcaptcha.com/c/b147199/hsl.js
return new Promise((resolve, reject) => {
const code = `
var self = {};
function atob(a) {
return new Buffer(a, 'base64').toString('binary');
globalThis.window = globalThis
globalThis.atob = function(a) {
return Buffer.from(a, "base64").toString("binary");
}
globalThis.btoa = function(a) {
return Buffer.from(a).toString("base64");
}
globalThis.navigator = {
userAgent: "${getRandomUserAgent()}"
}

${hsl}

hsl('${req}').then(resolve).catch(reject)
hsl("${req}").then(resolve).catch(reject)
`;
vm.runInNewContext(code, {
Buffer,
resolve,
reject,
vm.runInNewContext(code, {
Buffer,
resolve,
reject,
});
});
});
}


async function tryToSolve(sitekey, host) {
const userAgent = getRandomUserAgent();
const headers = {
'User-Agent': userAgent
};

let response = await request({
method: 'get',
headers,
json: true,
url: `https://hcaptcha.com/checksiteconfig?host=${host}&sitekey=${sitekey}&sc=1&swa=0`
});
const userAgent = getRandomUserAgent();
const headers = {
"user-agent": userAgent,
"origin": "https://assets.hcaptcha.com",
};

let timestamp = Date.now() + randomFromRange(30, 120);
response = await request({
method: 'post',
headers,
json: true,
url: 'https://hcaptcha.com/getcaptcha',
form: {
sitekey,
host,
n: await hsl(response.c.req),
c: JSON.stringify(response.c),
motionData: {
st: timestamp,
dct: timestamp,
mm: getMouseMovements(timestamp)
}
}
});

if (response.generated_pass_UUID) {
return response.generated_pass_UUID;
}
let response = await (await fetch(`https://hcaptcha.com/checksiteconfig?host=${host}&sitekey=${sitekey}&sc=1&swa=0`, {
method: "GET",
headers,
})).json()
let timestamp = Date.now() + randomFromRange(30, 120);
response = await (await fetch("https://hcaptcha.com/getcaptcha", {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
...headers
},
body: encodeFormData({
sitekey,
host,
n: await hsl(response.c.req),
c: JSON.stringify(response.c),
motionData: JSON.stringify({
st: timestamp,
dct: timestamp,
mm: getMouseMovements(timestamp)
})
})
})).json();

const key = response.key;
const tasks = response.tasklist;
const job = response.request_type;
timestamp = Date.now() + randomFromRange(30, 120);
const answers = tasks.reduce((accum, t) => ({ ...accum, [t.task_key]: randomTrueFalse() }), {});
const captchaResponse = {
answers,
sitekey,
serverdomain: host,
job_mode: job,
motionData: {
st: timestamp,
dct: timestamp,
mm: getMouseMovements(timestamp)
if (response.generated_pass_UUID) {
return response.generated_pass_UUID;
}
};
const key = response.key;
const tasks = response.tasklist;
const job = response.request_type;
timestamp = Date.now() + randomFromRange(30, 120);
const answers = tasks.reduce((accum, t) => ({ ...accum, [t.task_key]: randomTrueFalse() }), {});
const captchaResponse = {
job_mode: job,
answers,
serverdomain: host,
sitekey,
motionData: JSON.stringify({
st: timestamp,
dct: timestamp,
mm: getMouseMovements(timestamp)
}),
n: await hsl(response.c.req),
c: JSON.stringify(response.c),
};

response = await request(`https://hcaptcha.com/checkcaptcha/${key}`, {
method: 'post',
headers,
json: true,
form: captchaResponse
});
response = await (await fetch(`https://hcaptcha.com/checkcaptcha/${key}`, {
method: "POST",
headers: {
"content-type": "application/json;charset=UTF-8",
...headers
},
body: JSON.stringify(captchaResponse),
})).json()

if (response.generated_pass_UUID) {
return response.generated_pass_UUID;
}
if (response.generated_pass_UUID) {
return response.generated_pass_UUID;
}
}

/**
* Solve an hCaptcha challenge
* @param {string} url Site URL
* @param {{
* timeout: number,
* maxAttempts: number,
* siteKey: string,
* retryDelay: number,
* }} options Extra Options
* @returns {Promise<string>} hCaptcha challange result
*/
async function solveCaptcha(url, options = {}) {
const { gentleMode, timeoutInMs = 12000000 } = options;
const { hostname } = Url.parse(url);
const siteKey = uuid();
const startingTime = Date.now();
const {
timeout = 12000000,
siteKey = uuid(),
retryDelay = 0,
maxAttempts = Infinity
} = options;
const { hostname } = new URL(url);
const startingTime = Date.now();

while (true) {
try {
const result = await tryToSolve(siteKey, hostname);
if (result) {
return result;
}
} catch (e) {
if (e.statusCode === 429) {
// reached rate limit, wait 30 sec
await delay(30000);
} else {
throw e;
}
}
if (Date.now() - startingTime > timeoutInMs) {
throw new Error('captcha resolution timeout');
}
if (gentleMode) {
// wait a bit to avoid rate limit errors
delay(3000);
let retryCount = 0;
while (true) {
try {
const result = await tryToSolve(siteKey, hostname);
if (result) {
return result;
}
} catch (e) {
if (e.statusCode === 429) {
// reached rate limit, wait 30 sec
await delay(30000);
} else {
throw e;
}
}
if (Date.now() - startingTime > timeout) {
throw new Error("captcha resolution timeout");
}
if (retryCount >= maxAttempts) {
throw new Error("exceeded maximum attempts")
}

await delay(retryDelay)
retryCount++;
}
}
}

module.exports = solveCaptcha;
module.exports = solveCaptcha;
28 changes: 12 additions & 16 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
{
"name": "hcaptcha-solver",
"version": "1.0.2",
"name": "@hitthemoney/hcaptcha-solver",
"version": "1.0.3",
"description": "A library to solve hCaptcha challenges",
"author": "Jimmy Laurent",
"author": "hitthemoney",
"original-author": "Jimmy Laurent",
"repository": {
"type": "git",
"url": "git://github.com/JimmyLaurent/hcaptcha-solver.git"
"url": "git://github.com/hitthemoney/hcaptcha-solver.git"
},
"main": "index.js",
"license": "MIT",
Expand All @@ -14,16 +15,11 @@
"bypass",
"solve"
],
"prettier": {
"printWidth": 100,
"singleQuote": true,
"trailingComma": "none",
"parser": "flow",
"semi": true,
"tabWidth": 2
},
"dependencies": {
"request": "^2.88.2",
"request-promise-native": "^1.0.8"
}
}
"node-fetch": "^2.6.1"
},
"bugs": {
"url": "https://github.com/hitthemoney/hcaptcha-solver/issues"
},
"homepage": "https://github.com/hitthemoney/hcaptcha-solver#readme"
}
Loading