您可以通过您的代理和 VPN 配置访问哪些网站?在 Octo Browser 配置文件中进行检查

您可以通过您的代理和 VPN 配置访问哪些网站?在 Octo Browser 配置文件中进行检查
Alex Phillips
Alex Phillips

Customer Service Specialist

Octo Browser 是一款用于处理多账户的反检测浏览器:每个配置文件都有其独有的数字指纹和连接设置。连接决定了一个配置文件可以访问哪些网站:同一个网站可能通过某个代理可以正常打开,通过另一个代理则显示“您是真人吗?”验证,通过第三个代理则完全无法响应。手动检查所有内容非常耗时:针对 50 个网站测试 5 个代理可能需要耗费一整晚的时间。在本文中,我们将向您展示如何编写一个 Node.js 和 Puppeteer 脚本,该脚本可在 Octo Browser 配置文件中使用您的每个代理和 VPN 逐一检查网站列表,然后报告每个网站是否可访问,如果不可访问,还会说明具体原因。

内容

使用Octo Browser维护您的在线匿名性。您真实的数字指纹无法被追踪。

想以优惠价试用 Octo 浏览器吗?
使用优惠码 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 文件读取代理,并从 config 文件夹中的 WireGuard 配置文件读取 VPN。它支持与 Octo Browser 中批量代理导入相同的协议和行格式,包括 IPv6 地址。

  • 识别原因。如果网站无法加载,脚本会告诉您原因:是代理本身无法建立连接、网站屏蔽了 IP 地址、需要“确认您是人类”验证、在连接所在国家/地区不可用,还是根本没有响应。

  • 区分屏蔽与随机故障。如果连接中断或网站没有响应,脚本会再次检查。如果网站显示“确认您是人类”验证,脚本会等待其自行通过。如果页面正常加载,反机器人保护的存在本身不会被视为失败。

  • 并行运行检查。它最多可同时检查十个连接,并且每个网站的结果一准备好就会显示。

  • 按国家和 IP 命名配置文件。配置文件会获得诸如 DE_198.51.100.7 之类的名称。无法工作的连接被标记为 DEAD,而因其他原因无法启动的配置文件被标记为 ERROR。

  • 保存报告。它会创建一个 Excel 文件,其中包含每个连接的摘要。可访问的网站以绿色高亮显示,无法访问的以红色高亮显示。脚本还会保存每个失败页面的屏幕截图,以便您确切查看网站显示的内容。

  • 保护访问凭据。代理密码、VPN 密钥和令牌不会包含在控制台输出或报告中。即使您中断检查,配置文件也会被正确停止。

脚本仅进行观察。它不会解决验证码、点击按钮或输入任何内容。请注意以下几点:

  • challenge 结果并不意味着您已被封禁。网站是在要求您确认自己是人类,您通常可以在配置文件中手动打开它。

  • 脚本仅检查您提供的确切 URL。主页加载成功并不意味着账户登录或结账也能正常工作。如果这是您需要测试的内容,请将特定版块的 URL 添加到列表中。

  • 结果在检查时是准确的。轮换代理可能在一分钟后使用不同的 IP,因此结果可能会发生变化。

  • 每个连接都会获得一个新的配置文件,并且新代理会被添加到 Octo 代理列表中。两者都会消耗您的订阅额度。第 3 步解释了如何在检查后避免留下它们。

为什么不使用 curl?

您可以通过单个 curl 命令通过代理检查网站,但它回答的是另一个问题,即请求是否到达了服务器?它无法告诉您网站是否能在浏览器配置文件中打开。

  • curl 不是浏览器,网站能够识别。安全系统通过其 TLS 指纹和标头集对其进行识别,并且可能会拒绝 curl 客户端本身,而不是拒绝您的代理。

  • curl 不运行 JavaScript。浏览器可以在几秒钟内自动通过“请稍候”检查,而 curl 会卡在上面。

  • curl 看到的是响应代码,而不是页面。地理限制页面、验证码或状态码为 200 的拒绝访问,对它来说都像是成功打开的网站。

  • curl 无法检查 VPN。它可以通过 HTTP 和 SOCKS 代理进行连接,但您无法向其传递 WireGuard 配置。

curl 仍然有其用处:它是查明代理是否正常工作及其 IP 地址是什么的快速方法。只有配置文件中的浏览器才能告诉您网站是否会在该配置文件中打开。 

您需要准备什么

  • 具有 Base 或更高版本订阅的 Octo Browser,可让您访问 API。

  • Node.js 22.12 或更高版本。

  • 代理列表或 WireGuard VPN 配置文件。

步骤 1. 安装 Node.js

从 nodejs.org 下载 Node.js 并使用默认设置进行安装。然后打开 PowerShell:按 Win+R,键入 PowerShell,然后按 Enter。检查安装情况:

node --version
node --version

该命令应显示版本 22.12 或更高。这是用于测试该脚本的 Puppeteer 25 所必需的。如果 PowerShell 提示找不到该命令,请关闭 PowerShell,重新打开并重试。

步骤 2. 准备文件夹

为脚本选择一个文件夹,例如 D:\proxy_check,创建它,并在 PowerShell 中导航到该文件夹。在其中为您的 VPN 配置创建一个 config 文件夹:

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 令牌粘贴到 API_TOKEN 中。您可以在 Octo Browser 主账户设置下的 API 令牌选项卡中找到它。

const API_TOKEN = "your_token";
const API_TOKEN = "your_token";

您可以将其他设置保留为其默认值。但是,请注意以下两个参数:

KEEP_PROFILES = false 在检查后将配置文件移至回收站。

SAVE_PROXIES = false 可防止将测试过的代理添加到 Octo 代理列表中。通过这些设置,为测试创建的配置文件和代理将不会混杂在浏览器中的工作列表中。如果您的配置文件配额较低,这非常有用。

以下是设置的详细说明:

设置

控制内容

API_TOKEN

Octo Browser API 令牌

LOCAL_PORT

Octo 客户端的本地 API 端口,默认为 58888。您可以在设置中的“附加”选项卡下找到它。

OS

配置文件操作系统:win、mac 或 android。Octo 会选择版本和指纹的其余部分。

HEADLESS

true — 配置文件在无窗口模式下运行;false — 配置文件在窗口中运行,因此您可以查看网站的打开情况。

PARALLEL

同时检查的连接数,从 1 到 10。

PROXIES

直接在代码中指定的代理,作为文件内容的补充。

PROXY_FILE

包含代理的文件;默认为 proxies.txt。

DEFAULT_TYPE

用于未指定类型的代理行的类型。

SAVE_PROXIES

true — 新代理将添加到 Octo 代理列表中;false — 代理仅存在于其自己的配置文件中。

VPN_FOLDER

包含 VPN 配置的文件夹;默认为 config。

VPN_PROTOCOL、VPN_SYN_MODE

配置文件使用的协议以及在 Octo API 中标识它们的模式。默认值为 wireguard 和 profile_based。

SITES_FILE

包含网站列表的文件;默认为 sites.txt。

KEEP_PROFILES

false — 检查后配置文件被移至回收站。

SCREENSHOTS

是否保存失败页面的屏幕截图。

PAGE_TIMEOUT、CHECK_WAIT、EMPTY_WAIT

等待网站响应、“确认您是人类”验证通过以及页面内容出现的秒数。

代码如下:

import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { crc32 } from "node:zlib";

const API_TOKEN = ""; // paste your Octo API token between the quotes
const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional
const OS = "win"; // OS of the profiles: win, mac or android
const HEADLESS = false; // true: profiles run without a window; false: with a window
const PARALLEL = 5; // connections checked at the same time, from 1 to 10
const PROXIES = [
  // one proxy per line, for example "socks5://login:password@proxy.example.com:10000",
];
const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES
const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh
const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile
const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file
const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it
const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it
const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment
const KEEP_PROFILES = true; // false: every profile goes to the trash after its check
const SCREENSHOTS = true; // true: save a screenshot of every page that did not open
const PAGE_TIMEOUT = 45; // seconds a site gets to answer
const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself
const EMPTY_WAIT = 10; // seconds a blank page gets to show something

const HERE = dirname(fileURLToPath(import.meta.url));
const CLOUD = "https://app.octobrowser.net/api/v2/automation";
const LOCAL = `http://localhost:${LOCAL_PORT}/api`;
const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" };
const PROXY_TYPES = ["http", "https", "socks5", "ssh"];
const SHORT_PAGE = 2500;
const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 };
const RETRY_TIMEOUT = 20;
const PROXY_FAILURES = 3;
const BROWSER_TIMEOUT = 30;
const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]);

