
Alex Phillips
Customer Service Specialist
Octo Browser — это антидетект-браузер для работы со множеством аккаунтов: у каждого профиля свой цифровой отпечаток и подключение. От подключения зависит, какие сайты профиль вообще откроет: один и тот же сайт через один прокси работает, через другой показывает проверку «Вы человек?», а через третий не отвечает. Проверять это вручную долго: на пять прокси и пятьдесят сайтов уходит вечер. В этой статье разберем, как собрать скрипт на Node.js и Puppeteer, который сам проходит по списку сайтов через каждый ваш прокси и VPN в профилях Octo Browser и по каждому сайту отвечает, доступен он или нет и почему.
Содержание
Сохраняйте анонимность с Octo Browser, ведь отследить ваш реальный цифровой отпечаток невозможно.
Хотите попробовать Octo Browser со скидкой?
По промокоду OCTOBLOG получите 30% скидку на любую подписку. Предложение действительно только для новых пользователей.
Что умеет скрипт
Вы даете скрипту три списка: сайты, прокси и VPN-конфиги. Для каждого прокси и каждого VPN он создает в Octo Browser отдельный профиль, запускает его, по очереди открывает сайты и записывает результат. В конце получается таблица: строка на сайт, колонка на подключение, а под таблицей — итог с причинами.
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
Например, скрипт умеет:
Проверять прокси и VPN в одном запуске. Прокси берет из файла
proxies.txt, VPN — из файлов конфигурации WireGuard в папкеconfig. Принимает те же протоколы и форматы строк, что и массовое добавление прокси в Octo Browser, включая адреса IPv6.Называть причину. Если сайт не открылся, скрипт пишет почему: соединение не открыл сам прокси, сайт заблокировал этот IP, потребовал проверку «Вы человек?», закрыт для страны подключения или просто не ответил.
Отличать блокировку от случайного сбоя. Если соединение оборвалось или сайт не ответил, скрипт проверяет его еще раз. Если сайт показал проверку «Вы человек?», ждет, пока она пройдет сама. А если страница открылась нормально, наличие на ней защиты от ботов за отказ не считает.
Работать параллельно. Проверяет до десяти подключений одновременно, и результат каждого сайта виден сразу, как только он готов.
Называть профили по стране и IP. Профиль получает название вида
DE_198.51.100.7. Нерабочее подключение получает пометкуDEAD, а профиль, который не запустился по другой причине, —ERROR.Сохранять отчет. Пишет файл Excel со сводкой по каждому подключению, где доступные сайты выделены зеленым, а недоступные красным, и скриншот каждой страницы отказа: видно, что именно показал сайт.
Защищать данные доступа. Пароли прокси, ключи VPN и токен в консоль и в отчет не попадают, а профили корректно останавливаются, даже если прервать проверку.
Скрипт только смотрит. Он не решает капчи, не нажимает кнопки и ничего не вводит. Поэтому учитывайте:
Результат
challenge— это не бан. Сайт просит подтвердить, что вы человек, и вручную в профиле такой сайт обычно открывается.Проверяется только тот адрес, который вы указали. Открылась главная страница — еще не значит, что сработает вход в аккаунт или оплата. Если важен конкретный раздел, добавьте в список его адрес.
Результат верен на момент проверки. Ротируемый прокси через минуту выйдет с другим IP, и картина может измениться.
Каждое подключение — это новый профиль, а новые прокси попадают в список прокси Octo. И то и другое занимает место в лимитах подписки. Как не оставлять после проверки ничего, рассказано в шаге 3.
Почему не проверить через curl
Сайт через прокси можно проверить и одной командой curl, но она отвечает на другой вопрос: дошел ли запрос до сервера. Откроется ли сайт в браузере профиля, curl не знает.
curlне браузер, и сайты это видят. Защита узнает его по отпечатку TLS и набору заголовков и отказывает самомуcurl, а не вашему прокси.curlне выполняет JavaScript. Проверку «Just a moment» браузер проходит сам за пару секунд, аcurlна ней останавливается.curlвидит код ответа, а не страницу. Геозаглушка, капча или отказ с кодом 200 для него выглядят как открывшийся сайт.curlне проверяет VPN. Он ходит через HTTP- и SOCKS-прокси, а конфиг WireGuard в него передать нельзя.
У curl свое место: быстро узнать, жив ли прокси и какой у него IP. На вопрос, откроется ли сайт в профиле, отвечает только браузер этого профиля.
Что понадобится
Клиент Octo Browser на подписке Base или выше: с нее доступен API.
Node.js версии 22.12 или новее.
Список прокси или файлы VPN-конфигов WireGuard.
Шаг 1. Установите Node.js
Скачайте Node.js с nodejs.org и установите его, оставив все настройки по умолчанию. Затем откройте PowerShell: нажмите Win+R, введите PowerShell и нажмите Enter. Проверьте установку:
node --version
node --version
Команда должна показать версию 22.12 или новее: ее требует Puppeteer 25, с которым проверен скрипт. Если PowerShell пишет, что команда не найдена, закройте его, откройте снова и повторите.
Шаг 2. Подготовьте папку
Выберите папку для скрипта, например D:\proxy_check, создайте ее и перейдите в нее в PowerShell. Внутри сразу создайте папку config для VPN-конфигураций:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Установите Puppeteer. Версия указана явно, потому что скрипт проверен именно с ней:
npm install puppeteer-core@25
npm install puppeteer-core@25
Шаг 3. Скрипт site_access.mjs
В PowerShell, открытом в папке proxy_check, выполните notepad site_access.mjs. На вопрос «Создать новый файл?» нажмите Да, вставьте код целиком и сохраните сочетанием Ctrl+S. Создание файла через командную строку позволяет избежать ошибки с расширением: если создавать его через меню «Блокнота», он может сохраниться как site_access.mjs.txt, и скрипт не запустится. Остальные файлы из следующих шагов создаются так же.
В первых строках кода собраны настройки, каждая подписана комментарием. Обязательна одна: вставьте в API_TOKEN свой API-токен. Он находится в клиенте Octo Browser, в настройках мастер-аккаунта на вкладке «API-токены».
const API_TOKEN = "ваш_токен";
const API_TOKEN = "ваш_токен";
Для остальных настроек можно использовать значения по умолчанию. Однако обратите внимание на два параметра:
KEEP_PROFILES = false отправляет профили в корзину после проверки.
SAVE_PROXIES = false не добавляет проверяемые прокси в список прокси Octo. При таких настройках созданные для проверки профили и прокси не будут загромождать рабочие списки в клиенте. Это будет полезно, если у вас небольшой лимит профилей.
Вот подробное описание настроек:
Настройка | Что задает |
|---|---|
| API-токен Octo Browser |
| Порт локального API клиента Octo, по умолчанию 58888. Он указан в настройках клиента на вкладке «Дополнительные» |
| Система профилей: |
|
|
| Сколько подключений проверяется одновременно, от 1 до 10 |
| Прокси прямо в коде, в дополнение к файлу |
| Файл с прокси, по умолчанию |
| Тип для строк прокси, в которых он не указан |
|
|
| Папка с VPN-конфигурациями, по умолчанию |
| Протокол файлов конфигурации, а также режим, как их называет API Octo. По умолчанию |
| Файл со списком сайтов, по умолчанию |
|
|
| Сохранять ли скриншоты страниц отказа |
| Сколько секунд ждать ответа сайта, прохождения проверки «Вы человек?» и появления содержимого на странице |
А вот нужный код:
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 go 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 go 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)}`));
Шаг 4. Составьте список сайтов
Создайте файл командой notepad sites.txt. Соблюдайте следующие правила:
каждый адрес указывайте с новой строки;
адреса можно указывать с префиксом
https://или без него;строки с комментариями начинайте с символа
#, комментариями удобно делить списки на группы.
# Поиск и справочники google.com wikipedia.org # Магазины amazon.com ebay.com
# Поиск и справочники google.com wikipedia.org # Магазины amazon.com ebay.com
Шаг 5. Добавьте прокси и VPN
Для работы скрипта нужно хотя бы одно подключение: прокси или VPN-конфигурация. Можно настроить сразу оба типа подключения.
Прокси. Создайте файл командой notepad proxies.txt и запишите в него прокси, по одному в строке. Скрипт принимает те же протоколы и те же форматы строк, что и массовое добавление прокси в Octo Browser. Протоколы: http, https, socks5 и ssh. Форматы:
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
Адрес IPv6 пишется в квадратных скобках: socks5://[2001:db8::1]:1080:login:password. Строку можно указать и без протокола, тогда берется тип из настройки DEFAULT_TYPE. Строки, которые начинаются с #, пропускаются.
VPN. Положите конфиги WireGuard в папку config. Имя файла может быть любым: скрипт узнает конфиг по содержимому, по разделам [Interface] и [Peer]. В список прокси Octo конфиг не добавляется, он живет только внутри своего профиля.
[Interface] PrivateKey = <ключ клиента> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <ключ сервера>
[Interface] PrivateKey = <ключ клиента> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <ключ сервера>
Перед запуском скрипт проверяет каждый конфиг: есть ли в нем PrivateKey, Address, PublicKey и Endpoint и записан ли Endpoint как адрес:порт, без http://. Если скрипт обнаружит ошибку, он выведет имя файла и описание проблемы, а затем завершит работу без создания профилей.
В итоге у вас должны быть следующие файлы и папки:
D:\proxy_check\ site_access.mjs скрипт sites.txt список сайтов proxies.txt список прокси config\ VPN-конфиги
D:\proxy_check\ site_access.mjs скрипт sites.txt список сайтов proxies.txt список прокси config\ VPN-конфиги
Шаг 6. Запустите проверку
Откройте клиент Octo Browser и запустите скрипт из его папки:
cd D:\proxy_check node site_access.mjs
cd D:\proxy_check node site_access.mjs
Для первого запуска возьмите один прокси и три-четыре сайта: в окне профиля будет видно, как открываются сайты. Когда убедитесь, что все работает, добавляйте остальные.
В начале работы скрипт проверяет все, что может помешать работе: токен, файлы, конфигурации VPN, открыт ли клиент. Если скрипт обнаружит ошибку, он выведет сообщение с ее описанием и завершит работу без создания профилей. Затем начинается проверка, по каждому сайту сразу выводится результат.

В квадратных скобках — номер подключения, название его профиля и счетчик сайтов. При параллельной работе строки разных подключений могут чередоваться. По метке можно определить, к какому подключению относится каждая строка. От пароля прокси в выводе нет ничего, от логина — только последние символы. Чтобы прервать проверку, нажмите Ctrl+C: скрипт остановит профили, которые успел запустить.
Как читать результат
В конце скрипт печатает таблицу и итог по каждому подключению:

AVAILABLE означает, что сайт действительно открылся и показал содержимое. UNAVAILABLE — что сайт не открылся. В скобках после итогового результата перечислены причины в порядке убывания частоты их возникновения. DEAD в названии колонки означает, что не работает само подключение, а не то, что все проверяемые сайты недоступны.
Пометка ERROR означает, что профиль не запустился по причине, не связанной с подключением: текст ошибки Octo указан в строке этого подключения в консоли и в отчете.
В папке появляются результаты. Время в их названиях местное:
site_access_<время>.xlsx— отчет для Excel. Вверху сводка: сколько всего сайтов и по строке на каждое подключение — сколько сайтов доступно, сколько недоступно и по каким причинам. Ниже та же проверка построчно: профиль, подключение, сайт, результат, причина и IP. Строки доступных сайтов зеленые, недоступных — красные. Серые — строки нерабочего подключения и сайты, которые не проверялись, потому что прокси перестал работать.screens_<время>— скриншоты страниц отказа, по папке на подключение, пронумерованные в порядке списка сайтов. Если сайт не ответил или соединение не открыл сам прокси, снимать нечего, и скриншота не будет.
Профили остаются в Octo Browser с названиями по стране и IP.
Рассмотрим возможные проблемы:
Что видно в отчете | Что это значит | Что делать |
|---|---|---|
Подключение помечено | Не работает само подключение | Проверьте логин, пароль и тип прокси или данные VPN-конфигурации |
Подключение помечено | Профиль не запустился, но проблема не в подключении | Прочитайте текст ошибки в отчете или в консоли, устраните причину и запустите проверку заново |
Несколько | Прокси перестал работать посреди проверки: кончился трафик или истекла сессия | Проверьте прокси и запустите проверку заново |
У одного подключения много | Эти сайты закрыл провайдер прокси | Уточните у провайдера, какие категории сайтов он закрывает на вашем тарифе |
| Сайт не доверяет этому IP или его подсети | Смените IP или возьмите прокси другого типа |
| Сайт не работает в стране выхода | Нужен прокси другой страны |
| Не отвечает сам сайт | Повторите проверку позже |
| Подключение медленное или теряет соединения | Замените подключение |
| Слишком частые запросы с одного IP | Подождите и уменьшите |
Что означают причины
Код ответа сервера здесь ненадежен. Отказ не всегда приходит с ошибкой: Akamai может отдать «Access Denied» с кодом 200, проверка AWS WAF приходит с кодом 202, а блокировка DataDome — с кодом 401. Поэтому скрипт читает саму страницу. Крупные сайты редко пишут заглушку с нуля: отказ показывает одна из известных систем защиты, и у каждой свой почерк в заголовках и тексте.
Причина в отчете | Что произошло | Как распознается |
|---|---|---|
| Прокси не открыл соединение с этим сайтом | Ошибка туннеля или SOCKS в браузере. Так выглядит сайт, закрытый провайдером прокси |
| Не работает сам прокси | Прокси не отвечает или не принял логин и пароль, код 407 |
| Сайт отказал этому IP | Cloudflare 1005–1008, 1010, 1012, 1020 и «Sorry, you have been blocked», Akamai «Access Denied», Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome, коды 401, 403 и 406, сообщение сайта о том, что он видит прокси или VPN |
| Сайт требует проверку «Вы человек?» | Cloudflare «Just a moment» и Turnstile, PerimeterX «Press & Hold», капча DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard, Vercel, «unusual traffic» у Google, капча Amazon, reCAPTCHA, hCaptcha |
| Сайт закрыт для страны подключения | Cloudflare 1009, код 451, отказ CloudFront по стране, фразы вида «not available in your country», перенаправление на адрес вида |
| Слишком много запросов с этого IP | Код 429, Cloudflare 1015 |
| Сайт не ответил вовремя | За отведенное время не пришло ответа, или сайт начал отвечать и завис |
| Соединение оборвано или отклонено | Сброс, пустой ответ или отказ в соединении до загрузки страницы |
| Адрес сайта не найден | Ошибка DNS |
| Защищенное соединение не установилось | Ошибка сертификата или TLS: сертификат выдан на другой адрес, просрочен или подменен по пути |
| Сайт увел на чужой адрес | Конечный адрес принадлежит другому сайту, и там короткая страница или отказ |
| Сайт перенаправляет по кругу | Браузер прервал цепочку перенаправлений |
| Страница осталась пустой | За 10 секунд на ней ничего не появилось |
| Страница перестала отвечать | Страница открылась, но браузер 30 секунд не мог ее прочитать: на ней завис скрипт |
| Сайт ответил ошибкой | Коды 4xx, например 404 |
| Сайт сам сломан, подключение ни при чем | Код 5xx без признаков защиты |
| Другая сетевая ошибка | Код ошибки браузера указан в причине |
Причины делятся на три группы. proxy_refused и proxy_error означают, что отказало подключение: до сайта запрос не дошел. blocked, challenge, geo_blocked и rate_limited — что прокси соединение пропустил, а отказал уже сайт. timeout, connection_reset, dns_error и ssl_error — что ответа не пришло вовсе: причина может быть и в прокси, и в сайте, и в сети между ними.
Как скрипт избегает ложных результатов
Ошибиться можно в обе стороны: принять разовый сбой за блокировку или пустую страницу за открывшийся сайт. Вот как скрипт ведет себя в спорных случаях:
Случай | Что делает скрипт |
|---|---|
Соединение оборвалось, истекло время или прокси отказал | Пробует еще раз и ждет ответа до 20 секунд. |
Сайт показал проверку «Just a moment» | Ждет до 15 секунд: у обычного посетителя такая проверка часто проходит сама. Прошла — |
Страница рисуется скриптами не сразу | Ждет до 10 секунд, пока на ней что-то появится |
Сайт начал отвечать и завис | Отдельная причина |
Сайт открыл окно | Закрывает окно отменой, иначе страница не продолжит работу, и проверяет дальше |
На странице завис скрипт | Через 30 секунд ставит причину |
Сайт перенаправил на свою страну, | Это тот же сайт: |
Сайт перевел на другой домен, и там обычная страница |
|
Сайт увел на чужую короткую страницу или на страницу с отказом |
|
На странице есть скрипт защиты, но сайт открылся | Присутствие защиты не считается отказом. Учитывается только сама страница отказа |
Слова «access denied» в тексте обычной статьи | Фразы отказа учитываются в заголовке страницы и на короткой странице, но не в середине длинного текста |
Заключение
Скрипт автоматизирует проверку доступности сайтов через прокси и VPN: показывает, какие сайты открываются через каждое подключение, и помогает определить причины недоступности остальных. Заполните список сайтов один раз и запускайте проверку при покупке новых прокси, смене провайдера или возникновении проблем с доступом к сайтам. Так вам не придется проверять каждое подключение вручную.
Частые вопросы
Сколько подключений можно проверять одновременно?
Каждый профиль — это отдельный браузер, поэтому все упирается в память и процессор. На обычном компьютере разумно от трех до пяти, это задает настройка PARALLEL. Если все прокси идут через один шлюз провайдера, не ставьте много: у аккаунта провайдера может быть ограничение на одновременные соединения.
Сколько времени занимает проверка?
Открывшийся сайт занимает несколько секунд. Дольше всего проверяются сайты, которые не отвечают: скрипт ждет 45 секунд и повторяет попытку еще на 20. Подключения проверяются параллельно, поэтому пять прокси занимают примерно столько же времени, сколько один.
Почему все сайты у подключения помечены DEAD?
Octo не смог запустить профиль с этим прокси или VPN: подключение не работает. Проверьте логин и пароль прокси, протокол в строке и данные в VPN-конфиге. Если вместо DEAD стоит ERROR, профиль не запустился по другой причине, не из-за подключения: она указана в строке этого подключения.
Сайт помечен challenge, а вручную он открывается
Значит, проверка «Вы человек?» не прошла сама за 15 секунд. Вручную вы проходите ее кликом, а скрипт ничего не нажимает. Время ожидания задает настройка CHECK_WAIT.
Почему результат различается от запуска к запуску?
Чаще всего прокси сменил IP: у ротируемых прокси он меняется между подключениями, и сайт относится к новому адресу иначе. У некоторых провайдеров от выходного узла зависит и список закрытых сайтов: через один IP банк открывается, через другой провайдер его закрывает. Еще одна причина — лимиты самого сайта: после частых запросов он начинает отвечать кодом 429 или показывать проверку.
Профиль не запускается, хотя клиент Octo открыт
Проверьте порт локального API: настройки клиента, вкладка «Дополнительные», «Локальный HTTP-сервер». Если он отличается от 58888, укажите его в настройке LOCAL_PORT.
Скрипт не видит мой файл конфигурации VPN
Файл конфигурации должен лежать в папке config рядом со скриптом и содержать разделы [Interface] и [Peer]. Файлы без этих разделов скрипт пропускает и перечисляет в начале вывода.
Что будет, если прокси перестанет работать посреди проверки?
Так бывает, когда у прокси истекает сессия или кончается трафик: он перестает отвечать или принимать логин. После трех ошибок самого прокси подряд скрипт прекращает проверку через это подключение, чтобы не тратить время на оставшиеся сайты. В отчете они отмечены серым как SKIPPED, а в сводке написано, после какого сайта прокси перестал работать. Остальные подключения проверяются дальше как обычно. Отказы провайдера по отдельным сайтам, proxy_refused, в счет не идут: прокси при этом работает.
Что остается в Octo после проверки?
Профили с названиями по стране и IP и новые прокси в списке прокси. Чтобы не оставалось ничего, поставьте KEEP_PROFILES = false и SAVE_PROXIES = false: профили уйдут в корзину, а прокси в список не попадут.
Передает ли скрипт мои данные куда-то, кроме Octo?
Токен скрипт отправляет только на адрес API Octo. Есть одно обращение к стороннему сервису: если Octo не сообщил страну выхода, скрипт спрашивает ее по IP у GeoJS. Туда уходит только IP выхода прокси.
Сохраняйте анонимность с Octo Browser, ведь отследить ваш реальный цифровой отпечаток невозможно.
Хотите попробовать Octo Browser со скидкой?
По промокоду OCTOBLOG получите 30% скидку на любую подписку. Предложение действительно только для новых пользователей.
Что умеет скрипт
Вы даете скрипту три списка: сайты, прокси и VPN-конфиги. Для каждого прокси и каждого VPN он создает в Octo Browser отдельный профиль, запускает его, по очереди открывает сайты и записывает результат. В конце получается таблица: строка на сайт, колонка на подключение, а под таблицей — итог с причинами.
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
Например, скрипт умеет:
Проверять прокси и VPN в одном запуске. Прокси берет из файла
proxies.txt, VPN — из файлов конфигурации WireGuard в папкеconfig. Принимает те же протоколы и форматы строк, что и массовое добавление прокси в Octo Browser, включая адреса IPv6.Называть причину. Если сайт не открылся, скрипт пишет почему: соединение не открыл сам прокси, сайт заблокировал этот IP, потребовал проверку «Вы человек?», закрыт для страны подключения или просто не ответил.
Отличать блокировку от случайного сбоя. Если соединение оборвалось или сайт не ответил, скрипт проверяет его еще раз. Если сайт показал проверку «Вы человек?», ждет, пока она пройдет сама. А если страница открылась нормально, наличие на ней защиты от ботов за отказ не считает.
Работать параллельно. Проверяет до десяти подключений одновременно, и результат каждого сайта виден сразу, как только он готов.
Называть профили по стране и IP. Профиль получает название вида
DE_198.51.100.7. Нерабочее подключение получает пометкуDEAD, а профиль, который не запустился по другой причине, —ERROR.Сохранять отчет. Пишет файл Excel со сводкой по каждому подключению, где доступные сайты выделены зеленым, а недоступные красным, и скриншот каждой страницы отказа: видно, что именно показал сайт.
Защищать данные доступа. Пароли прокси, ключи VPN и токен в консоль и в отчет не попадают, а профили корректно останавливаются, даже если прервать проверку.
Скрипт только смотрит. Он не решает капчи, не нажимает кнопки и ничего не вводит. Поэтому учитывайте:
Результат
challenge— это не бан. Сайт просит подтвердить, что вы человек, и вручную в профиле такой сайт обычно открывается.Проверяется только тот адрес, который вы указали. Открылась главная страница — еще не значит, что сработает вход в аккаунт или оплата. Если важен конкретный раздел, добавьте в список его адрес.
Результат верен на момент проверки. Ротируемый прокси через минуту выйдет с другим IP, и картина может измениться.
Каждое подключение — это новый профиль, а новые прокси попадают в список прокси Octo. И то и другое занимает место в лимитах подписки. Как не оставлять после проверки ничего, рассказано в шаге 3.
Почему не проверить через curl
Сайт через прокси можно проверить и одной командой curl, но она отвечает на другой вопрос: дошел ли запрос до сервера. Откроется ли сайт в браузере профиля, curl не знает.
curlне браузер, и сайты это видят. Защита узнает его по отпечатку TLS и набору заголовков и отказывает самомуcurl, а не вашему прокси.curlне выполняет JavaScript. Проверку «Just a moment» браузер проходит сам за пару секунд, аcurlна ней останавливается.curlвидит код ответа, а не страницу. Геозаглушка, капча или отказ с кодом 200 для него выглядят как открывшийся сайт.curlне проверяет VPN. Он ходит через HTTP- и SOCKS-прокси, а конфиг WireGuard в него передать нельзя.
У curl свое место: быстро узнать, жив ли прокси и какой у него IP. На вопрос, откроется ли сайт в профиле, отвечает только браузер этого профиля.
Что понадобится
Клиент Octo Browser на подписке Base или выше: с нее доступен API.
Node.js версии 22.12 или новее.
Список прокси или файлы VPN-конфигов WireGuard.
Шаг 1. Установите Node.js
Скачайте Node.js с nodejs.org и установите его, оставив все настройки по умолчанию. Затем откройте PowerShell: нажмите Win+R, введите PowerShell и нажмите Enter. Проверьте установку:
node --version
Команда должна показать версию 22.12 или новее: ее требует Puppeteer 25, с которым проверен скрипт. Если PowerShell пишет, что команда не найдена, закройте его, откройте снова и повторите.
Шаг 2. Подготовьте папку
Выберите папку для скрипта, например D:\proxy_check, создайте ее и перейдите в нее в PowerShell. Внутри сразу создайте папку config для VPN-конфигураций:
cd D:\ mkdir proxy_check cd proxy_check mkdir config
Установите Puppeteer. Версия указана явно, потому что скрипт проверен именно с ней:
npm install puppeteer-core@25
Шаг 3. Скрипт site_access.mjs
В PowerShell, открытом в папке proxy_check, выполните notepad site_access.mjs. На вопрос «Создать новый файл?» нажмите Да, вставьте код целиком и сохраните сочетанием Ctrl+S. Создание файла через командную строку позволяет избежать ошибки с расширением: если создавать его через меню «Блокнота», он может сохраниться как site_access.mjs.txt, и скрипт не запустится. Остальные файлы из следующих шагов создаются так же.
В первых строках кода собраны настройки, каждая подписана комментарием. Обязательна одна: вставьте в API_TOKEN свой API-токен. Он находится в клиенте Octo Browser, в настройках мастер-аккаунта на вкладке «API-токены».
const API_TOKEN = "ваш_токен";
Для остальных настроек можно использовать значения по умолчанию. Однако обратите внимание на два параметра:
KEEP_PROFILES = false отправляет профили в корзину после проверки.
SAVE_PROXIES = false не добавляет проверяемые прокси в список прокси Octo. При таких настройках созданные для проверки профили и прокси не будут загромождать рабочие списки в клиенте. Это будет полезно, если у вас небольшой лимит профилей.
Вот подробное описание настроек:
Настройка | Что задает |
|---|---|
| API-токен Octo Browser |
| Порт локального API клиента Octo, по умолчанию 58888. Он указан в настройках клиента на вкладке «Дополнительные» |
| Система профилей: |
|
|
| Сколько подключений проверяется одновременно, от 1 до 10 |
| Прокси прямо в коде, в дополнение к файлу |
| Файл с прокси, по умолчанию |
| Тип для строк прокси, в которых он не указан |
|
|
| Папка с VPN-конфигурациями, по умолчанию |
| Протокол файлов конфигурации, а также режим, как их называет API Octo. По умолчанию |
| Файл со списком сайтов, по умолчанию |
|
|
| Сохранять ли скриншоты страниц отказа |
| Сколько секунд ждать ответа сайта, прохождения проверки «Вы человек?» и появления содержимого на странице |
А вот нужный код:
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 go 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)}`));
Шаг 4. Составьте список сайтов
Создайте файл командой notepad sites.txt. Соблюдайте следующие правила:
каждый адрес указывайте с новой строки;
адреса можно указывать с префиксом
https://или без него;строки с комментариями начинайте с символа
#, комментариями удобно делить списки на группы.
# Поиск и справочники google.com wikipedia.org # Магазины amazon.com ebay.com
Шаг 5. Добавьте прокси и VPN
Для работы скрипта нужно хотя бы одно подключение: прокси или VPN-конфигурация. Можно настроить сразу оба типа подключения.
Прокси. Создайте файл командой notepad proxies.txt и запишите в него прокси, по одному в строке. Скрипт принимает те же протоколы и те же форматы строк, что и массовое добавление прокси в Octo Browser. Протоколы: http, https, socks5 и ssh. Форматы:
protocol://ip:port protocol://login:password:ip:port protocol://login:password@ip:port protocol://ip:port:login:password
Адрес IPv6 пишется в квадратных скобках: socks5://[2001:db8::1]:1080:login:password. Строку можно указать и без протокола, тогда берется тип из настройки DEFAULT_TYPE. Строки, которые начинаются с #, пропускаются.
VPN. Положите конфиги WireGuard в папку config. Имя файла может быть любым: скрипт узнает конфиг по содержимому, по разделам [Interface] и [Peer]. В список прокси Octo конфиг не добавляется, он живет только внутри своего профиля.
[Interface] PrivateKey = <ключ клиента> Address = 10.0.0.2/32 DNS = 1.1.1.1 [Peer] PublicKey = <ключ сервера>
Перед запуском скрипт проверяет каждый конфиг: есть ли в нем PrivateKey, Address, PublicKey и Endpoint и записан ли Endpoint как адрес:порт, без http://. Если скрипт обнаружит ошибку, он выведет имя файла и описание проблемы, а затем завершит работу без создания профилей.
В итоге у вас должны быть следующие файлы и папки:
D:\proxy_check\ site_access.mjs скрипт sites.txt список сайтов proxies.txt список прокси config\ VPN-конфиги
Шаг 6. Запустите проверку
Откройте клиент Octo Browser и запустите скрипт из его папки:
cd D:\proxy_check node site_access.mjs
Для первого запуска возьмите один прокси и три-четыре сайта: в окне профиля будет видно, как открываются сайты. Когда убедитесь, что все работает, добавляйте остальные.
В начале работы скрипт проверяет все, что может помешать работе: токен, файлы, конфигурации VPN, открыт ли клиент. Если скрипт обнаружит ошибку, он выведет сообщение с ее описанием и завершит работу без создания профилей. Затем начинается проверка, по каждому сайту сразу выводится результат.

