Upload 11 files
Browse filesFiles changed (12)
- .gitattributes+1
- cert.pemAdded+28
- check_proxy_alive.jsAdded+73
- database.sqliteAdded+3
- key.pemAdded+28
- logger.jsAdded+51
- package-lock.jsonAdded
- package.jsonAdded+18
- server.jsAdded+399
- solver.jsAdded+197
- stress_test_queue.jsAdded+35
- test_proxy.jsAdded+66
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textdatabase.sqlite filter=lfs diff=lfs merge=lfs -text12345678910111213141516171819202122232425262728-----BEGIN CERTIFICATE-----
MIIEsjCCA5qgAwIBAgIUWjp7uG3wH7CzK8BZ2dGz3qMF4l8wDQYJKoZIhvcNAQEL
BQAwgYsxCzAJBgNVBAYTAlVTMRkwFwYDVQQKExBDbG91ZEZsYXJlLCBJbmMuMTQw
MgYDVQQLEytDbG91ZEZsYXJlIE9yaWdpbiBTU0wgQ2VydGlmaWNhdGUgQXV0aG9y
aXR5MRYwFAYDVQQHEw1TYW4gRnJhbmNpc2NvMRMwEQYDVQQIEwpDYWxpZm9ybmlh
MB4XDTI1MTIyOTA1NTMwMFoXDTQwMTIyNTA1NTMwMFowYjEZMBcGA1UEChMQQ2xv
dWRGbGFyZSwgSW5jLjEdMBsGA1UECxMUQ2xvdWRGbGFyZSBPcmlnaW4gQ0ExJjAk
BgNVBAMTHUNsb3VkRmxhcmUgT3JpZ2luIENlcnRpZmljYXRlMIIBIjANBgkqhkiG
9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqpUOrPW40xlB4F6MxiQmKgIHeSqJQBAzXkMq
Ec3Juhb1zT6FP5l2gKSUcX2WWriQBm82MRPca70ni22vEjNKfD76MC8yYun8E5mR
2hCOBfhn6ZBv5OCLDljfHg6p1umAhamGty3ACriI/j3WOMw0rhUJwqsIuQ5i3DK4
dbuqpNnqkBGcxy9Tzd+PYCbtl5z1QAKlVc1fvGJ4MJ/1m8yflyoYEcZ8aVdrBDwx
KV3Kpl6EpRS+NN0peFrPViOcaWunQPRIiYS/UyjLihoXVFrFFiDJL3DtwxPe7C+t
FHVW2I5UFNm1qRX4bSNZ6f9KEnNwtXZ+rriYXIkd23ENizpniQIDAQABo4IBNDCC
ATAwDgYDVR0PAQH/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcD
ATAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBT8P5IcgCbSZeu7AHjm/6ry0kw3KjAf
BgNVHSMEGDAWgBQk6FNXXXw0QIep65TbuuEWePwppDBABggrBgEFBQcBAQQ0MDIw
MAYIKwYBBQUHMAGGJGh0dHA6Ly9vY3NwLmNsb3VkZmxhcmUuY29tL29yaWdpbl9j
YTA1BgNVHREELjAsghUqLmtpbnhzb2Z0d2FyZS5vbmxpbmWCE2tpbnhzb2Z0d2Fy
ZS5vbmxpbmUwOAYDVR0fBDEwLzAtoCugKYYnaHR0cDovL2NybC5jbG91ZGZsYXJl
LmNvbS9vcmlnaW5fY2EuY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQBQMhFjPAOP398v
owmv7zOxYerdHwkZ9wp5TMDUV2dO8DuExmPzzuPmz34bIjVzFUS5B3vwelkzU4z4
MhpxWqeXB5iQWMYo3DzW8UQgGq8qKtZl/LHIuyAkNCWXdlepdsdo4625ehcddTE9
lG4qRuxV+9KavzFZhu14kqqZkQ+e7jqELF74dqx2tBGayQgP//0Z0AXgaLihvzAx
yc4suJp5tN3UCfyiFBhWyoD0cPhNNlyfM2O5g3mgo0nEvPSIyNQFfZF67Pcj/Gag
VylmV9p3XvAa8Nn+oHrnxck5YUhkdltExoSi9se0k8uP07Nzc6F/n51Mq9LO9HFS
YzcQo2vT
-----END CERTIFICATE-----12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273const http = require('http');
const https = require('https');
async function testProxy(protocol, targetHost, targetPath) {
const proxy = 'http://zlet9i3y:oZJQ0o4V@157.10.49.215:44128';
const targetUrl = `${protocol}://${targetHost}${targetPath}`;
console.log(`Testing Proxy: ${proxy}`);
console.log(`Target: ${targetUrl}`);
const url = new URL(proxy);
const auth = 'Basic ' + Buffer.from(url.username + ':' + url.password).toString('base64');
if (protocol === 'http') {
return new Promise((resolve) => {
const options = {
host: url.hostname,
port: url.port,
path: targetUrl,
headers: {
'Proxy-Authorization': auth,
'Host': targetHost
}
};
http.get(options, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
console.log(`HTTP Status: ${res.statusCode}`);
resolve(true);
});
}).on('error', e => {
console.error(`HTTP Proxy Error: ${e.message}`);
resolve(false);
});
});
} else {
// HTTPS CONNECT
return new Promise((resolve) => {
const req = http.request({
host: url.hostname,
port: url.port,
method: 'CONNECT',
path: `${targetHost}:443`,
headers: {
'Proxy-Authorization': auth
}
});
req.on('connect', (res, socket, head) => {
console.log('HTTPS CONNECT established');
socket.destroy();
resolve(true);
});
req.on('error', e => {
console.error(`HTTPS Proxy Error (CONNECT): ${e.message}`);
resolve(false);
});
req.end();
});
}
}
async function run() {
console.log('--- Step 1: HTTP Test ---');
await testProxy('http', 'httpbin.org', '/ip');
console.log('\n--- Step 2: HTTPS Test ---');
await testProxy('https', 'labs.google', '/');
}
run();123version https://git-lfs.github.com/spec/v1oid sha256:0b0e4ce04c7967f0e0b3b7e1d0daaefab740e8c7d7af0aa9275d9d66f8465cf5size 18432012345678910111213141516171819202122232425262728-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCqlQ6s9bjTGUHg
XozGJCYqAgd5KolAEDNeQyoRzcm6FvXNPoU/mXaApJRxfZZauJAGbzYxE9xrvSeL
ba8SM0p8PvowLzJi6fwTmZHaEI4F+GfpkG/k4IsOWN8eDqnW6YCFqYa3LcAKuIj+
PdY4zDSuFQnCqwi5DmLcMrh1u6qk2eqQEZzHL1PN349gJu2XnPVAAqVVzV+8Yngw
n/WbzJ+XKhgRxnxpV2sEPDEpXcqmXoSlFL403Sl4Ws9WI5xpa6dA9EiJhL9TKMuK
GhdUWsUWIMkvcO3DE97sL60UdVbYjlQU2bWpFfhtI1np/0oSc3C1dn6uuJhciR3b
cQ2LOmeJAgMBAAECggEAFKR4k+wha2RPUUJH2VN3DdbUhjBkTw0W1kWc8e4cBwmv
waBa+h0NVthzwT8gIobaoPi0z2AWqLAJeMkzaimsThhF6O5RM+CaWVnYaVHfCfBr
TLummsUkdr5A88909JWpsKMY8xJVfsahh1i+0308s8NGfNj7M3++7WQy58Znyk6E
zN+yRa7vSUZIvCoElzfZwGgcmTGZL3GomRCCOFqHP/+/iahm1N+8uLRa680mjnQ2
8twYjF2D5agOwmpKG9YOmt2rtUlTq+k0bEt+s1XOu5Lln7DC8z6d5LxMJqH6IYo2
HDnNo25EFK7Pg5Gi1iLrRJdW+mcePp/5JpJObyYl4QKBgQDm3iBKeYkToFvPTbBV
YiSc8t/8hnXTLV8HZtflr51nXVTALEUAg7NnWhWOzK60Ust1aCvqco3vgXzNXtEx
MS9Pp/Nb7l51W9uazocQmOZlUZut3wyMl6152Zk5rtjBmZ8RD1gP8/UVOwMkicDe
KgiCIse+PfyP990IC2Nu14oeGQKBgQC9JuIOgyl5v9v0F5JGJZ9vsADrT9LopHO3
Ecb838XnmV9YQS5pyZZwD5IEBsUbOsRchUEZJRcsPXKXse+N5Eu5qC6jOF2HR/rX
xUj2GQIWLKYvzPIpkWq7YFvZ5PdJp6uXWoA9TN544pvlmewcr3XixDZAGw/TTUls
HkzGQPLi8QKBgQCdZ7cmb+S43+2Y0sQ2AtspsyJqHxb4a4fOGR18OZcdIXImMEi/
iAvqnG30VbOLuKOFogfHKmGBeYyozUvduUYjjkQLWuNGKuH4k3VdKJJ1ZAW7r0b0
GHoriOPCg2a/4MimLgsBnXhtCDYlVFKOZqQ0bhg3qjWnxvwJfxJFQWmnCQKBgQCq
pI2D8ihUwhW43BsGVaLEq8/oehcX8mTCX7NZJrfv/JnbkNJCda7WYfWk1Ea2Dgpg
PYdBHAkPzE+5MrmfFLqMP4HzlkIqbXGLf1wXSPBs+NLkhMxjW+EiMggrRzkgpbdT
0D2pD9QU0rs6I+ay6kg70C/xHXjlc/AtLhitMqLswQKBgQDhz8aTa2B8jslQ8R/b
h1YXmrgkVjHimTYTeLXeE45sMna9HplIWDDUAeoD4GipbIbRVixwS7NTNW0lTGzk
ZeKiRUzz9og3W3KtXm9Sglfjk9IeOPGUH3VEah0D79LgsB0yi8IOzBCNXluFcI8p
q5kyqlfB1fRhzkZ6yqq43zD6EQ==
-----END PRIVATE KEY-----123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051const fs = require('fs');
const path = require('path');
const logFile = path.join(__dirname, 'app.log');
const logStream = fs.createWriteStream(logFile, { flags: 'a' });
class Logger {
constructor() {
this.queueCount = 0;
this.activeCount = 0;
this.lastStatusTime = 0;
}
info(msg) {
this.writeToFile(`[INFO] ${msg}`);
console.log(`[${new Date().toLocaleTimeString()}] INFO: ${msg}`);
}
warn(msg) {
this.writeToFile(`[WARN] ${msg}`);
console.warn(`[${new Date().toLocaleTimeString()}] WARN: ${msg}`);
}
error(msg) {
this.writeToFile(`[ERROR] ${msg}`);
console.error(`[${new Date().toLocaleTimeString()}] ERROR: ${msg}`);
}
debug(msg) {
this.writeToFile(`[DEBUG] ${msg}`);
}
writeToFile(msg) {
const timestamp = new Date().toISOString();
logStream.write(`[${timestamp}] ${msg}\n`);
}
// Specialized throttled stats for the console
updateStats(active, queue) {
this.activeCount = active;
this.queueCount = queue;
const now = Date.now();
if (now - this.lastStatusTime > 3000) { // Update console every 3 seconds
this.lastStatusTime = now;
process.stdout.write(`\r[Status] Active: ${active} | Queued: ${queue} | Logs: See app.log `);
}
}
}
module.exports = new Logger();123456789101112131415161718{
"name": "captcha-service-pro",
"version": "2.0.0",
"main": "server.js",
"scripts": {
"start": "electron ."
},
"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"electron": "^28.0.0",
"express": "^4.18.2",
"puppeteer": "^24.34.0",
"socket.io": "^4.8.3",
"sqlite3": "^5.1.7",
"uuid": "^9.0.1"
}
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399const { app: electronApp, session } = require("electron");
// Global Proxy Auth Handler
electronApp.on("login", (event, webContents, details, authInfo, callback) => {
if (authInfo.isProxy) {
const ses = webContents.session;
if (ses.proxyCredentials) {
logger.debug(`[Main] Providing credentials for proxy via app.on('login')`);
event.preventDefault();
callback(ses.proxyCredentials.username, ses.proxyCredentials.password);
}
}
});
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const sqlite3 = require("sqlite3");
const { v4: uuidv4 } = require("uuid");
const path = require("path");
const RecaptchaSolver = require("./solver");
const http = require("http");
const { Server } = require("socket.io");
const logger = require("./logger");
const PORT = 3000;
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: "*" },
});
const db = new sqlite3.Database("./database.sqlite");
// --- INIT DB ---
db.serialize(() => {
// Thêm cột role để phân quyền (admin/user)
db.run(`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password TEXT,
api_key TEXT,
credits INTEGER DEFAULT 0,
role TEXT DEFAULT 'user',
hwid TEXT
)`);
db.run("ALTER TABLE users ADD COLUMN hwid TEXT", (err) => {
if (err) {
if (!err.message.includes("duplicate column name")) {
console.error("Migration error (hwid):", err.message);
}
}
});
db.run("UPDATE users SET role = 'admin' WHERE username = 'admin'");
// Bảng lưu lịch sử nạp tiền chờ duyệt
db.run(`CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
username TEXT,
amount INTEGER,
method TEXT,
status TEXT DEFAULT 'pending', -- pending, approved, rejected
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
// Bảng log lịch sử sử dụng
db.run(`CREATE TABLE IF NOT EXISTS usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
action TEXT,
details TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)`);
});
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
// --- MIDDLEWARE CHECK ADMIN ---
const requireAdmin = (req, res, next) => {
const apiKey = req.headers["x-api-key"];
db.get("SELECT role FROM users WHERE api_key = ?", [apiKey], (err, row) => {
if (row && row.role === "admin") next();
else res.status(403).json({ error: "Bạn không phải Admin!" });
});
};
// --- AUTH ---
app.post("/api/register", (req, res) => {
const { username, password, hwid } = req.body;
const apiKey = uuidv4();
// Kiểm tra xem HWID này đã được cộng tiền lần nào chưa
db.get("SELECT id FROM users WHERE hwid = ?", [hwid], (err, row) => {
const initialCredits = row ? 0 : 100; // Nếu đã tồn tại HWID thì 0, mới thì 10
const message = row
? "Đăng ký thành công! (Máy này đã nhận bonus trước đó nên không được cộng thêm)"
: "Đăng ký thành công! Bạn nhận được +100 Credits bonus.";
const stmt = db.prepare(
"INSERT INTO users (username, password, api_key, credits, role, hwid) VALUES (?, ?, ?, ?, 'user', ?)"
);
stmt.run(username, password, apiKey, initialCredits, hwid, function (err) {
if (err) return res.status(400).json({ error: "User đã tồn tại" });
res.json({ success: true, message: message });
io.emit("admin:new-user");
});
stmt.finalize();
});
});
app.post("/api/login", (req, res) => {
const { username, password } = req.body;
db.get(
"SELECT * FROM users WHERE username = ? AND password = ?",
[username, password],
(err, row) => {
if (!row) return res.status(401).json({ error: "Sai thông tin" });
res.json({ success: true, user: row });
}
);
});
app.get("/api/me", (req, res) => {
const apiKey = req.headers["x-api-key"];
db.get(
"SELECT username, credits, api_key, role FROM users WHERE api_key = ?",
[apiKey],
(err, row) => {
if (row) res.json(row);
else res.status(401).json({ error: "Key lỗi" });
}
);
});
// --- HISTORY API ---
app.get("/api/history/usage", (req, res) => {
const apiKey = req.headers["x-api-key"];
db.get("SELECT id FROM users WHERE api_key = ?", [apiKey], (err, user) => {
if (!user) return res.status(401).json({ error: "Auth failed" });
db.all(
"SELECT * FROM usage_logs WHERE user_id = ? ORDER BY id DESC LIMIT 50",
[user.id],
(err, rows) => {
res.json(rows);
}
);
});
});
app.get("/api/history/transactions", (req, res) => {
const apiKey = req.headers["x-api-key"];
db.get("SELECT id FROM users WHERE api_key = ?", [apiKey], (err, user) => {
if (!user) return res.status(401).json({ error: "Auth failed" });
db.all(
"SELECT * FROM transactions WHERE user_id = ? ORDER BY id DESC",
[user.id],
(err, rows) => {
res.json(rows);
}
);
});
});
// --- USER: TẠO YÊU CẦU NẠP TIỀN ---
app.post("/api/deposit", (req, res) => {
const apiKey = req.headers["x-api-key"];
const { amount, method } = req.body; // amount tính bằng USD (1, 5, 10)
db.get(
"SELECT id, username FROM users WHERE api_key = ?",
[apiKey],
(err, user) => {
if (!user) return res.status(401).json({ error: "User không tồn tại" });
const stmt = db.prepare(
"INSERT INTO transactions (user_id, username, amount, method) VALUES (?, ?, ?, ?)"
);
stmt.run(user.id, user.username, amount, method, function (err) {
if (err) return res.status(500).json({ error: "Lỗi tạo giao dịch" });
res.json({
success: true,
message: "Đã gửi yêu cầu! Vui lòng đợi Admin duyệt.",
});
io.emit("admin:new-transaction"); // Notify admin
});
stmt.finalize();
}
);
});
// --- ADMIN API ---
// 1. Lấy danh sách user
app.get("/api/admin/users", requireAdmin, (req, res) => {
db.all(
"SELECT id, username, credits, role, api_key FROM users",
[],
(err, rows) => {
res.json(rows);
}
);
});
// 2. Lấy danh sách giao dịch nạp tiền
app.get("/api/admin/transactions", requireAdmin, (req, res) => {
db.all("SELECT * FROM transactions ORDER BY id DESC", [], (err, rows) => {
res.json(rows);
});
});
// 3. Duyệt hoặc Từ chối nạp tiền
app.post("/api/admin/approve", requireAdmin, (req, res) => {
const { transId, action } = req.body; // action: 'approve' | 'reject'
db.get("SELECT * FROM transactions WHERE id = ?", [transId], (err, trans) => {
if (!trans || trans.status !== "pending")
return res.status(400).json({ error: "Giao dịch không hợp lệ" });
if (action === "reject") {
db.run("UPDATE transactions SET status = 'rejected' WHERE id = ?", [
transId,
]);
io.emit("transaction-updated");
return res.json({ success: true, message: "Đã từ chối giao dịch" });
}
if (action === "approve") {
const creditsToAdd = trans.amount * 1000; // $1 = 1000 credits
db.serialize(() => {
db.run("UPDATE transactions SET status = 'approved' WHERE id = ?", [
transId,
]);
db.run("UPDATE users SET credits = credits + ? WHERE id = ?", [
creditsToAdd,
trans.user_id,
]);
});
return res.json({
success: true,
message: `Đã duyệt! Cộng ${creditsToAdd} credits cho ${trans.username}`,
});
io.emit("transaction-updated");
// Notify specific user to update credits (client filters by checking if it's their update)
io.emit("user:credit-update");
}
});
});
// 5. Xóa user
app.post("/api/admin/delete-user", requireAdmin, (req, res) => {
const { userId } = req.body;
db.run("DELETE FROM users WHERE id = ?", [userId], function (err) {
if (err) return res.status(500).json({ error: "Lỗi xóa user" });
res.json({ success: true, message: "Đã xóa người dùng thành công." });
io.emit("admin:user-deleted"); // Notify admin to refresh list
});
});
// 4. Cộng/Trừ tiền thủ công cho user
app.post("/api/admin/update-credits", requireAdmin, (req, res) => {
const { userId, amount } = req.body; // amount có thể là số âm để trừ
db.run(
"UPDATE users SET credits = credits + ? WHERE id = ?",
[amount, userId],
function (err) {
if (err) return res.status(500).json({ error: "Lỗi database" });
res.json({ success: true, message: "Đã cập nhật số dư user." });
io.emit("user:credit-update");
}
);
});
// --- CAPTCHA SOLVE QUEUE ---
const solveQueue = [];
let activeSolves = 0;
const MAX_CONCURRENT_SOLVES = 3; // Tăng lên 3 vì đã tối ưu logging
async function processQueue() {
if (solveQueue.length === 0 || activeSolves >= MAX_CONCURRENT_SOLVES) {
logger.updateStats(activeSolves, solveQueue.length);
return;
}
activeSolves++;
const { req, res, user, targetUrl, targetKey, action, proxy } = solveQueue.shift();
logger.debug(`Processing request for ${user.username}. Active: ${activeSolves}/${MAX_CONCURRENT_SOLVES}`);
logger.updateStats(activeSolves, solveQueue.length);
const solver = new RecaptchaSolver();
try {
const token = await solver.getRecaptchaToken(
targetUrl,
targetKey,
action || "homepage",
proxy
);
if (token && !token.startsWith("ERROR")) {
db.run("UPDATE users SET credits = credits - 1 WHERE id = ?", [user.id]);
db.run(
"INSERT INTO usage_logs (user_id, action, details) VALUES (?, ?, ?)",
[user.id, "SOLVE_CAPTCHA", targetUrl]
);
res.json({ success: true, token: token });
io.emit("user:credit-update");
logger.debug(`Success for ${user.username}`);
} else {
res.status(500).json({ success: false, error: token });
logger.warn(`Solver returned error for ${user.username}: ${token}`);
}
} catch (e) {
res.status(500).json({ success: false, error: e.message });
logger.error(`Catch error for ${user.username}: ${e.message}`);
} finally {
activeSolves--;
logger.updateStats(activeSolves, solveQueue.length);
processQueue();
}
}
// --- API GIẢI CAPTCHA ---
app.post("/api/solve", async (req, res) => {
const { action, proxy } = req.body;
const targetUrl = "https://labs.google";
const targetKey = "6LdsFiUsAAAAAIjVDZcuLhaHiDn5nnHVXVRQGeMV";
const apiKey = req.headers["x-api-key"];
if (!apiKey) return res.status(401).json({ error: "Thiếu API Key" });
db.get(
"SELECT * FROM users WHERE api_key = ?",
[apiKey],
async (err, user) => {
if (!user) return res.status(403).json({ error: "API Key không hợp lệ" });
if (user.credits < 1) return res.status(402).json({ error: "Hết tiền, nạp thêm đi!" });
solveQueue.push({ req, res, user, targetUrl, targetKey, action, proxy });
logger.updateStats(activeSolves, solveQueue.length);
processQueue();
}
);
});
const https = require("https");
const fs = require("fs");
electronApp.on("window-all-closed", (e) => e.preventDefault());
electronApp.whenReady().then(() => {
// 1. Start Default Port 3000
server.listen(PORT, () =>
console.log(`Server running at: http://localhost:${PORT}`)
);
// 2. Start HTTP Port 80
try {
const httpServer = http.createServer(app);
io.attach(httpServer);
httpServer.listen(80, () => console.log("HTTP Server running on port 80"));
httpServer.on("error", (e) =>
console.error("Error on Port 80:", e.message)
);
} catch (e) {
console.error("Could not start HTTP server on port 80");
}
// 3. Start HTTPS Port 443
const certPath = path.join(__dirname, "cert.pem");
const keyPath = path.join(__dirname, "key.pem");
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
try {
const httpsServer = https.createServer(
{
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certPath),
},
app
);
io.attach(httpsServer);
httpsServer.listen(443, () =>
console.log("HTTPS Server running on port 443")
);
httpsServer.on("error", (e) =>
console.error("Error on Port 443:", e.message)
);
} catch (e) {
console.error("Could not start HTTPS server on port 443");
}
} else {
console.log(
"No SSL certificates found (cert.pem, key.pem). Skipping HTTPS (443)."
);
}
});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197const { BrowserWindow, session } = require("electron");
const logger = require("./logger");
class RecaptchaSolver {
constructor() {
this.solverWindow = null;
}
findChrome() {
return "Electron";
}
async createSolverWindow(targetUrl, proxy = null) {
if (this.solverWindow && !this.solverWindow.isDestroyed()) {
this.solverWindow.destroy();
}
const partition = `temp:solver-${Date.now()}-${Math.random().toString(36).substring(7)}`;
const ses = session.fromPartition(partition);
if (proxy) {
try {
const proxyUrl = new URL(proxy);
const proxyRules = proxyUrl.host; // ip:port
logger.debug(`[RecaptchaSolver] Setting proxy: ${proxyRules}`);
// Store credentials in session for app-level login handler (app.on('login'))
ses.proxyCredentials = {
username: proxyUrl.username,
password: proxyUrl.password
};
await ses.setProxy({ proxyRules });
} catch (e) {
logger.error(`[RecaptchaSolver] Proxy format error: ${proxy}. Skipping.`);
}
}
this.solverWindow = new BrowserWindow({
width: 360,
height: 640,
show: true,
x: -32000,
y: -32000,
frame: false,
skipTaskbar: true,
focusable: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: false,
session: ses,
webSecurity: false,
backgroundThrottling: false,
},
});
this.solverWindow.webContents.session.webRequest.onHeadersReceived(
(details, callback) => {
const responseHeaders = Object.assign({}, details.responseHeaders);
if (responseHeaders["content-security-policy"])
delete responseHeaders["content-security-policy"];
if (responseHeaders["x-frame-options"])
delete responseHeaders["x-frame-options"];
callback({ responseHeaders, cancel: false });
}
);
this.solverWindow.webContents.setUserAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
);
this.solverWindow.webContents.setAudioMuted(true);
this.solverWindow.webContents.on("did-fail-load", (event, errorCode, errorDescription, validatedURL) => {
logger.warn(`[RecaptchaSolver] Failed to load URL: ${validatedURL} | Error: ${errorDescription} (${errorCode})`);
});
await this.solverWindow.loadURL(targetUrl);
}
async simulateHumanInteraction() {
if (!this.solverWindow || this.solverWindow.isDestroyed()) return;
const contents = this.solverWindow.webContents;
try {
contents.sendInputEvent({ type: "mouseEnter", x: 10, y: 10 });
contents.sendInputEvent({ type: "mouseMove", x: 100, y: 100 });
await new Promise((r) => setTimeout(r, 100));
contents.sendInputEvent({ type: "mouseMove", x: 200, y: 150 });
contents.sendInputEvent({
type: "mouseDown",
x: 200,
y: 150,
button: "left",
clickCount: 1,
});
await new Promise((r) => setTimeout(r, 50));
contents.sendInputEvent({
type: "mouseUp",
x: 200,
y: 150,
button: "left",
clickCount: 1,
});
} catch (e) { }
}
async getRecaptchaToken(websiteURL, websiteKey, pageAction, proxy = null) {
const FIXED_URL = "https://labs.google";
const FIXED_KEY = "6LdsFiUsAAAAAIjVDZcuLhaHiDn5nnHVXVRQGeMV";
try {
await this.createSolverWindow(FIXED_URL, proxy);
await this.simulateHumanInteraction();
const token = await this.solverWindow.webContents.executeJavaScript(
`
(async function() {
const siteKey = '${FIXED_KEY}';
const action = '${pageAction}';
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function ensureLibrary() {
if (window.grecaptcha && window.grecaptcha.execute) return;
const old = document.getElementById('recaptcha-solver-script');
if (old) old.remove();
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.id = 'recaptcha-solver-script';
script.src = 'https://www.google.com/recaptcha/api.js?render=' + siteKey;
script.onload = () => {
// Đợi thêm 1s để library init xong
setTimeout(resolve, 1000);
};
script.onerror = () => reject("Load script failed");
document.head.appendChild(script);
});
}
try {
await ensureLibrary();
let attempts = 0;
while (!window.grecaptcha || !window.grecaptcha.execute) {
if (attempts++ > 20) throw new Error("Timeout waiting for grecaptcha");
await wait(200);
}
return new Promise((resolve, reject) => {
window.grecaptcha.ready(() => {
window.grecaptcha.execute(siteKey, { action: action })
.then(token => resolve(token))
.catch(err => reject("Execute Error: " + err.message));
});
});
} catch (e) {
return "ERROR: " + e.message;
}
})();
`,
true
);
if (!token || typeof token !== "string" || token.startsWith("ERROR:")) {
throw new Error("Token lỗi: " + token);
}
logger.debug(`[Solver] Token generated: ${token.substring(0, 20)}...`);
this.close();
return token;
} catch (error) {
logger.error(`[Solver] Error: ${error.message}`);
this.close();
return "ERROR: " + error.message;
}
}
async close() {
if (this.solverWindow && !this.solverWindow.isDestroyed()) {
this.solverWindow.destroy();
this.solverWindow = null;
}
}
}
module.exports = RecaptchaSolver;1234567891011121314151617181920212223242526272829303132333435const axios = require('axios');
const API_KEY = '5db36803-12cb-469b-8919-cc02dc284693'; // Replace with a valid key from your DB if needed
const URL = 'http://localhost:3000/api/solve';
async function sendRequest(id) {
console.log(`[Test] Sending request #${id}...`);
try {
const startTime = Date.now();
const response = await axios.post(URL, {
action: 'test_stress'
}, {
headers: { 'x-api-key': API_KEY }
});
const duration = ((Date.now() - startTime) / 1000).toFixed(2);
console.log(`[Test] Request #${id} finished in ${duration}s. Success: ${response.data.success}`);
} catch (error) {
console.error(`[Test] Request #${id} failed: ${error.response?.data?.error || error.message}`);
}
}
async function runTest() {
console.log("Starting stress test with 5 concurrent requests...");
console.log("Since MAX_CONCURRENT_SOLVES is 2, you should see them being processed 2 at a time.");
const requests = [];
for (let i = 1; i <= 5; i++) {
requests.push(sendRequest(i));
}
await Promise.all(requests);
console.log("Stress test completed.");
}
runTest();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566const http = require('http');
const https = require('https');
/**
* Script kiểm tra API giải captcha với Proxy
* Hỗ trợ cả HTTP và HTTPS, tự động chọn module phù hợp
*/
async function testCaptchaWithProxy() {
const API_URL = 'https://kinxsoftware.online/api/solve';
const API_KEY = 'f064b7bf-8bcc-47f4-befe-1831540cffa5';
const PROXY = 'http://zlet9i3y:oZJQ0o4V@157.10.49.215:44128';
const postData = JSON.stringify({
action: 'FLOW_GENERATION',
proxy: PROXY
});
const url = new URL(API_URL);
const isHttps = url.protocol === 'https:';
const transport = isHttps ? https : http;
const options = {
hostname: url.hostname,
port: url.port || (isHttps ? 443 : 80),
path: url.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': API_KEY,
'Content-Length': Buffer.byteLength(postData)
},
// Bỏ qua kiểm tra SSL nếu là localhost hoặc server tự cấp chứng chỉ
rejectUnauthorized: false
};
console.log('--- Đang gửi yêu cầu giải captcha với Proxy ---');
console.log('URL:', API_URL);
console.log('Proxy:', PROXY);
const req = transport.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Phản hồi từ Server:', res.statusCode);
try {
const jsonResponse = JSON.parse(data);
console.log('Kết quả:', JSON.stringify(jsonResponse, null, 2));
} catch (e) {
console.log('Phản hồi không phải JSON:', data);
}
});
});
req.on('error', (e) => {
console.error('Lỗi kết nối:', e.message);
});
req.write(postData);
req.end();
}
testCaptchaWithProxy();.gitattributes+1
cert.pemAdded+28
check_proxy_alive.jsAdded+73
database.sqliteAdded+3
key.pemAdded+28
logger.jsAdded+51
package-lock.jsonAdded
package.jsonAdded+18
server.jsAdded+399
solver.jsAdded+197
stress_test_queue.jsAdded+35
test_proxy.jsAdded+66