const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
const anyOf = (phrases) => new RegExp(phrases.join("|"));
const secrets = new Set();
const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value));
const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
const redact = (text) =>
  [...secrets]
    .sort((a, b) => b.length - a.length)
    .reduce((clean, secret) => clean.split(secret).join("***"), printable(text))
    .replace(/\/\/[^\s/@]+@/g, "//***@");
const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200);
const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_");
const localStamp = () =>
  new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-");
const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, "");
const fail = (message) => {
  console.error(message);
  process.exit(1);
};

const GEO = anyOf([
  "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "not available in this (country|region)",
  "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)",
  "(from|in) a restricted (country|territory|jurisdiction|region|location)",
  "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)",
  "(do|does) not accept (players|customers|users|visitors|residents) from",
  "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)",
  "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)",
  "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)",
  "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)",
  "unavailable (due to|for) legal reasons",
  "configured to block access from your country",
  "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)",
  "nicht in (deinem|ihrem) land",
  "pas disponible dans votre (pays|région)",
  "no está disponible en (tu|su) (país|región)",
  "não está disponível (no|em) seu país",
]);

const PROXY_SEEN = anyOf([
  "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))",
  "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)",
  "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)",
  "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)",
]);

const CHECKS = anyOf([
  "checking (your browser|if the site connection is secure)",
  "verif(y|ying) (that )?you are (a )?human",
  "verify (that )?you are not a (robot|bot)",
  "(prove|confirm) (that )?you are (a )?human",
  "are you (a )?(human|robot)",
  "(complete|pass|performing) (a |the )?(security check|captcha)",
  "security checkpoint",
  "enable javascript and cookies to continue",
  "press (&|and) hold",
  "unusual (traffic|activity)",
  "suspicious (activity|traffic)",
  "automated (access|requests|queries|traffic)",
  "подтвердите, что вы не робот",
  "проверка браузера",
]);

const REFUSALS = anyOf([
  "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)",
  "you (have been|are|were) (blocked|banned)",
  "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)",
  "request (blocked|rejected|denied)",
  "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)",
  "403 forbidden",
  "error 403",
  "you (don.t|do not) have permission to (access|view)",
  "not authori[sz]ed to (access|view)",
  "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)",
  "ваш ip[^.]{0,30}(заблокирован|забанен)",
]);

const CLOUDFLARE_ERRORS = {
  1005: "the network of this IP is banned",
  1006: "this IP is banned",
  1007: "this IP is banned",
  1008: "this IP is banned",
  1010: "the browser signature is banned",
  1012: "access denied",
  1020: "access denied by a firewall rule",
};

function guardOf(header, html) {
  const server = header("server");
  if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare ";
  if (server.includes("akamai")) return "Akamai ";
  if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard ";
  return "";
}

function cloudflareError(guard, html, short, words) {
  const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare");
  if (!short || !onCloudflare) return "";
  return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || "";
}

function view(look) {
  const text = String(look.text || "");
  const title = String(look.title || "").toLowerCase();
  const heading = String(look.heading || "").toLowerCase();
  const html = String(look.html || "").toLowerCase();
  const header = (name) => String(look.headers?.[name] ?? "").toLowerCase();
  const short = text.trim().length < SHORT_PAGE;
  const words = `${title} | ${heading} | ${text.toLowerCase()}`;
  const guard = guardOf(header, html);
  return {
    status: Number(look.status) || 0,
    url: String(look.url || "").toLowerCase(),
    html,
    title,
    top: `${title} | ${heading}`,
    words,
    short,
    empty: !text.trim(),
    refusal: short || Number(look.status) >= 400,
    header,
    guard,
    cloudflare: cloudflareError(guard, html, short, words),
  };
}

const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0];
const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : "");