В квадратных скобках — номер подключения, название его профиля и счетчик сайтов. При параллельной работе строки разных подключений могут чередоваться. По метке можно определить, к какому подключению относится каждая строка. От пароля прокси в выводе нет ничего, от логина — только последние символы. Чтобы прервать проверку, нажмите Ctrl+C: скрипт остановит профили, которые успел запустить.
Как читать результат
В конце скрипт печатает таблицу и итог по каждому подключению:

AVAILABLE означает, что сайт действительно открылся и показал содержимое. UNAVAILABLE — что сайт не открылся. В скобках после итогового результата перечислены причины в порядке убывания частоты их возникновения. DEAD в названии колонки означает, что не работает само подключение, а не то, что все проверяемые сайты недоступны.
Пометка ERROR означает, что профиль не запустился по причине, не связанной с подключением: текст ошибки Octo указан в строке этого подключения в консоли и в отчете.
В папке появляются результаты. Время в их названиях местное:
site_access_<время>.xlsx— отчет для Excel. Вверху сводка: сколько всего сайтов и по строке на каждое подключение — сколько сайтов доступно, сколько недоступно и по каким причинам. Ниже та же проверка построчно: профиль, подключение, сайт, результат, причина и IP. Строки доступных сайтов зеленые, недоступных — красные. Серые — строки нерабочего подключения и сайты, которые не проверялись, потому что прокси перестал работать.screens_<время>— скриншоты страниц отказа, по папке на подключение, пронумерованные в порядке списка сайтов. Если сайт не ответил или соединение не открыл сам прокси, снимать нечего, и скриншота не будет.
Профили остаются в Octo Browser с названиями по стране и IP.
Рассмотрим возможные проблемы:
Что видно в отчете | Что это значит | Что делать |
|---|---|---|
Подключение помечено | Не работает само подключение | Проверьте логин, пароль и тип прокси или данные VPN-конфигурации |
Подключение помечено | Профиль не запустился, но проблема не в подключении | Прочитайте текст ошибки в отчете или в консоли, устраните причину и запустите проверку заново |
Несколько | Прокси перестал работать посреди проверки: кончился трафик или истекла сессия | Проверьте прокси и запустите проверку заново |
У одного подключения много | Эти сайты закрыл провайдер прокси | Уточните у провайдера, какие категории сайтов он закрывает на вашем тарифе |
| Сайт не доверяет этому IP или его подсети | Смените IP или возьмите прокси другого типа |
| Сайт не работает в стране выхода | Нужен прокси другой страны |
| Не отвечает сам сайт | Повторите проверку позже |
| Подключение медленное или теряет соединения | Замените подключение |
| Слишком частые запросы с одного IP | Подождите и уменьшите |
Что означают причины
Код ответа сервера здесь ненадежен. Отказ не всегда приходит с ошибкой: Akamai может отдать «Access Denied» с кодом 200, проверка AWS WAF приходит с кодом 202, а блокировка DataDome — с кодом 401. Поэтому скрипт читает саму страницу. Крупные сайты редко пишут заглушку с нуля: отказ показывает одна из известных систем защиты, и у каждой свой почерк в заголовках и тексте.
Причина в отчете | Что произошло | Как распознается |
|---|---|---|
| Прокси не открыл соединение с этим сайтом | Ошибка туннеля или SOCKS в браузере. Так выглядит сайт, закрытый провайдером прокси |
| Не работает сам прокси | Прокси не отвечает или не принял логин и пароль, код 407 |
| Сайт отказал этому IP | Cloudflare 1005–1008, 1010, 1012, 1020 и «Sorry, you have been blocked», Akamai «Access Denied», Imperva, Sucuri, F5, Wordfence, AWS WAF, DataDome, коды 401, 403 и 406, сообщение сайта о том, что он видит прокси или VPN |
| Сайт требует проверку «Вы человек?» | Cloudflare «Just a moment» и Turnstile, PerimeterX «Press & Hold», капча DataDome, Akamai, AWS WAF, Kasada, Radware, DDoS-Guard, Vercel, «unusual traffic» у Google, капча Amazon, reCAPTCHA, hCaptcha |
| Сайт закрыт для страны подключения | Cloudflare 1009, код 451, отказ CloudFront по стране, фразы вида «not available in your country», перенаправление на адрес вида |
| Слишком много запросов с этого IP | Код 429, Cloudflare 1015 |
| Сайт не ответил вовремя | За отведенное время не пришло ответа, или сайт начал отвечать и завис |
| Соединение оборвано или отклонено | Сброс, пустой ответ или отказ в соединении до загрузки страницы |
| Адрес сайта не найден | Ошибка DNS |
| Защищенное соединение не установилось | Ошибка сертификата или TLS: сертификат выдан на другой адрес, просрочен или подменен по пути |
| Сайт увел на чужой адрес | Конечный адрес принадлежит другому сайту, и там короткая страница или отказ |
| Сайт перенаправляет по кругу | Браузер прервал цепочку перенаправлений |
| Страница осталась пустой | За 10 секунд на ней ничего не появилось |
| Страница перестала отвечать | Страница открылась, но браузер 30 секунд не мог ее прочитать: на ней завис скрипт |
| Сайт ответил ошибкой | Коды 4xx, например 404 |
| Сайт сам сломан, подключение ни при чем | Код 5xx без признаков защиты |
| Другая сетевая ошибка | Код ошибки браузера указан в причине |
Причины делятся на три группы. proxy_refused и proxy_error означают, что отказало подключение: до сайта запрос не дошел. blocked, challenge, geo_blocked и rate_limited — что прокси соединение пропустил, а отказал уже сайт. timeout, connection_reset, dns_error и ssl_error — что ответа не пришло вовсе: причина может быть и в прокси, и в сайте, и в сети между ними.
Как скрипт избегает ложных результатов
Ошибиться можно в обе стороны: принять разовый сбой за блокировку или пустую страницу за открывшийся сайт. Вот как скрипт ведет себя в спорных случаях:
Случай | Что делает скрипт |
|---|---|
Соединение оборвалось, истекло время или прокси отказал | Пробует еще раз и ждет ответа до 20 секунд. |
Сайт показал проверку «Just a moment» | Ждет до 15 секунд: у обычного посетителя такая проверка часто проходит сама. Прошла — |
Страница рисуется скриптами не сразу | Ждет до 10 секунд, пока на ней что-то появится |
Сайт начал отвечать и завис | Отдельная причина |
Сайт открыл окно | Закрывает окно отменой, иначе страница не продолжит работу, и проверяет дальше |
На странице завис скрипт | Через 30 секунд ставит причину |
Сайт перенаправил на свою страну, | Это тот же сайт: |
Сайт перевел на другой домен, и там обычная страница |
|
Сайт увел на чужую короткую страницу или на страницу с отказом |
|
На странице есть скрипт защиты, но сайт открылся | Присутствие защиты не считается отказом. Учитывается только сама страница отказа |
Слова «access denied» в тексте обычной статьи | Фразы отказа учитываются в заголовке страницы и на короткой странице, но не в середине длинного текста |
Заключение
Скрипт автоматизирует проверку доступности сайтов через прокси и VPN: показывает, какие сайты открываются через каждое подключение, и помогает определить причины недоступности остальных. Заполните список сайтов один раз и запускайте проверку при покупке новых прокси, смене провайдера или возникновении проблем с доступом к сайтам. Так вам не придется проверять каждое подключение вручную.
Частые вопросы
Сколько подключений можно проверять одновременно?
Каждый профиль — это отдельный браузер, поэтому все упирается в память и процессор. На обычном компьютере разумно от трех до пяти, это задает настройка PARALLEL. Если все прокси идут через один шлюз провайдера, не ставьте много: у аккаунта провайдера может быть ограничение на одновременные соединения.
Сколько времени занимает проверка?
Открывшийся сайт занимает несколько секунд. Дольше всего проверяются сайты, которые не отвечают: скрипт ждет 45 секунд и повторяет попытку еще на 20. Подключения проверяются параллельно, поэтому пять прокси занимают примерно столько же времени, сколько один.
Почему все сайты у подключения помечены DEAD?
Octo не смог запустить профиль с этим прокси или VPN: подключение не работает. Проверьте логин и пароль прокси, протокол в строке и данные в VPN-конфиге. Если вместо DEAD стоит ERROR, профиль не запустился по другой причине, не из-за подключения: она указана в строке этого подключения.
Сайт помечен challenge, а вручную он открывается
Значит, проверка «Вы человек?» не прошла сама за 15 секунд. Вручную вы проходите ее кликом, а скрипт ничего не нажимает. Время ожидания задает настройка CHECK_WAIT.
Почему результат различается от запуска к запуску?
Чаще всего прокси сменил IP: у ротируемых прокси он меняется между подключениями, и сайт относится к новому адресу иначе. У некоторых провайдеров от выходного узла зависит и список закрытых сайтов: через один IP банк открывается, через другой провайдер его закрывает. Еще одна причина — лимиты самого сайта: после частых запросов он начинает отвечать кодом 429 или показывать проверку.
Профиль не запускается, хотя клиент Octo открыт
Проверьте порт локального API: настройки клиента, вкладка «Дополнительные», «Локальный HTTP-сервер». Если он отличается от 58888, укажите его в настройке LOCAL_PORT.
Скрипт не видит мой файл конфигурации VPN
Файл конфигурации должен лежать в папке config рядом со скриптом и содержать разделы [Interface] и [Peer]. Файлы без этих разделов скрипт пропускает и перечисляет в начале вывода.
Что будет, если прокси перестанет работать посреди проверки?
Так бывает, когда у прокси истекает сессия или кончается трафик: он перестает отвечать или принимать логин. После трех ошибок самого прокси подряд скрипт прекращает проверку через это подключение, чтобы не тратить время на оставшиеся сайты. В отчете они отмечены серым как SKIPPED, а в сводке написано, после какого сайта прокси перестал работать. Остальные подключения проверяются дальше как обычно. Отказы провайдера по отдельным сайтам, proxy_refused, в счет не идут: прокси при этом работает.
Что остается в Octo после проверки?
Профили с названиями по стране и IP и новые прокси в списке прокси. Чтобы не оставалось ничего, поставьте KEEP_PROFILES = false и SAVE_PROXIES = false: профили уйдут в корзину, а прокси в список не попадут.
Передает ли скрипт мои данные куда-то, кроме Octo?
Токен скрипт отправляет только на адрес API Octo. Есть одно обращение к стороннему сервису: если Octo не сообщил страну выхода, скрипт спрашивает ее по IP у GeoJS. Туда уходит только IP выхода прокси.
Следите за последними новостями Octo Browser
Нажимая кнопку, вы соглашаетесь с нашей политикой конфиденциальности.
Следите за последними новостями Octo Browser
Нажимая кнопку, вы соглашаетесь с нашей политикой конфиденциальности.
Следите за последними новостями Octo Browser
Нажимая кнопку, вы соглашаетесь с нашей политикой конфиденциальности.

Присоединяйтесь к Octo Browser сейчас
Вы можете обращаться за помощью к нашим специалистам службы поддержки в чате в любое время.

Присоединяйтесь к Octo Browser сейчас
Вы можете обращаться за помощью к нашим специалистам службы поддержки в чате в любое время.
Присоединяйтесь к Octo Browser сейчас
Вы можете обращаться за помощью к нашим специалистам службы поддержки в чате в любое время.
