Bạn có thể truy cập những trang web nào thông qua proxy và cấu hình VPN của mình? Hãy kiểm tra chúng trong các hồ sơ Octo Browser


Alex Phillips
Customer Service Specialist
Octo Browser là một trình duyệt chống phát hiện để làm việc với nhiều tài khoản: mỗi hồ sơ có một dấu vân tay kỹ thuật số và cài đặt kết nối riêng. Kết nối xác định trang web nào mà hồ sơ có thể truy cập: cùng một trang web có thể hoạt động qua một proxy này, hiển thị bước kiểm tra “Bạn có phải là con người không?” qua một proxy khác và không phản hồi qua proxy thứ ba. Việc kiểm tra thủ công mọi thứ mất rất nhiều thời gian: kiểm tra năm proxy với năm mươi trang web có thể mất cả buổi tối. Trong bài viết này, chúng tôi sẽ chỉ cho bạn cách tạo một tập lệnh Node.js và Puppeteer để duyệt qua danh sách các trang web bằng cách sử dụng từng proxy và VPN trong các hồ sơ Octo Browser của bạn, sau đó báo cáo xem từng trang web có thể truy cập được hay không và nếu không, thì lý do là gì.
Nội dung
Duy trì danh tính ẩn trực tuyến của bạn với Octo Browser. Dấu vân tay số thật của bạn sẽ không thể bị truy vết.
Bạn muốn thử Octo Browser với giá ưu đãi không?
Sử dụng mã khuyến mãi OCTOBLOG để được giảm giá 30% cho bất kỳ gói đăng ký nào. Ưu đãi này chỉ dành cho người dùng mới.
Script này có thể làm được gì
Bạn cung cấp cho script ba danh sách: các trang web, proxy và cấu hình VPN. Đối với mỗi proxy và mỗi VPN, script sẽ tạo một profile riêng biệt trong Octo Browser, khởi chạy profile đó, mở từng trang web một và ghi lại kết quả. Cuối cùng, bạn sẽ nhận được một bảng với mỗi hàng là một trang web và mỗi cột là một kết nối, tiếp theo là phần tóm tắt kèm theo lý do cho mọi trường hợp thất bại.
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Ví dụ, script có thể:
Kiểm tra proxy và VPN trong một lần chạy duy nhất. Script đọc proxy từ tệp
proxies.txtvà VPN từ các tệp cấu hình WireGuard trong thư mụcconfig. Nó hỗ trợ các giao thức và định dạng dòng tương tự như tính năng nhập proxy hàng loạt trong Octo Browser, bao gồm cả địa chỉ IPv6.Xác định lý do. Nếu một trang web không tải được, script sẽ cho bạn biết lý do: chính proxy không thể thiết lập kết nối, trang web đã chặn địa chỉ IP, yêu cầu kiểm tra “Bạn có phải là người không?”, không khả dụng ở quốc gia kết nối, hoặc đơn giản là không phản hồi.
Phân biệt giữa việc bị chặn và lỗi ngẫu nhiên. Nếu kết nối bị ngắt hoặc trang web không phản hồi, script sẽ kiểm tra lại. Nếu trang web hiển thị bước kiểm tra “Bạn có phải là người không?”, script sẽ đợi bước này tự biến mất. Nếu trang tải bình thường, việc có lớp bảo vệ chống bot đơn thuần sẽ không bị coi là lỗi.
Chạy kiểm tra song song. Script kiểm tra tối đa mười kết nối cùng lúc và kết quả cho từng trang web sẽ xuất hiện ngay khi có sẵn.
Đặt tên profile theo quốc gia và IP. Profile sẽ nhận được tên như
DE_198.51.100.7. Kết nối không hoạt động được đánh dấu làDEAD, trong khi profile không khởi chạy được vì lý do khác được đánh dấu làERROR.Lưu báo cáo. Script tạo một tệp Excel với bản tóm tắt cho từng kết nối. Các trang web truy cập được sẽ được đánh dấu màu xanh lá cây và các trang không truy cập được sẽ được đánh dấu màu đỏ. Script cũng lưu ảnh chụp màn hình của từng trang lỗi để bạn có thể thấy chính xác những gì trang web đã hiển thị.
Bảo vệ thông tin đăng nhập truy cập. Mật khẩu proxy, khóa VPN và token không được đưa vào kết quả đầu ra trên bảng điều khiển (console) hoặc báo cáo. Các profile cũng được dừng đúng cách, ngay cả khi bạn ngắt quá trình kiểm tra.
Script chỉ quan sát. Nó không giải mã CAPTCHA, nhấp vào các nút hoặc nhập bất kỳ nội dung nào. Hãy ghi nhớ những điều sau:
Kết quả
challengekhông có nghĩa là bạn đã bị cấm. Trang web đang yêu cầu bạn xác nhận mình là người thật và bạn thường có thể mở trang đó theo cách thủ công trong profile.Script chỉ kiểm tra chính xác URL bạn cung cấp. Trang chủ tải thành công không có nghĩa là đăng nhập tài khoản hoặc thanh toán sẽ hoạt động. Hãy thêm URL của một phần cụ thể vào danh sách nếu đó là phần bạn cần kiểm tra.
Kết quả chỉ chính xác tại thời điểm kiểm tra. Proxy xoay vòng có thể sử dụng một IP khác sau đó một phút, vì vậy kết quả có thể thay đổi.
Mỗi kết nối sẽ nhận được một profile mới và các proxy mới sẽ được thêm vào danh sách proxy của Octo. Cả hai đều tiêu tốn giới hạn gói đăng ký của bạn. Bước 3 giải thích cách tránh để lại chúng sau khi kiểm tra.
Tại sao không dùng curl?
Bạn có thể kiểm tra một trang web thông qua proxy bằng một lệnh curl duy nhất, nhưng lệnh này trả lời một câu hỏi khác, cụ thể là: yêu cầu có đến được máy chủ không? Nó không thể cho bạn biết liệu trang web có mở được trong profile trình duyệt hay không.
curlkhông phải là trình duyệt và các trang web có thể nhận ra điều đó. Các hệ thống bảo mật xác định nó bằng vân tay TLS và tập hợp các header, đồng thời có thể từ chối chính clientcurlthay vì proxy của bạn.curlkhông chạy JavaScript. Trình duyệt có thể vượt qua bước kiểm tra “Just a moment” tự động trong vài giây, trong khicurlsẽ bị kẹt ở đó.curlchỉ nhìn thấy mã phản hồi chứ không thấy trang. Một trang giới hạn địa lý, CAPTCHA hoặc từ chối truy cập với mã trạng thái 200 đều trông giống như một trang web được mở thành công đối với nó.curlkhông thể kiểm tra VPN. Nó có thể kết nối qua proxy HTTP và SOCKS, nhưng bạn không thể truyền cấu hình WireGuard vào nó.
curl vẫn có những công dụng riêng: đó là một cách nhanh chóng để tìm hiểu xem proxy có đang hoạt động hay không và địa chỉ IP của nó là gì. Chỉ có trình duyệt trong profile mới có thể cho bạn biết liệu trang web có mở được trong profile đó hay không.
Những thứ bạn sẽ cần
Octo Browser với Gói đăng kí Base trở lên, cho phép bạn truy cập vào API.
Phiên bản Node.js 22.12 trở lên.
Danh sách các proxy hoặc tệp cấu hình WireGuard VPN.
Bước 1. Cài đặt Node.js
Tải xuống Node.js từ nodejs.org và cài đặt bằng cài đặt mặc định. Sau đó mở PowerShell: nhấn Win+R, gõ PowerShell và nhấn Enter. Kiểm tra quá trình cài đặt:
node --version
node --version
Lệnh sẽ hiển thị phiên bản 22.12 trở lên. Điều này được yêu cầu bởi Puppeteer 25, phiên bản đã được sử dụng để kiểm tra script. Nếu PowerShell báo không tìm thấy lệnh, hãy đóng PowerShell, mở lại và thử lại.
Bước 2. Chuẩn bị thư mục
Chọn một thư mục cho script, ví dụ: D:\proxy_check, tạo thư mục đó và điều hướng đến thư mục đó trong PowerShell. Tạo một thư mục config bên trong để chứa cấu hình VPN của bạn:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Cài đặt Puppeteer. Phiên bản được chỉ định rõ ràng vì đây là phiên bản mà script đã được thử nghiệm:
npm install puppeteer-core@25
npm install puppeteer-core@25
Bước 3. Script site_access.mjs
Trong PowerShell, với proxy_check là thư mục hiện tại, hãy chạy notepad site_access.mjs. Khi được hỏi bạn có muốn tạo tệp mới không, hãy nhấp vào Yes, dán toàn bộ mã và lưu lại bằng cách nhấn Ctrl+S. Tạo tệp từ dòng lệnh giúp tránh sự cố phần mở rộng tệp: nếu bạn tạo tệp qua menu Notepad, tệp có thể được lưu dưới dạng site_access.mjs.txt và script sẽ không chạy. Tạo các tệp khác trong các bước tiếp theo theo cách tương tự.
Các cài đặt được liệt kê ở đầu mã, mỗi cài đặt đều có chú thích giải thích. Một cài đặt là bắt buộc: dán token API của bạn vào API_TOKEN. Bạn có thể tìm thấy nó trong Octo Browser, dưới tab Token API trong cài đặt tài khoản chính của bạn.
const API_TOKEN = "your_token";
const API_TOKEN = "your_token";
Bạn có thể để các cài đặt khác ở giá trị mặc định. Tuy nhiên, hãy chú ý đến hai thông số này:
KEEP_PROFILES = false gửi các profile vào thùng rác sau khi kiểm tra.
SAVE_PROXIES = false ngăn không cho các proxy đã kiểm tra được thêm vào danh sách proxy của Octo. Với các cài đặt này, các profile và proxy được tạo để thử nghiệm sẽ không làm lộn xộn danh sách làm việc của bạn trong trình duyệt. Điều này hữu ích nếu giới hạn profile của bạn thấp.
Dưới đây là mô tả chi tiết về các cài đặt:
Cài đặt | Nội dung kiểm soát |
|---|---|
| Token API Octo Browser |
| Cổng API cục bộ của Octo client, mặc định là 58888. Bạn có thể tìm thấy cổng này trong phần cài đặt dưới tab Bổ sung. |
| Hệ điều hành của profile: |
|
|
| Số lượng kết nối được kiểm tra đồng thời, từ 1 đến 10. |
| Proxy được chỉ định trực tiếp trong mã, ngoài các proxy trong tệp. |
| Tệp chứa proxy; mặc định là |
| Loại được sử dụng cho các dòng proxy không chỉ định loại. |
|
|
| Thư mục chứa cấu hình VPN; mặc định là |
| Giao thức được sử dụng bởi các tệp cấu hình và chế độ được sử dụng để xác định chúng trong Octo API. Mặc định là |
| Tệp chứa danh sách trang web; mặc định là |
|
|
| Có lưu ảnh chụp màn hình của các trang bị lỗi hay không. |
| Số giây chờ trang web phản hồi, để bước kiểm tra “Bạn có phải là người không?” tự biến mất và để nội dung trang xuất hiện. |
Dưới đây là mã:
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
Bước 4. Tạo danh sách các trang web
Tạo một tệp bằng cách chạy notepad sites.txt. Thực hiện theo các quy tắc sau:
Đặt mỗi địa chỉ trên một dòng mới.
Bạn có thể đưa tiền tố
https://vào hoặc bỏ qua.Bắt đầu các dòng chú thích bằng
#. Các chú thích rất hữu ích để chia danh sách thành các nhóm.
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
Bước 5. Thêm proxy và VPN
Script cần ít nhất một kết nối để hoạt động: proxy hoặc cấu hình VPN. Bạn cũng có thể định cấu hình cả hai loại kết nối.
Proxy. Tạo một tệp bằng cách chạy notepad proxies.txt và thêm các proxy của bạn, mỗi proxy trên một dòng. Script chấp nhận các giao thức và định dạng dòng tương tự như khi nhập proxy hàng loạt trong Octo Browser. Các giao thức được hỗ trợ: http, https, socks5, và ssh. Các định dạng được hỗ trợ:
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
Địa chỉ IPv6 phải được đặt trong dấu ngoặc vuông: socks5://[2001:db8::1]:1080:login:password. Bạn cũng có thể bỏ qua giao thức khỏi một dòng; trong trường hợp đó, loại được chỉ định trong DEFAULT_TYPE sẽ được sử dụng. Các dòng bắt đầu bằng # sẽ bị bỏ qua.
VPN. Đặt các tệp cấu hình WireGuard của bạn vào thư mục config. Tên tệp có thể là bất kỳ tên nào: script xác định cấu hình theo nội dung của nó, cụ thể là các phần [Interface] và [Peer]. Cấu hình không được thêm vào danh sách proxy của Octo; nó chỉ tồn tại bên trong profile riêng của chính nó.
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
Trước khi chạy, script sẽ kiểm tra từng cấu hình xem có PrivateKey, Address, PublicKey, và Endpoint hay không, đồng thời xác minh rằng Endpoint được viết dưới dạng địa chỉ và cổng, không có http://. Nếu script phát hiện lỗi, nó sẽ hiển thị tên tệp và mô tả sự cố, sau đó thoát ra mà không tạo bất kỳ profile nào.
Cấu trúc thư mục của bạn sẽ trông như thế này:
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
Bước 6. Chạy kiểm tra
Mở Octo Browser và chạy script từ thư mục của nó:
cd D:\proxy_check node site_access.mjs
cd D:\proxy_check node site_access.mjs
Trong lần chạy đầu tiên, hãy sử dụng một proxy và ba hoặc bốn trang web. Bạn sẽ có thể thấy các trang web mở trong cửa sổ profile. Khi bạn đã xác nhận rằng mọi thứ đều hoạt động, hãy thêm phần còn lại.
Khi script bắt đầu, nó sẽ kiểm tra mọi thứ có thể khiến nó không chạy được: token, các tệp, cấu hình VPN và việc Octo đã được mở hay chưa. Nếu phát hiện lỗi, nó sẽ hiển thị thông báo mô tả sự cố và thoát ra mà không tạo profile. Quá trình kiểm tra sau đó sẽ bắt đầu và kết quả cho từng trang web sẽ được hiển thị ngay khi có sẵn.