const RULES = [
  {
    verdict: "challenge",
    detail: "Cloudflare challenge",
    when: (page) => page.header("cf-mitigated").includes("challenge"),
  },
  {
    verdict: "blocked",
    detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`,
    when: (page) => page.header("cf-mitigated"),
  },
  {
    verdict: "blocked",
    detail: "AWS WAF refused",
    when: (page) => page.header("x-amzn-waf-action") === "block",
  },
  {
    verdict: "challenge",
    detail: (page, action) => `AWS WAF ${action}`,
    when: (page) => page.header("x-amzn-waf-action"),
  },
  {
    verdict: "blocked",
    detail: "Sucuri firewall refused",
    when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")),
  },
  {
    verdict: "challenge",
    detail: "Kasada check",
    when: (page) =>
      (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) ||
      (page.short && page.html.includes("kpsdk")),
  },
  {
    verdict: "geo_blocked",
    detail: "Cloudflare 1009: the site bans the country of this IP",
    when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")),
  },
  {
    verdict: "geo_blocked",
    detail: "HTTP 451: unavailable for legal reasons in this country",
    when: (page) => page.status === 451,
  },
  {
    verdict: "geo_blocked",
    detail: (page, phrase) => `the page says: "${phrase}"`,
    when: (page) => said(page, GEO),
  },
  {
    verdict: "rate_limited",
    detail: "Cloudflare 1015: too many requests from this IP",
    when: (page) => page.cloudflare === "1015",
  },
  {
    verdict: "blocked",
    detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`,
    when: (page) => CLOUDFLARE_ERRORS[page.cloudflare],
  },
  {
    verdict: "blocked",
    detail: "Cloudflare: 'you have been blocked'",
    when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare 'Just a moment' check",
    when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare Turnstile check",
    when: (page) => page.short && page.html.includes("cf-turnstile"),
  },
  {
    verdict: "blocked",
    detail: "Akamai: Access Denied",
    when: (page) =>
      page.refusal &&
      (page.html.includes("errors.edgesuite.net") ||
        page.html.includes("reference&#32;&#35;") ||
        /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 = { "<": "&lt;", ">": "&gt;", "&": "&amp;" };
  const text = (value) =>
    printable(value ?? "")
      .replace(/[\uFFFE\uFFFF]/g, "")
      .slice(0, 32000)
      .replace(/[<>&]/g, (sign) => escapes[sign]);
  const cell = (column, line, value, style) => {
    const where = `${String.fromCharCode(65 + column)}${line}`;
    if (typeof value === "number") return `<c r="${where}" s="${style}"><v>${value}</v></c>`;
    return `<c r="${where}" t="inlineStr" s="${style}"><is><t xml:space="preserve">${text(value)}</t></is></c>`;
  };
  const line = (values, number, styles) =>
    `<row r="${number}">${values
      .map((value, column) => cell(column, number, value, Array.isArray(styles) ? styles[column] : styles))
      .join("")}</row>`;
  const rows = results.flatMap((result) => result.rows);
  const lines = [];
  const add = (values, styles) => lines.push(line(values, lines.length + 1, styles));
  add(["TOTAL", `${siteCount} site(s) through ${results.length} connection(s)`], 1);
  add(SUMMARY_COLUMNS, 1);
  for (const { values, dead } of summaryRows(results, siteCount)) {
    add(values, dead ? XLSX_OTHER_STYLE : [0, 0, XLSX_ROW_STYLES.AVAILABLE, XLSX_ROW_STYLES.UNAVAILABLE, 0, 0]);
  }
  lines.push(`<row r="${lines.length + 1}"/>`);
  const header = lines.length + 1;
  add(REPORT_COLUMNS, 1);
  for (const entry of rows) {
    add(
      REPORT_COLUMNS.map((column) => entry[column]),
      XLSX_ROW_STYLES[entry.result] || XLSX_OTHER_STYLE,
    );
  }
  const widths = REPORT_COLUMNS.map((column, i) =>
    Math.min(
      90,
      Math.max(
        column.length,
        SUMMARY_COLUMNS[i].length,
        ...rows.map((entry) => String(entry[column] ?? "").length),
        ...summaryRows(results, siteCount).map((row) => String(row.values[i] ?? "").length),
      ) + 2,
    ),
  );
  const last = `${String.fromCharCode(64 + REPORT_COLUMNS.length)}${lines.length}`;
  return (
    `<cols>${widths.map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join("")}</cols>` +
    `<sheetData>${lines.join("")}</sheetData><autoFilter ref="A${header}:${last}"/>`
  );
}

function writeXlsx(results, siteCount, stamp) {
  const head = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
  const main = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
  const office = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
  const packageRels = "http://schemas.openxmlformats.org/package/2006/relationships";
  const type = "application/vnd.openxmlformats-officedocument.spreadsheetml";
  const file = join(HERE, `site_access_${stamp}.xlsx`);
  const files = [
    [
      "[Content_Types].xml",
      `${head}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
        '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' +
        '<Default Extension="xml" ContentType="application/xml"/>' +
        `<Override PartName="/xl/workbook.xml" ContentType="${type}.sheet.main+xml"/>` +
        `<Override PartName="/xl/worksheets/sheet1.xml" ContentType="${type}.worksheet+xml"/>` +
        `<Override PartName="/xl/styles.xml" ContentType="${type}.styles+xml"/></Types>`,
    ],
    [
      "_rels/.rels",
      `${head}<Relationships xmlns="${packageRels}">` +
        `<Relationship Id="rId1" Type="${office}/officeDocument" Target="xl/workbook.xml"/></Relationships>`,
    ],
    [
      "xl/workbook.xml",
      `${head}<workbook xmlns="${main}" xmlns:r="${office}">` +
        '<sheets><sheet name="Report" sheetId="1" r:id="rId1"/></sheets></workbook>',
    ],
    [
      "xl/_rels/workbook.xml.rels",
      `${head}<Relationships xmlns="${packageRels}">` +
        `<Relationship Id="rId1" Type="${office}/worksheet" Target="worksheets/sheet1.xml"/>` +
        `<Relationship Id="rId2" Type="${office}/styles" Target="styles.xml"/></Relationships>`,
    ],
    ["xl/styles.xml", `${head}<styleSheet xmlns="${main}">${XLSX_STYLES}</styleSheet>`],
    ["xl/worksheets/sheet1.xml", `${head}<worksheet xmlns="${main}">${xlsxSheet(results, siteCount)}</worksheet>`],
  ];
  writeFileSync(file, zip(files));
  return file;
}

async function main() {
  checkSettings();
  token = readToken();
  hide(token);
  const proxies = readProxies();
  const vpns = readVpns();
  if (!proxies.length && !vpns.length) {
    fail(
      `Nothing to check: put proxies into ${PROXY_FILE || "PROXIES"} or WireGuard configs into ${VPN_FOLDER}. Nothing was done.`,
    );
  }
  const sites = readSitesFile();
  const puppeteer = await import("puppeteer-core").then(
    (module) => module.default,
    () => fail("Puppeteer is not installed: run npm install puppeteer-core in this folder."),
  );
  await local("/profiles/active").catch(() =>
    fail(`The Octo client is not running, or its local port is not ${LOCAL_PORT}: set LOCAL_PORT. Nothing was done.`),
  );
  if (OS === "android") await loadAndroidModels();
  const list = SAVE_PROXIES && proxies.length ? await cloud("GET", "/proxies") : { ok: true };
  if (!list.ok) fail(`Could not read the saved proxies: HTTP ${list.status}. Nothing was done.`);
  const saved = Array.isArray(list.data?.data) ? list.data.data : [];

  const jobs = [
    ...proxies.map((proxy) => ({ proxy, label: proxyLabel(proxy) })),
    ...vpns.map((vpn) => ({ vpn, label: `VPN ${vpn.file}` })),
  ].map((job, index) => ({ ...job, number: index + 1 }));
  const workers = Math.min(PARALLEL, jobs.length);
  const stamp = localStamp();
  console.log(
    `Checking ${sites.length} site(s) through ${proxies.length} proxy(ies) and ${vpns.length} VPN config(s), ` +
      `one ${OS_NAMES[OS]} profile each, ${HEADLESS ? "without a window" : "in a window"}, ${workers} at a time.\n`,
  );

  const results = await runAll(jobs, workers, (job) => checkConnection(job, { sites, puppeteer, saved, stamp }));
  const rows = results.flatMap((result) => result.rows);
  console.log("");
  printTable(sites, results);
  console.log(`\nReport: ${writeXlsx(results, sites.length, stamp)}`);
  if (rows.some((entry) => entry.screenshot)) console.log(`Screenshots: ${join(HERE, `screens_${stamp}`)}`);
  const left = limits
    ? ` Left: ${limits.minute}${limits.minuteLimit ? ` of ${limits.minuteLimit}` : ""} this minute, ` +
      `${limits.hour}${limits.hourLimit ? ` of ${limits.hourLimit}` : ""} this hour.`
    : "";
  console.log(`${spent} request(s) counted by Octo's rate limits.${left}`);
}

main().catch((error) => fail(`Stopped: ${firstLine(error.message || error)}`));

import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { crc32 } from "node:zlib";

const API_TOKEN = ""; // paste your Octo API token between the quotes
const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional
const OS = "win"; // OS of the profiles: win, mac or android
const HEADLESS = false; // true: profiles run without a window; false: with a window
const PARALLEL = 5; // connections checked at the same time, from 1 to 10
const PROXIES = [
  // one proxy per line, for example "socks5://login:password@proxy.example.com:10000",
];
const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES
const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh
const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile
const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file
const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it
const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it
const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment
const KEEP_PROFILES = true; // false: every profile goes to the trash after its check
const SCREENSHOTS = true; // true: save a screenshot of every page that did not open
const PAGE_TIMEOUT = 45; // seconds a site gets to answer
const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself
const EMPTY_WAIT = 10; // seconds a blank page gets to show something

const HERE = dirname(fileURLToPath(import.meta.url));
const CLOUD = "https://app.octobrowser.net/api/v2/automation";
const LOCAL = `http://localhost:${LOCAL_PORT}/api`;
const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" };
const PROXY_TYPES = ["http", "https", "socks5", "ssh"];
const SHORT_PAGE = 2500;
const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 };
const RETRY_TIMEOUT = 20;
const PROXY_FAILURES = 3;
const BROWSER_TIMEOUT = 30;
const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]);

const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
const anyOf = (phrases) => new RegExp(phrases.join("|"));
const secrets = new Set();
const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value));
const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
const redact = (text) =>
  [...secrets]
    .sort((a, b) => b.length - a.length)
    .reduce((clean, secret) => clean.split(secret).join("***"), printable(text))
    .replace(/\/\/[^\s/@]+@/g, "//***@");
const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200);
const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_");
const localStamp = () =>
  new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-");
const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, "");
const fail = (message) => {
  console.error(message);
  process.exit(1);
};

const GEO = anyOf([
  "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "not available in this (country|region)",
  "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)",
  "(from|in) a restricted (country|territory|jurisdiction|region|location)",
  "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)",
  "(do|does) not accept (players|customers|users|visitors|residents) from",
  "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)",
  "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)",
  "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)",
  "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)",
  "unavailable (due to|for) legal reasons",
  "configured to block access from your country",
  "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)",
  "nicht in (deinem|ihrem) land",
  "pas disponible dans votre (pays|région)",
  "no está disponible en (tu|su) (país|región)",
  "não está disponível (no|em) seu país",
]);

const PROXY_SEEN = anyOf([
  "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))",
  "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)",
  "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)",
  "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)",
]);

const CHECKS = anyOf([
  "checking (your browser|if the site connection is secure)",
  "verif(y|ying) (that )?you are (a )?human",
  "verify (that )?you are not a (robot|bot)",
  "(prove|confirm) (that )?you are (a )?human",
  "are you (a )?(human|robot)",
  "(complete|pass|performing) (a |the )?(security check|captcha)",
  "security checkpoint",
  "enable javascript and cookies to continue",
  "press (&|and) hold",
  "unusual (traffic|activity)",
  "suspicious (activity|traffic)",
  "automated (access|requests|queries|traffic)",
  "подтвердите, что вы не робот",
  "проверка браузера",
]);

const REFUSALS = anyOf([
  "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)",
  "you (have been|are|were) (blocked|banned)",
  "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)",
  "request (blocked|rejected|denied)",
  "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)",
  "403 forbidden",
  "error 403",
  "you (don.t|do not) have permission to (access|view)",
  "not authori[sz]ed to (access|view)",
  "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)",
  "ваш ip[^.]{0,30}(заблокирован|забанен)",
]);

const CLOUDFLARE_ERRORS = {
  1005: "the network of this IP is banned",
  1006: "this IP is banned",
  1007: "this IP is banned",
  1008: "this IP is banned",
  1010: "the browser signature is banned",
  1012: "access denied",
  1020: "access denied by a firewall rule",
};

function guardOf(header, html) {
  const server = header("server");
  if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare ";
  if (server.includes("akamai")) return "Akamai ";
  if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard ";
  return "";
}

function cloudflareError(guard, html, short, words) {
  const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare");
  if (!short || !onCloudflare) return "";
  return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || "";
}

function view(look) {
  const text = String(look.text || "");
  const title = String(look.title || "").toLowerCase();
  const heading = String(look.heading || "").toLowerCase();
  const html = String(look.html || "").toLowerCase();
  const header = (name) => String(look.headers?.[name] ?? "").toLowerCase();
  const short = text.trim().length < SHORT_PAGE;
  const words = `${title} | ${heading} | ${text.toLowerCase()}`;
  const guard = guardOf(header, html);
  return {
    status: Number(look.status) || 0,
    url: String(look.url || "").toLowerCase(),
    html,
    title,
    top: `${title} | ${heading}`,
    words,
    short,
    empty: !text.trim(),
    refusal: short || Number(look.status) >= 400,
    header,
    guard,
    cloudflare: cloudflareError(guard, html, short, words),
  };
}

