cfpilot 0.13.1 → 0.13.6

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/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.1";
90
+ VERSION = "0.13.6";
91
91
  NAME = "cfpilot";
92
92
  }
93
93
  });
94
94
 
95
95
  // src/menu/ui.ts
96
- function wrap(open, close) {
97
- return (s) => useColor ? `\x1B[${open}m${s}\x1B[${close}m` : s;
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, text) {
144
- process.stdout.write(`${icon[kind]()} ${text}
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(text = "\u6309 Enter \u7EE7\u7EED") {
443
- await ask(c.gray(text), { allowEmpty: true });
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, text) {
552
+ function parseApiError(status2, text2) {
550
553
  let message = `HTTP ${status2}`;
551
554
  let code;
552
- if (text) {
555
+ if (text2) {
553
556
  try {
554
- const parsed = JSON.parse(text);
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} ${text.slice(0, 300)}`;
563
+ message = `${message} ${text2.slice(0, 300)}`;
561
564
  }
562
565
  } catch {
563
- message = `${message} ${text.slice(0, 300)}`;
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 text = await response.text();
570
- if (!response.ok) throw parseApiError(response.status, text);
571
- if (!text) return void 0;
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(text);
577
+ parsed = JSON.parse(text2);
575
578
  } catch {
576
- throw new CloudflareError(`\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF1A${text.slice(0, 200)}`, response.status);
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, text);
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 text = await response.text().catch(() => "");
718
- const detail = parseApiError(response.status, text).message;
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 text = await response.text().catch(() => "");
743
- throw parseApiError(response.status, text);
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(text) {
1168
+ function displayWidth2(text2) {
1166
1169
  let width = 0;
1167
- for (const char of text) width += charWidth(char);
1170
+ for (const char of text2) width += charWidth(char);
1168
1171
  return width;
1169
1172
  }
1170
- function padDisplay(text, width) {
1171
- return `${text}${" ".repeat(Math.max(0, width - displayWidth2(text)))}`;
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 text = input.trim();
1606
- if (!text) return null;
1607
- const matched = VERSION_RE.exec(text);
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 text = tag.trim();
1739
+ const text2 = tag.trim();
1737
1740
  for (const prefix of ["desktop-v", "gui-v", "v"]) {
1738
- if (text.startsWith(prefix)) {
1739
- const rest = text.slice(prefix.length);
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 text = await response.text();
1853
- if (Buffer.byteLength(text) > MAX_ASSET_BYTES) {
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 text;
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(text) {
1887
+ function parseChecksums(text2) {
1885
1888
  const out = /* @__PURE__ */ new Map();
1886
- for (const raw of text.split("\n")) {
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 text = await downloadAsset(info.checksumsUrl, timeoutMs, { allowMirrors: false });
1902
- const map = parseChecksums(text);
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 text = await readFile(path, "utf8");
1933
- return text.length > 0 ? text : null;
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 text = await readFile(candidate, "utf8");
1968
- if (text.length > 0) return text;
1970
+ const text2 = await readFile(candidate, "utf8");
1971
+ if (text2.length > 0) return text2;
1969
1972
  } catch {
1970
1973
  }
1971
1974
  }
@@ -2946,7 +2949,7 @@ ${NAME} deploy \u2014\u2014 \u53CC\u9762\u90E8\u7F72\uFF08\u63A7\u5236\u9762 Pag
2946
2949
  Worker \u7684\u300C\u57DF\u300D\u6807\u7B7E\u9875\u6DFB\u52A0\u3002**\u5DE5\u5177\u4E0D\u4F1A\u66FF\u4F60\u7ED1\u5B9A\u57DF\u540D**\u3002
2947
2950
  \u4E0D\u586B\u5219\u7528 *.workers.dev\uFF08\u591A\u6570\u7F51\u7EDC\u76F4\u8FDE\u4E0D\u53EF\u8BBF\u95EE\uFF0C\u8282\u70B9\u4F1A\u8FDE\u4E0D\u4E0A\uFF09
2948
2951
  --panel-path <path> \u9762\u677F\u8BBF\u95EE\u8DEF\u5F84\uFF08\u9ED8\u8BA4\u968F\u673A\uFF09
2949
- --mode <mode> \u90E8\u7F72\u6A21\u5F0F\uFF1Aauto\uFF08\u9ED8\u8BA4\uFF0C\u81EA\u52A8\u5224\u65AD\uFF09/ fresh\uFF08\u5F3A\u5236\u9996\u6B21\uFF09/ update\uFF08\u5F3A\u5236\u66F4\u65B0\uFF09
2952
+ --mode <mode> \u90E8\u7F72\u6A21\u5F0F\uFF1Aauto\uFF08\u9ED8\u8BA4\uFF0C\u81EA\u52A8\u5224\u65AD\uFF09/ fresh\uFF08\u5168\u65B0\u90E8\u7F72\uFF0C\u81EA\u52A8\u65B0\u5EFA KV\uFF09/ update\uFF08\u5F3A\u5236\u66F4\u65B0\uFF09
2950
2953
  --force \u5FFD\u7565\u7248\u672C\u68C0\u67E5\uFF0C\u5F3A\u5236\u91CD\u65B0\u90E8\u7F72
2951
2954
  --force-kv \u8DF3\u8FC7 KV \u5F52\u5C5E\u6821\u9A8C\uFF08\u660E\u77E5\u8BE5 KV \u5C5E\u4E8E\u522B\u7684\u5B9E\u4F8B\u4ECD\u7136\u7EE7\u7EED\uFF09
2952
2955
  --resolve-preferred=false
@@ -3152,7 +3155,19 @@ async function runDeployCommand(args) {
3152
3155
  await listKvInstances(client, resolvedAccount);
3153
3156
  return;
3154
3157
  }
3155
- const forceNewKv = flagBool(args, "new-kv");
3158
+ const mode = flagString(args, "mode") || "auto";
3159
+ if (!["auto", "fresh", "update"].includes(mode)) {
3160
+ process.stderr.write(`\u2717 --mode \u53EA\u63A5\u53D7 auto / fresh / update\uFF0C\u6536\u5230\uFF1A${mode}
3161
+ `);
3162
+ process.exitCode = 1;
3163
+ return;
3164
+ }
3165
+ if (mode === "fresh" && kvId) {
3166
+ process.stdout.write(`\xB7 \u5168\u65B0\u90E8\u7F72\u4F1A\u65B0\u5EFA\u72EC\u7ACB KV\uFF0C\u5DF2\u5FFD\u7565 --kv ${kvId}
3167
+ `);
3168
+ kvId = "";
3169
+ }
3170
+ const forceNewKv = flagBool(args, "new-kv") || mode === "fresh";
3156
3171
  const existing = await listCfPilotNamespaces(client, resolvedAccount);
3157
3172
  if (!kvId && !forceNewKv) {
3158
3173
  if (existing.length === 0) {
@@ -3186,8 +3201,10 @@ async function runDeployCommand(args) {
3186
3201
  }
3187
3202
  } else if (!kvId && forceNewKv) {
3188
3203
  const title = flagString(args, "kv-title") || `cfpilot-kv-${Date.now().toString(36)}`;
3189
- process.stdout.write(`\u521B\u5EFA\u65B0\u7684 KV \u547D\u540D\u7A7A\u95F4\uFF08--new-kv\uFF09\uFF1A${title}
3190
- `);
3204
+ process.stdout.write(
3205
+ `\u521B\u5EFA\u65B0\u7684 KV \u547D\u540D\u7A7A\u95F4\uFF08${mode === "fresh" ? "\u5168\u65B0\u90E8\u7F72" : "--new-kv"}\uFF09\uFF1A${title}
3206
+ `
3207
+ );
3191
3208
  const ns = await client.createKvNamespace(resolvedAccount, title);
3192
3209
  kvId = ns.id;
3193
3210
  process.stdout.write(`\u2713 KV \u5DF2\u521B\u5EFA\uFF1A${ns.id}
@@ -3197,13 +3214,6 @@ async function runDeployCommand(args) {
3197
3214
  `);
3198
3215
  }
3199
3216
  }
3200
- const mode = flagString(args, "mode") || "auto";
3201
- if (!["auto", "fresh", "update"].includes(mode)) {
3202
- process.stderr.write(`\u2717 --mode \u53EA\u63A5\u53D7 auto / fresh / update\uFF0C\u6536\u5230\uFF1A${mode}
3203
- `);
3204
- process.exitCode = 1;
3205
- return;
3206
- }
3207
3217
  const dataPlaneRaw = (flagString(args, "data-plane") || "").toLowerCase();
3208
3218
  if (dataPlaneRaw && dataPlaneRaw !== "pages" && dataPlaneRaw !== "workers") {
3209
3219
  process.stderr.write(`\u2717 --data-plane \u53EA\u63A5\u53D7 pages / workers\uFF0C\u6536\u5230\uFF1A${dataPlaneRaw}
@@ -3734,8 +3744,8 @@ var init_countries = __esm({
3734
3744
  // src/scan/true-probe.ts
3735
3745
  import * as tls from "node:tls";
3736
3746
  import * as crypto from "node:crypto";
3737
- function extractColo(text) {
3738
- const match = /cf-ray:\s*[0-9a-f]+-([A-Z]{3})/i.exec(text);
3747
+ function extractColo(text2) {
3748
+ const match = /cf-ray:\s*[0-9a-f]+-([A-Z]{3})/i.exec(text2);
3739
3749
  return match ? match[1].toUpperCase() : "";
3740
3750
  }
3741
3751
  function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
@@ -3754,7 +3764,7 @@ function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
3754
3764
  }
3755
3765
  resolve3({ ...result, latencyMs: Date.now() - started });
3756
3766
  };
3757
- const request = [
3767
+ const request3 = [
3758
3768
  `GET ${path} HTTP/1.1`,
3759
3769
  `Host: ${host}`,
3760
3770
  `Upgrade: websocket`,
@@ -3774,7 +3784,7 @@ function probeWs101(ip, port, host, timeoutMs = 3e3, path = "/__edge_probe") {
3774
3784
  ALPNProtocols: ["http/1.1"]
3775
3785
  },
3776
3786
  () => {
3777
- socket.write(request);
3787
+ socket.write(request3);
3778
3788
  }
3779
3789
  );
3780
3790
  const timer = setTimeout(() => {
@@ -3872,7 +3882,7 @@ function probeWsPing(ip, port, host, timeoutMs = 5e3, path = "/__edge_probe") {
3872
3882
  }
3873
3883
  resolve3({ ...result, latencyMs: Date.now() - started });
3874
3884
  };
3875
- const request = [
3885
+ const request3 = [
3876
3886
  `GET ${path} HTTP/1.1`,
3877
3887
  `Host: ${host}`,
3878
3888
  `Upgrade: websocket`,
@@ -3892,7 +3902,7 @@ function probeWsPing(ip, port, host, timeoutMs = 5e3, path = "/__edge_probe") {
3892
3902
  ALPNProtocols: ["http/1.1"]
3893
3903
  },
3894
3904
  () => {
3895
- socket.write(request);
3905
+ socket.write(request3);
3896
3906
  }
3897
3907
  );
3898
3908
  const timer = setTimeout(() => {
@@ -4031,7 +4041,7 @@ function measureThroughput(options) {
4031
4041
  requiredHeader,
4032
4042
  minBytes = 32 * 1024
4033
4043
  } = options;
4034
- const connCount = Math.max(1, Math.min(8, connections));
4044
+ const connCount = Math.max(1, Math.min(16, connections));
4035
4045
  return new Promise((resolve3) => {
4036
4046
  const started = Date.now();
4037
4047
  let settled = false;
@@ -4073,7 +4083,7 @@ function measureThroughput(options) {
4073
4083
  error
4074
4084
  });
4075
4085
  };
4076
- const request = [
4086
+ const request3 = [
4077
4087
  `GET ${path} HTTP/1.1`,
4078
4088
  `Host: ${requestHost}`,
4079
4089
  `User-Agent: ${USER_AGENT}`,
@@ -4096,7 +4106,7 @@ function measureThroughput(options) {
4096
4106
  },
4097
4107
  () => {
4098
4108
  openedCount++;
4099
- socket.write(request);
4109
+ socket.write(request3);
4100
4110
  }
4101
4111
  );
4102
4112
  sockets.push(socket);
@@ -4178,7 +4188,7 @@ async function measureProbeThroughput(options) {
4178
4188
  minBytes: 32 * 1024
4179
4189
  });
4180
4190
  }
4181
- function buildVlessTunnelPayload(uuid, targetHost, targetPort, request) {
4191
+ function buildVlessTunnelPayload(uuid, targetHost, targetPort, request3) {
4182
4192
  const clean = uuid.replace(/-/g, "");
4183
4193
  if (!/^[0-9a-fA-F]{32}$/.test(clean)) return null;
4184
4194
  const hostBuf = Buffer.from(targetHost, "utf8");
@@ -4187,10 +4197,10 @@ function buildVlessTunnelPayload(uuid, targetHost, targetPort, request) {
4187
4197
  Buffer.from(clean, "hex"),
4188
4198
  Buffer.from([0, 1, targetPort >> 8 & 255, targetPort & 255, 2, hostBuf.length]),
4189
4199
  hostBuf,
4190
- Buffer.from(request, "utf8")
4200
+ Buffer.from(request3, "utf8")
4191
4201
  ]);
4192
4202
  }
4193
- function buildTrojanTunnelPayload(password, targetHost, targetPort, request) {
4203
+ function buildTrojanTunnelPayload(password, targetHost, targetPort, request3) {
4194
4204
  const digest = crypto.createHash("sha224").update(password).digest("hex");
4195
4205
  const hostBuf = Buffer.from(targetHost, "utf8");
4196
4206
  return Buffer.concat([
@@ -4199,7 +4209,7 @@ function buildTrojanTunnelPayload(password, targetHost, targetPort, request) {
4199
4209
  hostBuf,
4200
4210
  Buffer.from([targetPort >> 8 & 255, targetPort & 255]),
4201
4211
  Buffer.from("\r\n", "ascii"),
4202
- Buffer.from(request, "utf8")
4212
+ Buffer.from(request3, "utf8")
4203
4213
  ]);
4204
4214
  }
4205
4215
  function tunnelUpgradeRequest(host, wsPath, key) {
@@ -4320,16 +4330,32 @@ var init_true_probe = __esm({
4320
4330
  this.windowStart = now;
4321
4331
  return this.peak;
4322
4332
  }
4323
- /** 结算一个窗口:慢启动期内只丢弃,不记峰值/稳态 */
4333
+ /**
4334
+ * 结算一个窗口:慢启动期内只丢弃,不记峰值/稳态。
4335
+ *
4336
+ * 两处口径细节(都会让稳态**偏低**,方向单一,必须排除):
4337
+ *
4338
+ * 1. **空窗不计时**:链路中途停顿(个别连接已结束、其余在等数据)时,
4339
+ * 把停顿时间算进分母等于把「没有测到」当成「测到很慢」。
4340
+ * 2. **跨界窗口只折算边界之后的部分**:预热结束前后各占一半的窗口若整窗计入,
4341
+ * 预热期的慢速样本会以整窗权重拉低稳态(反之也可能抬高)。
4342
+ */
4324
4343
  settle(now) {
4325
4344
  const dt = (now - this.windowStart) / 1e3;
4326
4345
  if (dt <= 0) return;
4327
4346
  const bytes = this.windowBytes;
4347
+ const windowStart = this.windowStart;
4328
4348
  this.windowBytes = 0;
4329
4349
  this.windowStart = now;
4330
- if (now - this.startedAt < this.warmupMs) return;
4331
- this.steadyBytes += bytes;
4332
- this.steadySeconds += dt;
4350
+ if (bytes === 0) return;
4351
+ const warmupEnd = this.startedAt + this.warmupMs;
4352
+ const effectiveStart = Math.max(windowStart, warmupEnd);
4353
+ const effectiveSeconds = (now - effectiveStart) / 1e3;
4354
+ if (effectiveSeconds <= 0) return;
4355
+ const share = effectiveSeconds / dt;
4356
+ const effectiveBytes = bytes * share;
4357
+ this.steadyBytes += effectiveBytes;
4358
+ this.steadySeconds += effectiveSeconds;
4333
4359
  const speed = bytes / dt / 1024 / 1024;
4334
4360
  if (speed > this.peak) this.peak = speed;
4335
4361
  }
@@ -4410,7 +4436,7 @@ function checkSpeedUrlAvailable(parsed, timeoutMs = 6e3) {
4410
4436
  resolve3({ available, status: status2, error });
4411
4437
  };
4412
4438
  const path = parsed.path.includes("bytes=") ? parsed.path.replace(/bytes=\d+/, "bytes=1024") : parsed.path;
4413
- const request = [
4439
+ const request3 = [
4414
4440
  `GET ${path} HTTP/1.1`,
4415
4441
  `Host: ${parsed.host}`,
4416
4442
  `User-Agent: ${USER_AGENT_FOR_CHECK}`,
@@ -4425,10 +4451,10 @@ function checkSpeedUrlAvailable(parsed, timeoutMs = 6e3) {
4425
4451
  servername: parsed.host,
4426
4452
  rejectUnauthorized: false
4427
4453
  };
4428
- const socket = parsed.scheme === "https" ? tls2.connect(connectOptions, () => socket.write(request)) : (
4454
+ const socket = parsed.scheme === "https" ? tls2.connect(connectOptions, () => socket.write(request3)) : (
4429
4455
  // http 明文:用 net 连接
4430
4456
  (() => {
4431
- const s = net.connect({ host: parsed.host, port: 80 }, () => s.write(request));
4457
+ const s = net.connect({ host: parsed.host, port: 80 }, () => s.write(request3));
4432
4458
  return s;
4433
4459
  })()
4434
4460
  );
@@ -4576,20 +4602,20 @@ var init_unlock = __esm({
4576
4602
  // src/scan/scan.ts
4577
4603
  import * as net2 from "node:net";
4578
4604
  function classifyFailure(error) {
4579
- const text = String(error ?? "").trim();
4580
- if (!text) return "\u672A\u77E5\u539F\u56E0";
4581
- if (/timeout|timed out|超时|ETIMEDOUT/i.test(text)) return "\u8D85\u65F6";
4582
- if (/ECONNREFUSED|connection refused|连接被拒/i.test(text)) return "\u8FDE\u63A5\u88AB\u62D2";
4583
- if (/ENETUNREACH|EHOSTUNREACH|unreachable/i.test(text)) return "\u7F51\u7EDC\u4E0D\u53EF\u8FBE";
4584
- if (/ECONNRESET|socket hang up|连接重置/i.test(text)) return "\u8FDE\u63A5\u91CD\u7F6E";
4585
- if (/certificate|CERT_|SELF_SIGNED|证书/i.test(text)) return "\u8BC1\u4E66\u95EE\u9898";
4586
- if (/ALPN/i.test(text)) return "ALPN \u534F\u5546\u5931\u8D25";
4587
- if (/HTTP\s*\d{3}/i.test(text)) {
4588
- const code = /HTTP\s*(\d{3})/i.exec(text)?.[1];
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];
4589
4615
  return code ? `HTTP ${code}` : "HTTP \u72B6\u6001\u5F02\u5E38";
4590
4616
  }
4591
- if (/PONG|pong/i.test(text)) return "\u5185\u5BB9\u6821\u9A8C\u4E0D\u901A\u8FC7";
4592
- if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(text)) return "\u57DF\u540D\u89E3\u6790\u5931\u8D25";
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";
4593
4619
  return "\u5176\u4ED6";
4594
4620
  }
4595
4621
  function countFailure(into, stage, error) {
@@ -4700,6 +4726,7 @@ async function runScan(options) {
4700
4726
  message: `TCP \u521D\u7B5B ${done}/${candidates.length}`
4701
4727
  });
4702
4728
  }
4729
+ options.onObservation?.({ ip, ok: result.ok, stage: "tcp", latencyMs: result.latency, error: result.ok ? void 0 : "TCP \u8FDE\u63A5\u5931\u8D25" });
4703
4730
  return result;
4704
4731
  });
4705
4732
  const tcpOk = tcpResults.filter((r) => r.ok);
@@ -4726,6 +4753,7 @@ async function runScan(options) {
4726
4753
  message: `TLS \u63E1\u624B ${tlsDone}/${tlsInput.length}${probe.tlsMs > 0 ? ` ${probe.tlsMs}ms` : " \u2717"}`
4727
4754
  });
4728
4755
  }
4756
+ options.onObservation?.({ ip: item.ip, ok: probe.tlsMs > 0, stage: "tls", latencyMs: probe.tlsMs, error: probe.error });
4729
4757
  return { ...item, tls: probe };
4730
4758
  });
4731
4759
  const failures = {};
@@ -4780,6 +4808,7 @@ async function runScan(options) {
4780
4808
  total: stage1.length,
4781
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}` : ""}`
4782
4810
  });
4811
+ options.onObservation?.({ ip: item.ip, ok: result.ok, stage: "ws", error: result.error });
4783
4812
  return { ...item, probe: result, pathOk };
4784
4813
  },
4785
4814
  () => {
@@ -4865,6 +4894,7 @@ async function runScan(options) {
4865
4894
  speedResults = await pool(stage2, speedConcurrency, async (item) => {
4866
4895
  const repeat = Math.max(1, options.speedRepeat ?? 1);
4867
4896
  const samples = [];
4897
+ const peakSamples = [];
4868
4898
  for (let r = 0; r < repeat; r++) {
4869
4899
  const one = await measureThroughput({
4870
4900
  ip: item.ip,
@@ -4876,12 +4906,17 @@ async function runScan(options) {
4876
4906
  durationMs: options.speedDurationMs ?? 6e3,
4877
4907
  timeoutMs: options.speedTimeoutMs ?? 2e4
4878
4908
  });
4879
- if (one.ok) samples.push(one.steadyMBps);
4909
+ if (one.ok) {
4910
+ samples.push(one.steadyMBps);
4911
+ peakSamples.push(one.peakMBps);
4912
+ }
4880
4913
  }
4881
4914
  samples.sort((a, b) => a - b);
4915
+ peakSamples.sort((a, b) => a - b);
4882
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)];
4883
4918
  const jitter = samples.length < 2 ? 0 : samples[samples.length - 1] - samples[0];
4884
- const result = { ok: samples.length > 0, steadyMBps: median };
4919
+ const result = { ok: samples.length > 0, steadyMBps: median, peakMBps: peak };
4885
4920
  speedDone++;
4886
4921
  report({
4887
4922
  type: "progress",
@@ -4890,7 +4925,7 @@ async function runScan(options) {
4890
4925
  total: stage2.length,
4891
4926
  message: `\u6D4B\u901F ${speedDone}/${stage2.length} [${item.probe.colo || "UNK"}] ${result.steadyMBps.toFixed(1)} MB/s${jitter > 0 ? ` \xB1${jitter.toFixed(1)}` : ""}`
4892
4927
  });
4893
- return { ...item, speed: result.ok ? result.steadyMBps : 0, jitter };
4928
+ return { ...item, speed: result.ok ? result.steadyMBps : 0, peakMBps: result.peakMBps, jitter };
4894
4929
  });
4895
4930
  } else {
4896
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 });
@@ -4898,6 +4933,7 @@ async function runScan(options) {
4898
4933
  speedResults = await pool(stage2, speedConcurrency, async (item) => {
4899
4934
  const repeat = Math.max(1, options.speedRepeat ?? 1);
4900
4935
  const samples = [];
4936
+ const peakSamples = [];
4901
4937
  for (let r = 0; r < repeat; r++) {
4902
4938
  const one = await measureProbeThroughput({
4903
4939
  ip: item.ip,
@@ -4910,12 +4946,17 @@ async function runScan(options) {
4910
4946
  timeoutMs: speedTimeoutMs,
4911
4947
  token: options.uuid
4912
4948
  });
4913
- if (one.ok) samples.push(one.steadyMBps);
4949
+ if (one.ok) {
4950
+ samples.push(one.steadyMBps);
4951
+ peakSamples.push(one.peakMBps);
4952
+ }
4914
4953
  }
4915
4954
  samples.sort((a, b) => a - b);
4955
+ peakSamples.sort((a, b) => a - b);
4916
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)];
4917
4958
  const jitter = samples.length < 2 ? 0 : samples[samples.length - 1] - samples[0];
4918
- const result = { ok: samples.length > 0, steadyMBps: median };
4959
+ const result = { ok: samples.length > 0, steadyMBps: median, peakMBps: peak };
4919
4960
  speedDone++;
4920
4961
  report({
4921
4962
  type: "progress",
@@ -4924,7 +4965,7 @@ async function runScan(options) {
4924
4965
  total: stage2.length,
4925
4966
  message: `\u6D4B\u901F ${speedDone}/${stage2.length} [${item.probe.colo || "UNK"}] ${result.steadyMBps.toFixed(1)} MB/s${jitter > 0 ? ` \xB1${jitter.toFixed(1)}` : ""}`
4926
4967
  });
4927
- return { ...item, speed: result.ok ? result.steadyMBps : 0 };
4968
+ return { ...item, speed: result.ok ? result.steadyMBps : 0, peakMBps: result.peakMBps, jitter };
4928
4969
  });
4929
4970
  }
4930
4971
  const ranked = speedResults.filter((r) => options.skipSpeed ? true : Boolean(r.speed && r.speed > 0)).map((r) => ({
@@ -4932,8 +4973,12 @@ async function runScan(options) {
4932
4973
  port: options.port,
4933
4974
  colo: r.probe.colo || "UNK",
4934
4975
  latency: r.latency,
4976
+ // tcpMs 是阶段一测得的 TCP 建连耗时(CLI 的 latency 字段本身就是它,
4977
+ // 这里显式补一份,便于与桌面版报告字段一一对应)。
4978
+ tcpMs: r.latency,
4935
4979
  tlsMs: r.tls.tlsMs,
4936
4980
  speed: r.speed ? Number(r.speed.toFixed(2)) : 0,
4981
+ peakMBps: r.peakMBps ? Number(r.peakMBps.toFixed(2)) : 0,
4937
4982
  speedJitter: r.jitter ? Number(r.jitter.toFixed(2)) : 0
4938
4983
  })).sort(
4939
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
@@ -4969,8 +5014,22 @@ async function runScan(options) {
4969
5014
  for (const entry of entries) {
4970
5015
  report({ type: "result", entry });
4971
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
+ }
4972
5030
  const summary = {
4973
5031
  entries,
5032
+ observations,
4974
5033
  stats: {
4975
5034
  candidates: candidates.length,
4976
5035
  tcpOk: tcpOk.length,
@@ -5060,8 +5119,8 @@ async function postResults(callbackUrl, token, entries, timeoutMs = 15e3) {
5060
5119
  signal: AbortSignal.timeout(timeoutMs)
5061
5120
  });
5062
5121
  if (!response.ok) {
5063
- const text = await response.text().catch(() => "");
5064
- return { ok: false, status: response.status, error: `\u56DE\u4F20\u5931\u8D25 HTTP ${response.status} ${text}`.trim() };
5122
+ const text2 = await response.text().catch(() => "");
5123
+ return { ok: false, status: response.status, error: `\u56DE\u4F20\u5931\u8D25 HTTP ${response.status} ${text2}`.trim() };
5065
5124
  }
5066
5125
  return { ok: true, status: response.status };
5067
5126
  } catch (err) {
@@ -5084,8 +5143,8 @@ async function fetchScannerToken(panelHost, password, timeoutMs = 25e3) {
5084
5143
  return { ok: false, error: "\u9762\u677F\u5BC6\u7801\u4E0D\u6B63\u786E" };
5085
5144
  }
5086
5145
  if (!loginRes.ok) {
5087
- const text = await loginRes.text().catch(() => "");
5088
- return { ok: false, error: `\u767B\u5F55\u5931\u8D25 HTTP ${loginRes.status} ${text.slice(0, 120)}` };
5146
+ const text2 = await loginRes.text().catch(() => "");
5147
+ return { ok: false, error: `\u767B\u5F55\u5931\u8D25 HTTP ${loginRes.status} ${text2.slice(0, 120)}` };
5089
5148
  }
5090
5149
  const headersWithCookies = loginRes.headers;
5091
5150
  const raw = headersWithCookies.getSetCookie?.() ?? [];
@@ -5109,22 +5168,22 @@ async function takeToken(base, cookie, timeoutMs) {
5109
5168
  signal: AbortSignal.timeout(timeoutMs)
5110
5169
  });
5111
5170
  if (!res.ok) {
5112
- const text2 = await res.text().catch(() => "");
5113
- return { ok: false, error: `\u83B7\u53D6\u4EE4\u724C\u5931\u8D25 HTTP ${res.status} ${text2.slice(0, 120)}` };
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)}` };
5114
5173
  }
5115
- const text = await res.text();
5116
- if (text.trimStart().startsWith("<")) {
5174
+ const text2 = await res.text();
5175
+ if (text2.trimStart().startsWith("<")) {
5117
5176
  return {
5118
5177
  ok: false,
5119
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"
5120
5179
  };
5121
5180
  }
5122
5181
  try {
5123
- const data = JSON.parse(text);
5182
+ const data = JSON.parse(text2);
5124
5183
  if (!data.token) return { ok: false, error: "\u9762\u677F\u6CA1\u6709\u8FD4\u56DE\u4EE4\u724C" };
5125
5184
  return { ok: true, token: data.token };
5126
5185
  } catch {
5127
- return { ok: false, error: "\u4EE4\u724C\u54CD\u5E94\u89E3\u6790\u5931\u8D25\uFF1A" + text.slice(0, 120) };
5186
+ return { ok: false, error: "\u4EE4\u724C\u54CD\u5E94\u89E3\u6790\u5931\u8D25\uFF1A" + text2.slice(0, 120) };
5128
5187
  }
5129
5188
  }
5130
5189
  var init_callback = __esm({
@@ -5161,7 +5220,7 @@ async function fetchCloudflareCidrs(timeoutMs = 8e3) {
5161
5220
  fetch("https://www.cloudflare.com/ips-v4", { signal: controller.signal }),
5162
5221
  fetch("https://www.cloudflare.com/ips-v6", { signal: controller.signal })
5163
5222
  ]);
5164
- const parse = (text) => text.split("\n").map((l) => l.trim()).filter((l) => l.includes("/"));
5223
+ const parse = (text2) => text2.split("\n").map((l) => l.trim()).filter((l) => l.includes("/"));
5165
5224
  return {
5166
5225
  ipv4: v4.ok ? parse(await v4.text()) : BUILTIN_IPV4_CIDRS,
5167
5226
  ipv6: v6.ok ? parse(await v6.text()) : BUILTIN_IPV6_CIDRS
@@ -5355,17 +5414,17 @@ function expandCidrs(cidrs, options = {}) {
5355
5414
  target.count -= 1;
5356
5415
  familySum -= 1;
5357
5416
  }
5358
- for (const { cidr, count } of usablePlans) {
5359
- if (count <= 0) continue;
5360
- if (count >= Number(cidr.size)) {
5417
+ for (const { cidr, count: count2 } of usablePlans) {
5418
+ if (count2 <= 0) continue;
5419
+ if (count2 >= Number(cidr.size)) {
5361
5420
  for (let i = 0n; i < cidr.size; i++) {
5362
5421
  const value = cidr.base + i;
5363
5422
  out.push(family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
5364
5423
  }
5365
5424
  continue;
5366
5425
  }
5367
- const step = Math.floor(Number(cidr.size) / count);
5368
- for (let i = 0; i < count; i++) {
5426
+ const step = Math.floor(Number(cidr.size) / count2);
5427
+ for (let i = 0; i < count2; i++) {
5369
5428
  const jitter = Math.floor(random() * step);
5370
5429
  let offsetValue = BigInt(i * step + jitter);
5371
5430
  if (offsetValue >= cidr.size) offsetValue = cidr.size - 1n;
@@ -5384,9 +5443,9 @@ function expandCidrs(cidrs, options = {}) {
5384
5443
  }
5385
5444
  return out;
5386
5445
  }
5387
- function readIpFile(text) {
5446
+ function readIpFile(text2) {
5388
5447
  const out = [];
5389
- for (const raw of text.split(/\r?\n/)) {
5448
+ for (const raw of text2.split(/\r?\n/)) {
5390
5449
  let line = raw.trim();
5391
5450
  if (!line || line.startsWith("#")) continue;
5392
5451
  if (line.includes(",")) line = line.split(",")[0].trim();
@@ -5500,14 +5559,14 @@ function isPortListening(port, timeoutMs = 400) {
5500
5559
  return new Promise((resolve3) => {
5501
5560
  const socket = new net3.Socket();
5502
5561
  let settled = false;
5503
- const done = (open) => {
5562
+ const done = (open2) => {
5504
5563
  if (settled) return;
5505
5564
  settled = true;
5506
5565
  try {
5507
5566
  socket.destroy();
5508
5567
  } catch {
5509
5568
  }
5510
- resolve3(open);
5569
+ resolve3(open2);
5511
5570
  };
5512
5571
  socket.setTimeout(timeoutMs, () => done(false));
5513
5572
  socket.once("connect", () => done(true));
@@ -5642,6 +5701,252 @@ var init_net_env = __esm({
5642
5701
  }
5643
5702
  });
5644
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
+
5645
5950
  // src/scan/candidates.ts
5646
5951
  function normalizeCidrInput(cidr) {
5647
5952
  if (cidr === void 0) return [];
@@ -5683,11 +5988,133 @@ async function resolveCandidates(opts = {}) {
5683
5988
  const family = opts.family ?? "both";
5684
5989
  const neutral = opts.neutral === true;
5685
5990
  const customCidrs = normalizeCidrInput(opts.cidr);
5686
- if (customCidrs.length > 0) {
5687
- return expandCidrs(filterByFamily(customCidrs, family), { sample, seed, neutral });
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
+ }
5688
6108
  }
5689
- const cidrs = await loadCloudflareCidrs(family);
5690
- return expandCidrs(cidrs, { sample, seed, neutral });
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
+ }
6116
+ }
6117
+ return out;
5691
6118
  }
5692
6119
  function randomSeed() {
5693
6120
  return (Date.now() ^ Math.floor(Math.random() * 4294967296)) >>> 0;
@@ -5710,14 +6137,18 @@ function normalizeCandidateList(input) {
5710
6137
  }
5711
6138
  return out;
5712
6139
  }
5713
- var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE;
6140
+ var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE, LEARN_PRIOR_ALPHA, LEARN_PRIOR_BETA, LEARN_PRIOR_TOTAL;
5714
6141
  var init_candidates = __esm({
5715
6142
  "src/scan/candidates.ts"() {
5716
6143
  "use strict";
5717
6144
  init_ip_ranges();
5718
6145
  init_net_env();
6146
+ init_network_profile();
5719
6147
  DEFAULT_CANDIDATE_SAMPLE = 2e4;
5720
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;
5721
6152
  }
5722
6153
  });
5723
6154
 
@@ -5821,9 +6252,9 @@ async function readBody(req) {
5821
6252
  for await (const chunk of req) chunks.push(chunk);
5822
6253
  return Buffer.concat(chunks).toString("utf8");
5823
6254
  }
5824
- function parseStartScanRequest(text) {
6255
+ function parseStartScanRequest(text2) {
5825
6256
  try {
5826
- const raw = JSON.parse(text || "{}");
6257
+ const raw = JSON.parse(text2 || "{}");
5827
6258
  if (typeof raw !== "object" || raw === null) return null;
5828
6259
  return raw;
5829
6260
  } catch {
@@ -6113,7 +6544,7 @@ scan \u9009\u9879:
6113
6544
  url = \u53EA\u7528\u516C\u5F00\u6D4B\u901F\u5730\u5740\uFF08\u4EFB\u4F55\u9879\u76EE\u90FD\u80FD\u6D4B\uFF09
6114
6545
  --speed-url <url> \u516C\u5F00\u6D4B\u901F\u5730\u5740\uFF0C\u9ED8\u8BA4 ${DEFAULT_SPEED_URL}
6115
6546
  \u53EF\u6362\u6210\u4EFB\u610F\u8FD4\u56DE\u5927\u6587\u4EF6\u7684\u5730\u5740
6116
- --speed-conns <n> \u6D4B\u901F\u5E76\u53D1\u8FDE\u63A5\u6570\uFF0C\u9ED8\u8BA4 8
6547
+ --speed-conns <n> \u6D4B\u901F\u5E76\u53D1\u8FDE\u63A5\u6570\uFF0C\u9ED8\u8BA4 8\uFF0C\u6700\u5927 16
6117
6548
  \u8DE8\u5883\u94FE\u8DEF\u5355\u6761 TCP \u53D7\u4E22\u5305 / \u62E5\u585E\u7A97\u53E3\u9650\u5236\u3002\u5B9E\u6D4B\u540C\u4E00\u4E2A IP\uFF1A
6118
6549
  1 \u6761 0.12 MB/s\u30013 \u6761 0.47\u30018 \u6761 1.15\u300116 \u6761 2.22 \u2014\u2014
6119
6550
  \u7528 1~3 \u6761\u4F1A\u7CFB\u7EDF\u6027\u4F4E\u4F30 2~4 \u500D\uFF1B8 \u6761\u66F4\u8D34\u8FD1\u6D4F\u89C8\u5668\u771F\u5B9E\u884C\u4E3A
@@ -6171,6 +6602,18 @@ scan \u9009\u9879:
6171
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
6172
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
6173
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
6174
6617
  --json \u4EE5 JSON \u8F93\u51FA\u7ED3\u679C
6175
6618
  --quiet \u4EC5\u8F93\u51FA\u7ED3\u679C
6176
6619
 
@@ -6191,6 +6634,7 @@ __export(command_exports2, {
6191
6634
  runScanCommand: () => runScanCommand
6192
6635
  });
6193
6636
  import { readFileSync as readFileSync2 } from "node:fs";
6637
+ import { join as join3 } from "node:path";
6194
6638
  function normalizeWsPath(raw, fallback) {
6195
6639
  const value = (raw ?? fallback).trim();
6196
6640
  if (!value) return fallback;
@@ -6223,13 +6667,31 @@ function normalizeWsPath(raw, fallback) {
6223
6667
  function seedFromArgs(args) {
6224
6668
  return args.flags["seed"] !== void 0 ? flagNumber(args, "seed", 24301) : void 0;
6225
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
+ }
6226
6688
  async function resolveCandidatesFromArgs(args) {
6227
6689
  const ipFile = flagString(args, "ip-file");
6228
6690
  if (ipFile) {
6229
- const text = readFileSync2(ipFile, "utf8");
6230
- return readIpFile(text);
6691
+ const text2 = readFileSync2(ipFile, "utf8");
6692
+ return readIpFile(text2);
6231
6693
  }
6232
- return resolveCandidates({
6694
+ const base = {
6233
6695
  // 选国家时**自动中性采样**:采样发生在阶段一之前、那时还不知道机房,
6234
6696
  // 若某国家的 IP 集中在低权重网段,候选会被压少 → 可能「扫了几千个还是找不到 HKG/NRT」。
6235
6697
  neutral: args.flags["neutral-sampling"] !== void 0 || flagList(args, "countries").length > 0,
@@ -6238,7 +6700,40 @@ async function resolveCandidatesFromArgs(args) {
6238
6700
  // ⚠️ 不传 seed = 每次随机(默认)。只有用户显式给了 --seed 才固定,
6239
6701
  // 否则「每次跑都测同一批 IP」——那批落在劣质路由段上时永远测不出好 IP。
6240
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
+ }
6241
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);
6242
6737
  }
6243
6738
  function printProgress(event, quiet) {
6244
6739
  if (quiet) return;
@@ -6276,10 +6771,10 @@ function printTable(entries) {
6276
6771
  const rank = String(index + 1).padStart(2, " ");
6277
6772
  const address = `${formatHost(entry.ip)}:${entry.port}`.padEnd(24, " ");
6278
6773
  const colo = (entry.colo || "UNK").padEnd(6, " ");
6279
- const tls4 = String(entry.tlsMs).padStart(7, " ");
6774
+ const tls6 = String(entry.tlsMs).padStart(7, " ");
6280
6775
  const latency = String(entry.latency).padStart(7, " ");
6281
6776
  const speed = entry.speed.toFixed(1).padStart(9, " ");
6282
- process.stdout.write(`${rank} ${address} ${colo} ${tls4} ${latency} ${speed}
6777
+ process.stdout.write(`${rank} ${address} ${colo} ${tls6} ${latency} ${speed}
6283
6778
  `);
6284
6779
  });
6285
6780
  const seen = [];
@@ -6516,6 +7011,7 @@ ${NAME} v${VERSION}
6516
7011
  top,
6517
7012
  onProgress: (event) => printProgress(event, quiet)
6518
7013
  });
7014
+ await saveAdaptiveObservations(args, summary.observations);
6519
7015
  if (asJson) {
6520
7016
  process.stdout.write(
6521
7017
  `${JSON.stringify(
@@ -6537,7 +7033,14 @@ ${NAME} v${VERSION}
6537
7033
  speedBytes: flagNumber(args, "speed-bytes", 5 * 1024 * 1024),
6538
7034
  skipSpeed,
6539
7035
  verifyPayload,
6540
- 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
6541
7044
  },
6542
7045
  env: envResult,
6543
7046
  stats: summary.stats,
@@ -6630,6 +7133,7 @@ async function promptCallback(entries, dataHost, panelHost, panelPassword) {
6630
7133
  process.stdout.write("\u2192 \u53EF\u624B\u52A8\u590D\u5236\u4E0A\u9762\u7684 IP \u5217\u8868\u7C98\u8D34\u5230\u9762\u677F\n");
6631
7134
  }
6632
7135
  }
7136
+ var adaptiveContexts;
6633
7137
  var init_command2 = __esm({
6634
7138
  "src/scan/command.ts"() {
6635
7139
  "use strict";
@@ -6639,11 +7143,14 @@ var init_command2 = __esm({
6639
7143
  init_scan();
6640
7144
  init_callback();
6641
7145
  init_candidates();
7146
+ init_network_profile();
7147
+ init_store();
6642
7148
  init_net_env();
6643
7149
  init_version();
6644
7150
  init_help2();
6645
7151
  init_speed_url();
6646
7152
  init_ip_ranges();
7153
+ adaptiveContexts = /* @__PURE__ */ new WeakMap();
6647
7154
  }
6648
7155
  });
6649
7156
 
@@ -7324,14 +7831,14 @@ async function runSingleTest(options) {
7324
7831
  const tcp = await probeTcp(ip, port, timeoutMs);
7325
7832
  push(tcp);
7326
7833
  if (!tcp.ok) return results;
7327
- const tls4 = await probeTlsHandshake(ip, port, host, timeoutMs);
7328
- const tlsOk = tls4.tlsMs >= 0 && !tls4.error;
7834
+ const tls6 = await probeTlsHandshake(ip, port, host, timeoutMs);
7835
+ const tlsOk = tls6.tlsMs >= 0 && !tls6.error;
7329
7836
  push({
7330
7837
  stage: "TLS \u63E1\u624B",
7331
7838
  ok: tlsOk,
7332
- ms: tls4.tlsMs >= 0 ? tls4.tlsMs : void 0,
7333
- detail: tls4.alpn ? `ALPN=${tls4.alpn}` : void 0,
7334
- error: tlsOk ? void 0 : tls4.error ?? "\u63E1\u624B\u5931\u8D25"
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"
7335
7842
  });
7336
7843
  if (!tlsOk) return results;
7337
7844
  const ws = await probeWs101(ip, port, host, timeoutMs, path);
@@ -7515,6 +8022,527 @@ ${NAME} test \u2014\u2014 \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u
7515
8022
  }
7516
8023
  });
7517
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
+
7518
8546
  // src/deploy/token-command.ts
7519
8547
  var token_command_exports = {};
7520
8548
  __export(token_command_exports, {
@@ -7582,10 +8610,10 @@ __export(command_exports3, {
7582
8610
  });
7583
8611
  import { spawn } from "node:child_process";
7584
8612
  import { existsSync as existsSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
7585
- import { dirname as dirname2, resolve as resolve2 } from "node:path";
8613
+ import { dirname as dirname3, resolve as resolve2 } from "node:path";
7586
8614
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7587
8615
  function loadScript() {
7588
- const here = dirname2(fileURLToPath2(import.meta.url));
8616
+ const here = dirname3(fileURLToPath2(import.meta.url));
7589
8617
  const candidates = [
7590
8618
  resolve2(here, "../assets/vps-socks5.sh"),
7591
8619
  resolve2(here, "../../assets/vps-socks5.sh")
@@ -7623,7 +8651,7 @@ ssh \u542F\u52A8\u5931\u8D25\uFF1A${err.message}
7623
8651
  }
7624
8652
  async function runVpsCommand(args) {
7625
8653
  if (flagBool(args, "h") || flagBool(args, "help")) {
7626
- process.stdout.write(HELP2);
8654
+ process.stdout.write(HELP4);
7627
8655
  return;
7628
8656
  }
7629
8657
  const port = flagNumber(args, "port", 0);
@@ -7670,13 +8698,13 @@ async function runVpsCommand(args) {
7670
8698
  `
7671
8699
  );
7672
8700
  }
7673
- var HELP2;
8701
+ var HELP4;
7674
8702
  var init_command3 = __esm({
7675
8703
  "src/vps/command.ts"() {
7676
8704
  "use strict";
7677
8705
  init_args();
7678
8706
  init_version();
7679
- HELP2 = `
8707
+ HELP4 = `
7680
8708
  ${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5 \u843D\u5730\u4EE3\u7406
7681
8709
 
7682
8710
  \u7528\u6CD5:
@@ -7709,7 +8737,7 @@ ${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5
7709
8737
  // src/cli.ts
7710
8738
  init_args();
7711
8739
  init_version();
7712
- var HELP3 = `
8740
+ var HELP5 = `
7713
8741
  ${NAME} v${VERSION}
7714
8742
  Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
7715
8743
 
@@ -7718,6 +8746,8 @@ Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
7718
8746
  ${NAME} deploy [\u9009\u9879] \u90E8\u7F72 Pages \u53CC\u9879\u76EE
7719
8747
  ${NAME} scan [\u9009\u9879] \u672C\u5730\u771F\u8FDE\u63A5\u4F18\u9009
7720
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
7721
8751
  ${NAME} status \u67E5\u770B\u5F53\u524D\u5B9E\u4F8B\u72B6\u6001
7722
8752
  ${NAME} token [\u9009\u9879] \u68C0\u67E5 API Token \u6743\u9650
7723
8753
  ${NAME} vps [\u9009\u9879] \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5 \u843D\u5730\u4EE3\u7406
@@ -7743,11 +8773,11 @@ async function main() {
7743
8773
  return;
7744
8774
  }
7745
8775
  if (!command && (flagBool(args, "h") || flagBool(args, "help"))) {
7746
- process.stdout.write(HELP3);
8776
+ process.stdout.write(HELP5);
7747
8777
  return;
7748
8778
  }
7749
8779
  if (command === "help") {
7750
- process.stdout.write(HELP3);
8780
+ process.stdout.write(HELP5);
7751
8781
  return;
7752
8782
  }
7753
8783
  switch (command) {
@@ -7772,6 +8802,16 @@ async function main() {
7772
8802
  await runTestCommand2(args);
7773
8803
  return;
7774
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
+ }
7775
8815
  case "status": {
7776
8816
  const { runStatus: runStatus2 } = await Promise.resolve().then(() => (init_status(), status_exports));
7777
8817
  await runStatus2();
@@ -7796,7 +8836,7 @@ async function main() {
7796
8836
  process.stderr.write(`\u672A\u77E5\u547D\u4EE4\uFF1A${command}
7797
8837
 
7798
8838
  `);
7799
- process.stderr.write(HELP3);
8839
+ process.stderr.write(HELP5);
7800
8840
  process.exitCode = 1;
7801
8841
  }
7802
8842
  }