Dấu ngoặc vuông hiển thị số thứ tự kết nối, tên profile của kết nối đó và bộ đếm trang web. Khi một số kết nối được kiểm tra song song, các dòng kết quả đầu ra của chúng có thể xen kẽ nhau. Hãy sử dụng nhãn để xem mỗi dòng thuộc về kết nối nào. Mật khẩu proxy không được hiển thị trong kết quả đầu ra và chỉ vài ký tự cuối của tên người dùng được hiển thị. Để dừng kiểm tra, hãy nhấn Ctrl+C. Script sẽ dừng các profile mà nó đã khởi chạy.
Cách đọc kết quả
Cuối cùng, script sẽ in một bảng và tóm tắt cho từng kết nối:

AVAILABLE có nghĩa là trang web đã mở thành công và hiển thị nội dung. UNAVAILABLE có nghĩa là trang web không mở được. Các lý do trong ngoặc đơn sau kết quả cuối cùng được liệt kê theo thứ tự tần suất giảm dần. DEAD trong tên cột có nghĩa là chính kết nối không hoạt động, chứ không phải là tất cả các trang web đang được kiểm tra đều không khả dụng.
Nhãn ERROR có nghĩa là profile không khởi chạy được vì lý do không liên quan đến kết nối. Thông báo lỗi của Octo xuất hiện trên dòng kết nối đó trong bảng điều khiển và trong báo cáo.
Các tệp đầu ra được lưu trong thư mục. Dấu thời gian trong tên tệp sử dụng giờ địa phương:
site_access_<time>.xlsx— một báo cáo Excel. Phần trên cùng chứa bản tóm tắt hiển thị tổng số trang web và đối với mỗi kết nối, có bao nhiêu trang web truy cập được, bao nhiêu trang không truy cập được và lý do. Bên dưới là kết quả kiểm tra chi tiết, với mỗi hàng cho một kết quả: profile, kết nối, trang web, kết quả, lý do và IP. Các hàng dành cho trang web truy cập được có màu xanh lá cây; các hàng không truy cập được có màu đỏ. Các hàng màu xám biểu thị kết nối không hoạt động và các trang web không được kiểm tra vì proxy đã ngừng hoạt động.screens_<time>— ảnh chụp màn hình của các trang lỗi, với một thư mục riêng cho từng kết nối và ảnh chụp màn hình được đánh số theo thứ tự của danh sách trang web. Nếu trang web không phản hồi hoặc chính proxy không thể thiết lập kết nối thì sẽ không có gì để chụp, do đó không có ảnh chụp màn hình nào được lưu.
Các profile vẫn còn trong Octo Browser và được đặt tên theo quốc gia và IP.
Chúng ta hãy xem xét một số vấn đề có thể xảy ra:
Những gì bạn thấy trong báo cáo | Ý nghĩa | Những việc cần làm |
|---|---|---|
Kết nối được đánh dấu | Bản thân kết nối không hoạt động. | Kiểm tra tên người dùng, mật khẩu và loại proxy hoặc chi tiết cấu hình VPN. |
Kết nối được đánh dấu | Profile không khởi chạy được, nhưng vấn đề không nằm ở kết nối. | Đọc lỗi trong báo cáo hoặc bảng điều khiển, khắc phục nguyên nhân và chạy lại kiểm tra. |
Một vài mục | Proxy ngừng hoạt động trong quá trình kiểm tra: lưu lượng đã hết hoặc phiên đã hết hạn. | Kiểm tra proxy và chạy lại quy trình kiểm tra. |
Một kết nối có nhiều kết quả | Nhà cung cấp proxy đã chặn các trang web đó. | Hỏi nhà cung cấp của bạn xem danh mục trang web nào bị chặn trên gói dịch vụ của bạn. |
Một kết nối nhận được | Trang web không tin tưởng địa chỉ IP này hoặc mạng con của nó. | Thay đổi IP hoặc sử dụng một loại proxy khác. |
| Trang web không khả dụng ở quốc gia đầu ra. | Sử dụng proxy từ quốc gia khác. |
| Chính trang web không phản hồi. | Hãy thử kiểm tra lại sau. |
| Kết nối chậm hoặc liên tục bị ngắt. | Thay thế kết nối. |
| Có quá nhiều yêu cầu đến từ cùng một IP. | Chờ và giảm giá trị |
Ý nghĩa của các lý do
Mã phản hồi của máy chủ không đáng tin cậy trong trường hợp này. Việc từ chối truy cập không phải lúc nào cũng đi kèm với lỗi: Akamai có thể trả về “Access Denied” với mã trạng thái 200, kiểm tra AWS WAF có thể trả về 202 và việc chặn từ DataDome có thể trả về 401. Đó là lý do tại sao script đọc trực tiếp trang web. Các trang web lớn hiếm khi tự tạo trang từ chối truy cập từ đầu: một trong những hệ thống bảo mật phổ biến sẽ hiển thị trang chặn, và mỗi hệ thống đều có chữ ký riêng trong header và văn bản.
Lý do trong báo cáo | Chuyện gì đã xảy ra | Cách nhận diện |
|---|---|---|
| Proxy không thể thiết lập kết nối tới trang web này. | Lỗi tunnel hoặc SOCKS trong trình duyệt. Đây là biểu hiện của một trang web bị nhà cung cấp proxy chặn. |
| Bản thân proxy không hoạt động. | Proxy không phản hồi hoặc không chấp nhận tên người dùng và mật khẩu; mã trạng thái 407. |
| Trang web đã từ chối quyền truy cập vào IP này. | Cloudflare 1005–1008, 1010, 1012, 1020 và “Sorry, you have been blocked”; Akamai “Access Denied”; Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome; mã trạng thái 401, 403 và 406; hoặc thông báo cho biết trang web đã phát hiện proxy hoặc VPN. |
| Trang web yêu cầu kiểm tra “Bạn có phải là người không?”. | Cloudflare “Just a moment” và Turnstile; PerimeterX “Press & Hold”; các trang CAPTCHA từ DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard và Vercel; thông báo “lưu lượng bất thường” của Google; Amazon CAPTCHA; reCAPTCHA; hCaptcha. |
| Trang web không khả dụng ở quốc gia của kết nối. | Cloudflare 1009, mã trạng thái 451, từ chối dựa trên quốc gia của CloudFront, các cụm từ như “not available in your country” hoặc chuyển hướng đến địa chỉ như |
| Quá nhiều yêu cầu đến từ IP này. | Mã trạng thái 429 hoặc Cloudflare 1015. |
| Trang web đã không phản hồi kịp thời. | Không có phản hồi nào đến trong thời gian quy định hoặc trang web bắt đầu phản hồi rồi bị treo. |
| Kết nối bị gián đoạn hoặc bị từ chối. | Kết nối bị gián đoạn, phản hồi trống hoặc từ chối kết nối trước khi trang được tải. |
| Không thể tìm thấy địa chỉ trang web. | Lỗi DNS. |
| Không thể thiết lập kết nối an toàn. | Lỗi chứng chỉ hoặc TLS: chứng chỉ được cấp cho một địa chỉ khác, đã hết hạn hoặc đã bị thay thế trên đường truyền. |
| Trang web đã chuyển hướng trình duyệt đến một địa chỉ không liên quan. | Địa chỉ cuối cùng thuộc về một trang web khác hiển thị trang ngắn hoặc thông báo từ chối truy cập. |
| Trang web liên tục chuyển hướng theo vòng lặp. | Trình duyệt đã dừng chuỗi chuyển hướng. |
| Trang vẫn trống. | Không có nội dung nào xuất hiện trên đó trong vòng 10 giây. |
| Trang đã ngừng phản hồi. | Trang đã mở nhưng trình duyệt không thể đọc được trong 30 giây vì một script trên đó đã bị treo. |
| Trang web đã trả về một lỗi. | Mã trạng thái 4xx, chẳng hạn như 404. |
| Bản thân trang web bị hỏng; kết nối không phải là vấn đề. | Mã trạng thái 5xx không có dấu hiệu bảo vệ an ninh. |
| Đã xảy ra một lỗi mạng khác. | Mã lỗi trình duyệt được bao gồm trong phần lý do. |
Các lý do được chia thành ba nhóm. proxy_refused và proxy_error có nghĩa là kết nối không thành công: yêu cầu không bao giờ đến được trang web. blocked, challenge, geo_blocked, và rate_limited có nghĩa là proxy đã cho phép yêu cầu đi qua, nhưng trang web đã từ chối quyền truy cập. timeout, connection_reset, dns_error, và ssl_error có nghĩa là hoàn toàn không nhận được phản hồi: nguyên nhân có thể là do proxy, trang web hoặc mạng ở giữa chúng.
Cách script tránh các kết quả sai lệch
Sai sót có thể xảy ra theo cả hai hướng: lỗi tạm thời có thể bị nhầm lẫn là bị chặn, hoặc trang trống có thể bị nhầm lẫn là trang web đã mở thành công. Dưới đây là cách script xử lý các trường hợp mơ hồ:
Tình huống | Những gì script thực hiện |
|---|---|
Kết nối bị ngắt, hết thời gian chờ hoặc proxy từ chối yêu cầu. | Nó thử lại và chờ tối đa 20 giây để có phản hồi. Trạng thái |
Trang web hiển thị bước kiểm tra “Just a moment”. | Nó đợi tối đa 15 giây: bước kiểm tra này thường tự động hoàn thành đối với khách truy cập bình thường. Nếu nó tự biến mất, kết quả là |
Trang mất thời gian để hiển thị các script của nó. | Nó đợi tối đa 10 giây để nội dung xuất hiện. |
Trang web bắt đầu phản hồi và sau đó bị treo. | Nó ghi lại lý do |
Trang web mở hộp thoại | Nó loại bỏ hộp thoại bằng cách hủy bỏ nó; nếu không, trang không thể tiếp tục. Script sau đó tiếp tục kiểm tra. |
Một script trên trang bị treo. | Sau 30 giây, nó sẽ gán lý do |
Trang web chuyển hướng đến phiên bản quốc gia cục bộ của nó, chẳng hạn như | Đó vẫn là cùng một trang web: kết quả là |
Trang web chuyển hướng sang một tên miền khác, nơi tải một trang thông thường. | Kết quả là |
Trang web chuyển hướng đến một trang ngắn không liên quan hoặc một trang từ chối truy cập. | Kết quả là |
Trang chứa script chống bot, nhưng trang web vẫn mở. | Sự hiện diện của lớp bảo vệ không bị coi là từ chối truy cập. Chỉ trang từ chối truy cập thực tế mới được tính. |
Các từ “access denied” xuất hiện trong nội dung của một bài viết thông thường. | Các cụm từ từ chối chỉ được kiểm tra trong tiêu đề trang và trên các trang ngắn, chứ không phải ở giữa các văn bản dài. |
Kết luận
Script tự động hóa việc kiểm tra tính khả dụng của trang web thông qua proxy và VPN. Nó cho biết trang web nào mở được qua từng kết nối và giúp xác định lý do tại sao các trang web khác không khả dụng. Hãy tạo danh sách trang web của bạn một lần, sau đó chạy kiểm tra bất cứ khi nào bạn mua proxy mới, chuyển đổi nhà cung cấp hoặc gặp phải sự cố truy cập trang web. Bằng cách này, bạn sẽ không phải kiểm tra từng kết nối theo cách thủ công.
Các câu hỏi thường gặp
Có thể kiểm tra bao nhiêu kết nối cùng một lúc?
Mỗi profile là một trình duyệt riêng biệt, vì vậy giới hạn phụ thuộc vào bộ nhớ và CPU của bạn. Trên một thiết bị trung bình, 3 đến 5 là một con số hợp lý; hãy đặt giá trị này bằng cài đặt PARALLEL. Nếu tất cả các proxy của bạn sử dụng cùng một cổng của nhà cung cấp, đừng đặt số lượng quá cao: tài khoản nhà cung cấp của bạn có thể giới hạn các kết nối đồng thời.
Một lần kiểm tra mất bao lâu?
Một trang web mở được chỉ mất vài giây. Những trang web không phản hồi sẽ mất nhiều thời gian nhất: script đợi 45 giây rồi thử lại thêm 20 giây nữa. Các kết nối được kiểm tra song song, do đó việc kiểm tra năm proxy sẽ mất khoảng thời gian tương đương với việc kiểm tra một proxy.
Tại sao tất cả các trang web của một kết nối đều được đánh dấu DEAD?
Octo không thể khởi chạy profile bằng proxy hoặc VPN đó: kết nối không hoạt động. Hãy kiểm tra tên người dùng và mật khẩu proxy, giao thức cũng như chi tiết cấu hình VPN. Nếu nhãn là ERROR thay vì DEAD, profile đã không khởi chạy được vì một lý do khác không liên quan đến kết nối. Lý do đó được hiển thị trên dòng của kết nối.
Một trang web được đánh dấu là challenge, nhưng nó vẫn mở được khi thao tác thủ công. Tại sao?
Bước kiểm tra “Bạn có phải là người không?” đã không tự biến mất trong vòng 15 giây. Bạn có thể hoàn tất bằng một cú nhấp chuột theo cách thủ công, nhưng script không nhấp vào bất kỳ mục nào. Thời gian chờ được kiểm soát bởi cài đặt CHECK_WAIT.
Tại sao kết quả giữa các lần chạy lại khác nhau?
Thường gặp nhất là proxy đã thay đổi địa chỉ IP của nó. Proxy xoay vòng sử dụng các IP khác nhau giữa các kết nối và trang web có thể xử lý địa chỉ mới theo cách khác. Với một số nhà cung cấp, danh sách các trang web bị chặn cũng phụ thuộc vào nút thoát: một ngân hàng có thể mở qua một IP này, trong khi nhà cung cấp lại chặn nó qua một IP khác. Một lý do khác có thể là giới hạn tốc độ (rate limit) của chính trang web: sau quá nhiều yêu cầu, nó bắt đầu trả về mã trạng thái 429 hoặc hiển thị bước kiểm tra.
Profile không khởi chạy ngay cả khi Octo đang mở. Tôi nên làm gì?
Kiểm tra cổng API cục bộ: mở cài đặt trình duyệt, chuyển đến tab Bổ sung và xem mục Local HTTP Server. Nếu cổng không phải là 58888, hãy nhập giá trị chính xác vào cài đặt LOCAL_PORT.
Script không tìm thấy tệp cấu hình VPN của tôi. Tại sao?
Tệp cấu hình phải nằm trong thư mục config cạnh script và phải chứa các phần [Interface] và [Peer]. Script sẽ bỏ qua các tệp không có các phần này và liệt kê chúng ở đầu kết quả đầu ra của nó.
Điều gì xảy ra nếu proxy ngừng hoạt động trong quá trình kiểm tra?
Điều này có thể xảy ra khi phiên proxy hết hạn hoặc hết lưu lượng: proxy ngừng phản hồi hoặc không chấp nhận đăng nhập. Sau ba lỗi liên tiếp từ chính proxy, script sẽ ngừng kiểm tra các trang web thông qua kết nối đó để không lãng phí thời gian vào các trang còn lại. Chúng được đánh dấu màu xám và SKIPPED trong báo cáo, đồng thời phần tóm tắt cho biết proxy đã ngừng hoạt động sau trang web nào. Các kết nối khác vẫn tiếp tục được kiểm tra như bình thường. Các trường hợp nhà cung cấp từ chối đối với từng trang web riêng lẻ (proxy_refused) không được tính: trong trường hợp đó, proxy vẫn đang hoạt động.
Điều gì còn lại trong Octo sau khi kiểm tra?
Các profile được đặt tên theo quốc gia và IP, cùng với mọi proxy mới trong danh sách proxy. Để không để lại dấu vết nào, hãy đặt KEEP_PROFILES = false và SAVE_PROXIES = false: các profile sẽ được chuyển vào thùng rác và các proxy sẽ không được thêm vào danh sách.
Script có gửi dữ liệu của tôi đến bất kỳ nơi nào khác ngoài Octo không?
Script chỉ gửi token đến địa chỉ Octo API. Nó thực hiện một yêu cầu tới dịch vụ của bên thứ ba: nếu Octo không báo cáo quốc gia đầu ra, script sẽ tra cứu quốc gia đó theo IP bằng GeoJS. Chỉ IP đầu ra của proxy mới được gửi đến GeoJS.
Duy trì danh tính ẩn trực tuyến của bạn với Octo Browser. Dấu vân tay số thật của bạn sẽ không thể bị truy vết.
Bạn muốn thử Octo Browser với giá ưu đãi không?
Sử dụng mã khuyến mãi OCTOBLOG để được giảm giá 30% cho bất kỳ gói đăng ký nào. Ưu đãi này chỉ dành cho người dùng mới.
Script này có thể làm được gì
Bạn cung cấp cho script ba danh sách: các trang web, proxy và cấu hình VPN. Đối với mỗi proxy và mỗi VPN, script sẽ tạo một profile riêng biệt trong Octo Browser, khởi chạy profile đó, mở từng trang web một và ghi lại kết quả. Cuối cùng, bạn sẽ nhận được một bảng với mỗi hàng là một trang web và mỗi cột là một kết nối, tiếp theo là phần tóm tắt kèm theo lý do cho mọi trường hợp thất bại.
Site GB_203.0.113.9 DE_198.51.100.7 google.com AVAILABLE AVAILABLE wikipedia.org AVAILABLE AVAILABLE amazon.com UNAVAILABLE AVAILABLE ebay.com AVAILABLE AVAILABLE GB_203.0.113.9: 3 AVAILABLE, 1 UNAVAILABLE (1 challenge) DE_198.51.100.7: 4 AVAILABLE, 0 UNAVAILABLE
Ví dụ, script có thể:
Kiểm tra proxy và VPN trong một lần chạy duy nhất. Script đọc proxy từ tệp
proxies.txtvà VPN từ các tệp cấu hình WireGuard trong thư mụcconfig. Nó hỗ trợ các giao thức và định dạng dòng tương tự như tính năng nhập proxy hàng loạt trong Octo Browser, bao gồm cả địa chỉ IPv6.Xác định lý do. Nếu một trang web không tải được, script sẽ cho bạn biết lý do: chính proxy không thể thiết lập kết nối, trang web đã chặn địa chỉ IP, yêu cầu kiểm tra “Bạn có phải là người không?”, không khả dụng ở quốc gia kết nối, hoặc đơn giản là không phản hồi.
Phân biệt giữa việc bị chặn và lỗi ngẫu nhiên. Nếu kết nối bị ngắt hoặc trang web không phản hồi, script sẽ kiểm tra lại. Nếu trang web hiển thị bước kiểm tra “Bạn có phải là người không?”, script sẽ đợi bước này tự biến mất. Nếu trang tải bình thường, việc có lớp bảo vệ chống bot đơn thuần sẽ không bị coi là lỗi.
Chạy kiểm tra song song. Script kiểm tra tối đa mười kết nối cùng lúc và kết quả cho từng trang web sẽ xuất hiện ngay khi có sẵn.
Đặt tên profile theo quốc gia và IP. Profile sẽ nhận được tên như
DE_198.51.100.7. Kết nối không hoạt động được đánh dấu làDEAD, trong khi profile không khởi chạy được vì lý do khác được đánh dấu làERROR.Lưu báo cáo. Script tạo một tệp Excel với bản tóm tắt cho từng kết nối. Các trang web truy cập được sẽ được đánh dấu màu xanh lá cây và các trang không truy cập được sẽ được đánh dấu màu đỏ. Script cũng lưu ảnh chụp màn hình của từng trang lỗi để bạn có thể thấy chính xác những gì trang web đã hiển thị.
Bảo vệ thông tin đăng nhập truy cập. Mật khẩu proxy, khóa VPN và token không được đưa vào kết quả đầu ra trên bảng điều khiển (console) hoặc báo cáo. Các profile cũng được dừng đúng cách, ngay cả khi bạn ngắt quá trình kiểm tra.
Script chỉ quan sát. Nó không giải mã CAPTCHA, nhấp vào các nút hoặc nhập bất kỳ nội dung nào. Hãy ghi nhớ những điều sau:
Kết quả
challengekhông có nghĩa là bạn đã bị cấm. Trang web đang yêu cầu bạn xác nhận mình là người thật và bạn thường có thể mở trang đó theo cách thủ công trong profile.Script chỉ kiểm tra chính xác URL bạn cung cấp. Trang chủ tải thành công không có nghĩa là đăng nhập tài khoản hoặc thanh toán sẽ hoạt động. Hãy thêm URL của một phần cụ thể vào danh sách nếu đó là phần bạn cần kiểm tra.
Kết quả chỉ chính xác tại thời điểm kiểm tra. Proxy xoay vòng có thể sử dụng một IP khác sau đó một phút, vì vậy kết quả có thể thay đổi.
Mỗi kết nối sẽ nhận được một profile mới và các proxy mới sẽ được thêm vào danh sách proxy của Octo. Cả hai đều tiêu tốn giới hạn gói đăng ký của bạn. Bước 3 giải thích cách tránh để lại chúng sau khi kiểm tra.
Tại sao không dùng curl?
Bạn có thể kiểm tra một trang web thông qua proxy bằng một lệnh curl duy nhất, nhưng lệnh này trả lời một câu hỏi khác, cụ thể là: yêu cầu có đến được máy chủ không? Nó không thể cho bạn biết liệu trang web có mở được trong profile trình duyệt hay không.
curlkhông phải là trình duyệt và các trang web có thể nhận ra điều đó. Các hệ thống bảo mật xác định nó bằng vân tay TLS và tập hợp các header, đồng thời có thể từ chối chính clientcurlthay vì proxy của bạn.curlkhông chạy JavaScript. Trình duyệt có thể vượt qua bước kiểm tra “Just a moment” tự động trong vài giây, trong khicurlsẽ bị kẹt ở đó.curlchỉ nhìn thấy mã phản hồi chứ không thấy trang. Một trang giới hạn địa lý, CAPTCHA hoặc từ chối truy cập với mã trạng thái 200 đều trông giống như một trang web được mở thành công đối với nó.curlkhông thể kiểm tra VPN. Nó có thể kết nối qua proxy HTTP và SOCKS, nhưng bạn không thể truyền cấu hình WireGuard vào nó.
curl vẫn có những công dụng riêng: đó là một cách nhanh chóng để tìm hiểu xem proxy có đang hoạt động hay không và địa chỉ IP của nó là gì. Chỉ có trình duyệt trong profile mới có thể cho bạn biết liệu trang web có mở được trong profile đó hay không.
Những thứ bạn sẽ cần
Octo Browser với Gói đăng kí Base trở lên, cho phép bạn truy cập vào API.
Phiên bản Node.js 22.12 trở lên.
Danh sách các proxy hoặc tệp cấu hình WireGuard VPN.
Bước 1. Cài đặt Node.js
Tải xuống Node.js từ nodejs.org và cài đặt bằng cài đặt mặc định. Sau đó mở PowerShell: nhấn Win+R, gõ PowerShell và nhấn Enter. Kiểm tra quá trình cài đặt:
node --version
Lệnh sẽ hiển thị phiên bản 22.12 trở lên. Điều này được yêu cầu bởi Puppeteer 25, phiên bản đã được sử dụng để kiểm tra script. Nếu PowerShell báo không tìm thấy lệnh, hãy đóng PowerShell, mở lại và thử lại.
Bước 2. Chuẩn bị thư mục
Chọn một thư mục cho script, ví dụ: D:\proxy_check, tạo thư mục đó và điều hướng đến thư mục đó trong PowerShell. Tạo một thư mục config bên trong để chứa cấu hình VPN của bạn:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Cài đặt Puppeteer. Phiên bản được chỉ định rõ ràng vì đây là phiên bản mà script đã được thử nghiệm:
npm install puppeteer-core@25
Bước 3. Script site_access.mjs
Trong PowerShell, với proxy_check là thư mục hiện tại, hãy chạy notepad site_access.mjs. Khi được hỏi bạn có muốn tạo tệp mới không, hãy nhấp vào Yes, dán toàn bộ mã và lưu lại bằng cách nhấn Ctrl+S. Tạo tệp từ dòng lệnh giúp tránh sự cố phần mở rộng tệp: nếu bạn tạo tệp qua menu Notepad, tệp có thể được lưu dưới dạng site_access.mjs.txt và script sẽ không chạy. Tạo các tệp khác trong các bước tiếp theo theo cách tương tự.
Các cài đặt được liệt kê ở đầu mã, mỗi cài đặt đều có chú thích giải thích. Một cài đặt là bắt buộc: dán token API của bạn vào API_TOKEN. Bạn có thể tìm thấy nó trong Octo Browser, dưới tab Token API trong cài đặt tài khoản chính của bạn.
const API_TOKEN = "your_token";
Bạn có thể để các cài đặt khác ở giá trị mặc định. Tuy nhiên, hãy chú ý đến hai thông số này:
KEEP_PROFILES = false gửi các profile vào thùng rác sau khi kiểm tra.
SAVE_PROXIES = false ngăn không cho các proxy đã kiểm tra được thêm vào danh sách proxy của Octo. Với các cài đặt này, các profile và proxy được tạo để thử nghiệm sẽ không làm lộn xộn danh sách làm việc của bạn trong trình duyệt. Điều này hữu ích nếu giới hạn profile của bạn thấp.
Dưới đây là mô tả chi tiết về các cài đặt:
Cài đặt | Nội dung kiểm soát |
|---|---|
| Token API Octo Browser |
| Cổng API cục bộ của Octo client, mặc định là 58888. Bạn có thể tìm thấy cổng này trong phần cài đặt dưới tab Bổ sung. |
| Hệ điều hành của profile: |
|
|
| Số lượng kết nối được kiểm tra đồng thời, từ 1 đến 10. |
| Proxy được chỉ định trực tiếp trong mã, ngoài các proxy trong tệp. |
| Tệp chứa proxy; mặc định là |
| Loại được sử dụng cho các dòng proxy không chỉ định loại. |
|
|
| Thư mục chứa cấu hình VPN; mặc định là |
| Giao thức được sử dụng bởi các tệp cấu hình và chế độ được sử dụng để xác định chúng trong Octo API. Mặc định là |
| Tệp chứa danh sách trang web; mặc định là |
|
|
| Có lưu ảnh chụp màn hình của các trang bị lỗi hay không. |
| Số giây chờ trang web phản hồi, để bước kiểm tra “Bạn có phải là người không?” tự biến mất và để nội dung trang xuất hiện. |
Dưới đây là mã:
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { crc32 } from "node:zlib"; const API_TOKEN = ""; // paste your Octo API token between the quotes const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional const OS = "win"; // OS of the profiles: win, mac or android const HEADLESS = false; // true: profiles run without a window; false: with a window const PARALLEL = 5; // connections checked at the same time, from 1 to 10 const PROXIES = [ // one proxy per line, for example "socks5://login:password@proxy.example.com:10000", ]; const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment const KEEP_PROFILES = true; // false: every profile goes to the trash after its check const SCREENSHOTS = true; // true: save a screenshot of every page that did not open const PAGE_TIMEOUT = 45; // seconds a site gets to answer const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself const EMPTY_WAIT = 10; // seconds a blank page gets to show something const HERE = dirname(fileURLToPath(import.meta.url)); const CLOUD = "https://app.octobrowser.net/api/v2/automation"; const LOCAL = `http://localhost:${LOCAL_PORT}/api`; const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" }; const PROXY_TYPES = ["http", "https", "socks5", "ssh"]; const SHORT_PAGE = 2500; const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 }; const RETRY_TIMEOUT = 20; const PROXY_FAILURES = 3; const BROWSER_TIMEOUT = 30; const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]); const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); const anyOf = (phrases) => new RegExp(phrases.join("|")); const secrets = new Set(); const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value)); const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "); const redact = (text) => [...secrets] .sort((a, b) => b.length - a.length) .reduce((clean, secret) => clean.split(secret).join("***"), printable(text)) .replace(/\/\/[^\s/@]+@/g, "//***@"); const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200); const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_"); const localStamp = () => new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-"); const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, ""); const fail = (message) => { console.error(message); process.exit(1); }; const GEO = anyOf([ "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)", "not available in this (country|region)", "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)", "(from|in) a restricted (country|territory|jurisdiction|region|location)", "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)", "(do|does) not accept (players|customers|users|visitors|residents) from", "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)", "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)", "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)", "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)", "unavailable (due to|for) legal reasons", "configured to block access from your country", "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)", "nicht in (deinem|ihrem) land", "pas disponible dans votre (pays|région)", "no está disponible en (tu|su) (país|región)", "não está disponível (no|em) seu país", ]); const PROXY_SEEN = anyOf([ "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))", "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)", "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)", "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)", ]); const CHECKS = anyOf([ "checking (your browser|if the site connection is secure)", "verif(y|ying) (that )?you are (a )?human", "verify (that )?you are not a (robot|bot)", "(prove|confirm) (that )?you are (a )?human", "are you (a )?(human|robot)", "(complete|pass|performing) (a |the )?(security check|captcha)", "security checkpoint", "enable javascript and cookies to continue", "press (&|and) hold", "unusual (traffic|activity)", "suspicious (activity|traffic)", "automated (access|requests|queries|traffic)", "подтвердите, что вы не робот", "проверка браузера", ]); const REFUSALS = anyOf([ "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)", "you (have been|are|were) (blocked|banned)", "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)", "request (blocked|rejected|denied)", "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)", "403 forbidden", "error 403", "you (don.t|do not) have permission to (access|view)", "not authori[sz]ed to (access|view)", "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)", "ваш ip[^.]{0,30}(заблокирован|забанен)", ]); const CLOUDFLARE_ERRORS = { 1005: "the network of this IP is banned", 1006: "this IP is banned", 1007: "this IP is banned", 1008: "this IP is banned", 1010: "the browser signature is banned", 1012: "access denied", 1020: "access denied by a firewall rule", }; function guardOf(header, html) { const server = header("server"); if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare "; if (server.includes("akamai")) return "Akamai "; if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard "; return ""; } function cloudflareError(guard, html, short, words) { const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare"); if (!short || !onCloudflare) return ""; return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || ""; } function view(look) { const text = String(look.text || ""); const title = String(look.title || "").toLowerCase(); const heading = String(look.heading || "").toLowerCase(); const html = String(look.html || "").toLowerCase(); const header = (name) => String(look.headers?.[name] ?? "").toLowerCase(); const short = text.trim().length < SHORT_PAGE; const words = `${title} | ${heading} | ${text.toLowerCase()}`; const guard = guardOf(header, html); return { status: Number(look.status) || 0, url: String(look.url || "").toLowerCase(), html, title, top: `${title} | ${heading}`, words, short, empty: !text.trim(), refusal: short || Number(look.status) >= 400, header, guard, cloudflare: cloudflareError(guard, html, short, words), }; } const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0]; const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : ""); const RULES = [ { verdict: "challenge", detail: "Cloudflare challenge", when: (page) => page.header("cf-mitigated").includes("challenge"), }, { verdict: "blocked", detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`, when: (page) => page.header("cf-mitigated"), }, { verdict: "blocked", detail: "AWS WAF refused", when: (page) => page.header("x-amzn-waf-action") === "block", }, { verdict: "challenge", detail: (page, action) => `AWS WAF ${action}`, when: (page) => page.header("x-amzn-waf-action"), }, { verdict: "blocked", detail: "Sucuri firewall refused", when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")), }, { verdict: "challenge", detail: "Kasada check", when: (page) => (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) || (page.short && page.html.includes("kpsdk")), }, { verdict: "geo_blocked", detail: "Cloudflare 1009: the site bans the country of this IP", when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")), }, { verdict: "geo_blocked", detail: "HTTP 451: unavailable for legal reasons in this country", when: (page) => page.status === 451, }, { verdict: "geo_blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, GEO), }, { verdict: "rate_limited", detail: "Cloudflare 1015: too many requests from this IP", when: (page) => page.cloudflare === "1015", }, { verdict: "blocked", detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`, when: (page) => CLOUDFLARE_ERRORS[page.cloudflare], }, { verdict: "blocked", detail: "Cloudflare: 'you have been blocked'", when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words), }, { verdict: "challenge", detail: "Cloudflare 'Just a moment' check", when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")), }, { verdict: "challenge", detail: "Cloudflare Turnstile check", when: (page) => page.short && page.html.includes("cf-turnstile"), }, { verdict: "blocked", detail: "Akamai: Access Denied", when: (page) => page.refusal && (page.html.includes("errors.edgesuite.net") || page.html.includes("reference #") || /reference #\d+\.[0-9a-f]{6,}/.test(page.words)), }, { verdict: "challenge", detail: "Akamai check", when: (page) => page.short && (page.html.includes("_sec/cp_challenge") || page.html.includes("sec-if-cpt")), }, { verdict: "blocked", detail: "DataDome refused", when: (page) => page.refusal && page.html.includes("captcha-delivery.com") && /temporarily restricted|you have been blocked|access (is |was )?(denied|blocked)/.test(page.words), }, { verdict: "challenge", detail: "DataDome captcha", when: (page) => page.refusal && page.html.includes("captcha-delivery.com"), }, { verdict: "challenge", detail: "PerimeterX (HUMAN) 'Press & Hold'", when: (page) => (page.refusal && page.html.includes("px-captcha")) || page.title.includes("access to this page has been denied") || (page.short && page.status >= 400 && /_pxappid|px-cloud\.net|px-cdn\.net/.test(page.html)), }, { verdict: "blocked", detail: "Imperva (Incapsula) refused", when: (page) => page.refusal && /incapsula incident id|request unsuccessful\. incapsula|this request was blocked by (our|the) security service/.test( page.words, ), }, { verdict: "challenge", detail: "Imperva check", when: (page) => (page.short && page.words.includes("pardon our interruption")) || (page.empty && page.html.includes("_incapsula_resource")), }, { verdict: "blocked", detail: "F5 BIG-IP refused", when: (page) => page.refusal && page.words.includes("the requested url was rejected"), }, { verdict: "blocked", detail: "AWS CloudFront refused", when: (page) => page.status === 403 && page.short && /request blocked|the request could not be satisfied/.test(page.words), }, { verdict: "challenge", detail: "AWS WAF check", when: (page) => page.short && /token\.awswaf\.com|awswafintegration/.test(page.html), }, { verdict: "challenge", detail: "Radware check", when: (page) => page.url.includes("perfdrive.com") || (page.short && page.html.includes("perfdrive.com")), }, { verdict: "challenge", detail: "Vercel security checkpoint", when: (page) => page.title.includes("vercel security checkpoint"), }, { verdict: "challenge", detail: "SiteGround captcha", when: (page) => page.url.includes("/.well-known/sgcaptcha"), }, { verdict: "blocked", detail: "Wordfence refused", when: (page) => page.short && /your access to this site has been limited|generated by wordfence/.test(page.words), }, { verdict: "blocked", detail: "the site blocked the request by its network policy", when: (page) => page.refusal && page.words.includes("blocked due to a network policy"), }, { verdict: "challenge", detail: "Google 'unusual traffic' check", when: (page) => (page.url.includes("google.") && page.url.includes("/sorry/")) || page.words.includes("our systems have detected unusual traffic"), }, { verdict: "challenge", detail: "Amazon captcha", when: (page) => page.refusal && /enter the characters you see below|to discuss automated access to amazon data/.test(page.words), }, { verdict: "challenge", detail: "captcha page", when: (page) => page.short && /recaptcha|hcaptcha|h-captcha|geetest|funcaptcha|arkoselabs/.test(page.html) && /captcha|robot|human|verify|security/.test(page.words), }, { verdict: "blocked", detail: (page, phrase) => `the site sees a proxy or VPN: "${phrase}"`, when: (page) => said(page, PROXY_SEEN), }, { verdict: "challenge", detail: (page, phrase) => `${page.guard}check page: "${phrase}"`, when: (page) => said(page, CHECKS), }, { verdict: "proxy_error", detail: "HTTP 407: the proxy wants another login or password", when: (page) => page.status === 407, }, { verdict: "rate_limited", detail: "HTTP 429: too many requests from this IP", when: (page) => page.status === 429, }, { verdict: "blocked", detail: (page) => `${page.guard}HTTP ${page.status}${quoted(said(page, REFUSALS))}`, when: (page) => [401, 403, 406].includes(page.status), }, { verdict: "blocked", detail: (page, phrase) => `the page says: "${phrase}"`, when: (page) => said(page, REFUSALS), }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: Cloudflare could not reach the site's own server`, when: (page) => page.status >= 520 && page.status <= 527, }, { verdict: "server_error", detail: (page) => `HTTP ${page.status}: the site itself fails`, when: (page) => page.status >= 500, }, { verdict: "http_error", detail: (page) => `HTTP ${page.status}`, when: (page) => page.status >= 400, }, ]; export function classify(look) { const page = view(look); for (const rule of RULES) { const match = rule.when(page); if (match) { return { verdict: rule.verdict, detail: typeof rule.detail === "function" ? rule.detail(page, match) : rule.detail, }; } } return { verdict: "ok", detail: `HTTP ${page.status || "?"}` }; } const NETWORK_ERRORS = [ { verdict: "proxy_error", codes: /ERR_SOCKS5_AUTH|ERR_SOCKS_AUTH|ERR_PROXY_AUTH_REQUESTED/, detail: "the proxy rejected its login or password: it may have expired or run out of traffic", }, { verdict: "proxy_error", codes: /ERR_PROXY_CONNECTION_FAILED|ERR_PROXY_AUTH|ERR_NO_SUPPORTED_PROXIES|ERR_PROXY_CERTIFICATE|ERR_MANDATORY_PROXY/, detail: "the proxy itself does not work", }, { verdict: "proxy_refused", codes: /ERR_TUNNEL_CONNECTION_FAILED|ERR_SOCKS_CONNECTION/, detail: "the proxy did not open a connection to this site, its provider may block the site", }, { verdict: "timeout", codes: /ERR_TIMED_OUT|ERR_CONNECTION_TIMED_OUT/, detail: "the site did not answer in time", }, { verdict: "connection_reset", codes: /ERR_CONNECTION_RESET|ERR_CONNECTION_CLOSED|ERR_CONNECTION_ABORTED|ERR_EMPTY_RESPONSE|ERR_SOCKET_NOT_CONNECTED/, detail: "the connection was cut before an answer came", }, { verdict: "connection_reset", codes: /ERR_HTTP2_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR/, detail: "the site cut the connection, the way some protection services refuse a visitor", }, { verdict: "connection_refused", codes: /ERR_CONNECTION_REFUSED/, detail: "the site refused the connection", }, { verdict: "dns_error", codes: /ERR_NAME_NOT_RESOLVED|ERR_NAME_RESOLUTION_FAILED|ERR_DNS/, detail: "the address of the site was not found", }, { verdict: "ssl_error", codes: /ERR_CERT_COMMON_NAME_INVALID/, detail: "the site's certificate is issued for another address", }, { verdict: "ssl_error", codes: /ERR_CERT_DATE_INVALID/, detail: "the site's certificate has expired or is not valid yet", }, { verdict: "ssl_error", codes: /ERR_SSL|ERR_CERT|ERR_BAD_SSL|ERR_TLS/, detail: "the secure connection failed, something on the way may replace the site's certificate", }, { verdict: "redirect_loop", codes: /ERR_TOO_MANY_REDIRECTS/, detail: "the site redirects in a circle", }, { verdict: "blocked", codes: /ERR_BLOCKED_BY/, detail: "the request was blocked", }, ]; export function networkError(message, timeout = PAGE_TIMEOUT) { const code = (String(message).match(/(?:net::)?\b(ERR_[A-Z0-9_]+)/) || [])[1]; if (!code) { return /timeout/i.test(message) ? { verdict: "timeout", detail: `no answer in ${timeout} s` } : { verdict: "unreachable", detail: firstLine(message) }; } const known = NETWORK_ERRORS.find((entry) => entry.codes.test(code)); return known ? { verdict: known.verdict, detail: `${code}: ${known.detail}` } : { verdict: "unreachable", detail: code }; } let token = ""; let spent = 0; let limits = null; const running = new Set(); const answerOf = async (response) => ({ status: response.status, ok: response.ok, data: await response.json().catch(() => ({})), }); async function cloud(method, path, body) { for (let attempt = 0; ; attempt++) { spent += 1; const response = await fetch(CLOUD + path, { method, headers: { "X-Octo-Api-Token": token, "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(120000), }); if (response.status === 429 && attempt < 5) { const wait = Number(response.headers.get("retry-after")) || 5; if (wait > 60) throw new Error(`Octo's rate limit is used up for ${wait} s, run the script again later`); await sleep(wait * 1000); continue; } const minute = response.headers.get("x-ratelimit-remaining"); const hour = response.headers.get("x-ratelimit-remaining-hour"); if (minute !== null && hour !== null) { limits = { minute, hour, minuteLimit: response.headers.get("x-ratelimit-limit"), hourLimit: response.headers.get("x-ratelimit-limit-hour"), }; if (Number(minute) < 5) await sleep(5000); } return answerOf(response); } } async function local(path, body) { spent += path === "/profiles/active" ? 0 : 1; const response = await fetch(LOCAL + path, { method: body ? "POST" : "GET", headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(180000), }); return answerOf(response); } async function stopProfile(uuid) { await local("/profiles/stop", { uuid }).catch(() => {}); running.delete(uuid); } process.on("SIGINT", async () => { console.log(`\nStopping ${running.size} running profile(s)...`); await Promise.all([...running].map(stopProfile)); process.exit(130); }); const splitOutsideBrackets = (text) => text.split(/:(?![^[]*\])/); const isPort = (text) => /^\d{1,5}$/.test(text || "") && Number(text) >= 1 && Number(text) <= 65535; const isAddress = (text) => /^\[.+\]$/.test(text) || text.includes(".") || text === "localhost"; export function parseProxy(line, defaultType = DEFAULT_TYPE) { const scheme = line.match(/^([a-z0-9]+):\/\//i); const type = scheme ? scheme[1].toLowerCase() : defaultType; const rest = scheme ? line.slice(scheme[0].length) : line; let host, port, login, secret; if (rest.includes("@")) { const at = rest.lastIndexOf("@"); [login, ...secret] = rest.slice(0, at).split(":"); [host, port] = splitOutsideBrackets(rest.slice(at + 1)); } else { const parts = splitOutsideBrackets(rest); const addressFirst = parts.length <= 2 || (isPort(parts[1]) && (isAddress(parts[0]) || !isPort(parts.at(-1)))); if (addressFirst) { [host, port, login, ...secret] = parts; } else { [login, ...secret] = parts.slice(0, -2); [host, port] = parts.slice(-2); } } const password = secret.join(":"); if (!PROXY_TYPES.includes(type) || !host || !isPort(port)) return null; const address = host.replace(/^\[(.+)\]$/, "$1"); return { type, host: address, port: Number(port), ...(login ? { login } : {}), ...(password ? { password } : {}) }; } function proxyLabel(proxy) { const host = proxy.host.includes(":") ? `[${proxy.host}]` : proxy.host; return `${proxy.type}://${proxy.login ? `…${proxy.login.slice(-10)}@` : ""}${host}:${proxy.port}`; } async function proxyUuid(job, saved) { const { proxy } = job; const same = (other) => proxy.type === String(other.type).toLowerCase() && proxy.host === other.host && String(proxy.port) === String(other.port) && (proxy.login || "") === (other.login || "") && (proxy.password || "") === (other.password || ""); const known = saved.find(same); if (known) return known.uuid; const added = await cloud("POST", "/proxies", { ...proxy, title: `proxy ${proxy.host}:${proxy.port} #${job.number}`, }); if (!added.data?.data?.uuid) { throw new Error(`could not add the proxy to Octo (HTTP ${added.status} ${added.data?.code || ""})`); } return added.data.data.uuid; } export function checkVpnConfig(text) { const keys = { interface: new Set(), peer: new Set() }; let section = ""; let endpoint = ""; for (const line of text.split("\n")) { const head = line.match(/^\s*\[(\w+)\]/); const pair = line.match(/^\s*(\w+)\s*=\s*(\S+)/); if (head) section = head[1].toLowerCase(); if (!pair || !keys[section]) continue; keys[section].add(pair[1].toLowerCase()); if (section === "peer" && pair[1].toLowerCase() === "endpoint") endpoint = pair[2]; } const required = [ ["Interface", "PrivateKey"], ["Interface", "Address"], ["Peer", "PublicKey"], ["Peer", "Endpoint"], ]; const missing = required .filter(([part, key]) => !keys[part.toLowerCase()].has(key.toLowerCase())) .map(([part, key]) => `${key} in [${part}]`); if (missing.length) return `no ${missing.join(", ")}`; if (!/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+):\d{1,5}$/i.test(endpoint)) { return `Endpoint must be address:port, without http://, not "${endpoint}"`; } return ""; } export function findVpns(folder) { const vpns = []; const skipped = []; if (!existsSync(folder) || !statSync(folder).isDirectory()) return { vpns, skipped }; const files = readdirSync(folder) .filter((file) => statSync(join(folder, file)).isFile()) .sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" })); for (const file of files) { const raw = readFileSync(join(folder, file)); const text = raw .toString("utf8") .replace(/^\uFEFF/, "") .replace(/\r\n/g, "\n"); if (!/^\s*\[Interface\]/im.test(text) || !/^\s*\[Peer\]/im.test(text)) { skipped.push(file); continue; } const problem = checkVpnConfig(text); if (problem) throw new Error(`${file}: ${problem}`); vpns.push({ file, conf: raw.toString("base64") }); } return { vpns, skipped }; } export function readSites(text) { const sites = []; for (const [index, raw] of text.split(/\r?\n/).entries()) { const line = raw.replace(/\s+#.*$/, "").trim(); if (!line || line.startsWith("#") || /^\[.*\]$/.test(line)) continue; let url; try { url = new URL(/^[a-z]+:\/\//i.test(line) ? line : `https://${line}`); } catch { url = null; } if (!url || !["http:", "https:"].includes(url.protocol) || !url.hostname.includes(".")) { throw new Error(`line ${index + 1}: "${line}" is not a site address`); } const site = url.href.replace(/\/$/, ""); if (!sites.includes(site)) sites.push(site); } return sites; } const REGION_NAMES = new Intl.DisplayNames(["en"], { type: "region" }); const COUNTRY_CODES = new Map(); for (let first = 65; first <= 90; first++) { for (let second = 65; second <= 90; second++) { const code = String.fromCharCode(first, second); try { const name = REGION_NAMES.of(code); if (new Intl.Locale(`und-${code}`).region === code && name && name !== code) { COUNTRY_CODES.set(name.toLowerCase(), code); } } catch { continue; } } } async function countryOf(exit) { const code = String(exit.countryCode || exit.country_code || ""); if (/^[A-Za-z]{2}$/.test(code)) return code.toUpperCase(); const byName = COUNTRY_CODES.get(String(exit.country || exit.countryName || "").toLowerCase()); if (byName) return byName; if (!exit.ip) return "XX"; try { const url = `https://get.geojs.io/v1/ip/country/${encodeURIComponent(exit.ip)}.json`; const found = (await (await fetch(url, { signal: AbortSignal.timeout(20000) })).json()).country; return /^[A-Z]{2}$/.test(found || "") ? found : "XX"; } catch { return "XX"; } } let androidModels = []; async function loadAndroidModels() { const answer = await cloud("GET", "/fingerprint/device_models?device_type=phone"); const models = Array.isArray(answer.data?.data) ? answer.data.data : []; androidModels = models.filter((model) => model?.value && model.os_versions?.length); if (!androidModels.length) fail(`Could not read the Android phone models: HTTP ${answer.status}. Nothing was done.`); } function fingerprint() { if (OS !== "android") return { os: OS }; const model = androidModels[Math.floor(Math.random() * androidModels.length)]; const version = model.os_versions[Math.floor(Math.random() * model.os_versions.length)]; return { os: "android", os_arch: "arm", device_type: "phone", device_model: model.value, os_version: String(version), }; } export function hostOf(url) { try { return new URL(url).hostname.replace(/^www\./, ""); } catch { return String(url); } } export function siteName(url) { try { const path = new URL(url).pathname.replace(/\/$/, ""); return hostOf(url) + path; } catch { return String(url); } } export function brandOf(url) { const parts = hostOf(url).split("."); const secondLevel = ["co", "com", "org", "net", "gov", "ac", "edu", "ltd", "plc"]; const deep = parts.length > 2 && secondLevel.includes(parts[parts.length - 2]); return parts[parts.length - (deep ? 3 : 2)] || parts[0]; } const shows = (look) => String(look.text || "").trim().length >= 20 || /<(img|canvas|svg|video)\b/i.test(String(look.html || "")); async function read(page, answer) { const nothing = { ...answer, title: "", heading: "", text: "", html: "" }; for (let attempt = 0; attempt < 3; attempt++) { try { const seen = await page.evaluate( (limits) => ({ text: (document.body?.innerText || "").slice(0, limits.text), heading: (document.querySelector("h1")?.innerText || "").slice(0, limits.title), title: document.title.slice(0, limits.title), html: (document.documentElement?.outerHTML || "").slice(0, limits.html), }), PAGE_LIMITS, ); if (seen.text.trim().length < SHORT_PAGE) { const frames = page.frames().slice(1, 6); const inside = (frame) => frame.evaluate(() => document.body?.innerText || "").catch(() => ""); const texts = await Promise.all( frames.map((frame) => Promise.race([inside(frame), sleep(3000).then(() => "")])), ); seen.text = [seen.text, ...texts].join("\n").slice(0, PAGE_LIMITS.text); } return { ...answer, ...seen, url: page.url() }; } catch (error) { if (/timed out/i.test(error.message)) return { ...nothing, url: page.url(), unresponsive: true }; await sleep(1000); } } return { ...nothing, url: page.url() }; } const RESTRICTION_PAGE = /(^|[./_-])(restricted|restriction|geo-?block(ed)?|geo-?restrict(ed|ion)?|not-?available|unavailable|access-?denied|blocked|forbidden|country-?(not-?)?(allowed|supported|restricted))([./?#_-]|$)/i; export function restrictionPage(asked, reached) { try { const from = new URL(asked); const to = new URL(reached); if (from.hostname === to.hostname && from.pathname === to.pathname) return ""; const where = `${to.hostname}${to.pathname}`; return RESTRICTION_PAGE.test(where) && !RESTRICTION_PAGE.test(`${from.hostname}${from.pathname}`) ? where : ""; } catch { return ""; } } function moved(asked, look, found) { const to = hostOf(look.url); if (!look.url || to === hostOf(asked)) return found; if (brandOf(look.url) === brandOf(asked)) return { ...found, detail: `${found.detail}, opened as ${to}` }; const page = view(look); const lead = `${page.top} | ${String(look.text || "") .toLowerCase() .slice(0, 1500)}`; const phrase = [GEO, PROXY_SEEN, REFUSALS, CHECKS].map((list) => (lead.match(list) || [""])[0]).find(Boolean); if (!page.short && !phrase) { return { ...found, detail: `${found.detail}, but opened another site: ${to} (check that it is the one you need)` }; } return { verdict: "redirected", detail: `sent to another site, ${to}` + (phrase ? `, which says: "${phrase}"` : "") }; } function watchAnswer(page) { const answer = { status: 0, headers: {} }; page.on("response", (response) => { try { if (response.request().isNavigationRequest() && response.frame() === page.mainFrame()) { Object.assign(answer, { status: response.status(), headers: response.headers() }); } } catch { return; } }); return answer; } async function waitFor(page, answer, look, seconds, pause, settled) { for (const until = Date.now() + seconds * 1000; !settled(look) && Date.now() < until;) { await sleep(pause); look = await read(page, answer); } return look; } async function judge(page, answer, url, slow, timeout) { const stuck = (seen) => seen.unresponsive && { verdict: "unresponsive", detail: `the page stopped responding (HTTP ${seen.status})` }; let look = await read(page, answer); if (look.url.startsWith("chrome-error://") && look.status < 400) return networkError(look.text, timeout); let found = classify(look); if (found.verdict === "challenge") { const check = found.detail; look = await waitFor(page, answer, look, CHECK_WAIT, 2500, (seen) => classify(seen).verdict !== "challenge"); found = classify(look); if (found.verdict === "ok") found.detail += `, passed a check by itself (${check})`; } if (found.verdict === "ok" && !shows(look) && !stuck(look)) { look = await waitFor(page, answer, look, EMPTY_WAIT, 2000, (seen) => shows(seen) || seen.unresponsive); found = classify(look); if (found.verdict === "ok" && !shows(look) && !stuck(look)) { return slow ? { verdict: "timeout", detail: `the site answered (HTTP ${look.status}) but the page did not load in ${timeout} s`, } : { verdict: "empty", detail: `the page stayed empty for ${EMPTY_WAIT} s` }; } } if (stuck(look)) return stuck(look); const restriction = found.verdict === "ok" && restrictionPage(url, look.url); if (restriction) return { verdict: "geo_blocked", detail: `sent to a restriction page, ${restriction.replace(/\/$/, "")}` }; if (found.verdict === "ok") found = moved(url, look, found); if (found.verdict === "ok" && slow) found.detail += ", loaded slowly"; return found; } async function inspect(browser, url, shot, timeout) { const page = await browser.newPage(); const answer = watchAnswer(page); page.on("dialog", (dialog) => dialog.dismiss().catch(() => {})); try { let slow = false; try { await page.goto(url, { waitUntil: "domcontentloaded", timeout: timeout * 1000 }); } catch (error) { const failed = /net::ERR_/.test(error.message) && !error.message.includes("ERR_ABORTED"); if (!answer.status || failed) return networkError(error.message, timeout); slow = /timeout/i.test(error.message); } await page.waitForNetworkIdle({ idleTime: 800, timeout: 8000 }).catch(() => {}); const found = await judge(page, answer, url, slow, timeout); if (found.verdict !== "ok" && found.verdict !== "unresponsive" && shot) { found.screenshot = await page.screenshot({ path: shot }).then( () => shot, () => "", ); } return found; } finally { await page.close().catch(() => {}); } } export async function checkSite(browser, url, shot = "") { let found = await inspect(browser, url, shot, PAGE_TIMEOUT); if (RETRY.has(found.verdict)) { const first = found.verdict; await sleep(3000); found = await inspect(browser, url, shot, Math.min(PAGE_TIMEOUT, RETRY_TIMEOUT)); found.detail += found.verdict === first ? " (on the second try too)" : ` (the first try: ${first})`; } return { result: found.verdict === "ok" ? "AVAILABLE" : "UNAVAILABLE", reason: `${found.verdict}: ${printable(found.detail)}`, screenshot: found.screenshot || "", }; } function checkSettings() { const seconds = [PAGE_TIMEOUT, CHECK_WAIT, EMPTY_WAIT]; const problems = [ [!OS_NAMES[OS], `OS is win, mac or android, not "${OS}".`], [typeof HEADLESS !== "boolean", "HEADLESS is true or false, without quotes."], [typeof KEEP_PROFILES !== "boolean", "KEEP_PROFILES is true or false, without quotes."], [typeof SCREENSHOTS !== "boolean", "SCREENSHOTS is true or false, without quotes."], [!Number.isInteger(PARALLEL) || PARALLEL < 1 || PARALLEL > 10, "PARALLEL is a whole number from 1 to 10."], [!PROXY_TYPES.includes(DEFAULT_TYPE), `DEFAULT_TYPE is one of ${PROXY_TYPES.join(", ")}.`], [seconds.some((value) => !(value > 0)), "PAGE_TIMEOUT, CHECK_WAIT and EMPTY_WAIT are seconds above zero."], [!Number.isInteger(LOCAL_PORT) || LOCAL_PORT < 1 || LOCAL_PORT > 65535, "LOCAL_PORT is a port number, 1 to 65535."], [typeof SAVE_PROXIES !== "boolean", "SAVE_PROXIES is true or false, without quotes."], ]; const problem = problems.find(([wrong]) => wrong); if (problem) fail(`${problem[1]} Nothing was done.`); } function readToken() { const found = String(API_TOKEN).trim(); if (!found) fail("No API token: paste it into API_TOKEN at the top of the script. Nothing was done."); return found; } function readProxies() { const file = join(HERE, PROXY_FILE); const fromFile = PROXY_FILE && existsSync(file) ? readText(file).split(/\r?\n/) : []; const lines = [...PROXIES, ...fromFile].map((line) => line.trim()).filter((line) => line && !line.startsWith("#")); const proxies = lines.map((line) => parseProxy(line)); const bad = proxies.flatMap((proxy, index) => (proxy ? [] : [index + 1])); if (bad.length) fail(`Proxy line(s) ${bad.join(", ")} not understood. Nothing was done.`); proxies.forEach((proxy) => hide(proxy.password)); return proxies; } function readVpns() { try { const { vpns, skipped } = findVpns(join(HERE, VPN_FOLDER)); if (skipped.length) console.log(`Not VPN configs, skipped in ${VPN_FOLDER}: ${skipped.join(", ")}`); if (vpns.length) console.log(`VPN configs found in ${VPN_FOLDER}: ${vpns.map((vpn) => vpn.file).join(", ")}`); if (vpns.length && !(String(VPN_PROTOCOL).trim() && String(VPN_SYN_MODE).trim())) { fail("VPN_PROTOCOL and VPN_SYN_MODE can't be empty. Nothing was done."); } for (const vpn of vpns) { hide(vpn.conf); const keys = Buffer.from(vpn.conf, "base64") .toString() .matchAll(/^\s*(?:PrivateKey|PresharedKey)\s*=\s*(\S+)/gim); for (const [, key] of keys) hide(key); } return vpns; } catch (error) { return fail(`VPN config ${error.message} (folder ${VPN_FOLDER}). Nothing was done.`); } } function readSitesFile() { const file = join(HERE, SITES_FILE); if (!existsSync(file)) fail(`${SITES_FILE} not found next to the script: put the sites there. Nothing was done.`); try { const sites = readSites(readText(file)); if (!sites.length) fail(`${SITES_FILE} has no sites. Nothing was done.`); return sites; } catch (error) { return fail(`${SITES_FILE}, ${error.message}. Nothing was done.`); } } async function connectionOf(job, saved) { if (job.vpn) return { type: "vpn", vpn_protocol: VPN_PROTOCOL, conf: job.vpn.conf, syn_mode: VPN_SYN_MODE }; return SAVE_PROXIES ? { uuid: await proxyUuid(job, saved) } : job.proxy; } async function createProfile(job, saved) { const connection = await connectionOf(job, saved); const profile = { title: `checking ${job.number}`, fingerprint: fingerprint(), proxy: connection }; const made = await cloud("POST", "/profiles", profile); if (made.data?.data?.uuid) return made.data.data.uuid; const errors = made.data?.errors ? JSON.stringify(made.data.errors).slice(0, 200) : ""; const why = [made.data?.code, made.data?.msg || made.data?.error, errors].filter(Boolean).join(" "); throw new Error(`could not create a profile (HTTP ${made.status} ${why})`); } async function startProfile(uuid) { const start = { uuid, headless: HEADLESS, debug_port: true, flags: ["--disable-backgrounding-occluded-windows"] }; const started = await local("/profiles/start", start).catch((error) => ({ ok: false, data: { error: error.message }, })); const works = Boolean(started.ok && started.data?.ws_endpoint); if (works) running.add(uuid); return { ...started, works }; } function progress(index, total, site, checked) { const count = `${String(index + 1).padStart(String(total).length)}/${total}`; const reason = /^ok: HTTP [\d?]+$/.test(checked.reason) ? "" : checked.reason; return `${count} ${checked.result.padEnd(11)} ${siteName(site).padEnd(30)} ${reason}`.trimEnd(); } async function visitSites(job, started, name, { sites, puppeteer, stamp }, say) { const entries = []; const ip = printable(started.data.connection_data?.ip || ""); const folder = join(HERE, `screens_${stamp}`, fileName(`${job.number}_${name}`)); if (SCREENSHOTS) mkdirSync(folder, { recursive: true }); let browser; let failures = 0; try { browser = await puppeteer.connect({ browserWSEndpoint: started.data.ws_endpoint, defaultViewport: null, protocolTimeout: BROWSER_TIMEOUT * 1000, }); for (const [index, site] of sites.entries()) { const number = String(index + 1).padStart(String(sites.length).length, "0"); const shot = SCREENSHOTS ? join(folder, `${number}_${fileName(siteName(site))}.png`) : ""; const checked = await checkSite(browser, site, shot); entries.push({ site, ...checked, ip }); say(progress(index, sites.length, site, checked)); failures = checked.reason.startsWith("proxy_error:") ? failures + 1 : 0; const rest = sites.slice(index + 1); if (failures === PROXY_FAILURES && rest.length) { const kind = job.vpn ? "VPN" : "proxy"; const reason = `not checked: the ${kind} stopped working after site ${index + 1}`; say(`the ${kind} stopped working: ${PROXY_FAILURES} proxy errors in a row, ${rest.length} site(s) not checked`); entries.push(...rest.map((left) => ({ site: left, result: "SKIPPED", reason, ip }))); break; } } } catch (error) { say(`stopped after ${entries.length} of ${sites.length} site(s): ${firstLine(error.message)}`); } finally { await browser?.disconnect().catch(() => {}); } return entries; } function startFailure(job, started, sites) { const reason = redact(started.data?.code || started.data?.error || `HTTP ${started.status}`); const dead = /proxy/i.test(reason) || [4, 5].includes(started.data?.error_code); const name = `${dead ? "DEAD" : "ERROR"}_${fileName(job.vpn ? job.vpn.file : job.proxy.host)}`; const problem = dead ? `the ${job.vpn ? "VPN" : "proxy"} does not work` : "could not start the profile"; return { name, message: `${job.label} -> ${name}: ${problem} (${reason})`, entries: sites.map((site) => ({ site, result: dead ? "DEAD" : "ERROR", reason })), }; } async function finishProfile(uuid, name, say) { const renamed = await cloud("PATCH", `/profiles/${uuid}`, { title: name }); if (!renamed.ok) say(`could not rename the profile (HTTP ${renamed.status})`); if (!KEEP_PROFILES) await cloud("DELETE", "/profiles", { uuids: [uuid], skip_trash_bin: false }); } async function checkConnection(job, context) { let tag = `#${job.number}`; const say = (text) => console.log(`[${tag}] ${text}`); const uuid = await createProfile(job, context.saved); say(`${job.label}: starting the profile...`); const started = await startProfile(uuid); let name, entries; if (started.works) { const exit = started.data.connection_data || {}; name = `${await countryOf(exit)}_${printable(exit.ip || "no-ip")}`; tag = `#${job.number} ${name}`; say(`${job.label}: started, ${context.sites.length} site(s) to check`); try { entries = await visitSites(job, started, name, context, say); } finally { await stopProfile(uuid); } } else { if (started.ok || started.status === undefined) await stopProfile(uuid); const failure = startFailure(job, started, context.sites); say(failure.message); ({ name, entries } = failure); } await finishProfile(uuid, name, say); const blank = { profile: name, proxy: `#${job.number} ${job.label}`, ip: "", screenshot: "" }; const rows = entries.map((entry) => ({ ...blank, ...entry })); if (rows.some((entry) => entry.result.endsWith("AVAILABLE"))) say(`done: ${summary(rows, context.sites.length)}`); return { name, rows }; } function reasonsOf(rows) { const reasons = new Map(); for (const entry of rows.filter((row) => row.result === "UNAVAILABLE")) { const reason = entry.reason.split(":")[0]; reasons.set(reason, (reasons.get(reason) || 0) + 1); } return [...reasons] .sort((a, b) => b[1] - a[1]) .map(([reason, times]) => `${times} ${reason}`) .join(", "); } function unchecked(rows, expected) { const skipped = rows.filter((entry) => entry.result === "SKIPPED"); const missed = expected - rows.length; return ( (skipped.length ? `, ${skipped.length} not checked: ${skipped[0].reason.replace(/^not checked: /, "")}` : "") + (missed ? `, ${missed} not checked` : "") ); } function summary(rows, expected) { const count = (result) => rows.filter((entry) => entry.result === result).length; if (count("DEAD")) return "does not work"; if (count("ERROR")) return `not checked: ${rows[0].reason}`; const why = reasonsOf(rows); return ( `${count("AVAILABLE")} AVAILABLE, ${count("UNAVAILABLE")} UNAVAILABLE` + (why ? ` (${why})` : "") + unchecked(rows, expected) ); } async function runAll(jobs, limit, work) { const results = new Array(jobs.length); let next = 0; const worker = async () => { while (next < jobs.length) { const index = next++; const job = jobs[index]; const done = await work(job).catch((error) => { console.log(`[#${job.number}] ${job.label}: ${firstLine(error.message)}`); return { name: "", rows: [] }; }); results[index] = { number: job.number, label: job.label, ...done }; } }; await Promise.all(Array.from({ length: limit }, worker)); return results; } function printTable(sites, results) { const columns = results.filter((column) => column.name); const repeated = (name) => columns.filter((column) => column.name === name).length > 1; const titles = columns.map((column) => (repeated(column.name) ? `${column.name} #${column.number}` : column.name)); const width = Math.max(11, ...titles.map((title) => title.length)) + 2; const siteWidth = Math.max(4, ...sites.map((site) => siteName(site).length)) + 2; console.log("Site".padEnd(siteWidth) + titles.map((title) => title.padEnd(width)).join("")); for (const site of sites) { const cells = columns.map((column) => column.rows.find((entry) => entry.site === site)?.result || "-"); console.log(siteName(site).padEnd(siteWidth) + cells.map((cell) => cell.padEnd(width)).join("")); } console.log(""); columns.forEach((column, index) => console.log(`${titles[index]}: ${summary(column.rows, sites.length)}`)); } const REPORT_COLUMNS = ["profile", "proxy", "site", "result", "reason", "ip"]; function zip(files) { const parts = []; const directory = []; let offset = 0; for (const [name, text] of files) { const title = Buffer.from(name); const data = Buffer.from(text); const local = Buffer.alloc(30); local.writeUInt32LE(0x04034b50, 0); local.writeUInt16LE(20, 4); local.writeUInt16LE(0x0800, 6); local.writeUInt16LE(0x21, 12); local.writeUInt32LE(crc32(data), 14); local.writeUInt32LE(data.length, 18); local.writeUInt32LE(data.length, 22); local.writeUInt16LE(title.length, 26); const central = Buffer.alloc(46); central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6); local.copy(central, 8, 6, 30); central.writeUInt32LE(offset, 42); parts.push(local, title, data); directory.push(central, title); offset += local.length + title.length + data.length; } const index = Buffer.concat(directory); const end = Buffer.alloc(22); end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10); end.writeUInt32LE(index.length, 12); end.writeUInt32LE(offset, 16); return Buffer.concat([...parts, index, end]); } const XLSX_ROW_STYLES = { AVAILABLE: 2, UNAVAILABLE: 3 }; const XLSX_OTHER_STYLE = 4; const XLSX_STYLES = '<fonts count="5"><font><sz val="11"/><name val="Calibri"/></font>' + '<font><b/><sz val="11"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF006100"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF9C0006"/><name val="Calibri"/></font>' + '<font><sz val="11"/><color rgb="FF595959"/><name val="Calibri"/></font></fonts>' + '<fills count="5"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFC6EFCE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFFFC7CE"/></patternFill></fill>' + '<fill><patternFill patternType="solid"><fgColor rgb="FFE7E6E6"/></patternFill></fill></fills>' + '<borders count="1"><border/></borders>' + '<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs>' + '<cellXfs count="5"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>' + '<xf numFmtId="0" fontId="1" fillId="0" borderId="0" xfId="0" applyFont="1"/>' + '<xf numFmtId="0" fontId="2" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="3" fillId="3" borderId="0" xfId="0" applyFont="1" applyFill="1"/>' + '<xf numFmtId="0" fontId="4" fillId="4" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs>' + '<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>'; const SUMMARY_COLUMNS = ["profile", "proxy", "AVAILABLE", "UNAVAILABLE", "why unavailable", "ip"]; function summaryRows(results, siteCount) { return results.map((result) => { const count = (word) => result.rows.filter((entry) => entry.result === word).length; const dead = count("DEAD") || count("ERROR"); const note = dead ? summary(result.rows, siteCount) : `${reasonsOf(result.rows)}${unchecked(result.rows, siteCount)}`.replace(/^, /, ""); return { values: [ result.name || "not started", `#${result.number} ${result.label}`, dead || !result.rows.length ? "" : count("AVAILABLE"), dead || !result.rows.length ? "" : count("UNAVAILABLE"), !result.rows.length ? "the profile was not created" : note, result.rows[0]?.ip || "", ], dead: dead || !result.rows.length, }; }); } function xlsxSheet(results, siteCount) { const escapes = { "<": "<", ">": ">", "&": "&" }; const text = (value) => printable(value ?? "") .replace(/[\uFFFE\uFFFF]/g, "") .slice(0, 32000) .replace(/[<>&]/g, (sign) => escapes[sign]); const cell = (column, line, value, style) => { const where = `${String.fromCharCode(65 + column)}${line}`; if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`; return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`; }; const line = (values, number, styles) => `<row r="${number}">${values .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles)) .join("")}</row>`; const rows = results.flatMap((result) => result.rows); const lines = []; const add = (values, styles) => lines.push(line(values, lines.length + 1, styles)); add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1); add(SUMMARY_COLUMNS, 1); for (const { values, dead } of summaryRows(results, siteCount)) { add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]); } lines.push(`<row r="${lines.length + 1}"/>`); const header = lines.length + 1; add(REPORT_COLUMNS, 1); for (const entry of rows) { add( REPORT_COLUMNS.map((column) => entry[column]), XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE, ); } const widths = REPORT_COLUMNS.map((column, i) => Math.min( 90, Math.max( column.length, SUMMARY_COLUMNS[i].length, ...rows.map((entry) => String(entry[column] ?? "").length), ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length), ) + 2, ), ); const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`; return ( `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` + `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>` ); } function writeXlsx(results, siteCount, stamp) { const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'; const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships"; const type = "application/vnd.openxmlformats-officedocument.spreadsheetml"; const file = join(HERE, `site_access_${stamp}.xlsx`); const files = [ [ "[Content_Types].xml", `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` + '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' + '<Default Extension="xml" ContentType="application/xml"/>' + `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` + `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` + `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`, ], [ "_rels/.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`, ], [ "xl/workbook.xml", `${head}<workbook xmlns="${main}" xmlns:r="${office}">` + '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>', ], [ "xl/_rels/workbook.xml.rels", `${head}<Relationships xmlns="${packageRels}">` + `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` + `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`, ], [ "xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`], ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`], ]; writeFileSync(file, zip(files)); return file; } async function main() { checkSettings(); token = readToken(); hide(token); const proxies = readProxies(); const vpns = readVpns(); if (!proxies.length && !vpns.length) { fail( `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`, ); } const sites = readSitesFile(); const puppeteer = await import("puppeteer-core").then( (module) => module.default, () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."), ); await local("/profiles/active").catch(() => fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`), ); if (OS === "android") await loadAndroidModels(); const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true }; if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`); const saved = Array.isArray(list.data?.data) ? list.data.data : []; const jobs = [ ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })), ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })), ].map((job, index) => ({ ...job, number: index + 1 })); const workers = Math.min(PARALLEL, jobs.length); const stamp = localStamp(); console.log( `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` + `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`, ); const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp })); const rows = results.flatMap((result) => result.rows); console.log(""); printTable(sites, results); console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`); if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`); const left = limits ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` + `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.` : ""; console.log(`${spent} request(s) counted by Octo's rate limits.${left}`); } main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));
Bước 4. Tạo danh sách các trang web
Tạo một tệp bằng cách chạy notepad sites.txt. Thực hiện theo các quy tắc sau:
Đặt mỗi địa chỉ trên một dòng mới.
Bạn có thể đưa tiền tố
https://vào hoặc bỏ qua.Bắt đầu các dòng chú thích bằng
#. Các chú thích rất hữu ích để chia danh sách thành các nhóm.
# Search and reference sites google.com wikipedia.org # Online stores amazon.com ebay.com
Bước 5. Thêm proxy và VPN
Script cần ít nhất một kết nối để hoạt động: proxy hoặc cấu hình VPN. Bạn cũng có thể định cấu hình cả hai loại kết nối.
Proxy. Tạo một tệp bằng cách chạy notepad proxies.txt và thêm các proxy của bạn, mỗi proxy trên một dòng. Script chấp nhận các giao thức và định dạng dòng tương tự như khi nhập proxy hàng loạt trong Octo Browser. Các giao thức được hỗ trợ: http, https, socks5, và ssh. Các định dạng được hỗ trợ:
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
Địa chỉ IPv6 phải được đặt trong dấu ngoặc vuông: socks5://[2001:db8::1]:1080:login:password. Bạn cũng có thể bỏ qua giao thức khỏi một dòng; trong trường hợp đó, loại được chỉ định trong DEFAULT_TYPE sẽ được sử dụng. Các dòng bắt đầu bằng # sẽ bị bỏ qua.
VPN. Đặt các tệp cấu hình WireGuard của bạn vào thư mục config. Tên tệp có thể là bất kỳ tên nào: script xác định cấu hình theo nội dung của nó, cụ thể là các phần [Interface] và [Peer]. Cấu hình không được thêm vào danh sách proxy của Octo; nó chỉ tồn tại bên trong profile riêng của chính nó.
[Interface] PrivateKey = <client key> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <server key>
Trước khi chạy, script sẽ kiểm tra từng cấu hình xem có PrivateKey, Address, PublicKey, và Endpoint hay không, đồng thời xác minh rằng Endpoint được viết dưới dạng địa chỉ và cổng, không có http://. Nếu script phát hiện lỗi, nó sẽ hiển thị tên tệp và mô tả sự cố, sau đó thoát ra mà không tạo bất kỳ profile nào.
Cấu trúc thư mục của bạn sẽ trông như thế này:
D:\proxy_check\ site_access.mjs script sites.txt website list proxies.txt proxy list config\ VPN configs
Bước 6. Chạy kiểm tra
Mở Octo Browser và chạy script từ thư mục của nó:
cd D:\proxy_check node site_access.mjs
Trong lần chạy đầu tiên, hãy sử dụng một proxy và ba hoặc bốn trang web. Bạn sẽ có thể thấy các trang web mở trong cửa sổ profile. Khi bạn đã xác nhận rằng mọi thứ đều hoạt động, hãy thêm phần còn lại.
Khi script bắt đầu, nó sẽ kiểm tra mọi thứ có thể khiến nó không chạy được: token, các tệp, cấu hình VPN và việc Octo đã được mở hay chưa. Nếu phát hiện lỗi, nó sẽ hiển thị thông báo mô tả sự cố và thoát ra mà không tạo profile. Quá trình kiểm tra sau đó sẽ bắt đầu và kết quả cho từng trang web sẽ được hiển thị ngay khi có sẵn.