const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0];
const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : "");

const RULES = [
  {
    verdict: "challenge",
    detail: "Cloudflare challenge",
    when: (page) => page.header("cf-mitigated").includes("challenge"),
  },
  {
    verdict: "blocked",
    detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`,
    when: (page) => page.header("cf-mitigated"),
  },
  {
    verdict: "blocked",
    detail: "AWS WAF refused",
    when: (page) => page.header("x-amzn-waf-action") === "block",
  },
  {
    verdict: "challenge",
    detail: (page, action) => `AWS WAF ${action}`,
    when: (page) => page.header("x-amzn-waf-action"),
  },
  {
    verdict: "blocked",
    detail: "Sucuri firewall refused",
    when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")),
  },
  {
    verdict: "challenge",
    detail: "Kasada check",
    when: (page) =>
      (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) ||
      (page.short && page.html.includes("kpsdk")),
  },
  {
    verdict: "geo_blocked",
    detail: "Cloudflare 1009: the site bans the country of this IP",
    when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")),
  },
  {
    verdict: "geo_blocked",
    detail: "HTTP 451: unavailable for legal reasons in this country",
    when: (page) => page.status === 451,
  },
  {
    verdict: "geo_blocked",
    detail: (page, phrase) => `the page says: "${phrase}"`,
    when: (page) => said(page, GEO),
  },
  {
    verdict: "rate_limited",
    detail: "Cloudflare 1015: too many requests from this IP",
    when: (page) => page.cloudflare === "1015",
  },
  {
    verdict: "blocked",
    detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`,
    when: (page) => CLOUDFLARE_ERRORS[page.cloudflare],
  },
  {
    verdict: "blocked",
    detail: "Cloudflare: 'you have been blocked'",
    when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare 'Just a moment' check",
    when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare Turnstile check",
    when: (page) => page.short && page.html.includes("cf-turnstile"),
  },
  {
    verdict: "blocked",
    detail: "Akamai: Access Denied",
    when: (page) =>
      page.refusal &&
      (page.html.includes("errors.edgesuite.net") ||
        page.html.includes("reference&#32;&#35;") ||
        /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 = { "<": "&lt;", ">": "&gt;", "&": "&amp;" };
  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:// 前缀,也可以省略。

  • 注释行以 # 开头。注释对于将列表分组非常有用。

# Search and reference sites
google.com
wikipedia.org

# Online stores
amazon.com
ebay.com
# Search and reference sites
google.com
wikipedia.org

# Online stores
amazon.com
ebay.com

步骤 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 = <client key>
Address = 10.0.0.2/32
DNS = 1.1.1.1

[Peer]
PublicKey = <server key>

[Interface]
PrivateKey = <client key>
Address = 10.0.0.2/32
DNS = 1.1.1.1

[Peer]
PublicKey = <server key>

在运行之前,脚本会检查每个配置中的 PrivateKey、Address、PublicKey 和 Endpoint,并验证 Endpoint 是否写为地址和端口(不带 http://)。如果脚本发现错误,它会显示文件名和问题描述,然后退出而不创建任何配置文件。

您的文件夹结构应如下所示:

D:\proxy_check\
  site_access.mjs     script
  sites.txt           website list
  proxies.txt         proxy list
  config\             VPN configs
D:\proxy_check\
  site_access.mjs     script
  sites.txt           website list
  proxies.txt         proxy list
  config\             VPN configs

步骤 6. 运行检查

打开 Octo Browser 并从其文件夹运行脚本:

cd D:\proxy_check 
node site_access.mjs

cd D:\proxy_check 
node site_access.mjs

对于首次运行,请使用一个代理和三到四个网站。您将能够看到网站在配置文件窗口中打开。确认一切正常后,再添加其余内容。

当脚本启动时,它会检查可能阻止其运行的所有内容:令牌、文件、VPN 配置以及 Octo 是否已打开。如果发现错误,它会显示一条描述该问题的消息并退出而不创建配置文件。随后检查开始,每个网站的结果一经得出就会立即显示。

Which websites can you access through your proxies and VPN configs? Check them in Octo Browser profiles

方括号显示连接编号、其配置文件名称和网站计数器。当并行检查多个连接时,它们的输出行可能会交错出现。使用标签查看每行属于哪个连接。输出中不显示代理密码,且仅显示用户名的最后几个字符。要停止检查,请按 Ctrl+C。脚本将停止已启动的配置文件。

如何解读结果

最后,脚本会为每个连接打印一个表格和一个摘要:

Which websites can you access through your proxies and VPN configs? Check them in Octo Browser profiles

AVAILABLE 表示网站成功打开并显示内容。UNAVAILABLE 表示未能打开。最终结果后括号中的原因是按出现频率降序排列的。列名中的 DEAD 表示连接本身无法工作,并不意味着正在检查的所有网站都不可用。

ERROR 标签表示配置文件由于与连接无关的原因而启动失败。Octo 错误消息会显示在控制台和报告中该连接所在行上。

输出文件保存在该文件夹中。其名称中的时间戳使用本地时间:

  • site_access_<time>.xlsx — Excel 报告。顶部包含一个摘要,显示网站总数,以及针对每个连接,有多少个网站可访问、有多少个不可访问以及原因。其下方是详细检查结果,每个结果占一行:配置文件、连接、网站、结果、原因和 IP。可访问网站的行显示为绿色;不可访问的显示为红色。灰色行表示无法工作的连接,以及因代理停止工作而未检查的网站。

  • screens_<time> — 失败页面的屏幕截图,每个连接都有一个单独的文件夹,屏幕截图按照网站列表的顺序进行编号。如果网站没有响应或代理本身无法建立连接,则没有任何内容可截取,因此不会保存屏幕截图。

配置文件仍保留在 Octo Browser 中,并按国家和 IP 命名。

让我们来看看一些可能出现的问题:

在报告中看到的内容

其含义

解决方法

连接被标记为 DEAD。

连接本身无法工作。

检查代理用户名、密码和类型,或 VPN 配置详细信息。

连接被标记为 ERROR。

配置文件无法启动,但问题不在于连接。

阅读报告或控制台中的错误,排查原因,然后重新运行检查。

连续出现多个 proxy_error 条目,后跟 SKIPPED。

代理在检查期间停止工作:其流量耗尽或会话过期。

检查代理并重新运行检查。

一个连接出现大量 proxy_refused 结果。

代理提供商屏蔽了这些网站。

向您的提供商咨询您的套餐中屏蔽了哪些网站类别。

一个连接显示 blocked 或 challenge,而网站通过其他连接可以打开。

该网站不信任此 IP 地址或其子网。

更换 IP 或使用不同类型的代理。

geo_blocked。

该网站在出口国家/地区不可用。

使用来自另一个国家/地区的代理。

某个网站在所有连接上均出现 timeout。

网站本身没有响应。

稍后重新尝试检查。

单个连接上的许多网站均出现 timeout。

连接速度慢或不断中断。

替换该连接。

rate_limited。

来自同一 IP 的请求过多。

请等待并调低 PARALLEL 的值。

原因的具体含义

在这种情况下,服务器响应代码并不可靠。拒绝并不总是伴随错误:Akamai 可能会返回带有 200 状态码的“Access Denied”,AWS WAF 检查可能会返回 202,而 DataDome 拦截可能会返回 401。这就是脚本需要读取页面本身的原因。大型网站很少从头构建拒绝访问页面:通常由某个知名的安全系统显示拦截页面,并且每个系统在标头和文本中都有自己的特征签名。

报告中的原因

实际发生的情况

如何识别

proxy_refused

代理无法建立到该网站的连接。

浏览器中出现隧道或 SOCKS 错误。被代理提供商屏蔽的网站通常表现为此状态。

proxy_error

代理本身无法工作。

代理没有响应或不接受用户名和密码;状态码 407。

blocked

网站拒绝此 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 的消息。

challenge

网站需要进行“确认您是人类”验证。

Cloudflare “Just a moment” 和 Turnstile;PerimeterX “Press & Hold”;来自 DataDome、Akamai、AWS WAF、Kasada、Radware、DDoS-Guard 和 Vercel 的验证码页面;Google 的“异常流量”提示;Amazon 验证码;reCAPTCHA;hCaptcha。

geo_blocked

网站在连接所在的国家/地区不可用。

Cloudflare 1009、状态码 451、基于国家/地区的 CloudFront 拒绝、诸如“在您所在国家/地区不可用”之类的短语,或重定向到诸如 restricted.site.com 之类的地址。

rate_limited

来自此 IP 的请求过多。

状态码 429 或 Cloudflare 1015。

timeout

网站未在规定时间内响应。

在指定时间内未收到响应,或者网站开始响应后卡死。

connection_reset、connection_refused

连接中断或被拒绝。

连接中断、空响应或页面加载前连接被拒绝。

dns_error

找不到网站地址。

DNS 错误。

ssl_error

无法建立安全连接。

证书或 TLS 错误:证书是为其他地址颁发的、已过期,或者在中途被替换。

redirected

网站将浏览器重定向到了无关地址。

最终地址属于另一个网站,该网站显示简短页面或拒绝提示。

redirect_loop

网站陷入无限重定向循环。

浏览器终止了重定向链。

empty

页面保持空白。

10 秒内没有任何内容显示。

unresponsive

页面停止响应。

页面已打开,但由于页面上的脚本卡死,浏览器在 30 秒内无法读取该页面。

http_error

网站返回了错误。

4xx 状态码,例如 404。

server_error

网站本身出现故障;与连接无关。

5xx 状态码,且无安全防护迹象。

unreachable

发生其他网络错误。

原因中包含浏览器错误代码。

这些原因分为三组。proxy_refused 和 proxy_error 表示连接失败:请求从未到达网站。blocked、challenge、geo_blocked 和 rate_limited 表示代理允许请求通过,但网站拒绝了访问。timeout、connection_reset、dns_error 和 ssl_error 表示根本没有收到任何响应:原因可能是代理、网站或它们之间的网络。

脚本如何避免误报

任何方向都可能出现错误:临时故障可能被误认为是屏蔽,空白页面也可能被误认为是成功打开的网站。以下是脚本处理模糊情况的方式:

情况

脚本的操作

连接断开、超时或代理拒绝请求。

它会重试并等待长达 20 秒以获得响应。仅当第二次尝试也失败时,才会分配 UNAVAILABLE,并记录原因。

网站显示“请稍候”验证。

它最多等待 15 秒:此检查通常会自动为普通访客通过。如果通过,结果为 AVAILABLE 并附带说明。

页面需要时间来呈现其脚本。

它最多等待 10 秒以等待内容出现。

网站开始响应然后卡死。

它会记录一个单独的 timeout 原因:网站响应了,但页面未能加载。

网站打开一个 alert 或 confirm 对话框。

它通过取消对话框来将其关闭;否则页面无法继续加载。脚本随后继续检查。

页面上的脚本卡死。

30 秒后,它会分配 unresponsive 原因并转至下一个网站。

网站重定向到其本地国家/地区版本,例如 example.com → example.de。

由于是同一个网站:结果为 AVAILABLE,并附带注释显示其打开时的实际地址。

网站重定向到另一个域名,并在该域名上加载了常规页面。

结果为 AVAILABLE,并附带注释“已打开另一个网站”及新地址。这可能是品牌重塑或迁移,例如 twitter.com → x.com,或者是一种替换——例如在美国境外,hulu.com 会重定向到 disneyplus.com。

网站重定向到无关的简短页面或拒绝访问页面。

结果为 UNAVAILABLE,并附带 redirected 原因以及该页面的文本。

页面包含反机器人脚本,但网站可以正常打开。

防护措施的存在不会被视为拒绝。只有拒绝页面本身才会被计入。

常规文章的文本中出现了“access denied”字样。

仅在页面标题和简短页面中检查拒绝短语,而不会在长文本中间进行检查。

结论

该脚本使通过代理和 VPN 进行网站可用性检查自动化。它可以显示哪些网站可以通过各个连接打开,并帮助识别其他网站不可用的原因。您只需创建一次网站列表,然后在购买新代理、更换提供商或遇到网站访问问题时运行检查即可。这样,您就不必手动测试每个连接。

常见问题解答

一次可以检查多少个连接?

每个配置文件都是一个单独的浏览器,因此限制取决于您的内存和 CPU。在普通设备上,三到五个是合理的数值;通过 PARALLEL 设置进行配置。如果您的所有代理都使用同一个提供商网关,请不要将该数字设置得太高:您的提供商账户可能会限制并发连接数。

检查需要多长时间?

能正常打开的网站只需要几秒钟。没有响应的网站耗时最长:脚本会等待 45 秒,然后再重试 20 秒。连接是并行检查的,因此检查五个代理所花费的时间与检查一个代理大致相同。

为什么某个连接的所有网站都被标记为 DEAD?

Octo 无法使用该代理或 VPN 启动配置文件:连接无法工作。请检查代理用户名和密码、协议以及 VPN 配置详情。如果标签是 ERROR 而不是 DEAD,则表示配置文件由于与连接无关的其他原因而未能启动。该原因会显示在该连接所在的行上。

某个网站被标记为 challenge,但手动可以打开。为什么?

“确认您是人类”验证未在 15 秒内自动通过。您可以通过点击手动完成它,但脚本不会执行任何点击操作。等待时间由 CHECK_WAIT 设置控制。

为什么两次运行的结果会有所不同?

最常见的原因是代理更改了其 IP 地址。轮换代理在两次连接之间会使用不同的 IP,并且网站对待新地址的方式可能有所不同。对于某些提供商,被屏蔽的网站列表也取决于出口节点:某家银行可能可以通过某个 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 以外的任何地方吗?

脚本仅将令牌发送到 Octo API 地址。它会对第三方服务发出一次请求:如果 Octo 未报告出口国家/地区,脚本会使用 GeoJS 按 IP 查询。只有代理的出口 IP 会发送给 GeoJS。

使用Octo Browser维护您的在线匿名性。您真实的数字指纹无法被追踪。

想以优惠价试用 Octo 浏览器吗?
使用优惠码 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 文件读取代理,并从 config 文件夹中的 WireGuard 配置文件读取 VPN。它支持与 Octo Browser 中批量代理导入相同的协议和行格式,包括 IPv6 地址。

  • 识别原因。如果网站无法加载,脚本会告诉您原因:是代理本身无法建立连接、网站屏蔽了 IP 地址、需要“确认您是人类”验证、在连接所在国家/地区不可用,还是根本没有响应。

  • 区分屏蔽与随机故障。如果连接中断或网站没有响应,脚本会再次检查。如果网站显示“确认您是人类”验证,脚本会等待其自行通过。如果页面正常加载,反机器人保护的存在本身不会被视为失败。

  • 并行运行检查。它最多可同时检查十个连接,并且每个网站的结果一准备好就会显示。

  • 按国家和 IP 命名配置文件。配置文件会获得诸如 DE_198.51.100.7 之类的名称。无法工作的连接被标记为 DEAD,而因其他原因无法启动的配置文件被标记为 ERROR。

  • 保存报告。它会创建一个 Excel 文件,其中包含每个连接的摘要。可访问的网站以绿色高亮显示,无法访问的以红色高亮显示。脚本还会保存每个失败页面的屏幕截图,以便您确切查看网站显示的内容。

  • 保护访问凭据。代理密码、VPN 密钥和令牌不会包含在控制台输出或报告中。即使您中断检查,配置文件也会被正确停止。

脚本仅进行观察。它不会解决验证码、点击按钮或输入任何内容。请注意以下几点:

  • challenge 结果并不意味着您已被封禁。网站是在要求您确认自己是人类,您通常可以在配置文件中手动打开它。

  • 脚本仅检查您提供的确切 URL。主页加载成功并不意味着账户登录或结账也能正常工作。如果这是您需要测试的内容,请将特定版块的 URL 添加到列表中。

  • 结果在检查时是准确的。轮换代理可能在一分钟后使用不同的 IP,因此结果可能会发生变化。

  • 每个连接都会获得一个新的配置文件,并且新代理会被添加到 Octo 代理列表中。两者都会消耗您的订阅额度。第 3 步解释了如何在检查后避免留下它们。

为什么不使用 curl?

您可以通过单个 curl 命令通过代理检查网站,但它回答的是另一个问题,即请求是否到达了服务器?它无法告诉您网站是否能在浏览器配置文件中打开。

  • curl 不是浏览器,网站能够识别。安全系统通过其 TLS 指纹和标头集对其进行识别,并且可能会拒绝 curl 客户端本身,而不是拒绝您的代理。

  • curl 不运行 JavaScript。浏览器可以在几秒钟内自动通过“请稍候”检查,而 curl 会卡在上面。

  • curl 看到的是响应代码,而不是页面。地理限制页面、验证码或状态码为 200 的拒绝访问,对它来说都像是成功打开的网站。

  • curl 无法检查 VPN。它可以通过 HTTP 和 SOCKS 代理进行连接,但您无法向其传递 WireGuard 配置。

curl 仍然有其用处:它是查明代理是否正常工作及其 IP 地址是什么的快速方法。只有配置文件中的浏览器才能告诉您网站是否会在该配置文件中打开。 

您需要准备什么

  • 具有 Base 或更高版本订阅的 Octo Browser,可让您访问 API。

  • Node.js 22.12 或更高版本。

  • 代理列表或 WireGuard VPN 配置文件。

步骤 1. 安装 Node.js

从 nodejs.org 下载 Node.js 并使用默认设置进行安装。然后打开 PowerShell:按 Win+R,键入 PowerShell,然后按 Enter。检查安装情况:

node --version

该命令应显示版本 22.12 或更高。这是用于测试该脚本的 Puppeteer 25 所必需的。如果 PowerShell 提示找不到该命令,请关闭 PowerShell,重新打开并重试。

步骤 2. 准备文件夹

为脚本选择一个文件夹,例如 D:\proxy_check,创建它,并在 PowerShell 中导航到该文件夹。在其中为您的 VPN 配置创建一个 config 文件夹:

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 令牌粘贴到 API_TOKEN 中。您可以在 Octo Browser 主账户设置下的 API 令牌选项卡中找到它。

const API_TOKEN = "your_token";

您可以将其他设置保留为其默认值。但是,请注意以下两个参数:

KEEP_PROFILES = false 在检查后将配置文件移至回收站。

SAVE_PROXIES = false 可防止将测试过的代理添加到 Octo 代理列表中。通过这些设置,为测试创建的配置文件和代理将不会混杂在浏览器中的工作列表中。如果您的配置文件配额较低,这非常有用。

以下是设置的详细说明:

设置

控制内容

API_TOKEN

Octo Browser API 令牌

LOCAL_PORT

Octo 客户端的本地 API 端口,默认为 58888。您可以在设置中的“附加”选项卡下找到它。

OS

配置文件操作系统:win、mac 或 android。Octo 会选择版本和指纹的其余部分。

HEADLESS

true — 配置文件在无窗口模式下运行;false — 配置文件在窗口中运行,因此您可以查看网站的打开情况。

PARALLEL

同时检查的连接数,从 1 到 10。

PROXIES

直接在代码中指定的代理,作为文件内容的补充。

PROXY_FILE

包含代理的文件;默认为 proxies.txt。

DEFAULT_TYPE

用于未指定类型的代理行的类型。

SAVE_PROXIES

true — 新代理将添加到 Octo 代理列表中;false — 代理仅存在于其自己的配置文件中。

VPN_FOLDER

包含 VPN 配置的文件夹;默认为 config。

VPN_PROTOCOL、VPN_SYN_MODE

配置文件使用的协议以及在 Octo API 中标识它们的模式。默认值为 wireguard 和 profile_based。

SITES_FILE

包含网站列表的文件;默认为 sites.txt。

KEEP_PROFILES

false — 检查后配置文件被移至回收站。

SCREENSHOTS

是否保存失败页面的屏幕截图。

PAGE_TIMEOUT、CHECK_WAIT、EMPTY_WAIT

等待网站响应、“确认您是人类”验证通过以及页面内容出现的秒数。

代码如下:

import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { crc32 } from "node:zlib";

const API_TOKEN = ""; // paste your Octo API token between the quotes
const LOCAL_PORT = 58888; // port of the local API of the Octo client: Octo client, Settings, Additional
const OS = "win"; // OS of the profiles: win, mac or android
const HEADLESS = false; // true: profiles run without a window; false: with a window
const PARALLEL = 5; // connections checked at the same time, from 1 to 10
const PROXIES = [
  // one proxy per line, for example "socks5://login:password@proxy.example.com:10000",
];
const PROXY_FILE = "proxies.txt"; // a file next to the script with one proxy per line, read together with PROXIES
const DEFAULT_TYPE = "socks5"; // type for proxy lines without one: http, https, socks5 or ssh
const SAVE_PROXIES = true; // true: new proxies are saved to Octo's proxy list; false: a proxy lives only in its profile
const VPN_FOLDER = "config"; // folder with WireGuard configs: one VPN profile per file
const VPN_PROTOCOL = "wireguard"; // protocol of the configs, as the Octo API names it
const VPN_SYN_MODE = "profile_based"; // syn_mode of the VPN, as the Octo API names it
const SITES_FILE = "sites.txt"; // sites to check: one per line, # starts a comment
const KEEP_PROFILES = true; // false: every profile goes to the trash after its check
const SCREENSHOTS = true; // true: save a screenshot of every page that did not open
const PAGE_TIMEOUT = 45; // seconds a site gets to answer
const CHECK_WAIT = 15; // seconds a "checking your browser" page gets to clear by itself
const EMPTY_WAIT = 10; // seconds a blank page gets to show something

const HERE = dirname(fileURLToPath(import.meta.url));
const CLOUD = "https://app.octobrowser.net/api/v2/automation";
const LOCAL = `http://localhost:${LOCAL_PORT}/api`;
const OS_NAMES = { win: "Windows", mac: "macOS", android: "Android" };
const PROXY_TYPES = ["http", "https", "socks5", "ssh"];
const SHORT_PAGE = 2500;
const PAGE_LIMITS = { text: 200000, html: 400000, title: 2000 };
const RETRY_TIMEOUT = 20;
const PROXY_FAILURES = 3;
const BROWSER_TIMEOUT = 30;
const RETRY = new Set(["timeout", "connection_reset", "dns_error", "proxy_refused", "unreachable"]);

const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
const anyOf = (phrases) => new RegExp(phrases.join("|"));
const secrets = new Set();
const hide = (value) => String(value || "").length >= 4 && secrets.add(String(value));
const printable = (text) => String(text).replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
const redact = (text) =>
  [...secrets]
    .sort((a, b) => b.length - a.length)
    .reduce((clean, secret) => clean.split(secret).join("***"), printable(text))
    .replace(/\/\/[^\s/@]+@/g, "//***@");
const firstLine = (text) => redact(String(text).split("\n")[0]).slice(0, 200);
const fileName = (text) => String(text).replace(/[^\w.-]+/g, "_");
const localStamp = () =>
  new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace(/[:T]/g, "-");
const readText = (file) => readFileSync(file, "utf8").replace(/^\uFEFF/, "");
const fail = (message) => {
  console.error(message);
  process.exit(1);
};

const GEO = anyOf([
  "(not|isn.t|aren.t) (currently |yet )?(available|accessible|offered|permitted|allowed|supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "(unavailable|blocked|restricted|prohibited|banned|not supported) (in|from|for) your (country|region|location|area|territory|jurisdiction)",
  "not available in this (country|region)",
  "access from your (country|region|location) (is|has been) (blocked|restricted|denied|disabled)",
  "(from|in) a restricted (country|territory|jurisdiction|region|location)",
  "your (country|region|location|territory) is (restricted|not supported|blocked|not allowed)",
  "(do|does) not accept (players|customers|users|visitors|residents) from",
  "(accessing|visiting|located|you are|you.re|you appear)[^.]{0,60}outside (of )?(the )?(uk|u[.]k[.]?|united kingdom|us|u[.]s[.]?|usa|united states|eu)([ .,!]|$)",
  "country (that |where )?you are (located in|in|accessing from|visiting from)[^.]{0,30}not (supported|allowed|available)",
  "(do not|don.t|cannot|can.t) allow access (in|from) your (current )?(country|region|location)",
  "(unavailable|not available|cannot be accessed|can.t be accessed)[^.]{0,120}european (economic area|union)",
  "unavailable (due to|for) legal reasons",
  "configured to block access from your country",
  "недоступ[а-яё]* (в|на территории|для) ваш[а-яё]* (стран|регион)",
  "nicht in (deinem|ihrem) land",
  "pas disponible dans votre (pays|région)",
  "no está disponible en (tu|su) (país|región)",
  "não está disponível (no|em) seu país",
]);

const PROXY_SEEN = anyOf([
  "(vpn|proxy|proxies|anonymizer|unblocker)[^.]{0,60}(detected|not (allowed|permitted|supported))",
  "(appear|seem)s? to be using (a |an )?(vpn|proxy|unblocker|anonymizer)",
  "(detected|blocked) (a |an |your )?(vpn|proxy|anonymous proxy)",
  "(disable|turn off|switch off) (your |the |any )?(vpn|proxy)",
]);

const CHECKS = anyOf([
  "checking (your browser|if the site connection is secure)",
  "verif(y|ying) (that )?you are (a )?human",
  "verify (that )?you are not a (robot|bot)",
  "(prove|confirm) (that )?you are (a )?human",
  "are you (a )?(human|robot)",
  "(complete|pass|performing) (a |the )?(security check|captcha)",
  "security checkpoint",
  "enable javascript and cookies to continue",
  "press (&|and) hold",
  "unusual (traffic|activity)",
  "suspicious (activity|traffic)",
  "automated (access|requests|queries|traffic)",
  "подтвердите, что вы не робот",
  "проверка браузера",
]);

const REFUSALS = anyOf([
  "access (to (this|the) (site|page|website|resource|service) )?(is |has been |was )?(denied|forbidden|blocked|restricted)",
  "you (have been|are|were) (blocked|banned)",
  "your (ip|ip address|request|access|connection) (has been|was|is) (temporarily )?(blocked|banned|denied|blacklisted|rejected|limited)",
  "request (blocked|rejected|denied)",
  "blocked (by|due to) [^.]{0,40}(security|firewall|policy|administrator|rules)",
  "403 forbidden",
  "error 403",
  "you (don.t|do not) have permission to (access|view)",
  "not authori[sz]ed to (access|view)",
  "доступ (к (сайту|ресурсу|странице) )?(запрещ|ограничен|заблокирован|закрыт)",
  "ваш ip[^.]{0,30}(заблокирован|забанен)",
]);

const CLOUDFLARE_ERRORS = {
  1005: "the network of this IP is banned",
  1006: "this IP is banned",
  1007: "this IP is banned",
  1008: "this IP is banned",
  1010: "the browser signature is banned",
  1012: "access denied",
  1020: "access denied by a firewall rule",
};

function guardOf(header, html) {
  const server = header("server");
  if (server.includes("cloudflare") || header("cf-ray")) return "Cloudflare ";
  if (server.includes("akamai")) return "Akamai ";
  if (server.includes("ddos-guard") || html.includes("ddos-guard")) return "DDoS-Guard ";
  return "";
}

function cloudflareError(guard, html, short, words) {
  const onCloudflare = guard === "Cloudflare " || html.includes("cloudflare");
  if (!short || !onCloudflare) return "";
  return (words.match(/error(?: code)?:? ?(1\d{3})(?!\d)/) || [])[1] || "";
}

function view(look) {
  const text = String(look.text || "");
  const title = String(look.title || "").toLowerCase();
  const heading = String(look.heading || "").toLowerCase();
  const html = String(look.html || "").toLowerCase();
  const header = (name) => String(look.headers?.[name] ?? "").toLowerCase();
  const short = text.trim().length < SHORT_PAGE;
  const words = `${title} | ${heading} | ${text.toLowerCase()}`;
  const guard = guardOf(header, html);
  return {
    status: Number(look.status) || 0,
    url: String(look.url || "").toLowerCase(),
    html,
    title,
    top: `${title} | ${heading}`,
    words,
    short,
    empty: !text.trim(),
    refusal: short || Number(look.status) >= 400,
    header,
    guard,
    cloudflare: cloudflareError(guard, html, short, words),
  };
}

const said = (page, phrases) => (page.top.match(phrases) || (page.short && page.words.match(phrases)) || [""])[0];
const quoted = (phrase) => (phrase ? `, the page says: "${phrase}"` : "");

const RULES = [
  {
    verdict: "challenge",
    detail: "Cloudflare challenge",
    when: (page) => page.header("cf-mitigated").includes("challenge"),
  },
  {
    verdict: "blocked",
    detail: (page, state) => `Cloudflare refused (cf-mitigated: ${state})`,
    when: (page) => page.header("cf-mitigated"),
  },
  {
    verdict: "blocked",
    detail: "AWS WAF refused",
    when: (page) => page.header("x-amzn-waf-action") === "block",
  },
  {
    verdict: "challenge",
    detail: (page, action) => `AWS WAF ${action}`,
    when: (page) => page.header("x-amzn-waf-action"),
  },
  {
    verdict: "blocked",
    detail: "Sucuri firewall refused",
    when: (page) => page.header("x-sucuri-block") || (page.refusal && page.words.includes("sucuri website firewall")),
  },
  {
    verdict: "challenge",
    detail: "Kasada check",
    when: (page) =>
      (page.status >= 400 && (page.header("x-kpsdk-ct") || page.header("x-kpsdk-cd"))) ||
      (page.short && page.html.includes("kpsdk")),
  },
  {
    verdict: "geo_blocked",
    detail: "Cloudflare 1009: the site bans the country of this IP",
    when: (page) => page.cloudflare === "1009" || (page.refusal && page.words.includes("banned the country or region")),
  },
  {
    verdict: "geo_blocked",
    detail: "HTTP 451: unavailable for legal reasons in this country",
    when: (page) => page.status === 451,
  },
  {
    verdict: "geo_blocked",
    detail: (page, phrase) => `the page says: "${phrase}"`,
    when: (page) => said(page, GEO),
  },
  {
    verdict: "rate_limited",
    detail: "Cloudflare 1015: too many requests from this IP",
    when: (page) => page.cloudflare === "1015",
  },
  {
    verdict: "blocked",
    detail: (page, meaning) => `Cloudflare ${page.cloudflare}: ${meaning}`,
    when: (page) => CLOUDFLARE_ERRORS[page.cloudflare],
  },
  {
    verdict: "blocked",
    detail: "Cloudflare: 'you have been blocked'",
    when: (page) => page.short && /sorry, you have been blocked|attention required! \| cloudflare/.test(page.words),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare 'Just a moment' check",
    when: (page) => page.refusal && (page.title.includes("just a moment") || page.html.includes("cf_chl_opt")),
  },
  {
    verdict: "challenge",
    detail: "Cloudflare Turnstile check",
    when: (page) => page.short && page.html.includes("cf-turnstile"),
  },
  {
    verdict: "blocked",
    detail: "Akamai: Access Denied",
    when: (page) =>
      page.refusal &&
      (page.html.includes("errors.edgesuite.net") ||
        page.html.includes("reference&#32;&#35;") ||
        /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 = { "<": "&lt;", ">": "&gt;", "&": "&amp;" };
  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:// 前缀,也可以省略。

  • 注释行以 # 开头。注释对于将列表分组非常有用。

# Search and reference sites
google.com
wikipedia.org

# Online stores
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 = <client key>
Address = 10.0.0.2/32
DNS = 1.1.1.1

[Peer]
PublicKey = <server key>

在运行之前,脚本会检查每个配置中的 PrivateKey、Address、PublicKey 和 Endpoint,并验证 Endpoint 是否写为地址和端口(不带 http://)。如果脚本发现错误,它会显示文件名和问题描述,然后退出而不创建任何配置文件。

您的文件夹结构应如下所示:

D:\proxy_check\
  site_access.mjs     script
  sites.txt           website list
  proxies.txt         proxy list
  config\             VPN configs

步骤 6. 运行检查

打开 Octo Browser 并从其文件夹运行脚本:

cd D:\proxy_check 
node site_access.mjs

对于首次运行,请使用一个代理和三到四个网站。您将能够看到网站在配置文件窗口中打开。确认一切正常后,再添加其余内容。

当脚本启动时,它会检查可能阻止其运行的所有内容:令牌、文件、VPN 配置以及 Octo 是否已打开。如果发现错误,它会显示一条描述该问题的消息并退出而不创建配置文件。随后检查开始,每个网站的结果一经得出就会立即显示。

Which websites can you access through your proxies and VPN configs? Check them in Octo Browser profiles

方括号显示连接编号、其配置文件名称和网站计数器。当并行检查多个连接时,它们的输出行可能会交错出现。使用标签查看每行属于哪个连接。输出中不显示代理密码,且仅显示用户名的最后几个字符。要停止检查,请按 Ctrl+C。脚本将停止已启动的配置文件。

如何解读结果

最后,脚本会为每个连接打印一个表格和一个摘要:

Which websites can you access through your proxies and VPN configs? Check them in Octo Browser profiles

AVAILABLE 表示网站成功打开并显示内容。UNAVAILABLE 表示未能打开。最终结果后括号中的原因是按出现频率降序排列的。列名中的 DEAD 表示连接本身无法工作,并不意味着正在检查的所有网站都不可用。

ERROR 标签表示配置文件由于与连接无关的原因而启动失败。Octo 错误消息会显示在控制台和报告中该连接所在行上。

输出文件保存在该文件夹中。其名称中的时间戳使用本地时间:

  • site_access_<time>.xlsx — Excel 报告。顶部包含一个摘要,显示网站总数,以及针对每个连接,有多少个网站可访问、有多少个不可访问以及原因。其下方是详细检查结果,每个结果占一行:配置文件、连接、网站、结果、原因和 IP。可访问网站的行显示为绿色;不可访问的显示为红色。灰色行表示无法工作的连接,以及因代理停止工作而未检查的网站。

  • screens_<time> — 失败页面的屏幕截图,每个连接都有一个单独的文件夹,屏幕截图按照网站列表的顺序进行编号。如果网站没有响应或代理本身无法建立连接,则没有任何内容可截取,因此不会保存屏幕截图。

配置文件仍保留在 Octo Browser 中,并按国家和 IP 命名。

让我们来看看一些可能出现的问题:

在报告中看到的内容

其含义

解决方法

连接被标记为 DEAD。

连接本身无法工作。

检查代理用户名、密码和类型,或 VPN 配置详细信息。

连接被标记为 ERROR。

配置文件无法启动,但问题不在于连接。

阅读报告或控制台中的错误,排查原因,然后重新运行检查。

连续出现多个 proxy_error 条目,后跟 SKIPPED。

代理在检查期间停止工作:其流量耗尽或会话过期。

检查代理并重新运行检查。

一个连接出现大量 proxy_refused 结果。

代理提供商屏蔽了这些网站。

向您的提供商咨询您的套餐中屏蔽了哪些网站类别。

一个连接显示 blocked 或 challenge,而网站通过其他连接可以打开。

该网站不信任此 IP 地址或其子网。

更换 IP 或使用不同类型的代理。

geo_blocked。

该网站在出口国家/地区不可用。

使用来自另一个国家/地区的代理。

某个网站在所有连接上均出现 timeout。

网站本身没有响应。

稍后重新尝试检查。

单个连接上的许多网站均出现 timeout。

连接速度慢或不断中断。

替换该连接。

rate_limited。

来自同一 IP 的请求过多。

请等待并调低 PARALLEL 的值。

原因的具体含义

在这种情况下,服务器响应代码并不可靠。拒绝并不总是伴随错误:Akamai 可能会返回带有 200 状态码的“Access Denied”,AWS WAF 检查可能会返回 202,而 DataDome 拦截可能会返回 401。这就是脚本需要读取页面本身的原因。大型网站很少从头构建拒绝访问页面:通常由某个知名的安全系统显示拦截页面,并且每个系统在标头和文本中都有自己的特征签名。

报告中的原因

实际发生的情况

如何识别

proxy_refused

代理无法建立到该网站的连接。

浏览器中出现隧道或 SOCKS 错误。被代理提供商屏蔽的网站通常表现为此状态。

proxy_error

代理本身无法工作。

代理没有响应或不接受用户名和密码;状态码 407。

blocked

网站拒绝此 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 的消息。

challenge

网站需要进行“确认您是人类”验证。

Cloudflare “Just a moment” 和 Turnstile;PerimeterX “Press & Hold”;来自 DataDome、Akamai、AWS WAF、Kasada、Radware、DDoS-Guard 和 Vercel 的验证码页面;Google 的“异常流量”提示;Amazon 验证码;reCAPTCHA;hCaptcha。

geo_blocked

网站在连接所在的国家/地区不可用。

Cloudflare 1009、状态码 451、基于国家/地区的 CloudFront 拒绝、诸如“在您所在国家/地区不可用”之类的短语,或重定向到诸如 restricted.site.com 之类的地址。

rate_limited

来自此 IP 的请求过多。

状态码 429 或 Cloudflare 1015。

timeout

网站未在规定时间内响应。

在指定时间内未收到响应,或者网站开始响应后卡死。

connection_reset、connection_refused

连接中断或被拒绝。

连接中断、空响应或页面加载前连接被拒绝。

dns_error

找不到网站地址。

DNS 错误。

ssl_error

无法建立安全连接。

证书或 TLS 错误:证书是为其他地址颁发的、已过期,或者在中途被替换。

redirected

网站将浏览器重定向到了无关地址。

最终地址属于另一个网站,该网站显示简短页面或拒绝提示。

redirect_loop

网站陷入无限重定向循环。

浏览器终止了重定向链。

empty

页面保持空白。

10 秒内没有任何内容显示。

unresponsive

页面停止响应。

页面已打开,但由于页面上的脚本卡死,浏览器在 30 秒内无法读取该页面。

http_error

网站返回了错误。

4xx 状态码,例如 404。

server_error

网站本身出现故障;与连接无关。

5xx 状态码,且无安全防护迹象。

unreachable

发生其他网络错误。

原因中包含浏览器错误代码。

这些原因分为三组。proxy_refused 和 proxy_error 表示连接失败:请求从未到达网站。blocked、challenge、geo_blocked 和 rate_limited 表示代理允许请求通过,但网站拒绝了访问。timeout、connection_reset、dns_error 和 ssl_error 表示根本没有收到任何响应:原因可能是代理、网站或它们之间的网络。

脚本如何避免误报

任何方向都可能出现错误:临时故障可能被误认为是屏蔽,空白页面也可能被误认为是成功打开的网站。以下是脚本处理模糊情况的方式:

情况

脚本的操作

连接断开、超时或代理拒绝请求。

它会重试并等待长达 20 秒以获得响应。仅当第二次尝试也失败时,才会分配 UNAVAILABLE,并记录原因。

网站显示“请稍候”验证。

它最多等待 15 秒:此检查通常会自动为普通访客通过。如果通过,结果为 AVAILABLE 并附带说明。

页面需要时间来呈现其脚本。

它最多等待 10 秒以等待内容出现。

网站开始响应然后卡死。

它会记录一个单独的 timeout 原因:网站响应了,但页面未能加载。

网站打开一个 alert 或 confirm 对话框。

它通过取消对话框来将其关闭;否则页面无法继续加载。脚本随后继续检查。

页面上的脚本卡死。

30 秒后,它会分配 unresponsive 原因并转至下一个网站。

网站重定向到其本地国家/地区版本,例如 example.com → example.de。

由于是同一个网站:结果为 AVAILABLE,并附带注释显示其打开时的实际地址。

网站重定向到另一个域名,并在该域名上加载了常规页面。

结果为 AVAILABLE,并附带注释“已打开另一个网站”及新地址。这可能是品牌重塑或迁移,例如 twitter.com → x.com,或者是一种替换——例如在美国境外,hulu.com 会重定向到 disneyplus.com。

网站重定向到无关的简短页面或拒绝访问页面。

结果为 UNAVAILABLE,并附带 redirected 原因以及该页面的文本。

页面包含反机器人脚本,但网站可以正常打开。

防护措施的存在不会被视为拒绝。只有拒绝页面本身才会被计入。

常规文章的文本中出现了“access denied”字样。

仅在页面标题和简短页面中检查拒绝短语,而不会在长文本中间进行检查。

结论

该脚本使通过代理和 VPN 进行网站可用性检查自动化。它可以显示哪些网站可以通过各个连接打开,并帮助识别其他网站不可用的原因。您只需创建一次网站列表,然后在购买新代理、更换提供商或遇到网站访问问题时运行检查即可。这样,您就不必手动测试每个连接。

常见问题解答

一次可以检查多少个连接?

每个配置文件都是一个单独的浏览器,因此限制取决于您的内存和 CPU。在普通设备上,三到五个是合理的数值;通过 PARALLEL 设置进行配置。如果您的所有代理都使用同一个提供商网关,请不要将该数字设置得太高:您的提供商账户可能会限制并发连接数。

检查需要多长时间?

能正常打开的网站只需要几秒钟。没有响应的网站耗时最长:脚本会等待 45 秒,然后再重试 20 秒。连接是并行检查的,因此检查五个代理所花费的时间与检查一个代理大致相同。

为什么某个连接的所有网站都被标记为 DEAD?

Octo 无法使用该代理或 VPN 启动配置文件:连接无法工作。请检查代理用户名和密码、协议以及 VPN 配置详情。如果标签是 ERROR 而不是 DEAD,则表示配置文件由于与连接无关的其他原因而未能启动。该原因会显示在该连接所在的行上。

某个网站被标记为 challenge,但手动可以打开。为什么?

“确认您是人类”验证未在 15 秒内自动通过。您可以通过点击手动完成它,但脚本不会执行任何点击操作。等待时间由 CHECK_WAIT 设置控制。

为什么两次运行的结果会有所不同?

最常见的原因是代理更改了其 IP 地址。轮换代理在两次连接之间会使用不同的 IP,并且网站对待新地址的方式可能有所不同。对于某些提供商,被屏蔽的网站列表也取决于出口节点:某家银行可能可以通过某个 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 以外的任何地方吗?

脚本仅将令牌发送到 Octo API 地址。它会对第三方服务发出一次请求:如果 Octo 未报告出口国家/地区,脚本会使用 GeoJS 按 IP 查询。只有代理的出口 IP 会发送给 GeoJS。

随时获取最新的Octo Browser新闻

通过点击按钮,您同意我们的 隐私政策。

随时获取最新的Octo Browser新闻

通过点击按钮,您同意我们的 隐私政策。

随时获取最新的Octo Browser新闻

通过点击按钮,您同意我们的 隐私政策。

立即加入Octo Browser

或者随时联系客户服务,如果您有任何问题。

立即加入Octo Browser

或者随时联系客户服务,如果您有任何问题。

立即加入Octo Browser

或者随时联系客户服务,如果您有任何问题。

©

2026年

Octo Browser

©

2026年

Octo Browser

©

2026年

Octo Browser