cfpilot 0.13.2 → 0.13.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -0
- package/assets/control.js +10 -10
- package/assets/dataplane.js +5 -5
- package/assets/worker.js +13 -13
- package/dist/cli.js +1141 -124
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -87,14 +87,14 @@ var VERSION, NAME;
|
|
|
87
87
|
var init_version = __esm({
|
|
88
88
|
"src/shared/version.ts"() {
|
|
89
89
|
"use strict";
|
|
90
|
-
VERSION = "0.13.
|
|
90
|
+
VERSION = "0.13.7";
|
|
91
91
|
NAME = "cfpilot";
|
|
92
92
|
}
|
|
93
93
|
});
|
|
94
94
|
|
|
95
95
|
// src/menu/ui.ts
|
|
96
|
-
function wrap(
|
|
97
|
-
return (s) => useColor ? `\x1B[${
|
|
96
|
+
function wrap(open2, close) {
|
|
97
|
+
return (s) => useColor ? `\x1B[${open2}m${s}\x1B[${close}m` : s;
|
|
98
98
|
}
|
|
99
99
|
function clearScreen() {
|
|
100
100
|
if (!process.stdout.isTTY) return;
|
|
@@ -140,8 +140,8 @@ function box(title, lines = [], width = 52) {
|
|
|
140
140
|
function rule(width = 52) {
|
|
141
141
|
process.stdout.write(c.gray("\u2500".repeat(width)) + "\n");
|
|
142
142
|
}
|
|
143
|
-
function status(kind,
|
|
144
|
-
process.stdout.write(`${icon[kind]()} ${
|
|
143
|
+
function status(kind, text2) {
|
|
144
|
+
process.stdout.write(`${icon[kind]()} ${text2}
|
|
145
145
|
`);
|
|
146
146
|
}
|
|
147
147
|
var useColor, c, icon;
|
|
@@ -439,8 +439,8 @@ async function confirm(question, fallback = false) {
|
|
|
439
439
|
if (!t) return fallback;
|
|
440
440
|
return t === "y" || t === "yes" || t === "\u662F";
|
|
441
441
|
}
|
|
442
|
-
async function pause(
|
|
443
|
-
await ask(c.gray(
|
|
442
|
+
async function pause(text2 = "\u6309 Enter \u7EE7\u7EED") {
|
|
443
|
+
await ask(c.gray(text2), { allowEmpty: true });
|
|
444
444
|
}
|
|
445
445
|
var init_prompt = __esm({
|
|
446
446
|
"src/menu/prompt.ts"() {
|
|
@@ -460,6 +460,9 @@ function configDir() {
|
|
|
460
460
|
function configFile() {
|
|
461
461
|
return join(configDir(), "config.json");
|
|
462
462
|
}
|
|
463
|
+
function configDirPath() {
|
|
464
|
+
return configDir();
|
|
465
|
+
}
|
|
463
466
|
function configPath() {
|
|
464
467
|
return configFile();
|
|
465
468
|
}
|
|
@@ -546,40 +549,40 @@ var init_store = __esm({
|
|
|
546
549
|
});
|
|
547
550
|
|
|
548
551
|
// src/deploy/cf-api.ts
|
|
549
|
-
function parseApiError(status2,
|
|
552
|
+
function parseApiError(status2, text2) {
|
|
550
553
|
let message = `HTTP ${status2}`;
|
|
551
554
|
let code;
|
|
552
|
-
if (
|
|
555
|
+
if (text2) {
|
|
553
556
|
try {
|
|
554
|
-
const parsed = JSON.parse(
|
|
557
|
+
const parsed = JSON.parse(text2);
|
|
555
558
|
const errors = Array.isArray(parsed.errors) ? parsed.errors : [];
|
|
556
559
|
if (errors.length > 0) {
|
|
557
560
|
message = errors.map((item) => item.message).join("; ");
|
|
558
561
|
code = errors[0]?.code;
|
|
559
562
|
} else {
|
|
560
|
-
message = `${message} ${
|
|
563
|
+
message = `${message} ${text2.slice(0, 300)}`;
|
|
561
564
|
}
|
|
562
565
|
} catch {
|
|
563
|
-
message = `${message} ${
|
|
566
|
+
message = `${message} ${text2.slice(0, 300)}`;
|
|
564
567
|
}
|
|
565
568
|
}
|
|
566
569
|
return new CloudflareError(message, status2, code);
|
|
567
570
|
}
|
|
568
571
|
async function readApiResponse(response) {
|
|
569
|
-
const
|
|
570
|
-
if (!response.ok) throw parseApiError(response.status,
|
|
571
|
-
if (!
|
|
572
|
+
const text2 = await response.text();
|
|
573
|
+
if (!response.ok) throw parseApiError(response.status, text2);
|
|
574
|
+
if (!text2) return void 0;
|
|
572
575
|
let parsed;
|
|
573
576
|
try {
|
|
574
|
-
parsed = JSON.parse(
|
|
577
|
+
parsed = JSON.parse(text2);
|
|
575
578
|
} catch {
|
|
576
|
-
throw new CloudflareError(`\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${
|
|
579
|
+
throw new CloudflareError(`\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${text2.slice(0, 200)}`, response.status);
|
|
577
580
|
}
|
|
578
581
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
579
582
|
throw new CloudflareError("Cloudflare \u54CD\u5E94\u683C\u5F0F\u65E0\u6548", response.status);
|
|
580
583
|
}
|
|
581
584
|
if ("success" in parsed && parsed.success === false) {
|
|
582
|
-
throw parseApiError(response.status,
|
|
585
|
+
throw parseApiError(response.status, text2);
|
|
583
586
|
}
|
|
584
587
|
return "result" in parsed ? parsed.result : void 0;
|
|
585
588
|
}
|
|
@@ -714,8 +717,8 @@ var init_cf_api = __esm({
|
|
|
714
717
|
}
|
|
715
718
|
if (response.status === 404) return null;
|
|
716
719
|
if (!response.ok) {
|
|
717
|
-
const
|
|
718
|
-
const detail = parseApiError(response.status,
|
|
720
|
+
const text2 = await response.text().catch(() => "");
|
|
721
|
+
const detail = parseApiError(response.status, text2).message;
|
|
719
722
|
throw new Error(`\u8BFB\u53D6 KV \u5931\u8D25\uFF08\u65E0\u6CD5\u786E\u8BA4\u5F52\u5C5E\uFF09\uFF1A${detail}`);
|
|
720
723
|
}
|
|
721
724
|
return await response.text();
|
|
@@ -739,8 +742,8 @@ var init_cf_api = __esm({
|
|
|
739
742
|
}
|
|
740
743
|
);
|
|
741
744
|
if (!response.ok) {
|
|
742
|
-
const
|
|
743
|
-
throw parseApiError(response.status,
|
|
745
|
+
const text2 = await response.text().catch(() => "");
|
|
746
|
+
throw parseApiError(response.status, text2);
|
|
744
747
|
}
|
|
745
748
|
}
|
|
746
749
|
/** 列出已部署的 Worker 脚本 */
|
|
@@ -1162,13 +1165,13 @@ function charWidth(char) {
|
|
|
1162
1165
|
const wide = code >= 4352 && code <= 4447 || code === 9001 || code === 9002 || code >= 11904 && code <= 42191 || code >= 44032 && code <= 55203 || code >= 63744 && code <= 64255 || code >= 65072 && code <= 65135 || code >= 65280 && code <= 65376 || code >= 65504 && code <= 65510 || code >= 127744 && code <= 129791;
|
|
1163
1166
|
return wide ? 2 : 1;
|
|
1164
1167
|
}
|
|
1165
|
-
function displayWidth2(
|
|
1168
|
+
function displayWidth2(text2) {
|
|
1166
1169
|
let width = 0;
|
|
1167
|
-
for (const char of
|
|
1170
|
+
for (const char of text2) width += charWidth(char);
|
|
1168
1171
|
return width;
|
|
1169
1172
|
}
|
|
1170
|
-
function padDisplay(
|
|
1171
|
-
return `${
|
|
1173
|
+
function padDisplay(text2, width) {
|
|
1174
|
+
return `${text2}${" ".repeat(Math.max(0, width - displayWidth2(text2)))}`;
|
|
1172
1175
|
}
|
|
1173
1176
|
function renderPermissionTable(rows) {
|
|
1174
1177
|
const header = ["\u6743\u9650\u9879", "\u72B6\u6001", "\u7F3A\u5931\u540E\u679C"];
|
|
@@ -1602,9 +1605,9 @@ var init_workers_deploy = __esm({
|
|
|
1602
1605
|
|
|
1603
1606
|
// src/shared/version-util.ts
|
|
1604
1607
|
function parseVersion(input) {
|
|
1605
|
-
const
|
|
1606
|
-
if (!
|
|
1607
|
-
const matched = VERSION_RE.exec(
|
|
1608
|
+
const text2 = input.trim();
|
|
1609
|
+
if (!text2) return null;
|
|
1610
|
+
const matched = VERSION_RE.exec(text2);
|
|
1608
1611
|
if (!matched) return null;
|
|
1609
1612
|
const major = Number(matched[1]);
|
|
1610
1613
|
const minor = matched[2] === void 0 ? 0 : Number(matched[2]);
|
|
@@ -1733,10 +1736,10 @@ import { homedir as homedir2 } from "node:os";
|
|
|
1733
1736
|
import { dirname, join as join2, resolve } from "node:path";
|
|
1734
1737
|
import { fileURLToPath } from "node:url";
|
|
1735
1738
|
function versionFromTag(tag) {
|
|
1736
|
-
const
|
|
1739
|
+
const text2 = tag.trim();
|
|
1737
1740
|
for (const prefix of ["desktop-v", "gui-v", "v"]) {
|
|
1738
|
-
if (
|
|
1739
|
-
const rest =
|
|
1741
|
+
if (text2.startsWith(prefix)) {
|
|
1742
|
+
const rest = text2.slice(prefix.length);
|
|
1740
1743
|
return /^\d+\.\d+\.\d+/.test(rest) ? rest : "";
|
|
1741
1744
|
}
|
|
1742
1745
|
}
|
|
@@ -1849,11 +1852,11 @@ async function downloadAsset(url, timeoutMs, options = {}) {
|
|
|
1849
1852
|
async function readBodyWithLimit(response) {
|
|
1850
1853
|
const body = response.body;
|
|
1851
1854
|
if (!body) {
|
|
1852
|
-
const
|
|
1853
|
-
if (Buffer.byteLength(
|
|
1855
|
+
const text2 = await response.text();
|
|
1856
|
+
if (Buffer.byteLength(text2) > MAX_ASSET_BYTES) {
|
|
1854
1857
|
throw new Error(`\u5185\u6838\u4EA7\u7269\u8D85\u8FC7 ${MAX_ASSET_BYTES} \u5B57\u8282\u4E0A\u9650\uFF0C\u7591\u4F3C\u5F02\u5E38\u5185\u5BB9`);
|
|
1855
1858
|
}
|
|
1856
|
-
return
|
|
1859
|
+
return text2;
|
|
1857
1860
|
}
|
|
1858
1861
|
const reader = body.getReader();
|
|
1859
1862
|
const decoder = new TextDecoder();
|
|
@@ -1881,9 +1884,9 @@ async function readBodyWithLimit(response) {
|
|
|
1881
1884
|
function sha256Hex(content) {
|
|
1882
1885
|
return createHash("sha256").update(content, "utf8").digest("hex");
|
|
1883
1886
|
}
|
|
1884
|
-
function parseChecksums(
|
|
1887
|
+
function parseChecksums(text2) {
|
|
1885
1888
|
const out = /* @__PURE__ */ new Map();
|
|
1886
|
-
for (const raw of
|
|
1889
|
+
for (const raw of text2.split("\n")) {
|
|
1887
1890
|
const line = raw.trim();
|
|
1888
1891
|
if (!line || line.startsWith("#")) continue;
|
|
1889
1892
|
const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line);
|
|
@@ -1898,14 +1901,14 @@ async function downloadChecksums(info, timeoutMs) {
|
|
|
1898
1901
|
`Release ${info.version} \u672A\u53D1\u5E03 ${CHECKSUMS_ASSET_NAME}\uFF0C\u65E0\u6CD5\u6821\u9A8C\u5185\u6838\u5B8C\u6574\u6027`
|
|
1899
1902
|
);
|
|
1900
1903
|
}
|
|
1901
|
-
const
|
|
1902
|
-
const map = parseChecksums(
|
|
1904
|
+
const text2 = await downloadAsset(info.checksumsUrl, timeoutMs, { allowMirrors: false });
|
|
1905
|
+
const map = parseChecksums(text2);
|
|
1903
1906
|
for (const name of [CONTROL_ASSET_NAME, DATA_ASSET_NAME]) {
|
|
1904
1907
|
if (!map.has(name.toLowerCase())) {
|
|
1905
1908
|
throw new Error(`\u5185\u6838\u6821\u9A8C\u6E05\u5355\u7F3A\u5C11 ${name} \u7684\u6458\u8981`);
|
|
1906
1909
|
}
|
|
1907
1910
|
}
|
|
1908
|
-
return { text, map };
|
|
1911
|
+
return { text: text2, map };
|
|
1909
1912
|
}
|
|
1910
1913
|
function verifyAsset(shortName, content, map) {
|
|
1911
1914
|
const assetName = ASSET_BY_SHORT_NAME[shortName];
|
|
@@ -1929,8 +1932,8 @@ function cacheDir(version) {
|
|
|
1929
1932
|
}
|
|
1930
1933
|
async function readCached(path) {
|
|
1931
1934
|
try {
|
|
1932
|
-
const
|
|
1933
|
-
return
|
|
1935
|
+
const text2 = await readFile(path, "utf8");
|
|
1936
|
+
return text2.length > 0 ? text2 : null;
|
|
1934
1937
|
} catch {
|
|
1935
1938
|
return null;
|
|
1936
1939
|
}
|
|
@@ -1964,8 +1967,8 @@ async function loadBuiltinBundle(fileName) {
|
|
|
1964
1967
|
];
|
|
1965
1968
|
for (const candidate of candidates) {
|
|
1966
1969
|
try {
|
|
1967
|
-
const
|
|
1968
|
-
if (
|
|
1970
|
+
const text2 = await readFile(candidate, "utf8");
|
|
1971
|
+
if (text2.length > 0) return text2;
|
|
1969
1972
|
} catch {
|
|
1970
1973
|
}
|
|
1971
1974
|
}
|
|
@@ -3741,8 +3744,8 @@ var init_countries = __esm({
|
|
|
3741
3744
|
// src/scan/true-probe.ts
|
|
3742
3745
|
import * as tls from "node:tls";
|
|
3743
3746
|
import * as crypto from "node:crypto";
|
|
3744
|
-
function extractColo(
|
|
3745
|
-
const match = /cf-ray:\s*[0-9a-f]+-([A-Z]{3})/i.exec(
|
|
3747
|
+
function extractColo(text2) {
|
|
3748
|
+
const match = /cf-ray:\s*[0-9a-f]+-([A-Z]{3})/i.exec(text2);
|
|
3746
3749
|
return match ? match[1].toUpperCase() : "";
|
|
3747
3750
|
}
|
|
3748
3751
|
function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
|
|
@@ -3761,7 +3764,7 @@ function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
|
|
|
3761
3764
|
}
|
|
3762
3765
|
resolve3({ ...result, latencyMs: Date.now() - started });
|
|
3763
3766
|
};
|
|
3764
|
-
const
|
|
3767
|
+
const request3 = [
|
|
3765
3768
|
`GET ${path} HTTP/1.1`,
|
|
3766
3769
|
`Host: ${host}`,
|
|
3767
3770
|
`Upgrade: websocket`,
|
|
@@ -3781,7 +3784,7 @@ function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
|
|
|
3781
3784
|
ALPNProtocols: ["http/1.1"]
|
|
3782
3785
|
},
|
|
3783
3786
|
() => {
|
|
3784
|
-
socket.write(
|
|
3787
|
+
socket.write(request3);
|
|
3785
3788
|
}
|
|
3786
3789
|
);
|
|
3787
3790
|
const timer = setTimeout(() => {
|
|
@@ -3879,7 +3882,7 @@ function probeWsPing(ip, port, host, timeoutMs = 5e3, path = "/__edge_probe") {
|
|
|
3879
3882
|
}
|
|
3880
3883
|
resolve3({ ...result, latencyMs: Date.now() - started });
|
|
3881
3884
|
};
|
|
3882
|
-
const
|
|
3885
|
+
const request3 = [
|
|
3883
3886
|
`GET ${path} HTTP/1.1`,
|
|
3884
3887
|
`Host: ${host}`,
|
|
3885
3888
|
`Upgrade: websocket`,
|
|
@@ -3899,7 +3902,7 @@ function probeWsPing(ip, port, host, timeoutMs = 5e3, path = "/__edge_probe") {
|
|
|
3899
3902
|
ALPNProtocols: ["http/1.1"]
|
|
3900
3903
|
},
|
|
3901
3904
|
() => {
|
|
3902
|
-
socket.write(
|
|
3905
|
+
socket.write(request3);
|
|
3903
3906
|
}
|
|
3904
3907
|
);
|
|
3905
3908
|
const timer = setTimeout(() => {
|
|
@@ -4080,7 +4083,7 @@ function measureThroughput(options) {
|
|
|
4080
4083
|
error
|
|
4081
4084
|
});
|
|
4082
4085
|
};
|
|
4083
|
-
const
|
|
4086
|
+
const request3 = [
|
|
4084
4087
|
`GET ${path} HTTP/1.1`,
|
|
4085
4088
|
`Host: ${requestHost}`,
|
|
4086
4089
|
`User-Agent: ${USER_AGENT}`,
|
|
@@ -4103,7 +4106,7 @@ function measureThroughput(options) {
|
|
|
4103
4106
|
},
|
|
4104
4107
|
() => {
|
|
4105
4108
|
openedCount++;
|
|
4106
|
-
socket.write(
|
|
4109
|
+
socket.write(request3);
|
|
4107
4110
|
}
|
|
4108
4111
|
);
|
|
4109
4112
|
sockets.push(socket);
|
|
@@ -4185,7 +4188,7 @@ async function measureProbeThroughput(options) {
|
|
|
4185
4188
|
minBytes: 32 * 1024
|
|
4186
4189
|
});
|
|
4187
4190
|
}
|
|
4188
|
-
function buildVlessTunnelPayload(uuid, targetHost, targetPort,
|
|
4191
|
+
function buildVlessTunnelPayload(uuid, targetHost, targetPort, request3) {
|
|
4189
4192
|
const clean = uuid.replace(/-/g, "");
|
|
4190
4193
|
if (!/^[0-9a-fA-F]{32}$/.test(clean)) return null;
|
|
4191
4194
|
const hostBuf = Buffer.from(targetHost, "utf8");
|
|
@@ -4194,10 +4197,10 @@ function buildVlessTunnelPayload(uuid, targetHost, targetPort, request) {
|
|
|
4194
4197
|
Buffer.from(clean, "hex"),
|
|
4195
4198
|
Buffer.from([0, 1, targetPort >> 8 & 255, targetPort & 255, 2, hostBuf.length]),
|
|
4196
4199
|
hostBuf,
|
|
4197
|
-
Buffer.from(
|
|
4200
|
+
Buffer.from(request3, "utf8")
|
|
4198
4201
|
]);
|
|
4199
4202
|
}
|
|
4200
|
-
function buildTrojanTunnelPayload(password, targetHost, targetPort,
|
|
4203
|
+
function buildTrojanTunnelPayload(password, targetHost, targetPort, request3) {
|
|
4201
4204
|
const digest = crypto.createHash("sha224").update(password).digest("hex");
|
|
4202
4205
|
const hostBuf = Buffer.from(targetHost, "utf8");
|
|
4203
4206
|
return Buffer.concat([
|
|
@@ -4206,7 +4209,7 @@ function buildTrojanTunnelPayload(password, targetHost, targetPort, request) {
|
|
|
4206
4209
|
hostBuf,
|
|
4207
4210
|
Buffer.from([targetPort >> 8 & 255, targetPort & 255]),
|
|
4208
4211
|
Buffer.from("\r\n", "ascii"),
|
|
4209
|
-
Buffer.from(
|
|
4212
|
+
Buffer.from(request3, "utf8")
|
|
4210
4213
|
]);
|
|
4211
4214
|
}
|
|
4212
4215
|
function tunnelUpgradeRequest(host, wsPath, key) {
|
|
@@ -4433,7 +4436,7 @@ function checkSpeedUrlAvailable(parsed, timeoutMs = 6e3) {
|
|
|
4433
4436
|
resolve3({ available, status: status2, error });
|
|
4434
4437
|
};
|
|
4435
4438
|
const path = parsed.path.includes("bytes=") ? parsed.path.replace(/bytes=\d+/, "bytes=1024") : parsed.path;
|
|
4436
|
-
const
|
|
4439
|
+
const request3 = [
|
|
4437
4440
|
`GET ${path} HTTP/1.1`,
|
|
4438
4441
|
`Host: ${parsed.host}`,
|
|
4439
4442
|
`User-Agent: ${USER_AGENT_FOR_CHECK}`,
|
|
@@ -4448,10 +4451,10 @@ function checkSpeedUrlAvailable(parsed, timeoutMs = 6e3) {
|
|
|
4448
4451
|
servername: parsed.host,
|
|
4449
4452
|
rejectUnauthorized: false
|
|
4450
4453
|
};
|
|
4451
|
-
const socket = parsed.scheme === "https" ? tls2.connect(connectOptions, () => socket.write(
|
|
4454
|
+
const socket = parsed.scheme === "https" ? tls2.connect(connectOptions, () => socket.write(request3)) : (
|
|
4452
4455
|
// http 明文:用 net 连接
|
|
4453
4456
|
(() => {
|
|
4454
|
-
const s = net.connect({ host: parsed.host, port: 80 }, () => s.write(
|
|
4457
|
+
const s = net.connect({ host: parsed.host, port: 80 }, () => s.write(request3));
|
|
4455
4458
|
return s;
|
|
4456
4459
|
})()
|
|
4457
4460
|
);
|
|
@@ -4599,20 +4602,20 @@ var init_unlock = __esm({
|
|
|
4599
4602
|
// src/scan/scan.ts
|
|
4600
4603
|
import * as net2 from "node:net";
|
|
4601
4604
|
function classifyFailure(error) {
|
|
4602
|
-
const
|
|
4603
|
-
if (!
|
|
4604
|
-
if (/timeout|timed out|超时|ETIMEDOUT/i.test(
|
|
4605
|
-
if (/ECONNREFUSED|connection refused|连接被拒/i.test(
|
|
4606
|
-
if (/ENETUNREACH|EHOSTUNREACH|unreachable/i.test(
|
|
4607
|
-
if (/ECONNRESET|socket hang up|连接重置/i.test(
|
|
4608
|
-
if (/certificate|CERT_|SELF_SIGNED|证书/i.test(
|
|
4609
|
-
if (/ALPN/i.test(
|
|
4610
|
-
if (/HTTP\s*\d{3}/i.test(
|
|
4611
|
-
const code = /HTTP\s*(\d{3})/i.exec(
|
|
4605
|
+
const text2 = String(error ?? "").trim();
|
|
4606
|
+
if (!text2) return "\u672A\u77E5\u539F\u56E0";
|
|
4607
|
+
if (/timeout|timed out|超时|ETIMEDOUT/i.test(text2)) return "\u8D85\u65F6";
|
|
4608
|
+
if (/ECONNREFUSED|connection refused|连接被拒/i.test(text2)) return "\u8FDE\u63A5\u88AB\u62D2";
|
|
4609
|
+
if (/ENETUNREACH|EHOSTUNREACH|unreachable/i.test(text2)) return "\u7F51\u7EDC\u4E0D\u53EF\u8FBE";
|
|
4610
|
+
if (/ECONNRESET|socket hang up|连接重置/i.test(text2)) return "\u8FDE\u63A5\u91CD\u7F6E";
|
|
4611
|
+
if (/certificate|CERT_|SELF_SIGNED|证书/i.test(text2)) return "\u8BC1\u4E66\u95EE\u9898";
|
|
4612
|
+
if (/ALPN/i.test(text2)) return "ALPN \u534F\u5546\u5931\u8D25";
|
|
4613
|
+
if (/HTTP\s*\d{3}/i.test(text2)) {
|
|
4614
|
+
const code = /HTTP\s*(\d{3})/i.exec(text2)?.[1];
|
|
4612
4615
|
return code ? `HTTP ${code}` : "HTTP \u72B6\u6001\u5F02\u5E38";
|
|
4613
4616
|
}
|
|
4614
|
-
if (/PONG|pong/i.test(
|
|
4615
|
-
if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(
|
|
4617
|
+
if (/PONG|pong/i.test(text2)) return "\u5185\u5BB9\u6821\u9A8C\u4E0D\u901A\u8FC7";
|
|
4618
|
+
if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(text2)) return "\u57DF\u540D\u89E3\u6790\u5931\u8D25";
|
|
4616
4619
|
return "\u5176\u4ED6";
|
|
4617
4620
|
}
|
|
4618
4621
|
function countFailure(into, stage, error) {
|
|
@@ -4723,6 +4726,7 @@ async function runScan(options) {
|
|
|
4723
4726
|
message: `TCP \u521D\u7B5B ${done}/${candidates.length}`
|
|
4724
4727
|
});
|
|
4725
4728
|
}
|
|
4729
|
+
options.onObservation?.({ ip, ok: result.ok, stage: "tcp", latencyMs: result.latency, error: result.ok ? void 0 : "TCP \u8FDE\u63A5\u5931\u8D25" });
|
|
4726
4730
|
return result;
|
|
4727
4731
|
});
|
|
4728
4732
|
const tcpOk = tcpResults.filter((r) => r.ok);
|
|
@@ -4749,6 +4753,7 @@ async function runScan(options) {
|
|
|
4749
4753
|
message: `TLS \u63E1\u624B ${tlsDone}/${tlsInput.length}${probe.tlsMs > 0 ? ` ${probe.tlsMs}ms` : " \u2717"}`
|
|
4750
4754
|
});
|
|
4751
4755
|
}
|
|
4756
|
+
options.onObservation?.({ ip: item.ip, ok: probe.tlsMs > 0, stage: "tls", latencyMs: probe.tlsMs, error: probe.error });
|
|
4752
4757
|
return { ...item, tls: probe };
|
|
4753
4758
|
});
|
|
4754
4759
|
const failures = {};
|
|
@@ -4803,6 +4808,7 @@ async function runScan(options) {
|
|
|
4803
4808
|
total: stage1.length,
|
|
4804
4809
|
message: strictProbe ? `101+PING \u6821\u9A8C ${probeDone}/${stage1.length}${result.ok ? ` \u2713 ${result.colo}` : result.pongVerified === false ? " \u2717 \u65E0\u54CD\u5E94" : ""}` : `101 \u6821\u9A8C ${probeDone}/${stage1.length}${result.ok ? ` \u2713 ${result.colo}` : ""}`
|
|
4805
4810
|
});
|
|
4811
|
+
options.onObservation?.({ ip: item.ip, ok: result.ok, stage: "ws", error: result.error });
|
|
4806
4812
|
return { ...item, probe: result, pathOk };
|
|
4807
4813
|
},
|
|
4808
4814
|
() => {
|
|
@@ -4888,6 +4894,7 @@ async function runScan(options) {
|
|
|
4888
4894
|
speedResults = await pool(stage2, speedConcurrency, async (item) => {
|
|
4889
4895
|
const repeat = Math.max(1, options.speedRepeat ?? 1);
|
|
4890
4896
|
const samples = [];
|
|
4897
|
+
const peakSamples = [];
|
|
4891
4898
|
for (let r = 0; r < repeat; r++) {
|
|
4892
4899
|
const one = await measureThroughput({
|
|
4893
4900
|
ip: item.ip,
|
|
@@ -4899,12 +4906,17 @@ async function runScan(options) {
|
|
|
4899
4906
|
durationMs: options.speedDurationMs ?? 6e3,
|
|
4900
4907
|
timeoutMs: options.speedTimeoutMs ?? 2e4
|
|
4901
4908
|
});
|
|
4902
|
-
if (one.ok)
|
|
4909
|
+
if (one.ok) {
|
|
4910
|
+
samples.push(one.steadyMBps);
|
|
4911
|
+
peakSamples.push(one.peakMBps);
|
|
4912
|
+
}
|
|
4903
4913
|
}
|
|
4904
4914
|
samples.sort((a, b) => a - b);
|
|
4915
|
+
peakSamples.sort((a, b) => a - b);
|
|
4905
4916
|
const median = samples.length === 0 ? 0 : samples[Math.floor(samples.length / 2)];
|
|
4917
|
+
const peak = peakSamples.length === 0 ? 0 : peakSamples[Math.floor(peakSamples.length / 2)];
|
|
4906
4918
|
const jitter = samples.length < 2 ? 0 : samples[samples.length - 1] - samples[0];
|
|
4907
|
-
const result = { ok: samples.length > 0, steadyMBps: median };
|
|
4919
|
+
const result = { ok: samples.length > 0, steadyMBps: median, peakMBps: peak };
|
|
4908
4920
|
speedDone++;
|
|
4909
4921
|
report({
|
|
4910
4922
|
type: "progress",
|
|
@@ -4913,7 +4925,7 @@ async function runScan(options) {
|
|
|
4913
4925
|
total: stage2.length,
|
|
4914
4926
|
message: `\u6D4B\u901F ${speedDone}/${stage2.length} [${item.probe.colo || "UNK"}] ${result.steadyMBps.toFixed(1)} MB/s${jitter > 0 ? ` \xB1${jitter.toFixed(1)}` : ""}`
|
|
4915
4927
|
});
|
|
4916
|
-
return { ...item, speed: result.ok ? result.steadyMBps : 0, jitter };
|
|
4928
|
+
return { ...item, speed: result.ok ? result.steadyMBps : 0, peakMBps: result.peakMBps, jitter };
|
|
4917
4929
|
});
|
|
4918
4930
|
} else {
|
|
4919
4931
|
report({ type: "stage", stage: 3, name: "\u771F\u5B9E\u4E0B\u884C\u901F\u5EA6\u6D4B\u8BD5\uFF08\u9879\u76EE\u63A2\u9488\u7AEF\u70B9 \xB7 \u591A\u6D41\u7A33\u6001\uFF09", total: stage2.length });
|
|
@@ -4921,6 +4933,7 @@ async function runScan(options) {
|
|
|
4921
4933
|
speedResults = await pool(stage2, speedConcurrency, async (item) => {
|
|
4922
4934
|
const repeat = Math.max(1, options.speedRepeat ?? 1);
|
|
4923
4935
|
const samples = [];
|
|
4936
|
+
const peakSamples = [];
|
|
4924
4937
|
for (let r = 0; r < repeat; r++) {
|
|
4925
4938
|
const one = await measureProbeThroughput({
|
|
4926
4939
|
ip: item.ip,
|
|
@@ -4933,12 +4946,17 @@ async function runScan(options) {
|
|
|
4933
4946
|
timeoutMs: speedTimeoutMs,
|
|
4934
4947
|
token: options.uuid
|
|
4935
4948
|
});
|
|
4936
|
-
if (one.ok)
|
|
4949
|
+
if (one.ok) {
|
|
4950
|
+
samples.push(one.steadyMBps);
|
|
4951
|
+
peakSamples.push(one.peakMBps);
|
|
4952
|
+
}
|
|
4937
4953
|
}
|
|
4938
4954
|
samples.sort((a, b) => a - b);
|
|
4955
|
+
peakSamples.sort((a, b) => a - b);
|
|
4939
4956
|
const median = samples.length === 0 ? 0 : samples[Math.floor(samples.length / 2)];
|
|
4957
|
+
const peak = peakSamples.length === 0 ? 0 : peakSamples[Math.floor(peakSamples.length / 2)];
|
|
4940
4958
|
const jitter = samples.length < 2 ? 0 : samples[samples.length - 1] - samples[0];
|
|
4941
|
-
const result = { ok: samples.length > 0, steadyMBps: median };
|
|
4959
|
+
const result = { ok: samples.length > 0, steadyMBps: median, peakMBps: peak };
|
|
4942
4960
|
speedDone++;
|
|
4943
4961
|
report({
|
|
4944
4962
|
type: "progress",
|
|
@@ -4947,7 +4965,7 @@ async function runScan(options) {
|
|
|
4947
4965
|
total: stage2.length,
|
|
4948
4966
|
message: `\u6D4B\u901F ${speedDone}/${stage2.length} [${item.probe.colo || "UNK"}] ${result.steadyMBps.toFixed(1)} MB/s${jitter > 0 ? ` \xB1${jitter.toFixed(1)}` : ""}`
|
|
4949
4967
|
});
|
|
4950
|
-
return { ...item, speed: result.ok ? result.steadyMBps : 0 };
|
|
4968
|
+
return { ...item, speed: result.ok ? result.steadyMBps : 0, peakMBps: result.peakMBps, jitter };
|
|
4951
4969
|
});
|
|
4952
4970
|
}
|
|
4953
4971
|
const ranked = speedResults.filter((r) => options.skipSpeed ? true : Boolean(r.speed && r.speed > 0)).map((r) => ({
|
|
@@ -4955,8 +4973,12 @@ async function runScan(options) {
|
|
|
4955
4973
|
port: options.port,
|
|
4956
4974
|
colo: r.probe.colo || "UNK",
|
|
4957
4975
|
latency: r.latency,
|
|
4976
|
+
// tcpMs 是阶段一测得的 TCP 建连耗时(CLI 的 latency 字段本身就是它,
|
|
4977
|
+
// 这里显式补一份,便于与桌面版报告字段一一对应)。
|
|
4978
|
+
tcpMs: r.latency,
|
|
4958
4979
|
tlsMs: r.tls.tlsMs,
|
|
4959
4980
|
speed: r.speed ? Number(r.speed.toFixed(2)) : 0,
|
|
4981
|
+
peakMBps: r.peakMBps ? Number(r.peakMBps.toFixed(2)) : 0,
|
|
4960
4982
|
speedJitter: r.jitter ? Number(r.jitter.toFixed(2)) : 0
|
|
4961
4983
|
})).sort(
|
|
4962
4984
|
(a, b) => options.skipSpeed ? a.tlsMs - b.tlsMs || a.latency - b.latency : b.speed - a.speed || a.tlsMs - b.tlsMs || a.latency - b.latency
|
|
@@ -4992,8 +5014,22 @@ async function runScan(options) {
|
|
|
4992
5014
|
for (const entry of entries) {
|
|
4993
5015
|
report({ type: "result", entry });
|
|
4994
5016
|
}
|
|
5017
|
+
const observations = probeResults.map((r) => ({
|
|
5018
|
+
ip: r.ip,
|
|
5019
|
+
ok: r.probe.ok && r.probe.pongVerified !== false,
|
|
5020
|
+
latencyMs: r.latency
|
|
5021
|
+
}));
|
|
5022
|
+
const speedByIp = /* @__PURE__ */ new Map();
|
|
5023
|
+
for (const item of speedResults) {
|
|
5024
|
+
if (item.speed && item.speed > 0) speedByIp.set(item.ip, item.speed);
|
|
5025
|
+
}
|
|
5026
|
+
for (const observation of observations) {
|
|
5027
|
+
const speed = speedByIp.get(observation.ip);
|
|
5028
|
+
if (speed !== void 0) observation.speedMBps = Number(speed.toFixed(2));
|
|
5029
|
+
}
|
|
4995
5030
|
const summary = {
|
|
4996
5031
|
entries,
|
|
5032
|
+
observations,
|
|
4997
5033
|
stats: {
|
|
4998
5034
|
candidates: candidates.length,
|
|
4999
5035
|
tcpOk: tcpOk.length,
|
|
@@ -5083,8 +5119,8 @@ async function postResults(callbackUrl, token, entries, timeoutMs = 15e3) {
|
|
|
5083
5119
|
signal: AbortSignal.timeout(timeoutMs)
|
|
5084
5120
|
});
|
|
5085
5121
|
if (!response.ok) {
|
|
5086
|
-
const
|
|
5087
|
-
return { ok: false, status: response.status, error: `\u56DE\u4F20\u5931\u8D25 HTTP ${response.status} ${
|
|
5122
|
+
const text2 = await response.text().catch(() => "");
|
|
5123
|
+
return { ok: false, status: response.status, error: `\u56DE\u4F20\u5931\u8D25 HTTP ${response.status} ${text2}`.trim() };
|
|
5088
5124
|
}
|
|
5089
5125
|
return { ok: true, status: response.status };
|
|
5090
5126
|
} catch (err) {
|
|
@@ -5107,8 +5143,8 @@ async function fetchScannerToken(panelHost, password, timeoutMs = 25e3) {
|
|
|
5107
5143
|
return { ok: false, error: "\u9762\u677F\u5BC6\u7801\u4E0D\u6B63\u786E" };
|
|
5108
5144
|
}
|
|
5109
5145
|
if (!loginRes.ok) {
|
|
5110
|
-
const
|
|
5111
|
-
return { ok: false, error: `\u767B\u5F55\u5931\u8D25 HTTP ${loginRes.status} ${
|
|
5146
|
+
const text2 = await loginRes.text().catch(() => "");
|
|
5147
|
+
return { ok: false, error: `\u767B\u5F55\u5931\u8D25 HTTP ${loginRes.status} ${text2.slice(0, 120)}` };
|
|
5112
5148
|
}
|
|
5113
5149
|
const headersWithCookies = loginRes.headers;
|
|
5114
5150
|
const raw = headersWithCookies.getSetCookie?.() ?? [];
|
|
@@ -5132,22 +5168,22 @@ async function takeToken(base, cookie, timeoutMs) {
|
|
|
5132
5168
|
signal: AbortSignal.timeout(timeoutMs)
|
|
5133
5169
|
});
|
|
5134
5170
|
if (!res.ok) {
|
|
5135
|
-
const
|
|
5136
|
-
return { ok: false, error: `\u83B7\u53D6\u4EE4\u724C\u5931\u8D25 HTTP ${res.status} ${
|
|
5171
|
+
const text3 = await res.text().catch(() => "");
|
|
5172
|
+
return { ok: false, error: `\u83B7\u53D6\u4EE4\u724C\u5931\u8D25 HTTP ${res.status} ${text3.slice(0, 120)}` };
|
|
5137
5173
|
}
|
|
5138
|
-
const
|
|
5139
|
-
if (
|
|
5174
|
+
const text2 = await res.text();
|
|
5175
|
+
if (text2.trimStart().startsWith("<")) {
|
|
5140
5176
|
return {
|
|
5141
5177
|
ok: false,
|
|
5142
5178
|
error: "\u9762\u677F\u8FD4\u56DE\u4E86\u7F51\u9875\u800C\u4E0D\u662F\u63A5\u53E3\u6570\u636E\uFF0C\u8BF7\u786E\u8BA4 --panel \u586B\u7684\u662F\u63A7\u5236\u9762\u57DF\u540D"
|
|
5143
5179
|
};
|
|
5144
5180
|
}
|
|
5145
5181
|
try {
|
|
5146
|
-
const data = JSON.parse(
|
|
5182
|
+
const data = JSON.parse(text2);
|
|
5147
5183
|
if (!data.token) return { ok: false, error: "\u9762\u677F\u6CA1\u6709\u8FD4\u56DE\u4EE4\u724C" };
|
|
5148
5184
|
return { ok: true, token: data.token };
|
|
5149
5185
|
} catch {
|
|
5150
|
-
return { ok: false, error: "\u4EE4\u724C\u54CD\u5E94\u89E3\u6790\u5931\u8D25\uFF1A" +
|
|
5186
|
+
return { ok: false, error: "\u4EE4\u724C\u54CD\u5E94\u89E3\u6790\u5931\u8D25\uFF1A" + text2.slice(0, 120) };
|
|
5151
5187
|
}
|
|
5152
5188
|
}
|
|
5153
5189
|
var init_callback = __esm({
|
|
@@ -5184,7 +5220,7 @@ async function fetchCloudflareCidrs(timeoutMs = 8e3) {
|
|
|
5184
5220
|
fetch("https://www.cloudflare.com/ips-v4", { signal: controller.signal }),
|
|
5185
5221
|
fetch("https://www.cloudflare.com/ips-v6", { signal: controller.signal })
|
|
5186
5222
|
]);
|
|
5187
|
-
const parse = (
|
|
5223
|
+
const parse = (text2) => text2.split("\n").map((l) => l.trim()).filter((l) => l.includes("/"));
|
|
5188
5224
|
return {
|
|
5189
5225
|
ipv4: v4.ok ? parse(await v4.text()) : BUILTIN_IPV4_CIDRS,
|
|
5190
5226
|
ipv6: v6.ok ? parse(await v6.text()) : BUILTIN_IPV6_CIDRS
|
|
@@ -5378,17 +5414,17 @@ function expandCidrs(cidrs, options = {}) {
|
|
|
5378
5414
|
target.count -= 1;
|
|
5379
5415
|
familySum -= 1;
|
|
5380
5416
|
}
|
|
5381
|
-
for (const { cidr, count } of usablePlans) {
|
|
5382
|
-
if (
|
|
5383
|
-
if (
|
|
5417
|
+
for (const { cidr, count: count2 } of usablePlans) {
|
|
5418
|
+
if (count2 <= 0) continue;
|
|
5419
|
+
if (count2 >= Number(cidr.size)) {
|
|
5384
5420
|
for (let i = 0n; i < cidr.size; i++) {
|
|
5385
5421
|
const value = cidr.base + i;
|
|
5386
5422
|
out.push(family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
|
|
5387
5423
|
}
|
|
5388
5424
|
continue;
|
|
5389
5425
|
}
|
|
5390
|
-
const step = Math.floor(Number(cidr.size) /
|
|
5391
|
-
for (let i = 0; i <
|
|
5426
|
+
const step = Math.floor(Number(cidr.size) / count2);
|
|
5427
|
+
for (let i = 0; i < count2; i++) {
|
|
5392
5428
|
const jitter = Math.floor(random() * step);
|
|
5393
5429
|
let offsetValue = BigInt(i * step + jitter);
|
|
5394
5430
|
if (offsetValue >= cidr.size) offsetValue = cidr.size - 1n;
|
|
@@ -5407,9 +5443,9 @@ function expandCidrs(cidrs, options = {}) {
|
|
|
5407
5443
|
}
|
|
5408
5444
|
return out;
|
|
5409
5445
|
}
|
|
5410
|
-
function readIpFile(
|
|
5446
|
+
function readIpFile(text2) {
|
|
5411
5447
|
const out = [];
|
|
5412
|
-
for (const raw of
|
|
5448
|
+
for (const raw of text2.split(/\r?\n/)) {
|
|
5413
5449
|
let line = raw.trim();
|
|
5414
5450
|
if (!line || line.startsWith("#")) continue;
|
|
5415
5451
|
if (line.includes(",")) line = line.split(",")[0].trim();
|
|
@@ -5523,14 +5559,14 @@ function isPortListening(port, timeoutMs = 400) {
|
|
|
5523
5559
|
return new Promise((resolve3) => {
|
|
5524
5560
|
const socket = new net3.Socket();
|
|
5525
5561
|
let settled = false;
|
|
5526
|
-
const done = (
|
|
5562
|
+
const done = (open2) => {
|
|
5527
5563
|
if (settled) return;
|
|
5528
5564
|
settled = true;
|
|
5529
5565
|
try {
|
|
5530
5566
|
socket.destroy();
|
|
5531
5567
|
} catch {
|
|
5532
5568
|
}
|
|
5533
|
-
resolve3(
|
|
5569
|
+
resolve3(open2);
|
|
5534
5570
|
};
|
|
5535
5571
|
socket.setTimeout(timeoutMs, () => done(false));
|
|
5536
5572
|
socket.once("connect", () => done(true));
|
|
@@ -5665,6 +5701,252 @@ var init_net_env = __esm({
|
|
|
5665
5701
|
}
|
|
5666
5702
|
});
|
|
5667
5703
|
|
|
5704
|
+
// src/scan/network-profile.ts
|
|
5705
|
+
import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
|
|
5706
|
+
import { mkdir as mkdir2, open, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
5707
|
+
import { isIP } from "node:net";
|
|
5708
|
+
import { dirname as dirname2 } from "node:path";
|
|
5709
|
+
function classifyFailureDetailed(error, status2) {
|
|
5710
|
+
const value = String(error ?? "").trim();
|
|
5711
|
+
if (status2 && status2 >= 400) return { kind: "http", status: status2, retryable: status2 >= 500 || status2 === 408 || status2 === 429, message: `HTTP ${status2}` };
|
|
5712
|
+
if (/cancel|abort|取消/i.test(value)) return { kind: "cancelled", retryable: false, message: "\u8BF7\u6C42\u53D6\u6D88" };
|
|
5713
|
+
if (/timeout|timed out|超时|ETIMEDOUT/i.test(value)) return { kind: "timeout", retryable: true, message: "\u8FDE\u63A5\u8D85\u65F6" };
|
|
5714
|
+
if (/ECONNREFUSED|connection refused|连接被拒/i.test(value)) return { kind: "refused", retryable: false, message: "\u8FDE\u63A5\u88AB\u62D2" };
|
|
5715
|
+
if (/ENETUNREACH|EHOSTUNREACH|unreachable|网络不可达/i.test(value)) return { kind: "unreachable", retryable: false, message: "\u7F51\u7EDC\u4E0D\u53EF\u8FBE" };
|
|
5716
|
+
if (/ECONNRESET|socket hang up|连接重置/i.test(value)) return { kind: "reset", retryable: true, message: "\u8FDE\u63A5\u91CD\u7F6E" };
|
|
5717
|
+
if (/certificate|CERT_|SELF_SIGNED|证书/i.test(value)) return { kind: "tls", retryable: false, message: "TLS \u8BC1\u4E66\u5931\u8D25" };
|
|
5718
|
+
if (/ALPN/i.test(value)) return { kind: "alpn", retryable: false, message: "ALPN \u534F\u5546\u5931\u8D25" };
|
|
5719
|
+
if (/ENOTFOUND|EAI_AGAIN|getaddrinfo|解析失败/i.test(value)) return { kind: "dns", retryable: true, message: "\u57DF\u540D\u89E3\u6790\u5931\u8D25" };
|
|
5720
|
+
if (/PONG|pong|内容校验|响应异常/i.test(value)) return { kind: "content", retryable: false, message: "\u5185\u5BB9\u6821\u9A8C\u5931\u8D25" };
|
|
5721
|
+
return { kind: "unknown", retryable: true, message: value || "\u672A\u77E5\u539F\u56E0" };
|
|
5722
|
+
}
|
|
5723
|
+
function networkBucket(ip) {
|
|
5724
|
+
const value = ip.trim().replace(/^\[|\]$/g, "");
|
|
5725
|
+
const family = isIP(value);
|
|
5726
|
+
if (family === 4) return `${value.split(".").slice(0, 3).join(".")}.0/24`;
|
|
5727
|
+
if (family === 6) {
|
|
5728
|
+
const parsed = parseCidr(`${value}/48`);
|
|
5729
|
+
if (parsed) return `${[112n, 96n, 80n].map((shift) => (parsed.base >> shift & 65535n).toString(16)).join(":")}::/48`;
|
|
5730
|
+
}
|
|
5731
|
+
return "";
|
|
5732
|
+
}
|
|
5733
|
+
function canonicalPrefix(value) {
|
|
5734
|
+
if (typeof value !== "string") return "";
|
|
5735
|
+
const parts = value.split("/");
|
|
5736
|
+
if (parts.length !== 2 || !["24", "48"].includes(parts[1])) return "";
|
|
5737
|
+
const prefix = networkBucket(parts[0]);
|
|
5738
|
+
return prefix.endsWith(`/${parts[1]}`) ? prefix : "";
|
|
5739
|
+
}
|
|
5740
|
+
function normalizeNetworkProfile(input, now = Date.now()) {
|
|
5741
|
+
const isp = text(input.isp), region = text(input.region), access = text(input.access).toLowerCase(), family = text(input.family).toLowerCase() || "ipv4";
|
|
5742
|
+
const id = createHash3("sha256").update(JSON.stringify([isp.toLowerCase(), region.toLowerCase(), access, family])).digest("hex").slice(0, 32);
|
|
5743
|
+
return { id, isp, region, access, family, source: text(input.source), confidence: Math.min(1, count(input.confidence)), updatedAt: time(input.updatedAt, time(now)) };
|
|
5744
|
+
}
|
|
5745
|
+
function createNetworkProfile(network, now = Date.now()) {
|
|
5746
|
+
const profile = normalizeNetworkProfile(typeof network === "string" ? { isp: network.trim() || "default", source: "manual" } : network, now);
|
|
5747
|
+
return { version: 1, profiles: { [profile.id]: profile }, observations: {} };
|
|
5748
|
+
}
|
|
5749
|
+
function selectedProfile(store, requested) {
|
|
5750
|
+
if (requested) return Object.hasOwn(store.profiles, requested) ? requested : void 0;
|
|
5751
|
+
const ids = Object.keys(store.profiles);
|
|
5752
|
+
return ids.length === 1 ? ids[0] : void 0;
|
|
5753
|
+
}
|
|
5754
|
+
function capStore(store) {
|
|
5755
|
+
const profiles = Object.values(store.profiles).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)).slice(0, PROFILE_CAPACITY);
|
|
5756
|
+
const ids = new Set(profiles.map((profile) => profile.id));
|
|
5757
|
+
const observations = Object.values(store.observations).filter((item) => ids.has(item.profileId)).sort((a, b) => b.updatedAt - a.updatedAt || observationKey(a.profileId, a.prefix, a.stage).localeCompare(observationKey(b.profileId, b.prefix, b.stage))).slice(0, OBSERVATION_CAPACITY);
|
|
5758
|
+
return { version: 1, profiles: Object.fromEntries(profiles.map((profile) => [profile.id, profile])), observations: Object.fromEntries(observations.map((item) => [observationKey(item.profileId, item.prefix, item.stage), item])) };
|
|
5759
|
+
}
|
|
5760
|
+
function updateNetworkProfile(store, observations, now = Date.now(), duration = DEFAULT_HALF_LIFE) {
|
|
5761
|
+
const next = { version: 1, profiles: { ...store.profiles }, observations: { ...store.observations } };
|
|
5762
|
+
for (const item of observations) {
|
|
5763
|
+
const profileId = selectedProfile(next, item.profileId), prefix = networkBucket(item.ip), stage = item.stage ?? "tcp";
|
|
5764
|
+
if (!profileId || !prefix || !STAGES.includes(stage) || item.failure?.kind === "cancelled") continue;
|
|
5765
|
+
const key = observationKey(profileId, prefix, stage), old = next.observations[key];
|
|
5766
|
+
const observedAt = time(item.at, time(now)), at = Math.max(time(now), observedAt, old?.updatedAt ?? 0);
|
|
5767
|
+
const decay = old ? decayAt(old.updatedAt, at, duration) : 0;
|
|
5768
|
+
const evidence = decayAt(observedAt, at, duration);
|
|
5769
|
+
const oldSuccesses = (old?.successes ?? 0) * decay;
|
|
5770
|
+
const failures = {};
|
|
5771
|
+
for (const kind of FAILURE_CLASSES) if (old?.failures[kind]) failures[kind] = old.failures[kind] * decay;
|
|
5772
|
+
const updated = { profileId, prefix, stage, attempts: count((old?.attempts ?? 0) * decay + evidence), successes: count(oldSuccesses + (item.ok ? evidence : 0)), failures, updatedAt: at };
|
|
5773
|
+
for (const metric of ["latencyMs", "speedMBps"]) {
|
|
5774
|
+
const value = item[metric], previous = old?.[metric];
|
|
5775
|
+
if (item.ok && finite(value) && value >= 0) updated[metric] = previous !== void 0 && oldSuccesses > 0 ? (previous * oldSuccesses + value * evidence) / (oldSuccesses + evidence) : value;
|
|
5776
|
+
else if (previous !== void 0) updated[metric] = previous;
|
|
5777
|
+
}
|
|
5778
|
+
if (!item.ok) {
|
|
5779
|
+
const kind = item.failure?.kind ?? classifyFailureDetailed(item.error).kind;
|
|
5780
|
+
updated.failures[kind] = count((updated.failures[kind] ?? 0) + evidence);
|
|
5781
|
+
}
|
|
5782
|
+
next.observations[key] = updated;
|
|
5783
|
+
next.profiles[profileId] = { ...next.profiles[profileId], updatedAt: Math.max(next.profiles[profileId].updatedAt, at) };
|
|
5784
|
+
}
|
|
5785
|
+
return capStore(next);
|
|
5786
|
+
}
|
|
5787
|
+
function sampleExploreExploit(candidates, store, options) {
|
|
5788
|
+
const limit = finite(options.limit) ? Math.max(0, Math.floor(options.limit)) : 0;
|
|
5789
|
+
if (!limit) return [];
|
|
5790
|
+
const draw = () => Math.min(1 - Number.EPSILON, Math.max(0, (options.random ?? Math.random)()));
|
|
5791
|
+
const pool2 = [...new Map(candidates.filter((item) => item.staticWeight !== 0 || options.includeZeroWeight === true).map((item) => [item.ip, item])).values()];
|
|
5792
|
+
const rate = finite(options.explorationRate) ? Math.min(1, Math.max(0, options.explorationRate)) : 0.2;
|
|
5793
|
+
const exploreCount = Math.min(pool2.length, limit, Math.ceil(limit * rate));
|
|
5794
|
+
const byBucket = /* @__PURE__ */ new Map();
|
|
5795
|
+
for (const candidate of pool2) {
|
|
5796
|
+
const key = networkBucket(candidate.ip) || candidate.ip;
|
|
5797
|
+
byBucket.set(key, [...byBucket.get(key) ?? [], candidate]);
|
|
5798
|
+
}
|
|
5799
|
+
const selected = [], used = /* @__PURE__ */ new Set();
|
|
5800
|
+
const take = (item) => {
|
|
5801
|
+
if (!used.has(item.ip)) {
|
|
5802
|
+
selected.push(item);
|
|
5803
|
+
used.add(item.ip);
|
|
5804
|
+
}
|
|
5805
|
+
};
|
|
5806
|
+
if (options.includeZeroWeight && exploreCount > 0) {
|
|
5807
|
+
const zero = pool2.filter((item) => item.staticWeight === 0);
|
|
5808
|
+
if (zero.length) take(zero[Math.floor(draw() * zero.length)]);
|
|
5809
|
+
}
|
|
5810
|
+
const buckets = [...byBucket.keys()];
|
|
5811
|
+
for (let index = buckets.length - 1; index > 0; index--) {
|
|
5812
|
+
const other = Math.floor(draw() * (index + 1));
|
|
5813
|
+
[buckets[index], buckets[other]] = [buckets[other], buckets[index]];
|
|
5814
|
+
}
|
|
5815
|
+
while (selected.length < exploreCount && buckets.length) {
|
|
5816
|
+
const key = buckets.shift(), list = byBucket.get(key).filter((item) => !used.has(item.ip));
|
|
5817
|
+
if (!list.length) continue;
|
|
5818
|
+
take(list[Math.floor(draw() * list.length)]);
|
|
5819
|
+
if (list.length > 1) buckets.push(key);
|
|
5820
|
+
}
|
|
5821
|
+
const profileId = selectedProfile(store, options.profileId), now = time(options.now, Date.now());
|
|
5822
|
+
const scored = pool2.filter((item) => !used.has(item.ip) && item.staticWeight !== 0).map((candidate) => {
|
|
5823
|
+
const prefix = networkBucket(candidate.ip);
|
|
5824
|
+
const stages = profileId ? STAGES.map((stage) => store.observations[observationKey(profileId, prefix, stage)]).filter((item) => !!item && item.attempts > 0) : [];
|
|
5825
|
+
const observation = stages.at(-1);
|
|
5826
|
+
const prior = finite(candidate.staticWeight) ? Math.min(1, Math.max(0.02, candidate.staticWeight)) : 0.2;
|
|
5827
|
+
const decay = observation ? decayAt(observation.updatedAt, now, options.halfLifeMs ?? DEFAULT_HALF_LIFE) : 0;
|
|
5828
|
+
const score = (prior * 2 + (observation?.successes ?? 0) * decay) / (2 + (observation?.attempts ?? 0) * decay);
|
|
5829
|
+
return { candidate, score: score + (finite(candidate.score) ? candidate.score * 1e-3 : 0) };
|
|
5830
|
+
}).sort((a, b) => b.score - a.score);
|
|
5831
|
+
return [...selected, ...scored.map((item) => item.candidate)].slice(0, limit);
|
|
5832
|
+
}
|
|
5833
|
+
function sanitizeObservation(raw, profiles) {
|
|
5834
|
+
if (!record(raw)) return void 0;
|
|
5835
|
+
const profileId = text(raw.profileId), prefix = canonicalPrefix(raw.prefix);
|
|
5836
|
+
if (!Object.hasOwn(profiles, profileId) || !prefix || !STAGES.includes(raw.stage)) return void 0;
|
|
5837
|
+
const attempts = count(raw.attempts), successes = Math.min(attempts, count(raw.successes)), failures = {};
|
|
5838
|
+
let remaining = attempts - successes;
|
|
5839
|
+
if (record(raw.failures)) for (const kind of FAILURE_CLASSES) {
|
|
5840
|
+
const value = Math.min(remaining, count(raw.failures[kind]));
|
|
5841
|
+
if (value > 0) {
|
|
5842
|
+
failures[kind] = value;
|
|
5843
|
+
remaining -= value;
|
|
5844
|
+
}
|
|
5845
|
+
}
|
|
5846
|
+
const item = { profileId, prefix, stage: raw.stage, attempts, successes, failures, updatedAt: time(raw.updatedAt) };
|
|
5847
|
+
for (const metric of ["latencyMs", "speedMBps"]) if (finite(raw[metric]) && raw[metric] >= 0) item[metric] = raw[metric];
|
|
5848
|
+
return item;
|
|
5849
|
+
}
|
|
5850
|
+
function sanitizeStore(raw) {
|
|
5851
|
+
if (!record(raw.profiles) || !record(raw.observations)) throw new Error("\u7F51\u7EDC\u6863\u6848\u7ED3\u6784\u65E0\u6548");
|
|
5852
|
+
const profiles = /* @__PURE__ */ Object.create(null);
|
|
5853
|
+
for (const [key, value] of Object.entries(raw.profiles)) {
|
|
5854
|
+
if (!record(value) || !key || key.length > 128 || text(value.id) !== key) continue;
|
|
5855
|
+
const profile = normalizeNetworkProfile(value, 0);
|
|
5856
|
+
profiles[key] = { ...profile, id: key };
|
|
5857
|
+
}
|
|
5858
|
+
const observations = /* @__PURE__ */ Object.create(null);
|
|
5859
|
+
for (const value of Object.values(raw.observations)) {
|
|
5860
|
+
const item = sanitizeObservation(value, profiles);
|
|
5861
|
+
if (!item) continue;
|
|
5862
|
+
const key = observationKey(item.profileId, item.prefix, item.stage), previous = observations[key];
|
|
5863
|
+
if (!previous || item.updatedAt > previous.updatedAt) observations[key] = item;
|
|
5864
|
+
}
|
|
5865
|
+
return capStore({ version: 1, profiles, observations });
|
|
5866
|
+
}
|
|
5867
|
+
function migrateLegacyCli(raw) {
|
|
5868
|
+
if (!record(raw.buckets) || typeof raw.networkKey !== "string") throw new Error("\u65E7\u7F51\u7EDC\u6863\u6848\u7ED3\u6784\u65E0\u6548");
|
|
5869
|
+
const store = createNetworkProfile(raw.networkKey, time(raw.updatedAt)), profileId = Object.keys(store.profiles)[0];
|
|
5870
|
+
for (const [key, value] of Object.entries(raw.buckets)) {
|
|
5871
|
+
if (!record(value)) continue;
|
|
5872
|
+
const prefix = key.startsWith("v4:") ? canonicalPrefix(key.slice(3).replace("/24", ".0/24")) : key.startsWith("v6:") ? canonicalPrefix(key.slice(3).replace("/48", "::/48")) : canonicalPrefix(key);
|
|
5873
|
+
const attempts = count(value.attempts), successes = Math.min(attempts, count(value.successes));
|
|
5874
|
+
const item = sanitizeObservation({ ...value, profileId, prefix, stage: "tcp", attempts, successes, failures: { unknown: attempts - successes } }, store.profiles);
|
|
5875
|
+
if (item) store.observations[observationKey(profileId, prefix, "tcp")] = item;
|
|
5876
|
+
}
|
|
5877
|
+
return capStore(store);
|
|
5878
|
+
}
|
|
5879
|
+
function migrateAggregateStore(raw) {
|
|
5880
|
+
if (!record(raw.profiles) || !record(raw.observations)) throw new Error("\u65E7\u7F51\u7EDC\u6863\u6848\u7ED3\u6784\u65E0\u6548");
|
|
5881
|
+
const expanded = {};
|
|
5882
|
+
for (const value of Object.values(raw.observations)) {
|
|
5883
|
+
if (!record(value)) continue;
|
|
5884
|
+
for (const stage of ["tcp", "tls", "ws"]) {
|
|
5885
|
+
const attempts = count(value[`${stage}Attempts`]);
|
|
5886
|
+
if (!attempts) continue;
|
|
5887
|
+
const successes = Math.min(attempts, count(value[`${stage}Success`]));
|
|
5888
|
+
const item = { profileId: value.profileId, prefix: value.prefix, stage, attempts, successes, failures: { unknown: attempts - successes }, updatedAt: typeof value.lastTestAt === "string" ? time(Date.parse(value.lastTestAt)) : 0 };
|
|
5889
|
+
expanded[`${String(value.profileId)}|${String(value.prefix)}|${stage}`] = item;
|
|
5890
|
+
}
|
|
5891
|
+
}
|
|
5892
|
+
return sanitizeStore({ profiles: raw.profiles, observations: expanded });
|
|
5893
|
+
}
|
|
5894
|
+
async function loadNetworkProfile(file, networkKey) {
|
|
5895
|
+
let handle;
|
|
5896
|
+
try {
|
|
5897
|
+
handle = await open(file, "r");
|
|
5898
|
+
} catch (error) {
|
|
5899
|
+
if (record(error) && error.code === "ENOENT") return createNetworkProfile(networkKey);
|
|
5900
|
+
throw error;
|
|
5901
|
+
}
|
|
5902
|
+
try {
|
|
5903
|
+
if ((await handle.stat()).size > MAX_FILE_BYTES) throw new Error("\u7F51\u7EDC\u6863\u6848\u8D85\u51FA\u5927\u5C0F\u9650\u5236");
|
|
5904
|
+
const raw = JSON.parse(await handle.readFile("utf8"));
|
|
5905
|
+
if (!record(raw)) throw new Error("\u7F51\u7EDC\u6863\u6848\u683C\u5F0F\u65E0\u6548");
|
|
5906
|
+
if (raw.version === 1 && record(raw.buckets)) return migrateLegacyCli(raw);
|
|
5907
|
+
if (raw.version === void 0 && record(raw.profiles) && record(raw.observations)) return migrateAggregateStore(raw);
|
|
5908
|
+
if (raw.version !== 1) throw new Error("\u7F51\u7EDC\u6863\u6848\u7248\u672C\u4E0D\u517C\u5BB9");
|
|
5909
|
+
return sanitizeStore(raw);
|
|
5910
|
+
} finally {
|
|
5911
|
+
await handle.close();
|
|
5912
|
+
}
|
|
5913
|
+
}
|
|
5914
|
+
async function saveNetworkProfile(file, store) {
|
|
5915
|
+
const sanitized = sanitizeStore(store);
|
|
5916
|
+
await mkdir2(dirname2(file), { recursive: true });
|
|
5917
|
+
const temporary = `${file}.tmp-${randomUUID2()}`;
|
|
5918
|
+
try {
|
|
5919
|
+
await writeFile2(temporary, `${JSON.stringify(sanitized, null, 2)}
|
|
5920
|
+
`, { encoding: "utf8", mode: 384, flag: "wx" });
|
|
5921
|
+
await rename2(temporary, file);
|
|
5922
|
+
} finally {
|
|
5923
|
+
await unlink2(temporary).catch(() => {
|
|
5924
|
+
});
|
|
5925
|
+
}
|
|
5926
|
+
}
|
|
5927
|
+
var PROFILE_CAPACITY, OBSERVATION_CAPACITY, MAX_COUNTER, MAX_FILE_BYTES, DEFAULT_HALF_LIFE, STAGES, FAILURE_CLASSES, record, finite, count, time, halfLife, decayAt, text, observationKey;
|
|
5928
|
+
var init_network_profile = __esm({
|
|
5929
|
+
"src/scan/network-profile.ts"() {
|
|
5930
|
+
"use strict";
|
|
5931
|
+
init_ip_ranges();
|
|
5932
|
+
PROFILE_CAPACITY = 32;
|
|
5933
|
+
OBSERVATION_CAPACITY = 4096;
|
|
5934
|
+
MAX_COUNTER = 1e9;
|
|
5935
|
+
MAX_FILE_BYTES = 4 * 1024 * 1024;
|
|
5936
|
+
DEFAULT_HALF_LIFE = 7 * 24 * 60 * 60 * 1e3;
|
|
5937
|
+
STAGES = ["tcp", "tls", "ws", "speed"];
|
|
5938
|
+
FAILURE_CLASSES = ["timeout", "refused", "unreachable", "reset", "tls", "alpn", "dns", "http", "content", "cancelled", "unknown"];
|
|
5939
|
+
record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5940
|
+
finite = (value) => typeof value === "number" && Number.isFinite(value);
|
|
5941
|
+
count = (value) => finite(value) ? Math.min(MAX_COUNTER, Math.max(0, value)) : 0;
|
|
5942
|
+
time = (value, fallback = 0) => finite(value) && value >= 0 ? Math.min(Number.MAX_SAFE_INTEGER, value) : fallback;
|
|
5943
|
+
halfLife = (value) => finite(value) && value > 0 ? value : DEFAULT_HALF_LIFE;
|
|
5944
|
+
decayAt = (from, to, duration) => 2 ** (-Math.max(0, to - from) / halfLife(duration));
|
|
5945
|
+
text = (value) => typeof value === "string" ? value.trim().slice(0, 128) : "";
|
|
5946
|
+
observationKey = (profileId, prefix, stage) => `${profileId}|${prefix}|${stage}`;
|
|
5947
|
+
}
|
|
5948
|
+
});
|
|
5949
|
+
|
|
5668
5950
|
// src/scan/candidates.ts
|
|
5669
5951
|
function normalizeCidrInput(cidr) {
|
|
5670
5952
|
if (cidr === void 0) return [];
|
|
@@ -5706,11 +5988,133 @@ async function resolveCandidates(opts = {}) {
|
|
|
5706
5988
|
const family = opts.family ?? "both";
|
|
5707
5989
|
const neutral = opts.neutral === true;
|
|
5708
5990
|
const customCidrs = normalizeCidrInput(opts.cidr);
|
|
5709
|
-
|
|
5710
|
-
|
|
5991
|
+
const cidrs = customCidrs.length > 0 ? filterByFamily(customCidrs, family) : await loadCloudflareCidrs(family);
|
|
5992
|
+
if (!opts.profile) return expandCidrs(cidrs, { sample, seed, neutral });
|
|
5993
|
+
const random = seededRandom(seed);
|
|
5994
|
+
const adaptive = { limit: sample > 0 ? sample : DEFAULT_CANDIDATE_SAMPLE, random, ...opts.adaptiveSampling };
|
|
5995
|
+
const candidates = adaptivePool(cidrs, adaptive.limit, adaptive.includeZeroWeight === true, neutral, random, opts.profile, {
|
|
5996
|
+
explorationRate: adaptive.explorationRate,
|
|
5997
|
+
now: adaptive.now,
|
|
5998
|
+
halfLifeMs: adaptive.halfLifeMs,
|
|
5999
|
+
profileId: adaptive.profileId
|
|
6000
|
+
});
|
|
6001
|
+
return sampleExploreExploit(candidates, opts.profile, adaptive).map((item) => item.ip);
|
|
6002
|
+
}
|
|
6003
|
+
function seededRandom(seed) {
|
|
6004
|
+
let state = seed >>> 0;
|
|
6005
|
+
return () => {
|
|
6006
|
+
state = state + 1831565813 | 0;
|
|
6007
|
+
let value = Math.imul(state ^ state >>> 15, 1 | state);
|
|
6008
|
+
value = value + Math.imul(value ^ value >>> 7, 61 | value) ^ value;
|
|
6009
|
+
return ((value ^ value >>> 14) >>> 0) / 4294967296;
|
|
6010
|
+
};
|
|
6011
|
+
}
|
|
6012
|
+
function segmentObservation(segment, store, profileId, now, halfLifeMs) {
|
|
6013
|
+
if (!store || segment.family !== 4 || !profileId) return void 0;
|
|
6014
|
+
const best = /* @__PURE__ */ new Map();
|
|
6015
|
+
for (const observation of Object.values(store.observations)) {
|
|
6016
|
+
if (observation.profileId !== profileId) continue;
|
|
6017
|
+
const parsed = parseCidr(observation.prefix);
|
|
6018
|
+
if (!parsed || parsed.family !== 4) continue;
|
|
6019
|
+
if (parsed.base < segment.start || parsed.base + parsed.size > segment.end) continue;
|
|
6020
|
+
const current = best.get(observation.prefix);
|
|
6021
|
+
const rank = (stage) => stage === "ws" ? 3 : stage === "tls" ? 2 : 1;
|
|
6022
|
+
if (!current || observation.attempts > current.attempts || observation.attempts === current.attempts && rank(observation.stage) > rank(current.stage)) {
|
|
6023
|
+
best.set(observation.prefix, { stage: observation.stage, attempts: observation.attempts });
|
|
6024
|
+
}
|
|
6025
|
+
}
|
|
6026
|
+
if (best.size === 0) return void 0;
|
|
6027
|
+
let attempts = 0;
|
|
6028
|
+
let successes = 0;
|
|
6029
|
+
let updated = 0;
|
|
6030
|
+
for (const observation of Object.values(store.observations)) {
|
|
6031
|
+
if (observation.profileId !== profileId) continue;
|
|
6032
|
+
const picked = best.get(observation.prefix);
|
|
6033
|
+
if (!picked || picked.stage !== observation.stage) continue;
|
|
6034
|
+
const parsed = parseCidr(observation.prefix);
|
|
6035
|
+
if (!parsed || parsed.family !== 4) continue;
|
|
6036
|
+
if (parsed.base < segment.start || parsed.base + parsed.size > segment.end) continue;
|
|
6037
|
+
attempts += observation.attempts;
|
|
6038
|
+
successes += observation.successes;
|
|
6039
|
+
if (observation.updatedAt > updated) updated = observation.updatedAt;
|
|
6040
|
+
}
|
|
6041
|
+
if (attempts <= 0) return void 0;
|
|
6042
|
+
const age = Math.max(0, now - updated);
|
|
6043
|
+
const decay = 2 ** (-age / Math.max(1, halfLifeMs));
|
|
6044
|
+
return { attempts, successes, decay };
|
|
6045
|
+
}
|
|
6046
|
+
function effectiveSegmentWeight(staticWeight, observation) {
|
|
6047
|
+
if (staticWeight <= 0) return 0;
|
|
6048
|
+
if (!observation) return staticWeight;
|
|
6049
|
+
const numerator = staticWeight * LEARN_PRIOR_TOTAL + observation.successes * observation.decay;
|
|
6050
|
+
const denominator = LEARN_PRIOR_TOTAL + observation.attempts * observation.decay;
|
|
6051
|
+
if (denominator <= 0) return staticWeight;
|
|
6052
|
+
return Math.max(0.02, Math.min(1, numerator / denominator));
|
|
6053
|
+
}
|
|
6054
|
+
function adaptivePool(cidrs, limit, includeZero, neutral, random, store, options) {
|
|
6055
|
+
const ranges = cidrs.map(parseCidr).filter((item) => item !== null).map((item) => ({ family: item.family, start: item.base, end: item.base + item.size })).sort((a, b) => a.family - b.family || (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));
|
|
6056
|
+
const merged = [];
|
|
6057
|
+
for (const range of ranges) {
|
|
6058
|
+
const previous = merged.at(-1);
|
|
6059
|
+
if (previous && previous.family === range.family && range.start <= previous.end) previous.end = previous.end > range.end ? previous.end : range.end;
|
|
6060
|
+
else merged.push({ ...range });
|
|
6061
|
+
}
|
|
6062
|
+
const format = (value, family) => family === 4 ? [24n, 16n, 8n, 0n].map((shift) => (value >> shift & 255n).toString()).join(".") : Array.from({ length: 8 }, (_, index) => (value >> BigInt(112 - index * 16) & 65535n).toString(16)).join(":");
|
|
6063
|
+
const boundaries = Object.keys(IPV4_CIDR_WEIGHTS).map(parseCidr).filter((item) => item !== null).flatMap((item) => [item.base, item.base + item.size]);
|
|
6064
|
+
const now = options?.now ?? Date.now();
|
|
6065
|
+
const halfLife2 = options?.halfLifeMs ?? 7 * 24 * 60 * 60 * 1e3;
|
|
6066
|
+
const segments = [];
|
|
6067
|
+
for (const range of merged) {
|
|
6068
|
+
const cuts = [.../* @__PURE__ */ new Set([range.start, ...range.family === 4 ? boundaries.filter((point) => point > range.start && point < range.end) : [], range.end])].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
6069
|
+
for (let index = 0; index < cuts.length - 1; index++) {
|
|
6070
|
+
const start = cuts[index], end = cuts[index + 1];
|
|
6071
|
+
const staticWeight = range.family === 4 ? cidrWeight(`${format(start, 4)}/32`) : 1;
|
|
6072
|
+
if (staticWeight === 0 && !includeZero) continue;
|
|
6073
|
+
const observation = segmentObservation({ family: range.family, start, end }, store, options?.profileId ?? "", now, halfLife2);
|
|
6074
|
+
const weight = neutral && staticWeight > 0 ? 1 : effectiveSegmentWeight(staticWeight, observation);
|
|
6075
|
+
segments.push({ family: range.family, start, end, staticWeight, weight, used: /* @__PURE__ */ new Set() });
|
|
6076
|
+
}
|
|
6077
|
+
}
|
|
6078
|
+
if (segments.length === 0) return [];
|
|
6079
|
+
const target = Math.max(0, Math.min(DEFAULT_CANDIDATE_SAMPLE * 4, Math.ceil(limit) * 4));
|
|
6080
|
+
const explorationRate = Math.min(1, Math.max(0, options?.explorationRate ?? 0.2));
|
|
6081
|
+
const exploreBudget = Math.min(target, Math.round(target * explorationRate));
|
|
6082
|
+
const exploitBudget = target - exploreBudget;
|
|
6083
|
+
const out = [];
|
|
6084
|
+
const drawFrom = (segment, count2) => {
|
|
6085
|
+
const size = segment.end - segment.start;
|
|
6086
|
+
if (size <= 0n) return;
|
|
6087
|
+
let taken = 0;
|
|
6088
|
+
for (let attempt = 0; attempt < count2 * 8 && taken < count2; attempt++) {
|
|
6089
|
+
if (BigInt(segment.used.size) >= size) break;
|
|
6090
|
+
let value = 0n;
|
|
6091
|
+
for (let word = 0; word < (segment.family === 4 ? 1 : 4); word++) value = value << 32n | BigInt(Math.floor(random() * 4294967296));
|
|
6092
|
+
let offset = value % size;
|
|
6093
|
+
for (let probe = 0n; probe < size && segment.used.has(offset); probe++) {
|
|
6094
|
+
offset = (offset + 1n) % size;
|
|
6095
|
+
}
|
|
6096
|
+
if (segment.used.has(offset)) break;
|
|
6097
|
+
segment.used.add(offset);
|
|
6098
|
+
out.push({ ip: format(segment.start + offset, segment.family), staticWeight: segment.staticWeight });
|
|
6099
|
+
taken++;
|
|
6100
|
+
}
|
|
6101
|
+
};
|
|
6102
|
+
const totalSize = segments.reduce((sum, segment) => sum + (segment.end - segment.start), 0n);
|
|
6103
|
+
if (exploreBudget > 0 && totalSize > 0n) {
|
|
6104
|
+
for (const segment of segments) {
|
|
6105
|
+
const share = Number((segment.end - segment.start) * BigInt(exploreBudget) / totalSize);
|
|
6106
|
+
if (share > 0) drawFrom(segment, share);
|
|
6107
|
+
}
|
|
6108
|
+
}
|
|
6109
|
+
const totalWeight = segments.reduce((sum, segment) => sum + Number(segment.end - segment.start) * segment.weight, 0);
|
|
6110
|
+
if (exploitBudget > 0 && totalWeight > 0) {
|
|
6111
|
+
for (const segment of segments) {
|
|
6112
|
+
if (segment.weight <= 0) continue;
|
|
6113
|
+
const share = Math.floor(Number(segment.end - segment.start) * segment.weight * exploitBudget / totalWeight);
|
|
6114
|
+
if (share > 0) drawFrom(segment, share);
|
|
6115
|
+
}
|
|
5711
6116
|
}
|
|
5712
|
-
|
|
5713
|
-
return expandCidrs(cidrs, { sample, seed, neutral });
|
|
6117
|
+
return out;
|
|
5714
6118
|
}
|
|
5715
6119
|
function randomSeed() {
|
|
5716
6120
|
return (Date.now() ^ Math.floor(Math.random() * 4294967296)) >>> 0;
|
|
@@ -5733,14 +6137,18 @@ function normalizeCandidateList(input) {
|
|
|
5733
6137
|
}
|
|
5734
6138
|
return out;
|
|
5735
6139
|
}
|
|
5736
|
-
var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE;
|
|
6140
|
+
var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE, LEARN_PRIOR_ALPHA, LEARN_PRIOR_BETA, LEARN_PRIOR_TOTAL;
|
|
5737
6141
|
var init_candidates = __esm({
|
|
5738
6142
|
"src/scan/candidates.ts"() {
|
|
5739
6143
|
"use strict";
|
|
5740
6144
|
init_ip_ranges();
|
|
5741
6145
|
init_net_env();
|
|
6146
|
+
init_network_profile();
|
|
5742
6147
|
DEFAULT_CANDIDATE_SAMPLE = 2e4;
|
|
5743
6148
|
DEFAULT_BRIDGE_SAMPLE = 6556;
|
|
6149
|
+
LEARN_PRIOR_ALPHA = 5.6;
|
|
6150
|
+
LEARN_PRIOR_BETA = 2.4;
|
|
6151
|
+
LEARN_PRIOR_TOTAL = LEARN_PRIOR_ALPHA + LEARN_PRIOR_BETA;
|
|
5744
6152
|
}
|
|
5745
6153
|
});
|
|
5746
6154
|
|
|
@@ -5844,9 +6252,9 @@ async function readBody(req) {
|
|
|
5844
6252
|
for await (const chunk of req) chunks.push(chunk);
|
|
5845
6253
|
return Buffer.concat(chunks).toString("utf8");
|
|
5846
6254
|
}
|
|
5847
|
-
function parseStartScanRequest(
|
|
6255
|
+
function parseStartScanRequest(text2) {
|
|
5848
6256
|
try {
|
|
5849
|
-
const raw = JSON.parse(
|
|
6257
|
+
const raw = JSON.parse(text2 || "{}");
|
|
5850
6258
|
if (typeof raw !== "object" || raw === null) return null;
|
|
5851
6259
|
return raw;
|
|
5852
6260
|
} catch {
|
|
@@ -6194,6 +6602,18 @@ scan \u9009\u9879:
|
|
|
6194
6602
|
--seed <n> \u91C7\u6837\u968F\u673A\u79CD\u5B50\u3002\u9ED8\u8BA4\u6BCF\u6B21\u968F\u673A \u2014\u2014 \u4FDD\u8BC1\u6BCF\u6B21\u63A2\u7D22\u4E0D\u540C\u7684 IP \u5B50\u96C6
|
|
6195
6603
|
\uFF08\u5199\u6B7B\u79CD\u5B50\u4F1A\u8BA9\u6BCF\u6B21\u8DD1\u90FD\u6D4B\u540C\u4E00\u6279 IP\uFF0C\u62BD\u5230\u52A3\u8D28\u6BB5\u5C31\u6C38\u8FDC\u6D4B\u4E0D\u51FA\u597D IP\uFF09
|
|
6196
6604
|
\u663E\u5F0F\u6307\u5B9A\u5219\u56FA\u5B9A\u3001\u7ED3\u679C\u53EF\u590D\u73B0\uFF08\u6392\u67E5 / \u5BF9\u6BD4\u65F6\u7528\uFF09
|
|
6605
|
+
|
|
6606
|
+
\u81EA\u9002\u5E94\u91C7\u6837\uFF08\u5B9E\u9A8C\u6027\uFF0C\u9ED8\u8BA4\u5173\u95ED\uFF09:
|
|
6607
|
+
--adaptive \u5F00\u542F\u300C\u6309\u7F51\u7EDC\u6863\u6848\u81EA\u9002\u5E94\u7F51\u6BB5\u6743\u91CD\u300D
|
|
6608
|
+
\u7F51\u6BB5\u53EF\u7528\u6027\u56E0\u7F51\u7EDC\u800C\u5F02\uFF1A\u6309\u672C\u673A\u7F51\u7EDC\u6863\u6848\u7684\u5386\u53F2\u6210\u8D25\u8C03\u6574\u91C7\u6837\u6743\u91CD\uFF0C
|
|
6609
|
+
\u4E0D\u540C\u6863\u6848\u7684\u5386\u53F2\u4E92\u4E0D\u6DF7\u7528\uFF08\u6863\u6848\u5B58\u5728 ~/.cfpilot/network-profiles.json\uFF09
|
|
6610
|
+
--isp <code> \u8FD0\u8425\u5546\uFF1Act \u7535\u4FE1 / cu \u8054\u901A / cm \u79FB\u52A8 / other\uFF0C\u9ED8\u8BA4 other
|
|
6611
|
+
--region <name> \u5730\u533A\uFF08\u7C97\u7C92\u5EA6\u5373\u53EF\uFF0C\u5982\u300C\u798F\u5EFA\u300D\uFF09\uFF0C\u53EF\u7559\u7A7A
|
|
6612
|
+
--access <type> \u63A5\u5165\u7C7B\u578B\uFF1Afixed \u56FA\u5B9A\u5BBD\u5E26 / mobile \u79FB\u52A8\u7F51\u7EDC\uFF0C\u9ED8\u8BA4 fixed
|
|
6613
|
+
--explore-rate <pct> \u63A2\u7D22\u9884\u7B97\u6BD4\u4F8B\uFF085~100\uFF09\uFF0C\u9ED8\u8BA4 20
|
|
6614
|
+
\u63A2\u7D22\u6BD4\u4F8B\u4FDD\u8BC1\u5386\u53F2\u7ED3\u8BBA\u4E0D\u4F1A\u6C38\u4E45\u9501\u6B7B\u91C7\u6837\u6C60
|
|
6615
|
+
--explore-zero \u5141\u8BB8\u5728\u63A2\u7D22\u9884\u7B97\u91CC\u91CD\u65B0\u9A8C\u8BC1\u9759\u6001\u96F6\u6743\u91CD\u7F51\u6BB5
|
|
6616
|
+
\uFF08\u8FD9\u4E9B\u7F51\u6BB5\u5728\u672C\u673A\u7F51\u7EDC\u91CC\u53EF\u80FD\u5176\u5B9E\u53EF\u7528\uFF09
|
|
6197
6617
|
--json \u4EE5 JSON \u8F93\u51FA\u7ED3\u679C
|
|
6198
6618
|
--quiet \u4EC5\u8F93\u51FA\u7ED3\u679C
|
|
6199
6619
|
|
|
@@ -6214,6 +6634,7 @@ __export(command_exports2, {
|
|
|
6214
6634
|
runScanCommand: () => runScanCommand
|
|
6215
6635
|
});
|
|
6216
6636
|
import { readFileSync as readFileSync2 } from "node:fs";
|
|
6637
|
+
import { join as join3 } from "node:path";
|
|
6217
6638
|
function normalizeWsPath(raw, fallback) {
|
|
6218
6639
|
const value = (raw ?? fallback).trim();
|
|
6219
6640
|
if (!value) return fallback;
|
|
@@ -6246,13 +6667,31 @@ function normalizeWsPath(raw, fallback) {
|
|
|
6246
6667
|
function seedFromArgs(args) {
|
|
6247
6668
|
return args.flags["seed"] !== void 0 ? flagNumber(args, "seed", 24301) : void 0;
|
|
6248
6669
|
}
|
|
6670
|
+
function normalizeIsp(raw) {
|
|
6671
|
+
const value = (raw ?? "").trim().toLowerCase();
|
|
6672
|
+
return ["ct", "cu", "cm", "other"].includes(value) ? value : "other";
|
|
6673
|
+
}
|
|
6674
|
+
function normalizeAccess(raw) {
|
|
6675
|
+
const value = (raw ?? "").trim().toLowerCase();
|
|
6676
|
+
return value === "mobile" ? "mobile" : "fixed";
|
|
6677
|
+
}
|
|
6678
|
+
async function loadAdaptiveContext(args) {
|
|
6679
|
+
const file = join3(configDirPath(), "network-profiles.json");
|
|
6680
|
+
const isp = normalizeIsp(flagString(args, "isp"));
|
|
6681
|
+
const region = (flagString(args, "region") ?? "").trim().slice(0, 32);
|
|
6682
|
+
const access = normalizeAccess(flagString(args, "access"));
|
|
6683
|
+
const store = await loadNetworkProfile(file, `${isp}-${region}-${access}`);
|
|
6684
|
+
const profile = normalizeNetworkProfile({ isp, region, access, family: "ipv4", source: "manual" });
|
|
6685
|
+
store.profiles[profile.id] = { ...profile, updatedAt: Date.now() };
|
|
6686
|
+
return { file, store, profileId: profile.id };
|
|
6687
|
+
}
|
|
6249
6688
|
async function resolveCandidatesFromArgs(args) {
|
|
6250
6689
|
const ipFile = flagString(args, "ip-file");
|
|
6251
6690
|
if (ipFile) {
|
|
6252
|
-
const
|
|
6253
|
-
return readIpFile(
|
|
6691
|
+
const text2 = readFileSync2(ipFile, "utf8");
|
|
6692
|
+
return readIpFile(text2);
|
|
6254
6693
|
}
|
|
6255
|
-
|
|
6694
|
+
const base = {
|
|
6256
6695
|
// 选国家时**自动中性采样**:采样发生在阶段一之前、那时还不知道机房,
|
|
6257
6696
|
// 若某国家的 IP 集中在低权重网段,候选会被压少 → 可能「扫了几千个还是找不到 HKG/NRT」。
|
|
6258
6697
|
neutral: args.flags["neutral-sampling"] !== void 0 || flagList(args, "countries").length > 0,
|
|
@@ -6261,7 +6700,40 @@ async function resolveCandidatesFromArgs(args) {
|
|
|
6261
6700
|
// ⚠️ 不传 seed = 每次随机(默认)。只有用户显式给了 --seed 才固定,
|
|
6262
6701
|
// 否则「每次跑都测同一批 IP」——那批落在劣质路由段上时永远测不出好 IP。
|
|
6263
6702
|
seed: seedFromArgs(args)
|
|
6703
|
+
};
|
|
6704
|
+
if (!flagBool(args, "adaptive")) return resolveCandidates(base);
|
|
6705
|
+
const context = await loadAdaptiveContext(args);
|
|
6706
|
+
const exploreRate = flagNumber(args, "explore-rate", 20) / 100;
|
|
6707
|
+
const candidates = await resolveCandidates({
|
|
6708
|
+
...base,
|
|
6709
|
+
profile: context.store,
|
|
6710
|
+
adaptiveSampling: {
|
|
6711
|
+
explorationRate: Math.min(1, Math.max(0.05, exploreRate)),
|
|
6712
|
+
includeZeroWeight: flagBool(args, "explore-zero"),
|
|
6713
|
+
profileId: context.profileId
|
|
6714
|
+
}
|
|
6264
6715
|
});
|
|
6716
|
+
adaptiveContexts.set(args, context);
|
|
6717
|
+
return candidates;
|
|
6718
|
+
}
|
|
6719
|
+
async function saveAdaptiveObservations(args, observations) {
|
|
6720
|
+
const context = adaptiveContexts.get(args);
|
|
6721
|
+
if (!context || observations.length === 0) return;
|
|
6722
|
+
const now = Date.now();
|
|
6723
|
+
const next = updateNetworkProfile(
|
|
6724
|
+
context.store,
|
|
6725
|
+
observations.map((observation) => ({
|
|
6726
|
+
ip: observation.ip,
|
|
6727
|
+
ok: observation.ok,
|
|
6728
|
+
latencyMs: observation.latencyMs,
|
|
6729
|
+
speedMBps: observation.speedMBps,
|
|
6730
|
+
at: now,
|
|
6731
|
+
profileId: context.profileId,
|
|
6732
|
+
stage: "ws"
|
|
6733
|
+
})),
|
|
6734
|
+
now
|
|
6735
|
+
);
|
|
6736
|
+
await saveNetworkProfile(context.file, next);
|
|
6265
6737
|
}
|
|
6266
6738
|
function printProgress(event, quiet) {
|
|
6267
6739
|
if (quiet) return;
|
|
@@ -6299,10 +6771,10 @@ function printTable(entries) {
|
|
|
6299
6771
|
const rank = String(index + 1).padStart(2, " ");
|
|
6300
6772
|
const address = `${formatHost(entry.ip)}:${entry.port}`.padEnd(24, " ");
|
|
6301
6773
|
const colo = (entry.colo || "UNK").padEnd(6, " ");
|
|
6302
|
-
const
|
|
6774
|
+
const tls6 = String(entry.tlsMs).padStart(7, " ");
|
|
6303
6775
|
const latency = String(entry.latency).padStart(7, " ");
|
|
6304
6776
|
const speed = entry.speed.toFixed(1).padStart(9, " ");
|
|
6305
|
-
process.stdout.write(`${rank} ${address} ${colo} ${
|
|
6777
|
+
process.stdout.write(`${rank} ${address} ${colo} ${tls6} ${latency} ${speed}
|
|
6306
6778
|
`);
|
|
6307
6779
|
});
|
|
6308
6780
|
const seen = [];
|
|
@@ -6539,6 +7011,7 @@ ${NAME} v${VERSION}
|
|
|
6539
7011
|
top,
|
|
6540
7012
|
onProgress: (event) => printProgress(event, quiet)
|
|
6541
7013
|
});
|
|
7014
|
+
await saveAdaptiveObservations(args, summary.observations);
|
|
6542
7015
|
if (asJson) {
|
|
6543
7016
|
process.stdout.write(
|
|
6544
7017
|
`${JSON.stringify(
|
|
@@ -6560,7 +7033,14 @@ ${NAME} v${VERSION}
|
|
|
6560
7033
|
speedBytes: flagNumber(args, "speed-bytes", 5 * 1024 * 1024),
|
|
6561
7034
|
skipSpeed,
|
|
6562
7035
|
verifyPayload,
|
|
6563
|
-
tunnelVerified: Boolean(flagString(args, "uuid") || flagString(args, "trojan-password"))
|
|
7036
|
+
tunnelVerified: Boolean(flagString(args, "uuid") || flagString(args, "trojan-password")),
|
|
7037
|
+
// 实验性:自适应采样的开关与档案(未开启时为 null,便于复现报告区分模式)
|
|
7038
|
+
adaptive: flagBool(args, "adaptive") ? {
|
|
7039
|
+
isp: normalizeIsp(flagString(args, "isp")),
|
|
7040
|
+
region: (flagString(args, "region") ?? "").trim().slice(0, 32),
|
|
7041
|
+
access: normalizeAccess(flagString(args, "access")),
|
|
7042
|
+
exploreRate: flagNumber(args, "explore-rate", 20) / 100
|
|
7043
|
+
} : null
|
|
6564
7044
|
},
|
|
6565
7045
|
env: envResult,
|
|
6566
7046
|
stats: summary.stats,
|
|
@@ -6653,6 +7133,7 @@ async function promptCallback(entries, dataHost, panelHost, panelPassword) {
|
|
|
6653
7133
|
process.stdout.write("\u2192 \u53EF\u624B\u52A8\u590D\u5236\u4E0A\u9762\u7684 IP \u5217\u8868\u7C98\u8D34\u5230\u9762\u677F\n");
|
|
6654
7134
|
}
|
|
6655
7135
|
}
|
|
7136
|
+
var adaptiveContexts;
|
|
6656
7137
|
var init_command2 = __esm({
|
|
6657
7138
|
"src/scan/command.ts"() {
|
|
6658
7139
|
"use strict";
|
|
@@ -6662,11 +7143,14 @@ var init_command2 = __esm({
|
|
|
6662
7143
|
init_scan();
|
|
6663
7144
|
init_callback();
|
|
6664
7145
|
init_candidates();
|
|
7146
|
+
init_network_profile();
|
|
7147
|
+
init_store();
|
|
6665
7148
|
init_net_env();
|
|
6666
7149
|
init_version();
|
|
6667
7150
|
init_help2();
|
|
6668
7151
|
init_speed_url();
|
|
6669
7152
|
init_ip_ranges();
|
|
7153
|
+
adaptiveContexts = /* @__PURE__ */ new WeakMap();
|
|
6670
7154
|
}
|
|
6671
7155
|
});
|
|
6672
7156
|
|
|
@@ -7347,14 +7831,14 @@ async function runSingleTest(options) {
|
|
|
7347
7831
|
const tcp = await probeTcp(ip, port, timeoutMs);
|
|
7348
7832
|
push(tcp);
|
|
7349
7833
|
if (!tcp.ok) return results;
|
|
7350
|
-
const
|
|
7351
|
-
const tlsOk =
|
|
7834
|
+
const tls6 = await probeTlsHandshake(ip, port, host, timeoutMs);
|
|
7835
|
+
const tlsOk = tls6.tlsMs >= 0 && !tls6.error;
|
|
7352
7836
|
push({
|
|
7353
7837
|
stage: "TLS \u63E1\u624B",
|
|
7354
7838
|
ok: tlsOk,
|
|
7355
|
-
ms:
|
|
7356
|
-
detail:
|
|
7357
|
-
error: tlsOk ? void 0 :
|
|
7839
|
+
ms: tls6.tlsMs >= 0 ? tls6.tlsMs : void 0,
|
|
7840
|
+
detail: tls6.alpn ? `ALPN=${tls6.alpn}` : void 0,
|
|
7841
|
+
error: tlsOk ? void 0 : tls6.error ?? "\u63E1\u624B\u5931\u8D25"
|
|
7358
7842
|
});
|
|
7359
7843
|
if (!tlsOk) return results;
|
|
7360
7844
|
const ws = await probeWs101(ip, port, host, timeoutMs, path);
|
|
@@ -7538,6 +8022,527 @@ ${NAME} test \u2014\u2014 \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u
|
|
|
7538
8022
|
}
|
|
7539
8023
|
});
|
|
7540
8024
|
|
|
8025
|
+
// src/experimental/egress-identity.ts
|
|
8026
|
+
import * as net5 from "node:net";
|
|
8027
|
+
import * as tls4 from "node:tls";
|
|
8028
|
+
import * as https from "node:https";
|
|
8029
|
+
function fail(code, error) {
|
|
8030
|
+
return { ok: false, code, error };
|
|
8031
|
+
}
|
|
8032
|
+
function isPublicIp(value) {
|
|
8033
|
+
const family = net5.isIP(value);
|
|
8034
|
+
if (family === 4) {
|
|
8035
|
+
const [a = 0, b = 0, c2 = 0] = value.split(".").map(Number);
|
|
8036
|
+
return !(a === 0 || a === 10 || a === 127 || a >= 224 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && (c2 === 0 || c2 === 2) || a === 192 && b === 88 && c2 === 99 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c2 === 100 || a === 203 && b === 0 && c2 === 113);
|
|
8037
|
+
}
|
|
8038
|
+
if (family !== 6 || value.includes("%") || value.includes(".")) return false;
|
|
8039
|
+
const halves = value.toLowerCase().split("::");
|
|
8040
|
+
const left = halves[0] ? halves[0].split(":") : [];
|
|
8041
|
+
const right = halves[1] ? halves[1].split(":") : [];
|
|
8042
|
+
const words = halves.length === 1 ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right];
|
|
8043
|
+
const parts = words.map((word) => parseInt(word, 16));
|
|
8044
|
+
const first = parts[0] ?? 0;
|
|
8045
|
+
return first >= 8192 && first <= 16383 && first !== 8194 && !(first === 8193 && ((parts[1] ?? 0) < 512 || parts[1] === 3512)) && !(first === 16383 && (parts[1] ?? 0) < 4096);
|
|
8046
|
+
}
|
|
8047
|
+
function timestamp(value) {
|
|
8048
|
+
if (typeof value !== "string") return null;
|
|
8049
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
8050
|
+
if (!match) return null;
|
|
8051
|
+
const [year, month, day, hour, minute, second] = match.slice(1, 7).map(Number);
|
|
8052
|
+
if (year === void 0 || month === void 0 || day === void 0 || hour === void 0 || minute === void 0 || second === void 0) return null;
|
|
8053
|
+
const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
8054
|
+
if (month < 1 || month > 12 || day < 1 || day > days || hour > 23 || minute > 59 || second > 59) return null;
|
|
8055
|
+
const zone = match[7];
|
|
8056
|
+
if (zone !== "Z" && (Number(zone.slice(1, 3)) > 23 || Number(zone.slice(4)) > 59)) return null;
|
|
8057
|
+
const parsed = Date.parse(value);
|
|
8058
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
8059
|
+
}
|
|
8060
|
+
function validateIdentityResponse(value, now) {
|
|
8061
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
8062
|
+
const data = value;
|
|
8063
|
+
const observed = timestamp(data.observed_at);
|
|
8064
|
+
if (typeof data.remote_ip !== "string" || !isPublicIp(data.remote_ip) || observed === null || observed > now + CLOCK_SKEW_MS || now - observed > 3e5) return null;
|
|
8065
|
+
for (const key of ["egress_kind", "colo"]) {
|
|
8066
|
+
if (data[key] !== void 0 && (typeof data[key] !== "string" || data[key].length < 1 || data[key].length > 128 || /[\u0000-\u001f\u007f-\u009f]/.test(data[key]))) return null;
|
|
8067
|
+
}
|
|
8068
|
+
return {
|
|
8069
|
+
remoteIp: data.remote_ip,
|
|
8070
|
+
observedAt: new Date(observed).toISOString(),
|
|
8071
|
+
fetchedAt: new Date(now).toISOString(),
|
|
8072
|
+
ageMs: Math.max(0, now - observed),
|
|
8073
|
+
...typeof data.egress_kind === "string" ? { egressKind: data.egress_kind } : {},
|
|
8074
|
+
...typeof data.colo === "string" ? { colo: data.colo } : {}
|
|
8075
|
+
};
|
|
8076
|
+
}
|
|
8077
|
+
function readExactly(socket, length) {
|
|
8078
|
+
return new Promise((resolve3, reject) => {
|
|
8079
|
+
let data = Buffer.alloc(0);
|
|
8080
|
+
const cleanup = () => {
|
|
8081
|
+
socket.off("data", onData);
|
|
8082
|
+
socket.off("error", onError);
|
|
8083
|
+
socket.off("close", onClose);
|
|
8084
|
+
};
|
|
8085
|
+
const onError = () => {
|
|
8086
|
+
cleanup();
|
|
8087
|
+
reject(new Error("SOCKS5 \u8FDE\u63A5\u5931\u8D25"));
|
|
8088
|
+
};
|
|
8089
|
+
const onClose = () => {
|
|
8090
|
+
cleanup();
|
|
8091
|
+
reject(new Error("SOCKS5 \u63D0\u524D\u5173\u95ED"));
|
|
8092
|
+
};
|
|
8093
|
+
const onData = (chunk) => {
|
|
8094
|
+
data = Buffer.concat([data, chunk]);
|
|
8095
|
+
if (data.length < length) return;
|
|
8096
|
+
socket.pause();
|
|
8097
|
+
cleanup();
|
|
8098
|
+
if (data.length > length) socket.unshift(data.subarray(length));
|
|
8099
|
+
resolve3(data.subarray(0, length));
|
|
8100
|
+
};
|
|
8101
|
+
socket.on("data", onData);
|
|
8102
|
+
socket.once("error", onError);
|
|
8103
|
+
socket.once("close", onClose);
|
|
8104
|
+
socket.resume();
|
|
8105
|
+
});
|
|
8106
|
+
}
|
|
8107
|
+
async function negotiateSocks(socket, proxy, target) {
|
|
8108
|
+
const user = Buffer.from(decodeURIComponent(proxy.username));
|
|
8109
|
+
const password = Buffer.from(decodeURIComponent(proxy.password));
|
|
8110
|
+
const authenticated = user.length > 0;
|
|
8111
|
+
const greeting = readExactly(socket, 2);
|
|
8112
|
+
socket.write(Buffer.from([5, 1, authenticated ? 2 : 0]));
|
|
8113
|
+
const method = await greeting;
|
|
8114
|
+
if (method[0] !== 5 || method[1] !== (authenticated ? 2 : 0)) throw new Error("SOCKS5 \u8BA4\u8BC1\u65B9\u5F0F\u4E0D\u5339\u914D");
|
|
8115
|
+
if (authenticated) {
|
|
8116
|
+
const auth = readExactly(socket, 2);
|
|
8117
|
+
socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([password.length]), password]));
|
|
8118
|
+
const response = await auth;
|
|
8119
|
+
if (response[0] !== 1 || response[1] !== 0) throw new Error("SOCKS5 \u8BA4\u8BC1\u5931\u8D25");
|
|
8120
|
+
}
|
|
8121
|
+
const hostname = target.hostname.replace(/^\[|\]$/g, "");
|
|
8122
|
+
const host = Buffer.from(hostname);
|
|
8123
|
+
let address = Buffer.concat([Buffer.from([3, host.length]), host]);
|
|
8124
|
+
if (net5.isIP(hostname) === 4) address = Buffer.from([1, ...hostname.split(".").map(Number)]);
|
|
8125
|
+
else if (net5.isIP(hostname) === 6) {
|
|
8126
|
+
const halves = hostname.split("::");
|
|
8127
|
+
const left = halves[0] ? halves[0].split(":") : [];
|
|
8128
|
+
const right = halves[1] ? halves[1].split(":") : [];
|
|
8129
|
+
const words = halves.length === 1 ? left : [...left, ...Array(8 - left.length - right.length).fill("0"), ...right];
|
|
8130
|
+
address = Buffer.alloc(17);
|
|
8131
|
+
address[0] = 4;
|
|
8132
|
+
words.forEach((word, index) => address.writeUInt16BE(parseInt(word, 16), index * 2 + 1));
|
|
8133
|
+
}
|
|
8134
|
+
const port = Number(target.port || 443);
|
|
8135
|
+
const reply = readExactly(socket, 4);
|
|
8136
|
+
socket.write(Buffer.concat([Buffer.from([5, 1, 0]), address, Buffer.from([port >> 8, port & 255])]));
|
|
8137
|
+
const head = await reply;
|
|
8138
|
+
if (head[0] !== 5 || head[1] !== 0 || head[2] !== 0) throw new Error("SOCKS5 CONNECT \u5931\u8D25");
|
|
8139
|
+
if (head[3] === 1) await readExactly(socket, 6);
|
|
8140
|
+
else if (head[3] === 4) await readExactly(socket, 18);
|
|
8141
|
+
else if (head[3] === 3) {
|
|
8142
|
+
const size = await readExactly(socket, 1);
|
|
8143
|
+
await readExactly(socket, size[0] + 2);
|
|
8144
|
+
} else throw new Error("SOCKS5 \u54CD\u5E94\u5730\u5740\u65E0\u6548");
|
|
8145
|
+
}
|
|
8146
|
+
function identifyEgress(options) {
|
|
8147
|
+
let target;
|
|
8148
|
+
let proxy;
|
|
8149
|
+
const timeoutMs = options.timeoutMs ?? IDENTITY_TIMEOUT_MS;
|
|
8150
|
+
try {
|
|
8151
|
+
target = new URL(options.url);
|
|
8152
|
+
const hostname = target.hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, "");
|
|
8153
|
+
if (target.protocol !== "https:" || target.username || target.password || target.hash || !hostname || hostname.length > 253) throw new Error();
|
|
8154
|
+
if (net5.isIP(hostname) ? !isPublicIp(hostname) : hostname === "localhost" || !hostname.includes(".") || /\.(?:localhost|local|internal|home|test|invalid)$/.test(hostname)) throw new Error();
|
|
8155
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > IDENTITY_TIMEOUT_MS) throw new Error();
|
|
8156
|
+
if (options.token !== void 0) {
|
|
8157
|
+
const expires = timestamp(options.tokenExpiresAt);
|
|
8158
|
+
if (!/^[A-Za-z0-9._~+/-]{16,2048}={0,2}$/.test(options.token) || expires === null || expires <= Date.now() || expires > Date.now() + MAX_TOKEN_TTL_MS) throw new Error();
|
|
8159
|
+
} else if (options.tokenExpiresAt !== void 0) throw new Error();
|
|
8160
|
+
if (options.proxy !== void 0) {
|
|
8161
|
+
proxy = new URL(options.proxy);
|
|
8162
|
+
const proxyPort = Number(proxy.port || 1080);
|
|
8163
|
+
if (proxy.protocol !== "socks5:" || !proxy.hostname || !Number.isInteger(proxyPort) || proxyPort < 1 || proxyPort > 65535 || proxy.pathname && proxy.pathname !== "/" || proxy.search || proxy.hash) throw new Error();
|
|
8164
|
+
const user = decodeURIComponent(proxy.username);
|
|
8165
|
+
const password = decodeURIComponent(proxy.password);
|
|
8166
|
+
if (Buffer.byteLength(user) > 255 || Buffer.byteLength(password) > 255 || !user && password) throw new Error();
|
|
8167
|
+
}
|
|
8168
|
+
} catch {
|
|
8169
|
+
return Promise.resolve(fail("config", "\u8BC6\u522B\u914D\u7F6E\u65E0\u6548\uFF1A\u9700\u8981 HTTPS\u3001\u6709\u6548\u77ED\u671F\u4EE4\u724C\u548C\u53EF\u9009 SOCKS5 \u5730\u5740"));
|
|
8170
|
+
}
|
|
8171
|
+
return new Promise((resolve3) => {
|
|
8172
|
+
let settled = false;
|
|
8173
|
+
let request3;
|
|
8174
|
+
let socket;
|
|
8175
|
+
const agent = new https.Agent({ keepAlive: false, maxSockets: 1 });
|
|
8176
|
+
const finish = (result) => {
|
|
8177
|
+
if (settled) return;
|
|
8178
|
+
settled = true;
|
|
8179
|
+
clearTimeout(timer);
|
|
8180
|
+
request3?.destroy();
|
|
8181
|
+
socket?.destroy();
|
|
8182
|
+
agent.destroy();
|
|
8183
|
+
resolve3(result);
|
|
8184
|
+
};
|
|
8185
|
+
const timer = setTimeout(() => finish(fail("timeout", "\u51FA\u53E3\u8BC6\u522B\u8D85\u8FC7\u603B\u8D85\u65F6\u9884\u7B97")), timeoutMs);
|
|
8186
|
+
if (proxy) {
|
|
8187
|
+
const selectedProxy = proxy;
|
|
8188
|
+
agent.createConnection = (_connectionOptions, callback) => {
|
|
8189
|
+
socket = net5.connect({ host: selectedProxy.hostname.replace(/^\[|\]$/g, ""), port: Number(selectedProxy.port || 1080) });
|
|
8190
|
+
socket.once("error", () => finish(fail("transport", "SOCKS5 \u8FDE\u63A5\u5931\u8D25")));
|
|
8191
|
+
socket.once("connect", () => {
|
|
8192
|
+
const raw = socket;
|
|
8193
|
+
void negotiateSocks(raw, selectedProxy, target).then(() => {
|
|
8194
|
+
if (settled) return;
|
|
8195
|
+
const hostname = target.hostname.replace(/^\[|\]$/g, "");
|
|
8196
|
+
const secure = tls4.connect({ socket: raw, host: hostname, servername: net5.isIP(hostname) ? void 0 : hostname, rejectUnauthorized: true });
|
|
8197
|
+
socket = secure;
|
|
8198
|
+
secure.once("error", () => finish(fail("transport", "\u8BC6\u522B\u670D\u52A1 TLS \u8FDE\u63A5\u5931\u8D25")));
|
|
8199
|
+
callback?.(null, secure);
|
|
8200
|
+
}).catch(() => finish(fail("transport", "SOCKS5 \u63E1\u624B\u5931\u8D25")));
|
|
8201
|
+
});
|
|
8202
|
+
return void 0;
|
|
8203
|
+
};
|
|
8204
|
+
}
|
|
8205
|
+
request3 = https.request(target, {
|
|
8206
|
+
method: "GET",
|
|
8207
|
+
agent,
|
|
8208
|
+
maxHeaderSize: 8192,
|
|
8209
|
+
headers: { Accept: "application/json", "Accept-Encoding": "identity", "Cache-Control": "no-store", ...options.token ? { Authorization: `Bearer ${options.token}` } : {} }
|
|
8210
|
+
}, (response) => {
|
|
8211
|
+
if (response.statusCode !== 200) {
|
|
8212
|
+
finish(fail("http", `\u8BC6\u522B\u670D\u52A1\u8FD4\u56DE HTTP ${response.statusCode ?? 0}`));
|
|
8213
|
+
return;
|
|
8214
|
+
}
|
|
8215
|
+
if (!/^application\/json(?:\s*;|$)/i.test(response.headers["content-type"] ?? "") || response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity") {
|
|
8216
|
+
finish(fail("response", "\u8BC6\u522B\u670D\u52A1\u5FC5\u987B\u8FD4\u56DE\u672A\u538B\u7F29\u7684 JSON"));
|
|
8217
|
+
return;
|
|
8218
|
+
}
|
|
8219
|
+
const declared = response.headers["content-length"];
|
|
8220
|
+
if (declared && (!/^\d+$/.test(declared) || Number(declared) > MAX_IDENTITY_BYTES)) {
|
|
8221
|
+
finish(fail("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
|
|
8222
|
+
return;
|
|
8223
|
+
}
|
|
8224
|
+
const chunks = [];
|
|
8225
|
+
let bytes = 0;
|
|
8226
|
+
response.on("data", (chunk) => {
|
|
8227
|
+
bytes += chunk.length;
|
|
8228
|
+
if (bytes > MAX_IDENTITY_BYTES) {
|
|
8229
|
+
finish(fail("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
|
|
8230
|
+
return;
|
|
8231
|
+
}
|
|
8232
|
+
chunks.push(chunk);
|
|
8233
|
+
});
|
|
8234
|
+
response.once("error", () => finish(fail("transport", "\u8BC6\u522B\u54CD\u5E94\u4F20\u8F93\u5931\u8D25")));
|
|
8235
|
+
response.once("end", () => {
|
|
8236
|
+
if (settled) return;
|
|
8237
|
+
try {
|
|
8238
|
+
const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
|
|
8239
|
+
const observation = validateIdentityResponse(value, Date.now());
|
|
8240
|
+
if (!observation) {
|
|
8241
|
+
finish(fail("response", "\u8BC6\u522B\u7ED3\u679C\u5B57\u6BB5\u6216\u516C\u7F51\u5730\u5740\u65E0\u6548"));
|
|
8242
|
+
return;
|
|
8243
|
+
}
|
|
8244
|
+
finish({ ok: true, observation: { ...observation, sourceUrl: target.origin + target.pathname, transport: proxy ? "socks5" : "direct" } });
|
|
8245
|
+
} catch {
|
|
8246
|
+
finish(fail("response", "\u8BC6\u522B\u54CD\u5E94\u4E0D\u662F\u6709\u6548 UTF-8 JSON"));
|
|
8247
|
+
}
|
|
8248
|
+
});
|
|
8249
|
+
});
|
|
8250
|
+
request3.once("error", () => finish(fail("transport", "\u8BC6\u522B\u8BF7\u6C42\u8FDE\u63A5\u5931\u8D25")));
|
|
8251
|
+
request3.end();
|
|
8252
|
+
});
|
|
8253
|
+
}
|
|
8254
|
+
var MAX_IDENTITY_BYTES, IDENTITY_TIMEOUT_MS, MAX_TOKEN_TTL_MS, CLOCK_SKEW_MS;
|
|
8255
|
+
var init_egress_identity = __esm({
|
|
8256
|
+
"src/experimental/egress-identity.ts"() {
|
|
8257
|
+
"use strict";
|
|
8258
|
+
MAX_IDENTITY_BYTES = 16 * 1024;
|
|
8259
|
+
IDENTITY_TIMEOUT_MS = 8e3;
|
|
8260
|
+
MAX_TOKEN_TTL_MS = 5 * 60 * 1e3;
|
|
8261
|
+
CLOCK_SKEW_MS = 3e4;
|
|
8262
|
+
}
|
|
8263
|
+
});
|
|
8264
|
+
|
|
8265
|
+
// src/experimental/egress-command.ts
|
|
8266
|
+
var egress_command_exports = {};
|
|
8267
|
+
__export(egress_command_exports, {
|
|
8268
|
+
runEgressIdentityCommand: () => runEgressIdentityCommand
|
|
8269
|
+
});
|
|
8270
|
+
async function runEgressIdentityCommand(args) {
|
|
8271
|
+
if (flagBool(args, "help") || flagBool(args, "h")) {
|
|
8272
|
+
process.stdout.write(HELP2);
|
|
8273
|
+
return;
|
|
8274
|
+
}
|
|
8275
|
+
const url = flagString(args, "url");
|
|
8276
|
+
if (!url || args.flags.timeout !== void 0 && typeof args.flags.timeout !== "string") {
|
|
8277
|
+
process.stderr.write("\u9700\u8981 --url\uFF0C\u5E76\u4F7F\u7528\u6709\u6548\u7684 --timeout \u6570\u503C\uFF1B\u8FD0\u884C egress-identify --help \u67E5\u770B\u534F\u8BAE\u3002\n");
|
|
8278
|
+
process.exitCode = 1;
|
|
8279
|
+
return;
|
|
8280
|
+
}
|
|
8281
|
+
const result = await identifyEgress({
|
|
8282
|
+
url,
|
|
8283
|
+
proxy: flagString(args, "proxy") || process.env.CFPILOT_EGRESS_PROXY,
|
|
8284
|
+
token: process.env.CFPILOT_EGRESS_TOKEN,
|
|
8285
|
+
tokenExpiresAt: process.env.CFPILOT_EGRESS_TOKEN_EXPIRES_AT,
|
|
8286
|
+
timeoutMs: args.flags.timeout === void 0 ? void 0 : flagNumber(args, "timeout", Number.NaN)
|
|
8287
|
+
});
|
|
8288
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}
|
|
8289
|
+
`);
|
|
8290
|
+
if (!result.ok) process.exitCode = 1;
|
|
8291
|
+
}
|
|
8292
|
+
var HELP2;
|
|
8293
|
+
var init_egress_command = __esm({
|
|
8294
|
+
"src/experimental/egress-command.ts"() {
|
|
8295
|
+
"use strict";
|
|
8296
|
+
init_args();
|
|
8297
|
+
init_egress_identity();
|
|
8298
|
+
HELP2 = `
|
|
8299
|
+
\u5B9E\u9A8C\u6027\u51FA\u53E3\u8BC6\u522B\uFF08\u4E0D\u53C2\u4E0E\u9ED8\u8BA4 scan \u6216\u5019\u9009\u6392\u5E8F\uFF09
|
|
8300
|
+
|
|
8301
|
+
\u7528\u6CD5\uFF1Acfpilot egress-identify --url https://\u81EA\u6709\u670D\u52A1/identify [--proxy socks5://127.0.0.1:10808]
|
|
8302
|
+
|
|
8303
|
+
\u9009\u9879\uFF1A
|
|
8304
|
+
--url <URL> \u7528\u6237\u81EA\u6709 HTTPS \u8BC6\u522B\u670D\u52A1\uFF08\u5FC5\u586B\uFF09
|
|
8305
|
+
--proxy <URL> \u663E\u5F0F\u6307\u5B9A SOCKS5 \u8DEF\u5F84\uFF1B\u7701\u7565\u65F6\u53EA\u6D4B\u672C\u673A\u76F4\u8FDE\u57FA\u7EBF
|
|
8306
|
+
--timeout <ms> \u603B\u8D85\u65F6\uFF0C\u53EF\u7F29\u77ED\u4F46\u4E0D\u8D85\u8FC7 8000ms
|
|
8307
|
+
--help \u663E\u793A\u5E2E\u52A9
|
|
8308
|
+
|
|
8309
|
+
\u53EF\u9009\u73AF\u5883\u53D8\u91CF\uFF1A
|
|
8310
|
+
CFPILOT_EGRESS_TOKEN \u670D\u52A1\u7AEF\u7B7E\u53D1\u7684\u4E13\u7528\u77ED\u671F Bearer token
|
|
8311
|
+
CFPILOT_EGRESS_TOKEN_EXPIRES_AT RFC3339 \u8FC7\u671F\u65F6\u95F4\uFF0C\u5269\u4F59\u6709\u6548\u671F\u987B\u5728\u4E94\u5206\u949F\u4EE5\u5185
|
|
8312
|
+
CFPILOT_EGRESS_PROXY SOCKS5 \u5730\u5740\uFF08\u542B\u51ED\u636E\u65F6\u5E94\u4F18\u5148\u7528\u6B64\u9879\uFF09
|
|
8313
|
+
|
|
8314
|
+
\u4EC5\u8BC6\u522B\u6307\u5B9A\u4F20\u8F93\u8DEF\u5F84\uFF0C\u4E0D\u7ED1\u5B9A\u626B\u63CF\u5019\u9009 IP\uFF0C\u4E0D\u8BC1\u660E\u9010\u5019\u9009\u5165\u53E3\u6216 Worker \u51FA\u53E3\u5DEE\u5F02\u3002
|
|
8315
|
+
\u4E0D\u4E0A\u4F20 UUID\u3001\u9762\u677F\u5BC6\u7801\u6216 Cloudflare Token\uFF1B\u8BC6\u522B\u670D\u52A1\u4F1A\u770B\u5230\u8BE5\u8DEF\u5F84\u7684\u6E90 IP\u3002
|
|
8316
|
+
`;
|
|
8317
|
+
}
|
|
8318
|
+
});
|
|
8319
|
+
|
|
8320
|
+
// src/experimental/website-compatibility.ts
|
|
8321
|
+
import * as https2 from "node:https";
|
|
8322
|
+
import * as net6 from "node:net";
|
|
8323
|
+
import * as tls5 from "node:tls";
|
|
8324
|
+
function targetUrl(value) {
|
|
8325
|
+
const target = new URL(value);
|
|
8326
|
+
const hostname = target.hostname.replace(/^\[|\]$/g, "").toLowerCase().replace(/\.$/, "");
|
|
8327
|
+
if (target.protocol !== "https:" || target.username || target.password || target.hash || !hostname || hostname.length > 253 || target.port === "0") throw new Error();
|
|
8328
|
+
if (net6.isIP(hostname) ? !isPublicIp(hostname) : hostname === "localhost" || !hostname.includes(".") || /\.(?:localhost|local|internal|home|test|invalid)$/.test(hostname)) throw new Error();
|
|
8329
|
+
return target;
|
|
8330
|
+
}
|
|
8331
|
+
function proxyUrl(value) {
|
|
8332
|
+
if (value === void 0) return void 0;
|
|
8333
|
+
const proxy = new URL(value);
|
|
8334
|
+
const port = Number(proxy.port || 1080);
|
|
8335
|
+
if (proxy.protocol !== "socks5:" || !proxy.hostname || !Number.isInteger(port) || port < 1 || port > 65535 || proxy.pathname && proxy.pathname !== "/" || proxy.search || proxy.hash) throw new Error();
|
|
8336
|
+
const user = decodeURIComponent(proxy.username);
|
|
8337
|
+
const password = decodeURIComponent(proxy.password);
|
|
8338
|
+
if (Buffer.byteLength(user) > 255 || Buffer.byteLength(password) > 255 || !user && password) throw new Error();
|
|
8339
|
+
return proxy;
|
|
8340
|
+
}
|
|
8341
|
+
function tlsFailure(error) {
|
|
8342
|
+
if (typeof error !== "object" || error === null) return false;
|
|
8343
|
+
const code = error.code;
|
|
8344
|
+
return typeof code === "string" && /^(?:ERR_TLS_|ERR_SSL_|CERT_|DEPTH_ZERO_SELF_SIGNED_CERT|SELF_SIGNED_CERT_IN_CHAIN|UNABLE_TO_VERIFY_LEAF_SIGNATURE|UNABLE_TO_GET_ISSUER_CERT)/.test(code);
|
|
8345
|
+
}
|
|
8346
|
+
function probeWebsite(target, options = {}) {
|
|
8347
|
+
const started = Date.now();
|
|
8348
|
+
const base = {
|
|
8349
|
+
label: typeof target.label === "string" && target.label.length > 0 && target.label.length <= 64 && !/[\u0000-\u001f\u007f-\u009f]/.test(target.label) ? target.label : "invalid",
|
|
8350
|
+
url: "",
|
|
8351
|
+
transport: options.proxy === void 0 ? "direct" : "socks5",
|
|
8352
|
+
ms: 0,
|
|
8353
|
+
status: "invalid_response",
|
|
8354
|
+
httpStatus: 0,
|
|
8355
|
+
challengeHeader: false
|
|
8356
|
+
};
|
|
8357
|
+
let url;
|
|
8358
|
+
let proxy;
|
|
8359
|
+
const timeout = options.timeoutMs ?? WEBSITE_TIMEOUT_MS;
|
|
8360
|
+
try {
|
|
8361
|
+
if (base.label !== target.label || !Number.isInteger(timeout) || timeout < 1 || timeout > WEBSITE_TIMEOUT_MS) throw new Error();
|
|
8362
|
+
if (target.expectedText !== void 0 && (typeof target.expectedText !== "string" || target.expectedText.length === 0 || Buffer.byteLength(target.expectedText) > 1024 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(target.expectedText))) throw new Error();
|
|
8363
|
+
url = targetUrl(target.url);
|
|
8364
|
+
base.url = url.origin + url.pathname;
|
|
8365
|
+
proxy = proxyUrl(options.proxy);
|
|
8366
|
+
} catch {
|
|
8367
|
+
return Promise.resolve({ ...base, error: "\u7F51\u7AD9\u68C0\u6D4B\u914D\u7F6E\u65E0\u6548" });
|
|
8368
|
+
}
|
|
8369
|
+
return new Promise((resolve3) => {
|
|
8370
|
+
let settled = false;
|
|
8371
|
+
let socket;
|
|
8372
|
+
let request3;
|
|
8373
|
+
const agent = new https2.Agent({ keepAlive: false, maxSockets: 1 });
|
|
8374
|
+
const finish = (patch) => {
|
|
8375
|
+
if (settled) return;
|
|
8376
|
+
settled = true;
|
|
8377
|
+
clearTimeout(timer);
|
|
8378
|
+
request3?.destroy();
|
|
8379
|
+
socket?.destroy();
|
|
8380
|
+
agent.destroy();
|
|
8381
|
+
resolve3({ ...base, ...patch, ms: Date.now() - started });
|
|
8382
|
+
};
|
|
8383
|
+
const onError = (error) => finish({ status: tlsFailure(error) ? "tls_error" : "http_error", error: tlsFailure(error) ? "\u7F51\u7AD9 TLS \u6821\u9A8C\u5931\u8D25" : "\u6307\u5B9A\u8DEF\u5F84\u8FDE\u63A5\u5931\u8D25" });
|
|
8384
|
+
const timer = setTimeout(() => finish({ status: "timeout", error: "\u7F51\u7AD9\u68C0\u6D4B\u8D85\u8FC7\u603B\u8D85\u65F6\u9884\u7B97" }), timeout);
|
|
8385
|
+
if (proxy) {
|
|
8386
|
+
const selected = proxy;
|
|
8387
|
+
agent.createConnection = (_connectionOptions, callback) => {
|
|
8388
|
+
socket = net6.connect({ host: selected.hostname.replace(/^\[|\]$/g, ""), port: Number(selected.port || 1080) });
|
|
8389
|
+
socket.once("error", onError);
|
|
8390
|
+
socket.once("connect", () => {
|
|
8391
|
+
const raw = socket;
|
|
8392
|
+
void negotiateSocks(raw, selected, url).then(() => {
|
|
8393
|
+
if (settled) return;
|
|
8394
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
8395
|
+
const secure = tls5.connect({ socket: raw, host, servername: net6.isIP(host) ? void 0 : host, rejectUnauthorized: true });
|
|
8396
|
+
socket = secure;
|
|
8397
|
+
secure.once("error", onError);
|
|
8398
|
+
callback?.(null, secure);
|
|
8399
|
+
}).catch(() => finish({ status: "http_error", error: "\u6307\u5B9A\u4EE3\u7406\u63E1\u624B\u5931\u8D25" }));
|
|
8400
|
+
});
|
|
8401
|
+
return void 0;
|
|
8402
|
+
};
|
|
8403
|
+
}
|
|
8404
|
+
request3 = https2.request(url, {
|
|
8405
|
+
method: "GET",
|
|
8406
|
+
agent,
|
|
8407
|
+
maxHeaderSize: 8192,
|
|
8408
|
+
headers: { Accept: "*/*", "Accept-Encoding": "identity", "Cache-Control": "no-store" }
|
|
8409
|
+
}, (response) => {
|
|
8410
|
+
const status2 = response.statusCode ?? 0;
|
|
8411
|
+
base.httpStatus = status2;
|
|
8412
|
+
const header = response.headers["cf-mitigated"];
|
|
8413
|
+
base.challengeHeader = typeof header === "string" && header.trim().toLowerCase() === "challenge";
|
|
8414
|
+
if (base.challengeHeader) {
|
|
8415
|
+
finish({ status: "challenge" });
|
|
8416
|
+
return;
|
|
8417
|
+
}
|
|
8418
|
+
if (status2 === 403) {
|
|
8419
|
+
finish({ status: "forbidden" });
|
|
8420
|
+
return;
|
|
8421
|
+
}
|
|
8422
|
+
if (status2 === 429) {
|
|
8423
|
+
finish({ status: "rate_limited" });
|
|
8424
|
+
return;
|
|
8425
|
+
}
|
|
8426
|
+
if (status2 < 200 || status2 >= 300) {
|
|
8427
|
+
finish({ status: "http_error", error: status2 >= 300 && status2 < 400 ? "\u76EE\u6807\u8FD4\u56DE\u91CD\u5B9A\u5411\uFF0C\u672A\u8DDF\u968F" : "\u76EE\u6807\u8FD4\u56DE\u975E\u6210\u529F\u72B6\u6001\u7801" });
|
|
8428
|
+
return;
|
|
8429
|
+
}
|
|
8430
|
+
if (response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity") {
|
|
8431
|
+
finish({ status: "invalid_response", error: "\u76EE\u6807\u8FD4\u56DE\u538B\u7F29\u5185\u5BB9\uFF0C\u672A\u89E3\u538B" });
|
|
8432
|
+
return;
|
|
8433
|
+
}
|
|
8434
|
+
const declared = response.headers["content-length"];
|
|
8435
|
+
if (declared && (!/^\d+$/.test(declared) || Number(declared) > WEBSITE_MAX_BYTES)) {
|
|
8436
|
+
finish({ status: "invalid_response", error: "\u7F51\u7AD9\u54CD\u5E94\u8D85\u8FC7 16 KiB" });
|
|
8437
|
+
return;
|
|
8438
|
+
}
|
|
8439
|
+
const chunks = [];
|
|
8440
|
+
let bytes = 0;
|
|
8441
|
+
response.on("data", (chunk) => {
|
|
8442
|
+
bytes += chunk.length;
|
|
8443
|
+
if (bytes > WEBSITE_MAX_BYTES) {
|
|
8444
|
+
finish({ status: "invalid_response", error: "\u7F51\u7AD9\u54CD\u5E94\u8D85\u8FC7 16 KiB" });
|
|
8445
|
+
return;
|
|
8446
|
+
}
|
|
8447
|
+
chunks.push(chunk);
|
|
8448
|
+
});
|
|
8449
|
+
response.once("error", () => finish({ status: "http_error", error: "\u7F51\u7AD9\u54CD\u5E94\u4F20\u8F93\u5931\u8D25" }));
|
|
8450
|
+
response.once("end", () => {
|
|
8451
|
+
if (settled) return;
|
|
8452
|
+
const bytes2 = Buffer.concat(chunks);
|
|
8453
|
+
const contentType = response.headers["content-type"] ?? "";
|
|
8454
|
+
if (/^text\/html(?:\s*;|$)/i.test(contentType) && /<script\b[^>]*\bsrc\s*=\s*["'][^"']*\/cdn-cgi\/challenge-platform\//i.test(bytes2.toString("utf8"))) {
|
|
8455
|
+
finish({ status: "challenge" });
|
|
8456
|
+
return;
|
|
8457
|
+
}
|
|
8458
|
+
if (target.expectedText !== void 0) {
|
|
8459
|
+
try {
|
|
8460
|
+
const body = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
|
|
8461
|
+
if (!body.includes(target.expectedText)) {
|
|
8462
|
+
finish({ status: "invalid_response", expectedContentOk: false, error: "\u6B63\u6587\u4E0D\u7B26\u5408\u663E\u5F0F\u68C0\u6D4B\u6761\u4EF6" });
|
|
8463
|
+
return;
|
|
8464
|
+
}
|
|
8465
|
+
} catch {
|
|
8466
|
+
finish({ status: "invalid_response", expectedContentOk: false, error: "\u76EE\u6807\u6B63\u6587\u4E0D\u662F\u6709\u6548 UTF-8" });
|
|
8467
|
+
return;
|
|
8468
|
+
}
|
|
8469
|
+
finish({ status: "ok", expectedContentOk: true });
|
|
8470
|
+
return;
|
|
8471
|
+
}
|
|
8472
|
+
finish({ status: "ok" });
|
|
8473
|
+
});
|
|
8474
|
+
});
|
|
8475
|
+
request3.once("error", onError);
|
|
8476
|
+
request3.end();
|
|
8477
|
+
});
|
|
8478
|
+
}
|
|
8479
|
+
async function probeWebsites(options) {
|
|
8480
|
+
if (options.targets.length < 1 || options.targets.length > WEBSITE_MAX_TARGETS || new Set(options.targets.map((target) => target.label)).size !== options.targets.length) throw new Error("\u7F51\u7AD9\u68C0\u6D4B\u9700\u8981 1\u201310 \u4E2A\u4E0D\u540C\u6807\u7B7E\u7684\u76EE\u6807");
|
|
8481
|
+
const results = [];
|
|
8482
|
+
for (const target of options.targets) results.push(await probeWebsite(target, options));
|
|
8483
|
+
return results;
|
|
8484
|
+
}
|
|
8485
|
+
var WEBSITE_TIMEOUT_MS, WEBSITE_MAX_BYTES, WEBSITE_MAX_TARGETS;
|
|
8486
|
+
var init_website_compatibility = __esm({
|
|
8487
|
+
"src/experimental/website-compatibility.ts"() {
|
|
8488
|
+
"use strict";
|
|
8489
|
+
init_egress_identity();
|
|
8490
|
+
WEBSITE_TIMEOUT_MS = 8e3;
|
|
8491
|
+
WEBSITE_MAX_BYTES = 16 * 1024;
|
|
8492
|
+
WEBSITE_MAX_TARGETS = 10;
|
|
8493
|
+
}
|
|
8494
|
+
});
|
|
8495
|
+
|
|
8496
|
+
// src/experimental/website-command.ts
|
|
8497
|
+
var website_command_exports = {};
|
|
8498
|
+
__export(website_command_exports, {
|
|
8499
|
+
runWebsiteCommand: () => runWebsiteCommand
|
|
8500
|
+
});
|
|
8501
|
+
async function runWebsiteCommand(args) {
|
|
8502
|
+
if (flagBool(args, "help") || flagBool(args, "h")) {
|
|
8503
|
+
process.stdout.write(HELP3);
|
|
8504
|
+
return;
|
|
8505
|
+
}
|
|
8506
|
+
if (!flagString(args, "url") || args.flags["expected-text"] !== void 0 && typeof args.flags["expected-text"] !== "string" || args.flags.timeout !== void 0 && typeof args.flags.timeout !== "string") {
|
|
8507
|
+
process.stderr.write("\u9700\u8981 --url \u548C\u6709\u6548\u68C0\u6D4B\u53C2\u6570\uFF1B\u8FD0\u884C website-check --help \u67E5\u770B\u8BF4\u660E\u3002\n");
|
|
8508
|
+
process.exitCode = 1;
|
|
8509
|
+
return;
|
|
8510
|
+
}
|
|
8511
|
+
const targets = await probeWebsites({
|
|
8512
|
+
targets: [{ label: flagString(args, "label", "target"), url: flagString(args, "url"), expectedText: typeof args.flags["expected-text"] === "string" ? args.flags["expected-text"] : void 0 }],
|
|
8513
|
+
proxy: flagString(args, "proxy") || process.env.CFPILOT_EGRESS_PROXY,
|
|
8514
|
+
timeoutMs: args.flags.timeout === void 0 ? void 0 : flagNumber(args, "timeout", Number.NaN)
|
|
8515
|
+
});
|
|
8516
|
+
process.stdout.write(`${JSON.stringify({ targets }, null, 2)}
|
|
8517
|
+
`);
|
|
8518
|
+
if (targets.some((result) => result.status !== "ok")) process.exitCode = 1;
|
|
8519
|
+
}
|
|
8520
|
+
var HELP3;
|
|
8521
|
+
var init_website_command = __esm({
|
|
8522
|
+
"src/experimental/website-command.ts"() {
|
|
8523
|
+
"use strict";
|
|
8524
|
+
init_args();
|
|
8525
|
+
init_website_compatibility();
|
|
8526
|
+
HELP3 = `
|
|
8527
|
+
\u5B9E\u9A8C\u6027\u7F51\u7AD9\u517C\u5BB9\u6027\u68C0\u6D4B\uFF08\u4E0D\u53C2\u4E0E\u9ED8\u8BA4 scan \u6216\u6392\u5E8F\uFF09
|
|
8528
|
+
|
|
8529
|
+
\u7528\u6CD5\uFF1Acfpilot website-check --url https://\u7528\u6237\u6307\u5B9A\u7F51\u7AD9/ [--proxy socks5://127.0.0.1:10808]
|
|
8530
|
+
|
|
8531
|
+
\u9009\u9879\uFF1A
|
|
8532
|
+
--url <URL> \u5FC5\u586B HTTPS \u76EE\u6807\uFF0C\u53EA\u8BF7\u6C42\u8FD9\u4E00\u5730\u5740
|
|
8533
|
+
--label <\u6587\u672C> \u76EE\u6807\u6807\u7B7E\uFF0C\u9ED8\u8BA4 target
|
|
8534
|
+
--expected-text <\u6587> \u53EF\u9009 UTF-8 \u6B63\u6587\u6807\u8BB0\uFF0C\u7EAF\u6587\u672C\u5339\u914D
|
|
8535
|
+
--proxy <URL> \u663E\u5F0F SOCKS5 \u8DEF\u5F84\uFF1B\u7701\u7565\u65F6\u662F\u672C\u673A\u76F4\u8FDE\u57FA\u7EBF
|
|
8536
|
+
--timeout <ms> \u603B\u8D85\u65F6\uFF0C\u4E0D\u8D85\u8FC7 8000ms
|
|
8537
|
+
--help \u663E\u793A\u5E2E\u52A9
|
|
8538
|
+
|
|
8539
|
+
\u4EE3\u7406\u51ED\u636E\u4F18\u5148\u901A\u8FC7 CFPILOT_EGRESS_PROXY \u73AF\u5883\u53D8\u91CF\u63D0\u4F9B\uFF0C\u4E0D\u8BFB\u53D6\u8BC6\u522B token \u6216\u8D26\u53F7\u51ED\u636E\u3002
|
|
8540
|
+
\u4E0D\u4F1A\u8DDF\u968F\u91CD\u5B9A\u5411\uFF0C\u4E0D\u6267\u884C\u9875\u9762\u811A\u672C\u3001\u4E0D\u767B\u5F55\u3001\u4E0D\u89E3\u538B\u3001\u4E0D\u5BA3\u79F0\u8D26\u53F7\u6743\u9650\u6216\u5B8C\u6574\u89E3\u9501\u3002
|
|
8541
|
+
\u6BCF\u6B21\u53EA\u8BC6\u522B\u6307\u5B9A\u4F20\u8F93\u8DEF\u5F84\uFF0C\u4E0D\u7ED1\u5B9A\u5019\u9009 IP\uFF1B\u5355\u54CD\u5E94\u6700\u591A 16 KiB\u3002
|
|
8542
|
+
`;
|
|
8543
|
+
}
|
|
8544
|
+
});
|
|
8545
|
+
|
|
7541
8546
|
// src/deploy/token-command.ts
|
|
7542
8547
|
var token_command_exports = {};
|
|
7543
8548
|
__export(token_command_exports, {
|
|
@@ -7605,10 +8610,10 @@ __export(command_exports3, {
|
|
|
7605
8610
|
});
|
|
7606
8611
|
import { spawn } from "node:child_process";
|
|
7607
8612
|
import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
7608
|
-
import { dirname as
|
|
8613
|
+
import { dirname as dirname3, resolve as resolve2 } from "node:path";
|
|
7609
8614
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
7610
8615
|
function loadScript() {
|
|
7611
|
-
const here =
|
|
8616
|
+
const here = dirname3(fileURLToPath2(import.meta.url));
|
|
7612
8617
|
const candidates = [
|
|
7613
8618
|
resolve2(here, "../assets/vps-socks5.sh"),
|
|
7614
8619
|
resolve2(here, "../../assets/vps-socks5.sh")
|
|
@@ -7646,7 +8651,7 @@ ssh \u542F\u52A8\u5931\u8D25\uFF1A${err.message}
|
|
|
7646
8651
|
}
|
|
7647
8652
|
async function runVpsCommand(args) {
|
|
7648
8653
|
if (flagBool(args, "h") || flagBool(args, "help")) {
|
|
7649
|
-
process.stdout.write(
|
|
8654
|
+
process.stdout.write(HELP4);
|
|
7650
8655
|
return;
|
|
7651
8656
|
}
|
|
7652
8657
|
const port = flagNumber(args, "port", 0);
|
|
@@ -7693,13 +8698,13 @@ async function runVpsCommand(args) {
|
|
|
7693
8698
|
`
|
|
7694
8699
|
);
|
|
7695
8700
|
}
|
|
7696
|
-
var
|
|
8701
|
+
var HELP4;
|
|
7697
8702
|
var init_command3 = __esm({
|
|
7698
8703
|
"src/vps/command.ts"() {
|
|
7699
8704
|
"use strict";
|
|
7700
8705
|
init_args();
|
|
7701
8706
|
init_version();
|
|
7702
|
-
|
|
8707
|
+
HELP4 = `
|
|
7703
8708
|
${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5 \u843D\u5730\u4EE3\u7406
|
|
7704
8709
|
|
|
7705
8710
|
\u7528\u6CD5:
|
|
@@ -7732,7 +8737,7 @@ ${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5
|
|
|
7732
8737
|
// src/cli.ts
|
|
7733
8738
|
init_args();
|
|
7734
8739
|
init_version();
|
|
7735
|
-
var
|
|
8740
|
+
var HELP5 = `
|
|
7736
8741
|
${NAME} v${VERSION}
|
|
7737
8742
|
Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
|
|
7738
8743
|
|
|
@@ -7741,6 +8746,8 @@ Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
|
|
|
7741
8746
|
${NAME} deploy [\u9009\u9879] \u90E8\u7F72 Pages \u53CC\u9879\u76EE
|
|
7742
8747
|
${NAME} scan [\u9009\u9879] \u672C\u5730\u771F\u8FDE\u63A5\u4F18\u9009
|
|
7743
8748
|
${NAME} test [\u9009\u9879] \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u8DEF
|
|
8749
|
+
${NAME} egress-identify \u5B9E\u9A8C\u6027\u6307\u5B9A\u4F20\u8F93\u8DEF\u5F84\u51FA\u53E3\u8BC6\u522B
|
|
8750
|
+
${NAME} website-check \u5B9E\u9A8C\u6027\u7F51\u7AD9\u517C\u5BB9\u6027\u68C0\u6D4B
|
|
7744
8751
|
${NAME} status \u67E5\u770B\u5F53\u524D\u5B9E\u4F8B\u72B6\u6001
|
|
7745
8752
|
${NAME} token [\u9009\u9879] \u68C0\u67E5 API Token \u6743\u9650
|
|
7746
8753
|
${NAME} vps [\u9009\u9879] \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5 \u843D\u5730\u4EE3\u7406
|
|
@@ -7766,11 +8773,11 @@ async function main() {
|
|
|
7766
8773
|
return;
|
|
7767
8774
|
}
|
|
7768
8775
|
if (!command && (flagBool(args, "h") || flagBool(args, "help"))) {
|
|
7769
|
-
process.stdout.write(
|
|
8776
|
+
process.stdout.write(HELP5);
|
|
7770
8777
|
return;
|
|
7771
8778
|
}
|
|
7772
8779
|
if (command === "help") {
|
|
7773
|
-
process.stdout.write(
|
|
8780
|
+
process.stdout.write(HELP5);
|
|
7774
8781
|
return;
|
|
7775
8782
|
}
|
|
7776
8783
|
switch (command) {
|
|
@@ -7795,6 +8802,16 @@ async function main() {
|
|
|
7795
8802
|
await runTestCommand2(args);
|
|
7796
8803
|
return;
|
|
7797
8804
|
}
|
|
8805
|
+
case "egress-identify": {
|
|
8806
|
+
const { runEgressIdentityCommand: runEgressIdentityCommand2 } = await Promise.resolve().then(() => (init_egress_command(), egress_command_exports));
|
|
8807
|
+
await runEgressIdentityCommand2(args);
|
|
8808
|
+
return;
|
|
8809
|
+
}
|
|
8810
|
+
case "website-check": {
|
|
8811
|
+
const { runWebsiteCommand: runWebsiteCommand2 } = await Promise.resolve().then(() => (init_website_command(), website_command_exports));
|
|
8812
|
+
await runWebsiteCommand2(args);
|
|
8813
|
+
return;
|
|
8814
|
+
}
|
|
7798
8815
|
case "status": {
|
|
7799
8816
|
const { runStatus: runStatus2 } = await Promise.resolve().then(() => (init_status(), status_exports));
|
|
7800
8817
|
await runStatus2();
|
|
@@ -7819,7 +8836,7 @@ async function main() {
|
|
|
7819
8836
|
process.stderr.write(`\u672A\u77E5\u547D\u4EE4\uFF1A${command}
|
|
7820
8837
|
|
|
7821
8838
|
`);
|
|
7822
|
-
process.stderr.write(
|
|
8839
|
+
process.stderr.write(HELP5);
|
|
7823
8840
|
process.exitCode = 1;
|
|
7824
8841
|
}
|
|
7825
8842
|
}
|