Dấu ngoặc vuông hiển thị số thứ tự kết nối, tên profile của kết nối đó và bộ đếm trang web. Khi một số kết nối được kiểm tra song song, các dòng kết quả đầu ra của chúng có thể xen kẽ nhau. Hãy sử dụng nhãn để xem mỗi dòng thuộc về kết nối nào. Mật khẩu proxy không được hiển thị trong kết quả đầu ra và chỉ vài ký tự cuối của tên người dùng được hiển thị. Để dừng kiểm tra, hãy nhấn Ctrl+C. Script sẽ dừng các profile mà nó đã khởi chạy.
Cách đọc kết quả
Cuối cùng, script sẽ in một bảng và tóm tắt cho từng kết nối:

AVAILABLE có nghĩa là trang web đã mở thành công và hiển thị nội dung. UNAVAILABLE có nghĩa là trang web không mở được. Các lý do trong ngoặc đơn sau kết quả cuối cùng được liệt kê theo thứ tự tần suất giảm dần. DEAD trong tên cột có nghĩa là chính kết nối không hoạt động, chứ không phải là tất cả các trang web đang được kiểm tra đều không khả dụng.
Nhãn ERROR có nghĩa là profile không khởi chạy được vì lý do không liên quan đến kết nối. Thông báo lỗi của Octo xuất hiện trên dòng kết nối đó trong bảng điều khiển và trong báo cáo.
Các tệp đầu ra được lưu trong thư mục. Dấu thời gian trong tên tệp sử dụng giờ địa phương:
site_access_<time>.xlsx— một báo cáo Excel. Phần trên cùng chứa bản tóm tắt hiển thị tổng số trang web và đối với mỗi kết nối, có bao nhiêu trang web truy cập được, bao nhiêu trang không truy cập được và lý do. Bên dưới là kết quả kiểm tra chi tiết, với mỗi hàng cho một kết quả: profile, kết nối, trang web, kết quả, lý do và IP. Các hàng dành cho trang web truy cập được có màu xanh lá cây; các hàng không truy cập được có màu đỏ. Các hàng màu xám biểu thị kết nối không hoạt động và các trang web không được kiểm tra vì proxy đã ngừng hoạt động.screens_<time>— ảnh chụp màn hình của các trang lỗi, với một thư mục riêng cho từng kết nối và ảnh chụp màn hình được đánh số theo thứ tự của danh sách trang web. Nếu trang web không phản hồi hoặc chính proxy không thể thiết lập kết nối thì sẽ không có gì để chụp, do đó không có ảnh chụp màn hình nào được lưu.
Các profile vẫn còn trong Octo Browser và được đặt tên theo quốc gia và IP.
Chúng ta hãy xem xét một số vấn đề có thể xảy ra:
Những gì bạn thấy trong báo cáo | Ý nghĩa | Những việc cần làm |
|---|---|---|
Kết nối được đánh dấu | Bản thân kết nối không hoạt động. | Kiểm tra tên người dùng, mật khẩu và loại proxy hoặc chi tiết cấu hình VPN. |
Kết nối được đánh dấu | Profile không khởi chạy được, nhưng vấn đề không nằm ở kết nối. | Đọc lỗi trong báo cáo hoặc bảng điều khiển, khắc phục nguyên nhân và chạy lại kiểm tra. |
Một vài mục | Proxy ngừng hoạt động trong quá trình kiểm tra: lưu lượng đã hết hoặc phiên đã hết hạn. | Kiểm tra proxy và chạy lại quy trình kiểm tra. |
Một kết nối có nhiều kết quả | Nhà cung cấp proxy đã chặn các trang web đó. | Hỏi nhà cung cấp của bạn xem danh mục trang web nào bị chặn trên gói dịch vụ của bạn. |
Một kết nối nhận được | Trang web không tin tưởng địa chỉ IP này hoặc mạng con của nó. | Thay đổi IP hoặc sử dụng một loại proxy khác. |
| Trang web không khả dụng ở quốc gia đầu ra. | Sử dụng proxy từ quốc gia khác. |
| Chính trang web không phản hồi. | Hãy thử kiểm tra lại sau. |
| Kết nối chậm hoặc liên tục bị ngắt. | Thay thế kết nối. |
| Có quá nhiều yêu cầu đến từ cùng một IP. | Chờ và giảm giá trị |
Ý nghĩa của các lý do
Mã phản hồi của máy chủ không đáng tin cậy trong trường hợp này. Việc từ chối truy cập không phải lúc nào cũng đi kèm với lỗi: Akamai có thể trả về “Access Denied” với mã trạng thái 200, kiểm tra AWS WAF có thể trả về 202 và việc chặn từ DataDome có thể trả về 401. Đó là lý do tại sao script đọc trực tiếp trang web. Các trang web lớn hiếm khi tự tạo trang từ chối truy cập từ đầu: một trong những hệ thống bảo mật phổ biến sẽ hiển thị trang chặn, và mỗi hệ thống đều có chữ ký riêng trong header và văn bản.
Lý do trong báo cáo | Chuyện gì đã xảy ra | Cách nhận diện |
|---|---|---|
| Proxy không thể thiết lập kết nối tới trang web này. | Lỗi tunnel hoặc SOCKS trong trình duyệt. Đây là biểu hiện của một trang web bị nhà cung cấp proxy chặn. |
| Bản thân proxy không hoạt động. | Proxy không phản hồi hoặc không chấp nhận tên người dùng và mật khẩu; mã trạng thái 407. |
| Trang web đã từ chối quyền truy cập vào IP này. | Cloudflare 1005–1008, 1010, 1012, 1020 và “Sorry, you have been blocked”; Akamai “Access Denied”; Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome; mã trạng thái 401, 403 và 406; hoặc thông báo cho biết trang web đã phát hiện proxy hoặc VPN. |
| Trang web yêu cầu kiểm tra “Bạn có phải là người không?”. | Cloudflare “Just a moment” và Turnstile; PerimeterX “Press & Hold”; các trang CAPTCHA từ DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard và Vercel; thông báo “lưu lượng bất thường” của Google; Amazon CAPTCHA; reCAPTCHA; hCaptcha. |
| Trang web không khả dụng ở quốc gia của kết nối. | Cloudflare 1009, mã trạng thái 451, từ chối dựa trên quốc gia của CloudFront, các cụm từ như “not available in your country” hoặc chuyển hướng đến địa chỉ như |
| Quá nhiều yêu cầu đến từ IP này. | Mã trạng thái 429 hoặc Cloudflare 1015. |
| Trang web đã không phản hồi kịp thời. | Không có phản hồi nào đến trong thời gian quy định hoặc trang web bắt đầu phản hồi rồi bị treo. |
| Kết nối bị gián đoạn hoặc bị từ chối. | Kết nối bị gián đoạn, phản hồi trống hoặc từ chối kết nối trước khi trang được tải. |
| Không thể tìm thấy địa chỉ trang web. | Lỗi DNS. |
| Không thể thiết lập kết nối an toàn. | Lỗi chứng chỉ hoặc TLS: chứng chỉ được cấp cho một địa chỉ khác, đã hết hạn hoặc đã bị thay thế trên đường truyền. |
| Trang web đã chuyển hướng trình duyệt đến một địa chỉ không liên quan. | Địa chỉ cuối cùng thuộc về một trang web khác hiển thị trang ngắn hoặc thông báo từ chối truy cập. |
| Trang web liên tục chuyển hướng theo vòng lặp. | Trình duyệt đã dừng chuỗi chuyển hướng. |
| Trang vẫn trống. | Không có nội dung nào xuất hiện trên đó trong vòng 10 giây. |
| Trang đã ngừng phản hồi. | Trang đã mở nhưng trình duyệt không thể đọc được trong 30 giây vì một script trên đó đã bị treo. |
| Trang web đã trả về một lỗi. | Mã trạng thái 4xx, chẳng hạn như 404. |
| Bản thân trang web bị hỏng; kết nối không phải là vấn đề. | Mã trạng thái 5xx không có dấu hiệu bảo vệ an ninh. |
| Đã xảy ra một lỗi mạng khác. | Mã lỗi trình duyệt được bao gồm trong phần lý do. |
Các lý do được chia thành ba nhóm. proxy_refused và proxy_error có nghĩa là kết nối không thành công: yêu cầu không bao giờ đến được trang web. blocked, challenge, geo_blocked, và rate_limited có nghĩa là proxy đã cho phép yêu cầu đi qua, nhưng trang web đã từ chối quyền truy cập. timeout, connection_reset, dns_error, và ssl_error có nghĩa là hoàn toàn không nhận được phản hồi: nguyên nhân có thể là do proxy, trang web hoặc mạng ở giữa chúng.
Cách script tránh các kết quả sai lệch
Sai sót có thể xảy ra theo cả hai hướng: lỗi tạm thời có thể bị nhầm lẫn là bị chặn, hoặc trang trống có thể bị nhầm lẫn là trang web đã mở thành công. Dưới đây là cách script xử lý các trường hợp mơ hồ:
Tình huống | Những gì script thực hiện |
|---|---|
Kết nối bị ngắt, hết thời gian chờ hoặc proxy từ chối yêu cầu. | Nó thử lại và chờ tối đa 20 giây để có phản hồi. Trạng thái |
Trang web hiển thị bước kiểm tra “Just a moment”. | Nó đợi tối đa 15 giây: bước kiểm tra này thường tự động hoàn thành đối với khách truy cập bình thường. Nếu nó tự biến mất, kết quả là |
Trang mất thời gian để hiển thị các script của nó. | Nó đợi tối đa 10 giây để nội dung xuất hiện. |
Trang web bắt đầu phản hồi và sau đó bị treo. | Nó ghi lại lý do |
Trang web mở hộp thoại | Nó loại bỏ hộp thoại bằng cách hủy bỏ nó; nếu không, trang không thể tiếp tục. Script sau đó tiếp tục kiểm tra. |
Một script trên trang bị treo. | Sau 30 giây, nó sẽ gán lý do |
Trang web chuyển hướng đến phiên bản quốc gia cục bộ của nó, chẳng hạn như | Đó vẫn là cùng một trang web: kết quả là |
Trang web chuyển hướng sang một tên miền khác, nơi tải một trang thông thường. | Kết quả là |
Trang web chuyển hướng đến một trang ngắn không liên quan hoặc một trang từ chối truy cập. | Kết quả là |
Trang chứa script chống bot, nhưng trang web vẫn mở. | Sự hiện diện của lớp bảo vệ không bị coi là từ chối truy cập. Chỉ trang từ chối truy cập thực tế mới được tính. |
Các từ “access denied” xuất hiện trong nội dung của một bài viết thông thường. | Các cụm từ từ chối chỉ được kiểm tra trong tiêu đề trang và trên các trang ngắn, chứ không phải ở giữa các văn bản dài. |
Kết luận
Script tự động hóa việc kiểm tra tính khả dụng của trang web thông qua proxy và VPN. Nó cho biết trang web nào mở được qua từng kết nối và giúp xác định lý do tại sao các trang web khác không khả dụng. Hãy tạo danh sách trang web của bạn một lần, sau đó chạy kiểm tra bất cứ khi nào bạn mua proxy mới, chuyển đổi nhà cung cấp hoặc gặp phải sự cố truy cập trang web. Bằng cách này, bạn sẽ không phải kiểm tra từng kết nối theo cách thủ công.
Các câu hỏi thường gặp
Có thể kiểm tra bao nhiêu kết nối cùng một lúc?
Mỗi profile là một trình duyệt riêng biệt, vì vậy giới hạn phụ thuộc vào bộ nhớ và CPU của bạn. Trên một thiết bị trung bình, 3 đến 5 là một con số hợp lý; hãy đặt giá trị này bằng cài đặt PARALLEL. Nếu tất cả các proxy của bạn sử dụng cùng một cổng của nhà cung cấp, đừng đặt số lượng quá cao: tài khoản nhà cung cấp của bạn có thể giới hạn các kết nối đồng thời.
Một lần kiểm tra mất bao lâu?
Một trang web mở được chỉ mất vài giây. Những trang web không phản hồi sẽ mất nhiều thời gian nhất: script đợi 45 giây rồi thử lại thêm 20 giây nữa. Các kết nối được kiểm tra song song, do đó việc kiểm tra năm proxy sẽ mất khoảng thời gian tương đương với việc kiểm tra một proxy.
Tại sao tất cả các trang web của một kết nối đều được đánh dấu DEAD?
Octo không thể khởi chạy profile bằng proxy hoặc VPN đó: kết nối không hoạt động. Hãy kiểm tra tên người dùng và mật khẩu proxy, giao thức cũng như chi tiết cấu hình VPN. Nếu nhãn là ERROR thay vì DEAD, profile đã không khởi chạy được vì một lý do khác không liên quan đến kết nối. Lý do đó được hiển thị trên dòng của kết nối.
Một trang web được đánh dấu là challenge, nhưng nó vẫn mở được khi thao tác thủ công. Tại sao?
Bước kiểm tra “Bạn có phải là người không?” đã không tự biến mất trong vòng 15 giây. Bạn có thể hoàn tất bằng một cú nhấp chuột theo cách thủ công, nhưng script không nhấp vào bất kỳ mục nào. Thời gian chờ được kiểm soát bởi cài đặt CHECK_WAIT.
Tại sao kết quả giữa các lần chạy lại khác nhau?
Thường gặp nhất là proxy đã thay đổi địa chỉ IP của nó. Proxy xoay vòng sử dụng các IP khác nhau giữa các kết nối và trang web có thể xử lý địa chỉ mới theo cách khác. Với một số nhà cung cấp, danh sách các trang web bị chặn cũng phụ thuộc vào nút thoát: một ngân hàng có thể mở qua một IP này, trong khi nhà cung cấp lại chặn nó qua một IP khác. Một lý do khác có thể là giới hạn tốc độ (rate limit) của chính trang web: sau quá nhiều yêu cầu, nó bắt đầu trả về mã trạng thái 429 hoặc hiển thị bước kiểm tra.
Profile không khởi chạy ngay cả khi Octo đang mở. Tôi nên làm gì?
Kiểm tra cổng API cục bộ: mở cài đặt trình duyệt, chuyển đến tab Bổ sung và xem mục Local HTTP Server. Nếu cổng không phải là 58888, hãy nhập giá trị chính xác vào cài đặt LOCAL_PORT.
Script không tìm thấy tệp cấu hình VPN của tôi. Tại sao?
Tệp cấu hình phải nằm trong thư mục config cạnh script và phải chứa các phần [Interface] và [Peer]. Script sẽ bỏ qua các tệp không có các phần này và liệt kê chúng ở đầu kết quả đầu ra của nó.
Điều gì xảy ra nếu proxy ngừng hoạt động trong quá trình kiểm tra?
Điều này có thể xảy ra khi phiên proxy hết hạn hoặc hết lưu lượng: proxy ngừng phản hồi hoặc không chấp nhận đăng nhập. Sau ba lỗi liên tiếp từ chính proxy, script sẽ ngừng kiểm tra các trang web thông qua kết nối đó để không lãng phí thời gian vào các trang còn lại. Chúng được đánh dấu màu xám và SKIPPED trong báo cáo, đồng thời phần tóm tắt cho biết proxy đã ngừng hoạt động sau trang web nào. Các kết nối khác vẫn tiếp tục được kiểm tra như bình thường. Các trường hợp nhà cung cấp từ chối đối với từng trang web riêng lẻ (proxy_refused) không được tính: trong trường hợp đó, proxy vẫn đang hoạt động.
Điều gì còn lại trong Octo sau khi kiểm tra?
Các profile được đặt tên theo quốc gia và IP, cùng với mọi proxy mới trong danh sách proxy. Để không để lại dấu vết nào, hãy đặt KEEP_PROFILES = false và SAVE_PROXIES = false: các profile sẽ được chuyển vào thùng rác và các proxy sẽ không được thêm vào danh sách.
Script có gửi dữ liệu của tôi đến bất kỳ nơi nào khác ngoài Octo không?
Script chỉ gửi token đến địa chỉ Octo API. Nó thực hiện một yêu cầu tới dịch vụ của bên thứ ba: nếu Octo không báo cáo quốc gia đầu ra, script sẽ tra cứu quốc gia đó theo IP bằng GeoJS. Chỉ IP đầu ra của proxy mới được gửi đến GeoJS.
Cập nhật với các tin tức Octo Browser mới nhất
Khi nhấp vào nút này, bạn sẽ đồng ý với Chính sách Quyền riêng tư của chúng tôi.
Cập nhật với các tin tức Octo Browser mới nhất
Khi nhấp vào nút này, bạn sẽ đồng ý với Chính sách Quyền riêng tư của chúng tôi.
Cập nhật với các tin tức Octo Browser mới nhất
Khi nhấp vào nút này, bạn sẽ đồng ý với Chính sách Quyền riêng tư của chúng tôi.

Tham gia Octo Browser ngay
Hoặc liên hệ với Dịch vụ khách hàng bất kì lúc nào nếu bạn có bất cứ thắc mắc nào.

Tham gia Octo Browser ngay
Hoặc liên hệ với Dịch vụ khách hàng bất kì lúc nào nếu bạn có bất cứ thắc mắc nào.
Tham gia Octo Browser ngay
Hoặc liên hệ với Dịch vụ khách hàng bất kì lúc nào nếu bạn có bất cứ thắc mắc nào.