cfpilot 0.15.7 → 0.15.8

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,7 +87,7 @@ var VERSION, NAME;
87
87
  var init_version = __esm({
88
88
  "src/shared/version.ts"() {
89
89
  "use strict";
90
- VERSION = "0.15.7";
90
+ VERSION = "0.15.8";
91
91
  NAME = "cfpilot";
92
92
  }
93
93
  });
@@ -1115,9 +1115,9 @@ var init_account_resolve = __esm({
1115
1115
  import { randomBytes } from "node:crypto";
1116
1116
  function randomAlnum(length) {
1117
1117
  const bytes = randomBytes(length);
1118
- let out = "";
1119
- for (const byte of bytes) out += ALPHABET[byte % ALPHABET.length];
1120
- return out;
1118
+ let out2 = "";
1119
+ for (const byte of bytes) out2 += ALPHABET[byte % ALPHABET.length];
1120
+ return out2;
1121
1121
  }
1122
1122
  function randomPassword() {
1123
1123
  return `cfp-${randomAlnum(14)}`;
@@ -1933,7 +1933,7 @@ async function readBodyWithLimit(response) {
1933
1933
  const reader = body.getReader();
1934
1934
  const decoder = new TextDecoder();
1935
1935
  let total = 0;
1936
- let out = "";
1936
+ let out2 = "";
1937
1937
  try {
1938
1938
  for (; ; ) {
1939
1939
  const { done, value } = await reader.read();
@@ -1945,27 +1945,27 @@ async function readBodyWithLimit(response) {
1945
1945
  await reader.cancel().catch(() => void 0);
1946
1946
  throw new Error(`\u5185\u6838\u4EA7\u7269\u8D85\u8FC7 ${MAX_ASSET_BYTES} \u5B57\u8282\u4E0A\u9650\uFF0C\u7591\u4F3C\u5F02\u5E38\u5185\u5BB9`);
1947
1947
  }
1948
- out += decoder.decode(chunk, { stream: true });
1948
+ out2 += decoder.decode(chunk, { stream: true });
1949
1949
  }
1950
1950
  } finally {
1951
1951
  reader.releaseLock();
1952
1952
  }
1953
- out += decoder.decode();
1954
- return out;
1953
+ out2 += decoder.decode();
1954
+ return out2;
1955
1955
  }
1956
1956
  function sha256Hex(content) {
1957
1957
  return createHash("sha256").update(content, "utf8").digest("hex");
1958
1958
  }
1959
1959
  function parseChecksums(text2) {
1960
- const out = /* @__PURE__ */ new Map();
1960
+ const out2 = /* @__PURE__ */ new Map();
1961
1961
  for (const raw of text2.split("\n")) {
1962
1962
  const line = raw.trim();
1963
1963
  if (!line || line.startsWith("#")) continue;
1964
1964
  const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line);
1965
1965
  if (!match) continue;
1966
- out.set(match[2].trim().toLowerCase(), match[1].toLowerCase());
1966
+ out2.set(match[2].trim().toLowerCase(), match[1].toLowerCase());
1967
1967
  }
1968
- return out;
1968
+ return out2;
1969
1969
  }
1970
1970
  async function downloadChecksums(info, timeoutMs) {
1971
1971
  if (!info.checksumsUrl.trim()) {
@@ -2180,7 +2180,7 @@ async function readManifest(client, accountId, namespaceId) {
2180
2180
  }
2181
2181
  async function listCfPilotNamespaces(client, accountId) {
2182
2182
  const namespaces = await client.listKvNamespaces(accountId);
2183
- const out = [];
2183
+ const out2 = [];
2184
2184
  for (const ns of namespaces) {
2185
2185
  let manifest = null;
2186
2186
  try {
@@ -2188,9 +2188,9 @@ async function listCfPilotNamespaces(client, accountId) {
2188
2188
  } catch {
2189
2189
  continue;
2190
2190
  }
2191
- if (manifest) out.push({ id: ns.id, title: ns.title, manifest });
2191
+ if (manifest) out2.push({ id: ns.id, title: ns.title, manifest });
2192
2192
  }
2193
- return out;
2193
+ return out2;
2194
2194
  }
2195
2195
  async function writeManifest(client, accountId, namespaceId, manifest) {
2196
2196
  try {
@@ -2850,9 +2850,9 @@ async function deployPagesSplit(options) {
2850
2850
  function randomSuffix(length) {
2851
2851
  const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789";
2852
2852
  const bytes = randomBytes2(length);
2853
- let out = "";
2854
- for (const byte of bytes) out += alphabet[byte % alphabet.length];
2855
- return out;
2853
+ let out2 = "";
2854
+ for (const byte of bytes) out2 += alphabet[byte % alphabet.length];
2855
+ return out2;
2856
2856
  }
2857
2857
  async function configureProject(client, accountId, project, label, result, options, log, warnings, effective) {
2858
2858
  const kvBindings = {
@@ -3667,9 +3667,9 @@ function isKnownCountry(code) {
3667
3667
  }
3668
3668
  function normalizeCountryFilter(input) {
3669
3669
  if (!Array.isArray(input)) return [];
3670
- const out = [];
3670
+ const out2 = [];
3671
3671
  const push = (code) => {
3672
- if (code && !out.includes(code)) out.push(code);
3672
+ if (code && !out2.includes(code)) out2.push(code);
3673
3673
  };
3674
3674
  for (const raw of input) {
3675
3675
  const code = String(raw ?? "").trim().toUpperCase();
@@ -3685,7 +3685,7 @@ function normalizeCountryFilter(input) {
3685
3685
  const country = countryOfColo(code);
3686
3686
  if (country) push(country);
3687
3687
  }
3688
- return out;
3688
+ return out2;
3689
3689
  }
3690
3690
  function coloCity(colo) {
3691
3691
  return COLO_CITIES[colo.toUpperCase()] ?? "";
@@ -4681,13 +4681,13 @@ function ipv6Prefix48(cidr) {
4681
4681
  return `${groups[0]}:${groups[1]}:${groups[2]}::/48`;
4682
4682
  }
4683
4683
  function buildWeightEntries(src, family) {
4684
- const out = [];
4684
+ const out2 = [];
4685
4685
  for (const [cidr, weight] of Object.entries(src)) {
4686
4686
  const parsed = parseCidr(cidr);
4687
4687
  if (!parsed || parsed.family !== family) continue;
4688
- out.push({ base: parsed.base, prefix: parsed.prefix, weight });
4688
+ out2.push({ base: parsed.base, prefix: parsed.prefix, weight });
4689
4689
  }
4690
- return out;
4690
+ return out2;
4691
4691
  }
4692
4692
  function lpmWeight(table, parsed, bits, fallback) {
4693
4693
  let bestPrefix = -1;
@@ -4850,23 +4850,23 @@ function splitByWeight(cidr, weightFn = cidrWeight) {
4850
4850
  }
4851
4851
  return false;
4852
4852
  };
4853
- const out = [];
4853
+ const out2 = [];
4854
4854
  const stack = [{ c: cidr }];
4855
4855
  while (stack.length > 0) {
4856
4856
  const item = stack.pop();
4857
4857
  const c2 = item.c;
4858
4858
  const weight = item.known ?? weightFn(c2.cidr);
4859
4859
  if (c2.prefix >= maxPrefix) {
4860
- out.push(c2);
4860
+ out2.push(c2);
4861
4861
  continue;
4862
4862
  }
4863
4863
  if (cidr.family === 6) {
4864
4864
  if (weight > 0) {
4865
- out.push(c2);
4865
+ out2.push(c2);
4866
4866
  continue;
4867
4867
  }
4868
4868
  if (!v6HasEntryInside(c2)) {
4869
- out.push(c2);
4869
+ out2.push(c2);
4870
4870
  continue;
4871
4871
  }
4872
4872
  }
@@ -4880,12 +4880,12 @@ function splitByWeight(cidr, weightFn = cidrWeight) {
4880
4880
  const lw = weightFn(left.cidr);
4881
4881
  const rw = weightFn(right.cidr);
4882
4882
  if (cidr.family === 4 && lw === rw) {
4883
- out.push(c2);
4883
+ out2.push(c2);
4884
4884
  continue;
4885
4885
  }
4886
4886
  stack.push({ c: left, known: lw }, { c: right, known: rw });
4887
4887
  }
4888
- return out.sort((a, b) => a.base < b.base ? -1 : a.base > b.base ? 1 : 0);
4888
+ return out2.sort((a, b) => a.base < b.base ? -1 : a.base > b.base ? 1 : 0);
4889
4889
  }
4890
4890
  function expandCidrs(cidrs, options = {}) {
4891
4891
  const neutral = options.neutral === true;
@@ -4908,7 +4908,7 @@ function expandCidrs(cidrs, options = {}) {
4908
4908
  return all;
4909
4909
  }
4910
4910
  const minPerCidr = sample <= 1e3 ? 1 : 64;
4911
- const out = [];
4911
+ const out2 = [];
4912
4912
  for (const family of [4, 6]) {
4913
4913
  const group = parsed.filter((c2) => c2.family === family);
4914
4914
  if (group.length === 0) continue;
@@ -4959,7 +4959,7 @@ function expandCidrs(cidrs, options = {}) {
4959
4959
  if (count2 >= Number(cidr.size)) {
4960
4960
  for (let i = 0n; i < cidr.size; i++) {
4961
4961
  const value = cidr.base + i;
4962
- out.push(family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
4962
+ out2.push(family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
4963
4963
  }
4964
4964
  continue;
4965
4965
  }
@@ -4977,11 +4977,11 @@ function expandCidrs(cidrs, options = {}) {
4977
4977
  value = cidr.base + offsetValue;
4978
4978
  }
4979
4979
  }
4980
- out.push(cidr.family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
4980
+ out2.push(cidr.family === 4 ? bigIntToIpv4(value) : bigIntToIpv6(value));
4981
4981
  }
4982
4982
  }
4983
4983
  }
4984
- return out;
4984
+ return out2;
4985
4985
  }
4986
4986
  function looksLikeIpLiteral(rawValue) {
4987
4987
  if (!rawValue) return false;
@@ -4998,7 +4998,7 @@ function looksLikeIpLiteral(rawValue) {
4998
4998
  return false;
4999
4999
  }
5000
5000
  function readIpFile(text2) {
5001
- const out = [];
5001
+ const out2 = [];
5002
5002
  for (const raw of text2.split(/\r?\n/)) {
5003
5003
  let line = raw.trim();
5004
5004
  if (!line || line.startsWith("#")) continue;
@@ -5017,21 +5017,21 @@ function readIpFile(text2) {
5017
5017
  if (/\s/.test(line)) continue;
5018
5018
  const bracket = /^\[([^\]]+)\](?::\d+)?$/.exec(line);
5019
5019
  if (bracket) {
5020
- out.push(bracket[1]);
5020
+ out2.push(bracket[1]);
5021
5021
  continue;
5022
5022
  }
5023
5023
  if (line.includes(":") && line.split(":").length > 2) {
5024
- out.push(line);
5024
+ out2.push(line);
5025
5025
  continue;
5026
5026
  }
5027
5027
  if (line.includes(":")) {
5028
5028
  const [host] = line.split(":");
5029
- if (host) out.push(host);
5029
+ if (host) out2.push(host);
5030
5030
  continue;
5031
5031
  }
5032
- out.push(line);
5032
+ out2.push(line);
5033
5033
  }
5034
- return out;
5034
+ return out2;
5035
5035
  }
5036
5036
  async function readIpUrl(rawUrl, timeoutMs = IP_URL_TIMEOUT_MS, maxBytes = IP_URL_MAX_BYTES) {
5037
5037
  const trimmed = rawUrl.trim();
@@ -5241,28 +5241,28 @@ async function tcpPing(ip, port, timeoutMs) {
5241
5241
  });
5242
5242
  }
5243
5243
  async function pool(items, concurrency, worker, shouldStop) {
5244
- const out = new Array(items.length);
5244
+ const out2 = new Array(items.length);
5245
5245
  let cursor = 0;
5246
5246
  const runners = Array.from({ length: Math.max(1, Math.min(concurrency, items.length)) }, async () => {
5247
5247
  for (; ; ) {
5248
5248
  if (shouldStop?.()) return;
5249
5249
  const index = cursor++;
5250
5250
  if (index >= items.length) return;
5251
- out[index] = await worker(items[index], index);
5251
+ out2[index] = await worker(items[index], index);
5252
5252
  }
5253
5253
  });
5254
5254
  await Promise.all(runners);
5255
- return out;
5255
+ return out2;
5256
5256
  }
5257
5257
  async function poolAdaptive(items, concurrency, worker, batchSize = 200) {
5258
- const out = [];
5258
+ const out2 = [];
5259
5259
  const maxConcurrency = Math.max(1, concurrency);
5260
5260
  const minConcurrency = Math.min(8, maxConcurrency);
5261
5261
  let current = maxConcurrency;
5262
5262
  for (let start = 0; start < items.length; start += batchSize) {
5263
5263
  const batch = items.slice(start, start + batchSize);
5264
5264
  const results = await pool(batch, current, worker);
5265
- out.push(...results);
5265
+ out2.push(...results);
5266
5266
  const okCount = results.reduce((n, r) => n + (r.ok ? 1 : 0), 0);
5267
5267
  const rate2 = results.length > 0 ? okCount / results.length : 1;
5268
5268
  if (rate2 < 0.4) {
@@ -5271,7 +5271,7 @@ async function poolAdaptive(items, concurrency, worker, batchSize = 200) {
5271
5271
  current = Math.min(maxConcurrency, current * 2);
5272
5272
  }
5273
5273
  }
5274
- return out;
5274
+ return out2;
5275
5275
  }
5276
5276
  function isTimeoutError(error) {
5277
5277
  if (!error) return false;
@@ -5792,20 +5792,20 @@ function roundRobinBy(ranked, top, keyOf) {
5792
5792
  }
5793
5793
  if (buckets.size <= 1) return ranked.slice(0, top);
5794
5794
  const groups = [...buckets.values()];
5795
- const out = [];
5796
- for (let round = 0; out.length < top; round++) {
5795
+ const out2 = [];
5796
+ for (let round = 0; out2.length < top; round++) {
5797
5797
  let pickedAny = false;
5798
5798
  for (const group of groups) {
5799
- if (out.length >= top) break;
5799
+ if (out2.length >= top) break;
5800
5800
  const item = group[round];
5801
5801
  if (item) {
5802
- out.push(item);
5802
+ out2.push(item);
5803
5803
  pickedAny = true;
5804
5804
  }
5805
5805
  }
5806
5806
  if (!pickedAny) break;
5807
5807
  }
5808
- return out;
5808
+ return out2;
5809
5809
  }
5810
5810
  var COARSE_SPEED_DEFAULTS;
5811
5811
  var init_scan = __esm({
@@ -6239,10 +6239,10 @@ function adaptivePool(cidrs, limit, includeZero, neutral, random, store, options
6239
6239
  const exploreBudgetCount = exploreBudget(budget, explorationRate);
6240
6240
  let capPerPrefix = prefixCap(budget);
6241
6241
  const byPrefix = /* @__PURE__ */ new Map();
6242
- const out = [];
6242
+ const out2 = [];
6243
6243
  const capacityOf = (bucket) => bucket.capacity - bucket.used;
6244
- while (out.length < budget) {
6245
- const isExplore = out.length < exploreBudgetCount;
6244
+ while (out2.length < budget) {
6245
+ const isExplore = out2.length < exploreBudgetCount;
6246
6246
  const weights = [];
6247
6247
  let totalWeight = 0;
6248
6248
  for (const bucket2 of pool2) {
@@ -6306,9 +6306,9 @@ function adaptivePool(cidrs, limit, includeZero, neutral, random, store, options
6306
6306
  bucket.used++;
6307
6307
  const prefixKey = `${bucket.family}:${bucket.family24}`;
6308
6308
  byPrefix.set(prefixKey, (byPrefix.get(prefixKey) ?? 0) + 1);
6309
- out.push({ ip: format(address, bucket.family), staticWeight: bucket.staticWeight });
6309
+ out2.push({ ip: format(address, bucket.family), staticWeight: bucket.staticWeight });
6310
6310
  }
6311
- return out;
6311
+ return out2;
6312
6312
  }
6313
6313
  const v4Pool = buckets.filter((bucket) => bucket.family === 4);
6314
6314
  const v6Pool = buckets.filter((bucket) => bucket.family === 6);
@@ -6664,15 +6664,15 @@ async function probeDefaultRoute(timeoutMs = 800) {
6664
6664
  });
6665
6665
  try {
6666
6666
  if (platform === "win32") {
6667
- const out2 = await run("route", ["print", "-6"]);
6668
- return out2.includes("::/0");
6667
+ const out3 = await run("route", ["print", "-6"]);
6668
+ return out3.includes("::/0");
6669
6669
  }
6670
6670
  if (platform === "darwin") {
6671
- const out2 = await run("netstat", ["-rn", "-f", "inet6"]);
6672
- return /^default\b/m.test(out2);
6671
+ const out3 = await run("netstat", ["-rn", "-f", "inet6"]);
6672
+ return /^default\b/m.test(out3);
6673
6673
  }
6674
- const out = await run("ip", ["-6", "route", "show", "default"]);
6675
- return /^default\b/m.test(out);
6674
+ const out2 = await run("ip", ["-6", "route", "show", "default"]);
6675
+ return /^default\b/m.test(out2);
6676
6676
  } catch {
6677
6677
  return null;
6678
6678
  }
@@ -6811,7 +6811,7 @@ import net5 from "node:net";
6811
6811
  function normalizeCidrInput(cidr) {
6812
6812
  if (cidr === void 0) return [];
6813
6813
  const list = Array.isArray(cidr) ? cidr : [cidr];
6814
- const out = [];
6814
+ const out2 = [];
6815
6815
  const rejected = [];
6816
6816
  for (const item of list) {
6817
6817
  if (typeof item !== "string") continue;
@@ -6819,7 +6819,7 @@ function normalizeCidrInput(cidr) {
6819
6819
  const value = part.trim();
6820
6820
  if (!value) continue;
6821
6821
  const normalized = withDefaultPrefix(value);
6822
- if (parseCidr(normalized)) out.push(normalized);
6822
+ if (parseCidr(normalized)) out2.push(normalized);
6823
6823
  else rejected.push(value);
6824
6824
  }
6825
6825
  }
@@ -6830,7 +6830,7 @@ function normalizeCidrInput(cidr) {
6830
6830
  `\u65E0\u6CD5\u8BC6\u522B\u7684\u7F51\u6BB5/IP\uFF1A${head}${more}\u3002\u6B63\u786E\u5199\u6CD5\u662F 1.2.3.4\u30011.2.3.0/24\u30012606:4700::1 \u6216 2606:4700::/48`
6831
6831
  );
6832
6832
  }
6833
- return out;
6833
+ return out2;
6834
6834
  }
6835
6835
  function withDefaultPrefix(value) {
6836
6836
  if (value.includes("/")) return value;
@@ -6860,7 +6860,7 @@ async function loadCloudflareCidrs(family) {
6860
6860
  return [...ipv4, ...ipv6];
6861
6861
  }
6862
6862
  async function discoverIPv6Prefixes(hosts, timeoutMs = 6e3) {
6863
- const out = /* @__PURE__ */ new Set();
6863
+ const out2 = /* @__PURE__ */ new Set();
6864
6864
  for (const raw of hosts) {
6865
6865
  const host = String(raw ?? "").trim().toLowerCase().replace(/^https?:\/\//, "").replace(/\/.*$/, "");
6866
6866
  if (!host || net5.isIP(host)) continue;
@@ -6868,12 +6868,12 @@ async function discoverIPv6Prefixes(hosts, timeoutMs = 6e3) {
6868
6868
  const addresses = await withTimeout(resolve6(host), timeoutMs);
6869
6869
  for (const address of addresses) {
6870
6870
  const bucket = networkBucket(address);
6871
- if (bucket) out.add(bucket);
6871
+ if (bucket) out2.add(bucket);
6872
6872
  }
6873
6873
  } catch {
6874
6874
  }
6875
6875
  }
6876
- return [...out].sort();
6876
+ return [...out2].sort();
6877
6877
  }
6878
6878
  function withTimeout(promise, ms) {
6879
6879
  return new Promise((resolve4, reject) => {
@@ -6891,9 +6891,9 @@ function withTimeout(promise, ms) {
6891
6891
  });
6892
6892
  }
6893
6893
  function weightsOf(prefixes) {
6894
- const out = {};
6895
- for (const cidr of prefixes) out[cidr] = 1;
6896
- return out;
6894
+ const out2 = {};
6895
+ for (const cidr of prefixes) out2[cidr] = 1;
6896
+ return out2;
6897
6897
  }
6898
6898
  function pickCanary(pool2, extraWeights, seed) {
6899
6899
  try {
@@ -7007,7 +7007,7 @@ function normalizeCandidateList(input) {
7007
7007
  const lines = input.filter((item) => typeof item === "string");
7008
7008
  if (lines.length === 0) return [];
7009
7009
  const seen = /* @__PURE__ */ new Set();
7010
- const out = [];
7010
+ const out2 = [];
7011
7011
  for (const ip of readIpFile(lines.join("\n"))) {
7012
7012
  if (seen.has(ip)) continue;
7013
7013
  seen.add(ip);
@@ -7016,9 +7016,9 @@ function normalizeCandidateList(input) {
7016
7016
  if (isIpv4Literal || isIpv6Literal) {
7017
7017
  if (!isPublicAddress(ip)) continue;
7018
7018
  }
7019
- out.push(ip);
7019
+ out2.push(ip);
7020
7020
  }
7021
- return out;
7021
+ return out2;
7022
7022
  }
7023
7023
  var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE;
7024
7024
  var init_candidates = __esm({
@@ -7492,6 +7492,9 @@ scan \u9009\u9879:
7492
7492
  --cidr <a,b> \u81EA\u5B9A\u4E49\u7F51\u6BB5\uFF08\u53EF\u91CD\u590D\uFF0C\u7528\u9017\u53F7\u5206\u9694\uFF09
7493
7493
  --ip-file <path> \u4F7F\u7528\u672C\u5730 IP \u5217\u8868\u6587\u4EF6
7494
7494
  --ip-url <\u94FE\u63A5> \u4F7F\u7528\u8FDC\u7A0B IP \u5217\u8868\uFF08http/https\uFF0C\u4E0A\u9650 2MB\uFF0C\u4E0E --ip-file \u4E8C\u9009\u4E00\uFF09
7495
+ --from-pool \u4ECE\u672C\u5730\u5916\u90E8\u5019\u9009\u6C60\u5206\u5C42\u53D6\u6837\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF0C\u5173\u95ED\u65F6\u884C\u4E3A\u5B8C\u5168\u4E0D\u53D8\uFF09
7496
+ \u6C60\u7531 cfpilot source sync \u957F\u671F\u79EF\u7D2F\uFF1B\u53D6\u6837\u53EA\u53D6\u7AEF\u53E3 == --port \u7684\u6761\u76EE
7497
+ --pool-sample <n> --from-pool \u7684\u53D6\u6837\u4E0A\u9650\uFF0C\u9ED8\u8BA4 200\uFF08\u4E0D\u4F1A\u653E\u5927\u6D4B\u901F\u5E76\u53D1\uFF09
7495
7498
  --max-latency <ms> \u9636\u6BB5\u4E00 TCP \u5EF6\u8FDF\u4E0A\u9650\uFF0C\u9ED8\u8BA4 0\uFF08\u4E0D\u9650\uFF09
7496
7499
  --tls-timeout <ms> \u9636\u6BB5\u4E00 TLS \u63E1\u624B\u8D85\u65F6\uFF0C\u9ED8\u8BA4 2000
7497
7500
  \u8D85\u65F6\u4E0D\u518D\u91CD\u8BD5\uFF08\u8BE5 IP \u5728\u5F53\u524D\u7F51\u7EDC\u4E0B\u5C31\u662F\u4E0D\u53EF\u7528\uFF09
@@ -7622,6 +7625,430 @@ ${NAME} scan relay \u2014\u2014 \u53CD\u4EE3\u5165\u53E3\uFF08ProxyIP \u6C60\uFF
7622
7625
  }
7623
7626
  });
7624
7627
 
7628
+ // src/sources/pool.ts
7629
+ import {
7630
+ closeSync,
7631
+ existsSync as existsSync2,
7632
+ mkdirSync as mkdirSync2,
7633
+ openSync,
7634
+ readFileSync as readFileSync2,
7635
+ renameSync,
7636
+ statSync,
7637
+ unlinkSync,
7638
+ writeFileSync as writeFileSync2,
7639
+ writeSync
7640
+ } from "node:fs";
7641
+ import { homedir as homedir3 } from "node:os";
7642
+ import { isIP as isIP2 } from "node:net";
7643
+ import { join as join4 } from "node:path";
7644
+ import { randomUUID as randomUUID3 } from "node:crypto";
7645
+ function poolDir() {
7646
+ const override = process.env.CFPILOT_CONFIG_DIR?.trim();
7647
+ return override ? override : join4(homedir3(), ".cfpilot");
7648
+ }
7649
+ function poolPath() {
7650
+ return join4(poolDir(), POOL_FILENAME);
7651
+ }
7652
+ function poolLockPath() {
7653
+ return poolPath() + ".lock";
7654
+ }
7655
+ function normalizeCandidateKey(ip, port) {
7656
+ const clean = ip.trim();
7657
+ const family = isIP2(clean);
7658
+ if (family !== 4 && family !== 6) return null;
7659
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return null;
7660
+ return family === 6 ? `[${clean}]:${port}` : `${clean}:${port}`;
7661
+ }
7662
+ function isCloudflareEntryIp(ip) {
7663
+ const family = isIP2(ip.trim());
7664
+ if (family !== 4 && family !== 6) return false;
7665
+ const bits = family === 4 ? 32 : 128;
7666
+ const parsed = parseCidr(`${ip.trim()}/${bits}`);
7667
+ if (!parsed || parsed.family !== family) return false;
7668
+ const allOnes = (1n << BigInt(bits)) - 1n;
7669
+ const nets = family === 4 ? V4_NETS : V6_NETS;
7670
+ for (const net9 of nets) {
7671
+ const hostBits = bits - net9.prefix;
7672
+ const mask = allOnes << BigInt(hostBits) & allOnes;
7673
+ if ((parsed.base & mask) === net9.base) return true;
7674
+ }
7675
+ return false;
7676
+ }
7677
+ function emptyPool() {
7678
+ return { schema: POOL_SCHEMA, updatedAt: 0, candidates: [] };
7679
+ }
7680
+ function readPoolRaw() {
7681
+ try {
7682
+ return readFileSync2(poolPath(), "utf8");
7683
+ } catch {
7684
+ return "";
7685
+ }
7686
+ }
7687
+ function isValidCandidate(value) {
7688
+ if (!value || typeof value !== "object") return false;
7689
+ const c2 = value;
7690
+ if (typeof c2.key !== "string" || !c2.key || typeof c2.ip !== "string" || !c2.ip || !Number.isInteger(c2.port) || (c2.port ?? 0) < 1 || (c2.port ?? 0) > 65535 || c2.ipVersion !== 4 && c2.ipVersion !== 6 || c2.candidateType !== ENTRY_IP || !Array.isArray(c2.sources) || !c2.sources.every((s) => typeof s === "string") || typeof c2.firstSeen !== "number" || !Number.isFinite(c2.firstSeen) || c2.firstSeen < 0 || typeof c2.lastSeen !== "number" || !Number.isFinite(c2.lastSeen) || c2.lastSeen < 0 || typeof c2.status !== "string" || !c2.status || !isValidOptionalNumber(c2.failCount) || !isValidOptionalNumber(c2.successCount)) return false;
7691
+ if (c2.lightCheck !== null && c2.lightCheck !== void 0 && !isValidLightCheck(c2.lightCheck)) return false;
7692
+ if (c2.fullTest !== null && c2.fullTest !== void 0 && !isValidFullTest(c2.fullTest)) return false;
7693
+ return true;
7694
+ }
7695
+ function isValidOptionalNumber(v) {
7696
+ return v === void 0 || typeof v === "number" && Number.isFinite(v);
7697
+ }
7698
+ function isValidLightCheck(v) {
7699
+ if (!v || typeof v !== "object") return false;
7700
+ const x = v;
7701
+ return typeof x.tcpOk === "boolean" && typeof x.tlsOk === "boolean" && typeof x.at === "number" && (x.tlsMs === void 0 || typeof x.tlsMs === "number");
7702
+ }
7703
+ function isValidFullTest(v) {
7704
+ if (!v || typeof v !== "object") return false;
7705
+ const x = v;
7706
+ return (x.at === null || x.at === void 0 || typeof x.at === "number") && (x.wsOk === null || x.wsOk === void 0 || typeof x.wsOk === "boolean") && (x.speedMBps === null || x.speedMBps === void 0 || typeof x.speedMBps === "number") && (x.colo === null || x.colo === void 0 || typeof x.colo === "string");
7707
+ }
7708
+ function normalizeCandidate(value) {
7709
+ if (!isValidCandidate(value)) return null;
7710
+ const c2 = value;
7711
+ const lightCheck = c2.lightCheck ? {
7712
+ tcpOk: c2.lightCheck.tcpOk,
7713
+ tlsOk: c2.lightCheck.tlsOk,
7714
+ // tlsMs 是可选字段:位置必须排在 at 之前,与 Go struct 一致
7715
+ ...typeof c2.lightCheck.tlsMs === "number" ? { tlsMs: c2.lightCheck.tlsMs } : {},
7716
+ at: c2.lightCheck.at
7717
+ } : null;
7718
+ const fullTest = c2.fullTest ? {
7719
+ at: typeof c2.fullTest.at === "number" ? c2.fullTest.at : null,
7720
+ wsOk: typeof c2.fullTest.wsOk === "boolean" ? c2.fullTest.wsOk : null,
7721
+ speedMBps: typeof c2.fullTest.speedMBps === "number" ? c2.fullTest.speedMBps : null,
7722
+ colo: typeof c2.fullTest.colo === "string" ? c2.fullTest.colo : null
7723
+ } : null;
7724
+ return {
7725
+ key: c2.key,
7726
+ ip: c2.ip,
7727
+ port: c2.port,
7728
+ ipVersion: c2.ipVersion,
7729
+ candidateType: ENTRY_IP,
7730
+ sources: [...c2.sources],
7731
+ firstSeen: c2.firstSeen,
7732
+ lastSeen: c2.lastSeen,
7733
+ lightCheck,
7734
+ fullTest,
7735
+ status: c2.status,
7736
+ failCount: c2.failCount ?? 0,
7737
+ successCount: c2.successCount ?? 0
7738
+ };
7739
+ }
7740
+ function parsePool(raw) {
7741
+ if (!raw.trim()) return emptyPool();
7742
+ try {
7743
+ const obj = JSON.parse(raw);
7744
+ if (obj.schema !== POOL_SCHEMA) throw new Error(`schema ${String(obj.schema)} \u4E0D\u517C\u5BB9`);
7745
+ const list = Array.isArray(obj.candidates) ? obj.candidates : [];
7746
+ return {
7747
+ schema: POOL_SCHEMA,
7748
+ updatedAt: typeof obj.updatedAt === "number" ? obj.updatedAt : 0,
7749
+ // candidateType 隔离:异类型 / 结构损坏的条目直接丢弃,不进池
7750
+ candidates: list.map(normalizeCandidate).filter((c2) => c2 !== null)
7751
+ };
7752
+ } catch {
7753
+ const backup = `${poolPath()}.corrupt-${Date.now()}`;
7754
+ try {
7755
+ if (existsSync2(poolPath())) renameSync(poolPath(), backup);
7756
+ } catch {
7757
+ }
7758
+ return emptyPool();
7759
+ }
7760
+ }
7761
+ function serializePool(pool2) {
7762
+ return `${JSON.stringify(pool2, null, 2)}
7763
+ `;
7764
+ }
7765
+ function writePoolAtomic(text2) {
7766
+ const dir = poolDir();
7767
+ mkdirSync2(dir, { recursive: true, mode: 448 });
7768
+ const tmp = join4(dir, `${POOL_FILENAME}.${process.pid}.${randomUUID3()}.tmp`);
7769
+ try {
7770
+ writeFileSync2(tmp, text2, { mode: 384 });
7771
+ renameSync(tmp, poolPath());
7772
+ } catch (err) {
7773
+ try {
7774
+ unlinkSync(tmp);
7775
+ } catch {
7776
+ }
7777
+ throw err;
7778
+ }
7779
+ }
7780
+ async function acquirePoolLock() {
7781
+ mkdirSync2(poolDir(), { recursive: true, mode: 448 });
7782
+ const started = Date.now();
7783
+ for (; ; ) {
7784
+ try {
7785
+ const fd = openSync(poolLockPath(), "wx", 384);
7786
+ try {
7787
+ writeSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));
7788
+ } finally {
7789
+ closeSync(fd);
7790
+ }
7791
+ return;
7792
+ } catch (err) {
7793
+ const code = err.code;
7794
+ if (code !== "EEXIST") throw err;
7795
+ try {
7796
+ const st = statSync(poolLockPath());
7797
+ if (Date.now() - st.mtimeMs > LOCK_STALE_MS) {
7798
+ unlinkSync(poolLockPath());
7799
+ continue;
7800
+ }
7801
+ } catch {
7802
+ continue;
7803
+ }
7804
+ if (Date.now() - started > LOCK_TIMEOUT_MS) {
7805
+ throw new Error("\u672C\u5730\u5019\u9009\u6C60\u6B63\u88AB\u53E6\u4E00\u4E2A\u8FDB\u7A0B\u5360\u7528\uFF08\u9501\u8D85\u65F6\uFF09");
7806
+ }
7807
+ await sleep(LOCK_RETRY_MS);
7808
+ }
7809
+ }
7810
+ }
7811
+ function releasePoolLock() {
7812
+ try {
7813
+ unlinkSync(poolLockPath());
7814
+ } catch {
7815
+ }
7816
+ }
7817
+ async function withConfigDirLock(fn) {
7818
+ await acquirePoolLock();
7819
+ try {
7820
+ return await fn();
7821
+ } finally {
7822
+ releasePoolLock();
7823
+ }
7824
+ }
7825
+ async function withPool(fn) {
7826
+ return withConfigDirLock(async () => {
7827
+ const before = readPoolRaw();
7828
+ const pool2 = parsePool(before);
7829
+ const result = await fn(pool2);
7830
+ const after = serializePool(pool2);
7831
+ if (after !== before) writePoolAtomic(after);
7832
+ return result;
7833
+ });
7834
+ }
7835
+ function bumpReason(reasons, reason) {
7836
+ reasons[reason] = (reasons[reason] ?? 0) + 1;
7837
+ }
7838
+ function upsertCandidates(pool2, inputs, now = Date.now(), maxCandidates = POOL_MAX_CANDIDATES) {
7839
+ const byKey = /* @__PURE__ */ new Map();
7840
+ for (const c2 of pool2.candidates) byKey.set(c2.key, c2);
7841
+ const result = { added: 0, updated: 0, rejected: 0, reasons: {} };
7842
+ for (const input of inputs) {
7843
+ const port = input.port ?? 443;
7844
+ if (input.candidateType !== void 0 && input.candidateType !== ENTRY_IP) {
7845
+ result.rejected++;
7846
+ bumpReason(result.reasons, "candidateType");
7847
+ continue;
7848
+ }
7849
+ const key = normalizeCandidateKey(input.ip, port);
7850
+ if (!key) {
7851
+ result.rejected++;
7852
+ bumpReason(result.reasons, "invalidIp");
7853
+ continue;
7854
+ }
7855
+ if (!isCloudflareEntryIp(input.ip)) {
7856
+ result.rejected++;
7857
+ bumpReason(result.reasons, "notCloudflare");
7858
+ continue;
7859
+ }
7860
+ const family = isIP2(input.ip.trim());
7861
+ const existing = byKey.get(key);
7862
+ if (existing) {
7863
+ if (!existing.sources.includes(input.source)) existing.sources.push(input.source);
7864
+ existing.lastSeen = now;
7865
+ if (existing.status === "disabled") {
7866
+ } else if (existing.status === "expired" || existing.status === "failed") {
7867
+ existing.status = "pending";
7868
+ }
7869
+ if (input.lightCheck) existing.lightCheck = input.lightCheck;
7870
+ result.updated++;
7871
+ continue;
7872
+ }
7873
+ const created = {
7874
+ key,
7875
+ ip: input.ip.trim(),
7876
+ port,
7877
+ ipVersion: family,
7878
+ candidateType: ENTRY_IP,
7879
+ sources: [input.source],
7880
+ firstSeen: now,
7881
+ lastSeen: now,
7882
+ lightCheck: input.lightCheck ?? null,
7883
+ fullTest: null,
7884
+ status: "pending",
7885
+ failCount: 0,
7886
+ successCount: 0
7887
+ };
7888
+ byKey.set(key, created);
7889
+ pool2.candidates.push(created);
7890
+ result.added++;
7891
+ }
7892
+ for (const c2 of pool2.candidates) {
7893
+ if (c2.status !== "disabled" && now - c2.lastSeen > POOL_EXPIRE_MS) c2.status = "expired";
7894
+ }
7895
+ if (pool2.candidates.length > maxCandidates) {
7896
+ const disposable = pool2.candidates.filter((c2) => c2.status !== "disabled").sort((a, b) => a.lastSeen - b.lastSeen);
7897
+ const overflow = pool2.candidates.length - maxCandidates;
7898
+ const drop = new Set(disposable.slice(0, overflow).map((c2) => c2.key));
7899
+ if (drop.size > 0) {
7900
+ pool2.candidates = pool2.candidates.filter((c2) => !drop.has(c2.key));
7901
+ bumpReason(result.reasons, "evicted");
7902
+ }
7903
+ }
7904
+ pool2.updatedAt = now;
7905
+ return result;
7906
+ }
7907
+ var POOL_SCHEMA, POOL_FILENAME, ENTRY_IP, POOL_EXPIRE_MS, POOL_MAX_CANDIDATES, LOCK_STALE_MS, LOCK_TIMEOUT_MS, LOCK_RETRY_MS, V4_NETS, V6_NETS, sleep;
7908
+ var init_pool = __esm({
7909
+ "src/sources/pool.ts"() {
7910
+ "use strict";
7911
+ init_ip_ranges();
7912
+ POOL_SCHEMA = 1;
7913
+ POOL_FILENAME = "external-candidates.json";
7914
+ ENTRY_IP = "entry_ip";
7915
+ POOL_EXPIRE_MS = 30 * 24 * 60 * 60 * 1e3;
7916
+ POOL_MAX_CANDIDATES = 5e3;
7917
+ LOCK_STALE_MS = 3e4;
7918
+ LOCK_TIMEOUT_MS = 5e3;
7919
+ LOCK_RETRY_MS = 25;
7920
+ V4_NETS = BUILTIN_IPV4_CIDRS.map(parseCidr).filter(
7921
+ (v) => v !== null && v.family === 4
7922
+ );
7923
+ V6_NETS = BUILTIN_IPV6_CIDRS.map(parseCidr).filter(
7924
+ (v) => v !== null && v.family === 6
7925
+ );
7926
+ sleep = (ms) => new Promise((resolve4) => setTimeout(resolve4, ms));
7927
+ }
7928
+ });
7929
+
7930
+ // src/sources/sample.ts
7931
+ function networkBucket2(ip) {
7932
+ if (ip.includes(":")) {
7933
+ const parsed = parseCidr(`${ip}/48`);
7934
+ if (parsed && parsed.family === 6) {
7935
+ return [112n, 96n, 80n].map((s) => (parsed.base >> s & 65535n).toString(16)).join(":");
7936
+ }
7937
+ return ip;
7938
+ }
7939
+ const parts = ip.split(".");
7940
+ return parts.length === 4 ? parts.slice(0, 3).join(".") : ip;
7941
+ }
7942
+ function eligible(pool2, port, includeUnchecked) {
7943
+ return pool2.candidates.filter((c2) => {
7944
+ if (c2.port !== port || c2.status === "disabled" || c2.status === "expired") return false;
7945
+ if (c2.lightCheck === null) return includeUnchecked;
7946
+ return c2.lightCheck.tcpOk && c2.lightCheck.tlsOk;
7947
+ });
7948
+ }
7949
+ function roundRobin(items, quota) {
7950
+ const buckets = /* @__PURE__ */ new Map();
7951
+ for (const c2 of items) {
7952
+ const key = networkBucket2(c2.ip);
7953
+ const list = buckets.get(key);
7954
+ if (list) list.push(c2);
7955
+ else buckets.set(key, [c2]);
7956
+ }
7957
+ for (const list of buckets.values()) {
7958
+ list.sort(
7959
+ (a, b) => b.successCount - a.successCount || b.lastSeen - a.lastSeen || a.key.localeCompare(b.key)
7960
+ );
7961
+ }
7962
+ const keys = [...buckets.keys()].sort();
7963
+ const out2 = [];
7964
+ for (let round = 0; out2.length < quota; round++) {
7965
+ let progressed = false;
7966
+ for (const key of keys) {
7967
+ if (out2.length >= quota) break;
7968
+ const c2 = buckets.get(key)[round];
7969
+ if (c2) {
7970
+ out2.push(c2);
7971
+ progressed = true;
7972
+ }
7973
+ }
7974
+ if (!progressed) break;
7975
+ }
7976
+ return out2;
7977
+ }
7978
+ function sampleFromPool(pool2, options = {}) {
7979
+ const limit = Math.max(1, options.limit ?? POOL_SAMPLE_LIMIT);
7980
+ const port = options.port ?? 443;
7981
+ const candidates = eligible(pool2, port, options.includeUnchecked !== false);
7982
+ const v4 = candidates.filter((c2) => c2.ipVersion === 4);
7983
+ const v6 = candidates.filter((c2) => c2.ipVersion === 6);
7984
+ let v4Quota = Math.ceil(limit / 2);
7985
+ let v6Quota = limit - v4Quota;
7986
+ if (v4.length < v4Quota) {
7987
+ v6Quota += v4Quota - v4.length;
7988
+ v4Quota = v4.length;
7989
+ }
7990
+ if (v6.length < v6Quota) {
7991
+ v4Quota += v6Quota - v6.length;
7992
+ v6Quota = v6.length;
7993
+ }
7994
+ const picked = [
7995
+ ...roundRobin(v4, v4Quota),
7996
+ ...roundRobin(v6, v6Quota)
7997
+ ].slice(0, limit);
7998
+ return {
7999
+ candidates: picked.map((c2) => c2.ip),
8000
+ keys: picked.map((c2) => c2.key),
8001
+ family: v4.length > 0 && v6.length > 0 ? "both" : v6.length > 0 ? "v6" : "v4",
8002
+ counts: {
8003
+ v4: picked.filter((c2) => c2.ipVersion === 4).length,
8004
+ v6: picked.filter((c2) => c2.ipVersion === 6).length
8005
+ },
8006
+ totalEligible: candidates.length,
8007
+ note: `\u672C\u5730\u6C60\u5206\u5C42\u53D6\u6837\uFF1A\u7AEF\u53E3 ${port}\uFF0C\u53EF\u53D6\u6837 ${candidates.length} \u6761\uFF08v4 ${v4.length} / v6 ${v6.length}\uFF09\uFF0C\u672C\u6B21\u53D6 ${picked.length} \u6761`
8008
+ };
8009
+ }
8010
+ async function applyFullTestResults(keys, port, summary, now = Date.now()) {
8011
+ const winners = /* @__PURE__ */ new Map();
8012
+ for (const entry of summary.entries) {
8013
+ const key = entry.ip.includes(":") ? `[${entry.ip}]:${port}` : `${entry.ip}:${port}`;
8014
+ winners.set(key, {
8015
+ speedMBps: entry.peakMBps || entry.speed,
8016
+ colo: entry.colo
8017
+ });
8018
+ }
8019
+ let active = 0;
8020
+ let failed = 0;
8021
+ await withPool((pool2) => {
8022
+ for (const key of keys) {
8023
+ const c2 = pool2.candidates.find((x) => x.key === key);
8024
+ if (!c2 || c2.status === "disabled") continue;
8025
+ const win = winners.get(key);
8026
+ if (win) {
8027
+ c2.status = "active";
8028
+ c2.fullTest = { at: now, wsOk: true, speedMBps: win.speedMBps, colo: win.colo };
8029
+ c2.successCount += 1;
8030
+ active++;
8031
+ } else {
8032
+ c2.status = "failed";
8033
+ c2.fullTest = { at: now, wsOk: false, speedMBps: null, colo: null };
8034
+ c2.failCount += 1;
8035
+ failed++;
8036
+ }
8037
+ }
8038
+ pool2.updatedAt = now;
8039
+ });
8040
+ return { active, failed };
8041
+ }
8042
+ var POOL_SAMPLE_LIMIT;
8043
+ var init_sample = __esm({
8044
+ "src/sources/sample.ts"() {
8045
+ "use strict";
8046
+ init_ip_ranges();
8047
+ init_pool();
8048
+ POOL_SAMPLE_LIMIT = 200;
8049
+ }
8050
+ });
8051
+
7625
8052
  // src/scan/compare.ts
7626
8053
  var compare_exports = {};
7627
8054
  __export(compare_exports, {
@@ -7918,7 +8345,7 @@ var init_compare = __esm({
7918
8345
  });
7919
8346
 
7920
8347
  // src/scan/relay-builtin.ts
7921
- import { readFileSync as readFileSync2 } from "node:fs";
8348
+ import { readFileSync as readFileSync3 } from "node:fs";
7922
8349
  import { dirname as dirname3, resolve as resolve2 } from "node:path";
7923
8350
  import { fileURLToPath as fileURLToPath2 } from "node:url";
7924
8351
  function moduleDir2() {
@@ -7937,7 +8364,7 @@ function readBuiltinRelayCandidates() {
7937
8364
  ];
7938
8365
  for (const path of paths) {
7939
8366
  try {
7940
- const list = readIpFile(readFileSync2(path, "utf8")).filter(
8367
+ const list = readIpFile(readFileSync3(path, "utf8")).filter(
7941
8368
  (ip) => /^\d{1,3}(\.\d{1,3}){3}$/.test(ip)
7942
8369
  );
7943
8370
  if (list.length > 0) return list;
@@ -7963,37 +8390,37 @@ var relay_exports = {};
7963
8390
  __export(relay_exports, {
7964
8391
  runRelayCommand: () => runRelayCommand
7965
8392
  });
7966
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "node:fs";
8393
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "node:fs";
7967
8394
  import { Duplex } from "node:stream";
7968
8395
  import * as tls4 from "node:tls";
7969
8396
  function uuidToBytes(uuid) {
7970
8397
  const hex = uuid.replace(/[^0-9a-fA-F]/g, "");
7971
8398
  if (hex.length !== 32) throw new Error(`UUID \u5E94\u4E3A 32 \u4F4D\u5341\u516D\u8FDB\u5236\uFF0C\u5B9E\u9645 ${hex.length} \u4F4D`);
7972
- const out = new Uint8Array(16);
7973
- for (let i = 0; i < 16; i++) out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
7974
- return out;
8399
+ const out2 = new Uint8Array(16);
8400
+ for (let i = 0; i < 16; i++) out2[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
8401
+ return out2;
7975
8402
  }
7976
8403
  function ipv4Address(ip) {
7977
8404
  const parts = ip.split(".").map((p) => Number(p));
7978
8405
  if (parts.length !== 4 || parts.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) {
7979
8406
  throw new Error(`\u4E0D\u662F\u5408\u6CD5\u7684 IPv4\uFF1A${ip}`);
7980
8407
  }
7981
- const out = new Uint8Array(5);
7982
- out[0] = 1;
7983
- out.set(parts, 1);
7984
- return out;
8408
+ const out2 = new Uint8Array(5);
8409
+ out2[0] = 1;
8410
+ out2.set(parts, 1);
8411
+ return out2;
7985
8412
  }
7986
8413
  function buildVlessHello(uuid, ip, port) {
7987
8414
  const addr = ipv4Address(ip);
7988
- const out = new Uint8Array(21 + addr.length);
7989
- out[0] = 0;
7990
- out.set(uuidToBytes(uuid), 1);
7991
- out[17] = 0;
7992
- out[18] = 1;
7993
- out[19] = port >> 8 & 255;
7994
- out[20] = port & 255;
7995
- out.set(addr, 21);
7996
- return out;
8415
+ const out2 = new Uint8Array(21 + addr.length);
8416
+ out2[0] = 0;
8417
+ out2.set(uuidToBytes(uuid), 1);
8418
+ out2[17] = 0;
8419
+ out2[18] = 1;
8420
+ out2[19] = port >> 8 & 255;
8421
+ out2[20] = port & 255;
8422
+ out2.set(addr, 21);
8423
+ return out2;
7997
8424
  }
7998
8425
  function createDuplex(ws) {
7999
8426
  const duplex = new Duplex({
@@ -8118,7 +8545,7 @@ function readHttp(socket, timeoutMs) {
8118
8545
  });
8119
8546
  }
8120
8547
  async function probeOne(opts, ip, timeoutMs) {
8121
- const out = {
8548
+ const out2 = {
8122
8549
  ip,
8123
8550
  ok: false,
8124
8551
  tunnelMs: 0,
@@ -8136,7 +8563,7 @@ async function probeOne(opts, ip, timeoutMs) {
8136
8563
  const tunnel = await openTunnel(opts.wsUrl, opts.uuid, ip, 443, timeoutMs);
8137
8564
  ws = tunnel.ws;
8138
8565
  sniff = tunnel.first;
8139
- out.tunnelMs = tunnel.tunnelMs;
8566
+ out2.tunnelMs = tunnel.tunnelMs;
8140
8567
  const tlsStarted = Date.now();
8141
8568
  socket = await withTimeout2(
8142
8569
  new Promise((resolve4, reject) => {
@@ -8155,7 +8582,7 @@ async function probeOne(opts, ip, timeoutMs) {
8155
8582
  timeoutMs,
8156
8583
  "TLS \u63E1\u624B"
8157
8584
  );
8158
- out.tlsMs = Date.now() - tlsStarted;
8585
+ out2.tlsMs = Date.now() - tlsStarted;
8159
8586
  const httpStarted = Date.now();
8160
8587
  socket.write(
8161
8588
  `GET /__cfp_version HTTP/1.1\r
@@ -8166,28 +8593,28 @@ User-Agent: cfpilot-scan-relay\r
8166
8593
  `
8167
8594
  );
8168
8595
  const res = await readHttp(socket, timeoutMs);
8169
- out.httpMs = Date.now() - httpStarted;
8170
- out.status = res.status;
8596
+ out2.httpMs = Date.now() - httpStarted;
8597
+ out2.status = res.status;
8171
8598
  if (res.status === 200) {
8172
8599
  try {
8173
8600
  const parsed = JSON.parse(res.body);
8174
- out.build = typeof parsed.build === "string" ? parsed.build : "";
8175
- out.buildOk = out.build !== "" && out.build === opts.expectedBuild;
8601
+ out2.build = typeof parsed.build === "string" ? parsed.build : "";
8602
+ out2.buildOk = out2.build !== "" && out2.build === opts.expectedBuild;
8176
8603
  } catch {
8177
8604
  }
8178
8605
  }
8179
- if (out.buildOk) {
8180
- out.ok = true;
8606
+ if (out2.buildOk) {
8607
+ out2.ok = true;
8181
8608
  } else if (res.status === 0) {
8182
- out.error = `\u65E0\u6709\u6548 HTTP \u54CD\u5E94\uFF08\u6536\u5230 ${res.raw.length} \u5B57\u8282\uFF09`;
8609
+ out2.error = `\u65E0\u6709\u6548 HTTP \u54CD\u5E94\uFF08\u6536\u5230 ${res.raw.length} \u5B57\u8282\uFF09`;
8183
8610
  } else if (res.status === 200) {
8184
- out.error = `build \u4E0D\u5339\u914D\uFF08${out.build || "\u7A7A"} \u2260 ${opts.expectedBuild}\uFF09`;
8611
+ out2.error = `build \u4E0D\u5339\u914D\uFF08${out2.build || "\u7A7A"} \u2260 ${opts.expectedBuild}\uFF09`;
8185
8612
  } else {
8186
- out.error = `HTTP ${res.status}`;
8613
+ out2.error = `HTTP ${res.status}`;
8187
8614
  }
8188
8615
  } catch (err) {
8189
8616
  const preview = sniff && sniff.first.length > 0 ? ` | \u9996\u5305=${JSON.stringify(sniff.first.subarray(0, 40).toString("utf8"))}` : " | \u9996\u5305=\uFF08\u7A7A\uFF09";
8190
- out.error = (String(err instanceof Error ? err.message : err) + preview).slice(0, 400);
8617
+ out2.error = (String(err instanceof Error ? err.message : err) + preview).slice(0, 400);
8191
8618
  } finally {
8192
8619
  try {
8193
8620
  socket?.destroy();
@@ -8198,7 +8625,7 @@ User-Agent: cfpilot-scan-relay\r
8198
8625
  } catch {
8199
8626
  }
8200
8627
  }
8201
- return out;
8628
+ return out2;
8202
8629
  }
8203
8630
  function median2(values) {
8204
8631
  if (values.length === 0) return 0;
@@ -8251,7 +8678,7 @@ async function runRelayCommand(args) {
8251
8678
  let rawCount = 0;
8252
8679
  const sourceLabel = file ? `\u6587\u4EF6 ${file}` : url ? `\u94FE\u63A5 ${url}` : "\u5185\u7F6E\u6E05\u5355";
8253
8680
  try {
8254
- const raw = file ? readIpFile(readFileSync3(file, "utf8")) : url ? await readIpUrl(url) : readBuiltinRelayCandidates();
8681
+ const raw = file ? readIpFile(readFileSync4(file, "utf8")) : url ? await readIpUrl(url) : readBuiltinRelayCandidates();
8255
8682
  rawCount = raw.length;
8256
8683
  ips = raw.filter((ip) => /^\d{1,3}(\.\d{1,3}){3}$/.test(ip));
8257
8684
  } catch (err) {
@@ -8343,7 +8770,7 @@ async function runRelayCommand(args) {
8343
8770
  const neverOk = aggregates.filter((a) => a.successPct === 0).length;
8344
8771
  const picked = aggregates.filter((a) => a.successPct === 100).slice(0, topN).map((a) => a.ip);
8345
8772
  if (outPath) {
8346
- writeFileSync2(outPath, picked.join("\n") + (picked.length > 0 ? "\n" : ""), "utf8");
8773
+ writeFileSync3(outPath, picked.join("\n") + (picked.length > 0 ? "\n" : ""), "utf8");
8347
8774
  if (!quiet) process.stderr.write(`\u5DF2\u5199\u51FA ${picked.length} \u6761\u5230 ${outPath}
8348
8775
  `);
8349
8776
  }
@@ -8445,8 +8872,8 @@ __export(command_exports2, {
8445
8872
  normalizeWsPath: () => normalizeWsPath,
8446
8873
  runScanCommand: () => runScanCommand
8447
8874
  });
8448
- import { readFileSync as readFileSync4 } from "node:fs";
8449
- import { join as join4 } from "node:path";
8875
+ import { readFileSync as readFileSync5 } from "node:fs";
8876
+ import { join as join5 } from "node:path";
8450
8877
  function normalizeWsPath(raw, fallback) {
8451
8878
  const value = (raw ?? fallback).trim();
8452
8879
  if (!value) return fallback;
@@ -8488,7 +8915,7 @@ function normalizeAccess(raw) {
8488
8915
  return value === "mobile" ? "mobile" : "fixed";
8489
8916
  }
8490
8917
  async function loadAdaptiveContext(args) {
8491
- const file = join4(configDirPath(), "network-profiles.json");
8918
+ const file = join5(configDirPath(), "network-profiles.json");
8492
8919
  const isp = normalizeIsp(flagString(args, "isp"));
8493
8920
  const region = normalizeRegion(flagString(args, "region") ?? "").slice(0, 32);
8494
8921
  const access = normalizeAccess(flagString(args, "access"));
@@ -8533,11 +8960,25 @@ function familyFromArgs(args) {
8533
8960
  `);
8534
8961
  process.exit(1);
8535
8962
  }
8536
- async function resolveCandidatesFromArgs(args, extraHosts = []) {
8963
+ async function resolveCandidatesFromArgs(args, extraHosts = [], port = 443) {
8964
+ if (flagBool(args, "from-pool")) {
8965
+ const limit = flagNumber(args, "pool-sample", POOL_SAMPLE_LIMIT);
8966
+ const sample = sampleFromPool(parsePool(readPoolRaw()), { limit, port });
8967
+ poolSamples.set(args, { keys: sample.keys, port });
8968
+ return {
8969
+ candidates: sample.candidates,
8970
+ family: sample.family === "both" ? "both" : sample.family,
8971
+ ipv6Env: null,
8972
+ v6Prefixes: [],
8973
+ v6Discovered: [],
8974
+ counts: sample.counts,
8975
+ note: sample.note
8976
+ };
8977
+ }
8537
8978
  const ipFile = flagString(args, "ip-file");
8538
8979
  const ipUrl = flagString(args, "ip-url");
8539
8980
  if (ipFile || ipUrl) {
8540
- const candidates = ipFile ? readIpFile(readFileSync4(ipFile, "utf8")) : await readIpUrl(ipUrl);
8981
+ const candidates = ipFile ? readIpFile(readFileSync5(ipFile, "utf8")) : await readIpUrl(ipUrl);
8541
8982
  return {
8542
8983
  candidates,
8543
8984
  family: "both",
@@ -8600,23 +9041,23 @@ async function saveAdaptiveObservations(args, observations) {
8600
9041
  }
8601
9042
  function printProgress2(event, quiet, asJson = false) {
8602
9043
  if (quiet) return;
8603
- const out = asJson ? process.stderr : process.stdout;
9044
+ const out2 = asJson ? process.stderr : process.stdout;
8604
9045
  switch (event.type) {
8605
9046
  case "stage":
8606
- out.write(`
9047
+ out2.write(`
8607
9048
  \u25B6 \u9636\u6BB5 ${event.stage}\uFF1A${event.name}\uFF08\u5171 ${event.total} \u4E2A\u5019\u9009\uFF09
8608
9049
  `);
8609
9050
  break;
8610
9051
  case "progress":
8611
- if (event.message) out.write(`\r ${event.message}`.padEnd(78));
9052
+ if (event.message) out2.write(`\r ${event.message}`.padEnd(78));
8612
9053
  break;
8613
9054
  case "done":
8614
- out.write(`
9055
+ out2.write(`
8615
9056
  \u2713 \u4F18\u9009\u5B8C\u6210\uFF0C\u5171 ${event.count} \u6761
8616
9057
  `);
8617
9058
  break;
8618
9059
  case "error":
8619
- out.write(`
9060
+ out2.write(`
8620
9061
  \u2717 ${event.message}
8621
9062
  `);
8622
9063
  break;
@@ -8780,10 +9221,12 @@ ${NAME} v${VERSION}
8780
9221
  }
8781
9222
  }
8782
9223
  if (!quiet && !asJson) process.stdout.write("\u6B63\u5728\u51C6\u5907 Cloudflare \u7F51\u6BB5\u2026\n");
8783
- const candidatePlan = await resolveCandidatesFromArgs(args, [host, panelHost]);
9224
+ const candidatePlan = await resolveCandidatesFromArgs(args, [host, panelHost], port);
8784
9225
  const candidates = candidatePlan.candidates;
8785
9226
  if (candidates.length === 0) {
8786
- process.stderr.write("\u5019\u9009 IP \u4E3A\u7A7A\uFF0C\u8BF7\u68C0\u67E5 --ip-file / --cidr \u53C2\u6570\n");
9227
+ process.stderr.write(
9228
+ flagBool(args, "from-pool") ? "\u672C\u5730\u5019\u9009\u6C60\u6CA1\u6709\u53EF\u53D6\u6837\u6761\u76EE\uFF0C\u8BF7\u5148\u8DD1 `cfpilot source sync`\uFF08\u6216\u53BB\u6389 --from-pool \u7528\u5B98\u65B9\u7F51\u6BB5\uFF09\n" : "\u5019\u9009 IP \u4E3A\u7A7A\uFF0C\u8BF7\u68C0\u67E5 --ip-file / --cidr \u53C2\u6570\n"
9229
+ );
8787
9230
  if (candidatePlan.ipv6Env && candidatePlan.ipv6Env.status !== "ok") {
8788
9231
  process.stderr.write(` ${candidatePlan.ipv6Env.message}
8789
9232
  `);
@@ -8915,6 +9358,16 @@ ${NAME} v${VERSION}
8915
9358
  onProgress: (event) => printProgress2(event, quiet, asJson)
8916
9359
  });
8917
9360
  await saveAdaptiveObservations(args, summary.observations);
9361
+ const sampled = poolSamples.get(args);
9362
+ if (sampled && sampled.keys.length > 0) {
9363
+ const applied = await applyFullTestResults(sampled.keys, sampled.port, summary);
9364
+ if (!quiet && !asJson) {
9365
+ process.stdout.write(
9366
+ `\u672C\u5730\u6C60\u5DF2\u56DE\u5199\uFF1Aactive ${applied.active} \u6761 / failed ${applied.failed} \u6761
9367
+ `
9368
+ );
9369
+ }
9370
+ }
8918
9371
  const fillable = summary.entries;
8919
9372
  if (asJson) {
8920
9373
  process.stdout.write(
@@ -9051,7 +9504,7 @@ async function promptCallback(entries, dataHost, panelHost, panelPassword, mode)
9051
9504
  process.stdout.write("\u2192 \u53EF\u624B\u52A8\u590D\u5236\u4E0A\u9762\u7684 IP \u5217\u8868\u7C98\u8D34\u5230\u9762\u677F\n");
9052
9505
  }
9053
9506
  }
9054
- var adaptiveContexts;
9507
+ var adaptiveContexts, poolSamples;
9055
9508
  var init_command2 = __esm({
9056
9509
  "src/scan/command.ts"() {
9057
9510
  "use strict";
@@ -9068,7 +9521,10 @@ var init_command2 = __esm({
9068
9521
  init_help2();
9069
9522
  init_speed_url();
9070
9523
  init_ip_ranges();
9524
+ init_pool();
9525
+ init_sample();
9071
9526
  adaptiveContexts = /* @__PURE__ */ new WeakMap();
9527
+ poolSamples = /* @__PURE__ */ new WeakMap();
9072
9528
  }
9073
9529
  });
9074
9530
 
@@ -9786,6 +10242,1156 @@ var init_main = __esm({
9786
10242
  }
9787
10243
  });
9788
10244
 
10245
+ // src/sources/config.ts
10246
+ import {
10247
+ existsSync as existsSync3,
10248
+ mkdirSync as mkdirSync3,
10249
+ readFileSync as readFileSync6,
10250
+ renameSync as renameSync2,
10251
+ unlinkSync as unlinkSync2,
10252
+ writeFileSync as writeFileSync4
10253
+ } from "node:fs";
10254
+ import { join as join6 } from "node:path";
10255
+ import { randomUUID as randomUUID4 } from "node:crypto";
10256
+ function sourcesPath() {
10257
+ return join6(poolDir(), SOURCES_FILENAME);
10258
+ }
10259
+ function emptySources() {
10260
+ return { schema: SOURCES_SCHEMA, updatedAt: 0, sources: [], runs: [] };
10261
+ }
10262
+ function readSourcesRaw() {
10263
+ try {
10264
+ return readFileSync6(sourcesPath(), "utf8");
10265
+ } catch {
10266
+ return "";
10267
+ }
10268
+ }
10269
+ function validSource(v) {
10270
+ if (!v || typeof v !== "object") return false;
10271
+ const s = v;
10272
+ return typeof s.id === "string" && s.id.length > 0 && typeof s.name === "string" && SOURCE_TYPES.includes(s.type) && typeof s.url === "string" && Array.isArray(s.mirrors) && s.mirrors.every((m) => typeof m === "string") && typeof s.enabled === "boolean" && typeof s.intervalHours === "number" && typeof s.etag === "string" && typeof s.lastModified === "string" && typeof s.lastSyncAt === "number" && typeof s.lastError === "string" && typeof s.failCount === "number";
10273
+ }
10274
+ function validRun(v) {
10275
+ if (!v || typeof v !== "object") return false;
10276
+ const r = v;
10277
+ return typeof r.at === "number" && typeof r.sourceId === "string" && typeof r.ok === "boolean" && typeof r.added === "number" && typeof r.updated === "number" && typeof r.rejected === "number" && typeof r.error === "string" && typeof r.durationMs === "number" && typeof r.notModified === "boolean";
10278
+ }
10279
+ function normalizeSource(v) {
10280
+ return {
10281
+ id: v.id,
10282
+ name: v.name,
10283
+ type: v.type,
10284
+ url: v.url,
10285
+ mirrors: [...v.mirrors],
10286
+ enabled: v.enabled,
10287
+ intervalHours: v.intervalHours,
10288
+ etag: v.etag,
10289
+ lastModified: v.lastModified,
10290
+ lastSyncAt: v.lastSyncAt,
10291
+ lastError: v.lastError,
10292
+ failCount: v.failCount,
10293
+ query: typeof v.query === "string" ? v.query : "",
10294
+ maxResults: typeof v.maxResults === "number" && v.maxResults > 0 ? v.maxResults : 200
10295
+ };
10296
+ }
10297
+ function normalizeRun(v) {
10298
+ return {
10299
+ at: v.at,
10300
+ sourceId: v.sourceId,
10301
+ ok: v.ok,
10302
+ added: v.added,
10303
+ updated: v.updated,
10304
+ rejected: v.rejected,
10305
+ error: v.error,
10306
+ durationMs: v.durationMs,
10307
+ notModified: v.notModified
10308
+ };
10309
+ }
10310
+ function parseSources(raw) {
10311
+ if (!raw.trim()) return emptySources();
10312
+ try {
10313
+ const obj = JSON.parse(raw);
10314
+ if (obj.schema !== SOURCES_SCHEMA && obj.schema !== SOURCES_SCHEMA_V1) {
10315
+ throw new Error(`schema ${String(obj.schema)} \u4E0D\u517C\u5BB9`);
10316
+ }
10317
+ return {
10318
+ schema: SOURCES_SCHEMA,
10319
+ updatedAt: typeof obj.updatedAt === "number" ? obj.updatedAt : 0,
10320
+ sources: (Array.isArray(obj.sources) ? obj.sources : []).filter(validSource).map(normalizeSource),
10321
+ runs: (Array.isArray(obj.runs) ? obj.runs : []).filter(validRun).map(normalizeRun).slice(-MAX_SYNC_RUNS)
10322
+ };
10323
+ } catch {
10324
+ const backup = `${sourcesPath()}.corrupt-${Date.now()}`;
10325
+ try {
10326
+ if (existsSync3(sourcesPath())) renameSync2(sourcesPath(), backup);
10327
+ } catch {
10328
+ }
10329
+ return emptySources();
10330
+ }
10331
+ }
10332
+ function serializeSources(file) {
10333
+ return `${JSON.stringify(file, null, 2)}
10334
+ `;
10335
+ }
10336
+ function writeSourcesAtomic(text2) {
10337
+ const dir = poolDir();
10338
+ mkdirSync3(dir, { recursive: true, mode: 448 });
10339
+ const tmp = join6(dir, `${SOURCES_FILENAME}.${process.pid}.${randomUUID4()}.tmp`);
10340
+ try {
10341
+ writeFileSync4(tmp, text2, { mode: 384 });
10342
+ renameSync2(tmp, sourcesPath());
10343
+ } catch (err) {
10344
+ try {
10345
+ unlinkSync2(tmp);
10346
+ } catch {
10347
+ }
10348
+ throw err;
10349
+ }
10350
+ }
10351
+ function loadSources() {
10352
+ return parseSources(readSourcesRaw());
10353
+ }
10354
+ function makeSource(input) {
10355
+ return {
10356
+ id: input.id,
10357
+ name: input.name ?? input.id,
10358
+ type: input.type,
10359
+ url: input.url ?? "",
10360
+ mirrors: input.mirrors ?? [],
10361
+ enabled: input.enabled ?? true,
10362
+ intervalHours: input.intervalHours ?? (input.type === "github-raw" ? 12 : 24),
10363
+ etag: "",
10364
+ lastModified: "",
10365
+ lastSyncAt: 0,
10366
+ lastError: "",
10367
+ failCount: 0,
10368
+ query: input.query ?? "",
10369
+ maxResults: input.maxResults ?? 200
10370
+ };
10371
+ }
10372
+ function appendRun(file, run) {
10373
+ file.runs.push(run);
10374
+ if (file.runs.length > MAX_SYNC_RUNS) {
10375
+ file.runs = file.runs.slice(-MAX_SYNC_RUNS);
10376
+ }
10377
+ file.updatedAt = run.at;
10378
+ }
10379
+ var SOURCES_SCHEMA, SOURCES_SCHEMA_V1, SOURCES_FILENAME, MAX_SYNC_RUNS, SOURCE_TYPES;
10380
+ var init_config2 = __esm({
10381
+ "src/sources/config.ts"() {
10382
+ "use strict";
10383
+ init_pool();
10384
+ SOURCES_SCHEMA = 2;
10385
+ SOURCES_SCHEMA_V1 = 1;
10386
+ SOURCES_FILENAME = "external-sources.json";
10387
+ MAX_SYNC_RUNS = 50;
10388
+ SOURCE_TYPES = ["github-raw", "custom-url", "ripe-stat"];
10389
+ }
10390
+ });
10391
+
10392
+ // src/sources/fetch.ts
10393
+ import { isIP as isIP3 } from "node:net";
10394
+ function isPrivateIPv4(ip) {
10395
+ const p = ip.split(".").map(Number);
10396
+ const [a, b] = p;
10397
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
10398
+ if (a === 0 || a === 10 || a === 127) return true;
10399
+ if (a === 100 && b !== void 0 && b >= 64 && b <= 127) return true;
10400
+ if (a === 169 && b === 254) return true;
10401
+ if (a === 172 && b !== void 0 && b >= 16 && b <= 31) return true;
10402
+ if (a === 192 && b === 168) return true;
10403
+ if (a === 192 && b === 0) return true;
10404
+ if (a === 198 && (b === 18 || b === 19)) return true;
10405
+ if (a === 198 && b === 51 && p[2] === 100) return true;
10406
+ if (a === 203 && b === 0 && p[2] === 113) return true;
10407
+ if (a !== void 0 && a >= 224) return true;
10408
+ return false;
10409
+ }
10410
+ function isPrivateIPv6(ip) {
10411
+ const lower = ip.toLowerCase();
10412
+ if (lower === "::" || lower === "::1") return true;
10413
+ if (lower.startsWith("::ffff:")) return true;
10414
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
10415
+ if (/^fe[89ab]/.test(lower)) return true;
10416
+ return false;
10417
+ }
10418
+ function validateSourceUrl(raw, opts = {}) {
10419
+ let url;
10420
+ try {
10421
+ url = new URL(raw.trim());
10422
+ } catch {
10423
+ throw new Error(`\u4E0D\u662F\u5408\u6CD5\u7684\u94FE\u63A5\uFF1A${raw}`);
10424
+ }
10425
+ if (url.protocol !== "https:" && !(opts.allowHttp === true && url.protocol === "http:")) {
10426
+ throw new Error(`\u5916\u90E8\u6570\u636E\u6E90\u53EA\u652F\u6301 HTTPS\uFF0C\u5B9E\u9645\u662F ${url.protocol}`);
10427
+ }
10428
+ if (url.username || url.password) {
10429
+ throw new Error("\u5916\u90E8\u6570\u636E\u6E90\u94FE\u63A5\u4E0D\u5141\u8BB8\u5E26\u7528\u6237\u540D/\u5BC6\u7801");
10430
+ }
10431
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "");
10432
+ if (BLOCKED_HOSTS.has(host) || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
10433
+ throw new Error(`\u5916\u90E8\u6570\u636E\u6E90\u4E0D\u5141\u8BB8\u6307\u5411\u672C\u673A\u6216\u5185\u7F51\u57DF\u540D\uFF1A${host}`);
10434
+ }
10435
+ const family = isIP3(host);
10436
+ if (family === 4 && isPrivateIPv4(host)) {
10437
+ throw new Error(`\u5916\u90E8\u6570\u636E\u6E90\u4E0D\u5141\u8BB8\u6307\u5411\u79C1\u7F51/\u4FDD\u7559\u5730\u5740\uFF1A${host}`);
10438
+ }
10439
+ if (family === 6 && isPrivateIPv6(host)) {
10440
+ throw new Error(`\u5916\u90E8\u6570\u636E\u6E90\u4E0D\u5141\u8BB8\u6307\u5411\u79C1\u7F51/\u4FDD\u7559\u5730\u5740\uFF1A${host}`);
10441
+ }
10442
+ return url;
10443
+ }
10444
+ async function fetchWithRedirects(url, headers, opts, hopsLeft, fetchImpl = fetch) {
10445
+ const res = await fetchImpl(url, {
10446
+ redirect: "manual",
10447
+ signal: AbortSignal.timeout(opts.timeoutMs),
10448
+ headers
10449
+ });
10450
+ if (REDIRECT_CODES.has(res.status)) {
10451
+ if (hopsLeft <= 0) throw new Error(`\u91CD\u5B9A\u5411\u8D85\u8FC7 ${SOURCE_MAX_REDIRECTS} \u8DF3\u4E0A\u9650`);
10452
+ const loc = res.headers.get("location");
10453
+ if (!loc) throw new Error(`HTTP ${res.status} \u91CD\u5B9A\u5411\u6CA1\u6709 Location`);
10454
+ const next = validateSourceUrl(new URL(loc, url).toString(), opts);
10455
+ return fetchWithRedirects(next, headers, opts, hopsLeft - 1, fetchImpl);
10456
+ }
10457
+ return res;
10458
+ }
10459
+ async function readBodyLimited(res, maxBytes) {
10460
+ const declared = Number(res.headers.get("content-length") ?? "");
10461
+ if (Number.isFinite(declared) && declared > maxBytes) {
10462
+ throw new Error(`\u6E05\u5355\u8FC7\u5927\uFF1A\u58F0\u660E ${declared} \u5B57\u8282\uFF0C\u4E0A\u9650 ${maxBytes} \u5B57\u8282`);
10463
+ }
10464
+ const reader = res.body?.getReader();
10465
+ if (!reader) {
10466
+ const text3 = await res.text();
10467
+ if (Buffer.byteLength(text3) > maxBytes) throw new Error(`\u6E05\u5355\u8FC7\u5927\uFF1A\u8D85\u8FC7 ${maxBytes} \u5B57\u8282\u4E0A\u9650`);
10468
+ return text3;
10469
+ }
10470
+ const decoder = new TextDecoder();
10471
+ let text2 = "";
10472
+ let total = 0;
10473
+ for (; ; ) {
10474
+ const { done, value } = await reader.read();
10475
+ if (done) break;
10476
+ if (!value || value.byteLength === 0) continue;
10477
+ total += value.byteLength;
10478
+ if (total > maxBytes) {
10479
+ try {
10480
+ await reader.cancel();
10481
+ } catch {
10482
+ }
10483
+ throw new Error(`\u6E05\u5355\u8FC7\u5927\uFF1A\u8D85\u8FC7 ${maxBytes} \u5B57\u8282\u4E0A\u9650`);
10484
+ }
10485
+ text2 += decoder.decode(value, { stream: true });
10486
+ }
10487
+ return text2 + decoder.decode();
10488
+ }
10489
+ function sourceUrls(source) {
10490
+ const out2 = [source.url, ...source.mirrors];
10491
+ if (source.type === "github-raw") {
10492
+ for (const m of MIRRORS) {
10493
+ out2.push(m.prefix + source.url);
10494
+ for (const mirror of source.mirrors) out2.push(m.prefix + mirror);
10495
+ }
10496
+ }
10497
+ return [...new Set(out2)];
10498
+ }
10499
+ async function fetchSourceText(source, opts = {}) {
10500
+ const timeoutMs = opts.timeoutMs ?? SOURCE_TIMEOUT_MS;
10501
+ const maxBytes = opts.maxBytes ?? SOURCE_MAX_BYTES;
10502
+ const headers = {
10503
+ "User-Agent": "CFPilot-ExternalSources/1.0",
10504
+ Accept: "text/plain, application/json, text/csv, */*"
10505
+ };
10506
+ if (source.etag) headers["If-None-Match"] = source.etag;
10507
+ if (source.lastModified) headers["If-Modified-Since"] = source.lastModified;
10508
+ const errors = [];
10509
+ for (const raw of sourceUrls(source)) {
10510
+ let url;
10511
+ try {
10512
+ url = validateSourceUrl(raw, opts);
10513
+ } catch (err) {
10514
+ errors.push(`${sanitizeUrl(raw)}\uFF1A${err instanceof Error ? err.message : String(err)}`);
10515
+ continue;
10516
+ }
10517
+ try {
10518
+ const res = await fetchWithRedirects(url, headers, { ...opts, timeoutMs }, SOURCE_MAX_REDIRECTS);
10519
+ if (res.status === 304) {
10520
+ return { text: "", url: sanitizeUrl(raw), etag: source.etag, lastModified: source.lastModified, notModified: true };
10521
+ }
10522
+ if (!res.ok) {
10523
+ errors.push(`${sanitizeUrl(raw)}\uFF1AHTTP ${res.status}`);
10524
+ continue;
10525
+ }
10526
+ const text2 = await readBodyLimited(res, maxBytes);
10527
+ return {
10528
+ text: text2,
10529
+ url: sanitizeUrl(raw),
10530
+ etag: res.headers.get("etag") ?? source.etag,
10531
+ lastModified: res.headers.get("last-modified") ?? source.lastModified,
10532
+ notModified: false
10533
+ };
10534
+ } catch (err) {
10535
+ errors.push(`${sanitizeUrl(raw)}\uFF1A${err instanceof Error ? err.message : String(err)}`);
10536
+ }
10537
+ }
10538
+ throw new Error(errors.length > 0 ? errors.join("\uFF1B") : "\u6570\u636E\u6E90\u6CA1\u6709\u53EF\u7528\u94FE\u63A5");
10539
+ }
10540
+ function sanitizeUrl(raw) {
10541
+ try {
10542
+ const u = new URL(raw);
10543
+ return `${u.protocol}//${u.host}${u.pathname}`;
10544
+ } catch {
10545
+ return "<invalid-url>";
10546
+ }
10547
+ }
10548
+ var SOURCE_MAX_BYTES, SOURCE_TIMEOUT_MS, SOURCE_MAX_REDIRECTS, BLOCKED_HOSTS, REDIRECT_CODES;
10549
+ var init_fetch = __esm({
10550
+ "src/sources/fetch.ts"() {
10551
+ "use strict";
10552
+ init_github_mirrors();
10553
+ SOURCE_MAX_BYTES = 2 * 1024 * 1024;
10554
+ SOURCE_TIMEOUT_MS = 15e3;
10555
+ SOURCE_MAX_REDIRECTS = 3;
10556
+ BLOCKED_HOSTS = /* @__PURE__ */ new Set([
10557
+ "localhost",
10558
+ "metadata",
10559
+ "metadata.google.internal",
10560
+ "instance-data"
10561
+ ]);
10562
+ REDIRECT_CODES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
10563
+ }
10564
+ });
10565
+
10566
+ // src/sources/providers.ts
10567
+ function isProviderId(value) {
10568
+ return value === "ripe-stat";
10569
+ }
10570
+ async function getJson(req, rawUrl) {
10571
+ const url = validateSourceUrl(rawUrl);
10572
+ const timeoutMs = req.timeoutMs ?? SOURCE_TIMEOUT_MS;
10573
+ const maxBytes = req.maxBytes ?? SOURCE_MAX_BYTES;
10574
+ const opts = {
10575
+ timeoutMs,
10576
+ maxBytes,
10577
+ allowHttp: false
10578
+ };
10579
+ const res = await fetchWithRedirects(url, {}, opts, 3, req.fetchImpl ?? fetch);
10580
+ if (!res.ok) {
10581
+ throw new Error(`HTTP ${res.status}\uFF08${sanitizeUrl(rawUrl)}\uFF09`);
10582
+ }
10583
+ const text2 = await readBodyLimited(res, maxBytes);
10584
+ try {
10585
+ return JSON.parse(text2);
10586
+ } catch {
10587
+ throw new Error(`\u54CD\u5E94\u4E0D\u662F\u5408\u6CD5 JSON\uFF08${sanitizeUrl(rawUrl)}\uFF09`);
10588
+ }
10589
+ }
10590
+ function representativeIp(prefix) {
10591
+ const [addr, bits] = prefix.trim().split("/");
10592
+ if (!addr || !bits) return null;
10593
+ if (addr.includes(":")) {
10594
+ if (bits !== "48") return null;
10595
+ const groups = addr.split(":").filter((g) => g !== "");
10596
+ if (groups.length < 3) return null;
10597
+ return `${groups[0]}:${groups[1]}:${groups[2]}::1`;
10598
+ }
10599
+ if (bits !== "24") return null;
10600
+ const parts = addr.split(".");
10601
+ if (parts.length !== 4) return null;
10602
+ return `${parts[0]}.${parts[1]}.${parts[2]}.130`;
10603
+ }
10604
+ function spread(items, bucketOf, limit) {
10605
+ const buckets = /* @__PURE__ */ new Map();
10606
+ for (const item of items) {
10607
+ const key = bucketOf(item);
10608
+ const list = buckets.get(key);
10609
+ if (list) list.push(item);
10610
+ else buckets.set(key, [item]);
10611
+ }
10612
+ const keys = [...buckets.keys()].sort();
10613
+ const out2 = [];
10614
+ for (let round = 0; out2.length < limit; round++) {
10615
+ let progressed = false;
10616
+ for (const key of keys) {
10617
+ if (out2.length >= limit) break;
10618
+ const value = buckets.get(key)[round];
10619
+ if (value !== void 0) {
10620
+ out2.push(value);
10621
+ progressed = true;
10622
+ }
10623
+ }
10624
+ if (!progressed) break;
10625
+ }
10626
+ return out2;
10627
+ }
10628
+ async function runRipeStat(req) {
10629
+ const asn = (req.source.query || PROVIDERS["ripe-stat"].defaultQuery).trim();
10630
+ if (!/^AS\d{1,10}$/i.test(asn)) {
10631
+ throw new Error(`RIPEstat \u7684 query \u5FC5\u987B\u662F ASN\uFF08\u5982 AS13335\uFF09\uFF0C\u6536\u5230\u300C${asn}\u300D`);
10632
+ }
10633
+ const rawUrl = `https://stat.ripe.net/data/announced-prefixes/data.json?resource=${encodeURIComponent(asn)}`;
10634
+ const data = await getJson(req, rawUrl);
10635
+ if (data.status && data.status !== "ok") {
10636
+ throw new Error(`RIPEstat \u8FD4\u56DE ${data.status}`);
10637
+ }
10638
+ const prefixes = (data.data?.prefixes ?? []).map((p) => typeof p.prefix === "string" ? p.prefix : "").filter(Boolean);
10639
+ const v4 = [];
10640
+ const v6 = [];
10641
+ for (const prefix of prefixes) {
10642
+ const ip = representativeIp(prefix);
10643
+ if (!ip || !isCloudflareEntryIp(ip)) continue;
10644
+ if (ip.includes(":")) v6.push(ip);
10645
+ else v4.push(ip);
10646
+ }
10647
+ const max = Math.max(1, Math.min(2e3, req.source.maxResults || PROVIDERS["ripe-stat"].defaultMaxResults));
10648
+ const v6Limit = Math.floor(max / 4);
10649
+ const picked = [
10650
+ ...spread(v4, (ip) => ip.split(".").slice(0, 2).join("."), max - v6Limit),
10651
+ ...spread(v6, (ip) => ip.split(":").slice(0, 2).join(":"), v6Limit)
10652
+ ];
10653
+ return {
10654
+ candidates: picked.map((ip) => ({ ip, port: 443 })),
10655
+ note: `${asn} \u5BA3\u544A ${prefixes.length} \u4E2A\u524D\u7F00\uFF08v4 ${v4.length} / v6 ${v6.length} \u53EF\u7528\uFF09\uFF0C\u6309\u7236\u6BB5\u5206\u6563\u53D6 ${picked.length} \u4E2A\u4EE3\u8868 IP`,
10656
+ upstreamCount: prefixes.length
10657
+ };
10658
+ }
10659
+ async function runProvider(req) {
10660
+ const provider = req.source.type;
10661
+ if (!isProviderId(provider)) {
10662
+ throw new Error(`\u672A\u77E5 Provider\uFF1A${provider}\uFF08\u5F53\u524D\u53EA\u652F\u6301 ripe-stat\uFF09`);
10663
+ }
10664
+ return runRipeStat(req);
10665
+ }
10666
+ function isApiSource(source) {
10667
+ return API_SOURCE_TYPES.includes(source.type);
10668
+ }
10669
+ var API_SOURCE_TYPES, PROVIDERS;
10670
+ var init_providers = __esm({
10671
+ "src/sources/providers.ts"() {
10672
+ "use strict";
10673
+ init_fetch();
10674
+ init_pool();
10675
+ API_SOURCE_TYPES = ["ripe-stat"];
10676
+ PROVIDERS = {
10677
+ "ripe-stat": {
10678
+ id: "ripe-stat",
10679
+ requiresKey: false,
10680
+ minIntervalMs: 2e3,
10681
+ defaultQuery: "AS13335",
10682
+ defaultIntervalHours: 24,
10683
+ defaultMaxResults: 200,
10684
+ label: "RIPEstat \u5BA3\u544A\u524D\u7F00\uFF08\u96F6 Key\uFF09"
10685
+ }
10686
+ };
10687
+ }
10688
+ });
10689
+
10690
+ // src/sources/normalizer.ts
10691
+ function objString(v, keys) {
10692
+ if (!v || typeof v !== "object") return null;
10693
+ const o = v;
10694
+ for (const k of keys) {
10695
+ if (typeof o[k] === "string" && o[k].trim()) return o[k].trim();
10696
+ }
10697
+ return null;
10698
+ }
10699
+ function objPort(v) {
10700
+ if (!v || typeof v !== "object") return null;
10701
+ const raw = v.port;
10702
+ if (typeof raw === "number" && Number.isInteger(raw) && raw >= 1 && raw <= 65535) return raw;
10703
+ if (typeof raw === "string" && /^\d{1,5}$/.test(raw)) {
10704
+ const n = Number(raw);
10705
+ if (n >= 1 && n <= 65535) return n;
10706
+ }
10707
+ return null;
10708
+ }
10709
+ function splitHostPort(token) {
10710
+ let t = token.trim();
10711
+ const hash = t.indexOf("#");
10712
+ if (hash >= 0) t = t.slice(0, hash).trim();
10713
+ if (!t) return null;
10714
+ if (t.startsWith("[")) {
10715
+ const end = t.indexOf("]");
10716
+ if (end < 0) return null;
10717
+ const host = t.slice(1, end);
10718
+ const rest = t.slice(end + 1);
10719
+ const port = /^:\d{1,5}$/.test(rest) ? Number(rest.slice(1)) : null;
10720
+ return { ip: host, port: port && port >= 1 && port <= 65535 ? port : null };
10721
+ }
10722
+ const m = new RegExp(`^(${IPV4}):(\\d{1,5})$`).exec(t);
10723
+ if (m) {
10724
+ const port = Number(m[2]);
10725
+ return { ip: m[1], port: port >= 1 && port <= 65535 ? port : null };
10726
+ }
10727
+ return { ip: t, port: null };
10728
+ }
10729
+ function collectPorts(text2) {
10730
+ const ports = /* @__PURE__ */ new Map();
10731
+ for (const rawLine of text2.split(/\r?\n/)) {
10732
+ const line = rawLine.trim();
10733
+ if (!line || line.startsWith("#")) continue;
10734
+ for (const m of line.matchAll(new RegExp(HOST_PORT, "g"))) {
10735
+ const host = m[1] ?? m[2];
10736
+ const port = Number(m[3]);
10737
+ if (host && port >= 1 && port <= 65535 && !ports.has(host)) ports.set(host, port);
10738
+ }
10739
+ if (line.includes(",")) {
10740
+ const cols = line.split(",").map((c2) => c2.trim().replace(/^"|"$/g, "").replace(/#.*$/, "").trim());
10741
+ for (let i = 0; i < cols.length - 1; i++) {
10742
+ const host = cols[i];
10743
+ if (!new RegExp(`^(?:${IPV4}|\\[${IPV6}\\])$`).test(host)) continue;
10744
+ if (!/^\d{1,5}$/.test(cols[i + 1])) continue;
10745
+ const port = Number(cols[i + 1]);
10746
+ const clean = host.startsWith("[") ? host.slice(1, -1) : host;
10747
+ if (port >= 1 && port <= 65535 && !ports.has(clean)) ports.set(clean, port);
10748
+ }
10749
+ }
10750
+ }
10751
+ return ports;
10752
+ }
10753
+ function parseJson(text2) {
10754
+ let data;
10755
+ try {
10756
+ data = JSON.parse(text2);
10757
+ } catch {
10758
+ return null;
10759
+ }
10760
+ let list = data;
10761
+ if (data && typeof data === "object" && !Array.isArray(data)) {
10762
+ for (const k of LIST_KEYS) {
10763
+ const v = data[k];
10764
+ if (Array.isArray(v)) {
10765
+ list = v;
10766
+ break;
10767
+ }
10768
+ }
10769
+ }
10770
+ if (!Array.isArray(list)) return null;
10771
+ const out2 = [];
10772
+ for (const item of list) {
10773
+ if (typeof item === "string") {
10774
+ const parsed2 = splitHostPort(item);
10775
+ if (parsed2) out2.push(parsed2);
10776
+ continue;
10777
+ }
10778
+ const host = objString(item, IP_KEYS);
10779
+ if (!host) continue;
10780
+ const parsed = splitHostPort(host);
10781
+ if (!parsed) continue;
10782
+ out2.push({ ip: parsed.ip, port: objPort(item) ?? parsed.port });
10783
+ }
10784
+ return out2;
10785
+ }
10786
+ function parseSourcePayload(text2) {
10787
+ const trimmed = text2.trim();
10788
+ if (!trimmed) return [];
10789
+ if (trimmed.startsWith("[") || trimmed.startsWith("{")) {
10790
+ const json = parseJson(trimmed);
10791
+ if (json !== null) return json;
10792
+ }
10793
+ const hosts = readIpFile(text2);
10794
+ const ports = collectPorts(text2);
10795
+ return hosts.map((ip) => ({ ip, port: ports.get(ip) ?? null }));
10796
+ }
10797
+ function toCandidateInputs(parsed, sourceId) {
10798
+ return parsed.map((p) => ({
10799
+ ip: p.ip,
10800
+ ...p.port === null ? {} : { port: p.port },
10801
+ source: sourceId
10802
+ }));
10803
+ }
10804
+ var IPV4, IPV6, HOST_PORT, IP_KEYS, LIST_KEYS;
10805
+ var init_normalizer = __esm({
10806
+ "src/sources/normalizer.ts"() {
10807
+ "use strict";
10808
+ init_ip_ranges();
10809
+ IPV4 = "\\d{1,3}(?:\\.\\d{1,3}){3}";
10810
+ IPV6 = "[0-9a-fA-F:.]+";
10811
+ HOST_PORT = new RegExp(`(?:\\[(${IPV6})\\]:|(${IPV4}):)(\\d{1,5})`);
10812
+ IP_KEYS = ["ip", "address", "addr", "host", "target", "value"];
10813
+ LIST_KEYS = ["ips", "data", "list", "candidates", "result", "items", "records"];
10814
+ }
10815
+ });
10816
+
10817
+ // src/sources/manager.ts
10818
+ function failure(source, error, startedAt) {
10819
+ return {
10820
+ source,
10821
+ inputs: [],
10822
+ etag: source.etag,
10823
+ lastModified: source.lastModified,
10824
+ outcome: {
10825
+ sourceId: source.id,
10826
+ ok: false,
10827
+ added: 0,
10828
+ updated: 0,
10829
+ rejected: 0,
10830
+ reasons: {},
10831
+ notModified: false,
10832
+ error: error.slice(0, 300),
10833
+ durationMs: Date.now() - startedAt,
10834
+ // API 型源没有 url,别把空串渲染成 <invalid-url>
10835
+ url: source.url ? sanitizeUrl(source.url) : ""
10836
+ }
10837
+ };
10838
+ }
10839
+ async function syncSources(options = {}) {
10840
+ const now = options.now ?? Date.now();
10841
+ const configured = loadSources();
10842
+ const wanted = new Set(options.sourceIds ?? []);
10843
+ const targets = configured.sources.filter(
10844
+ (s) => s.enabled && (wanted.size === 0 || wanted.has(s.id))
10845
+ );
10846
+ const fetcher = options.fetcher ?? fetchSourceText;
10847
+ const fetched = [];
10848
+ const listTargets = targets.filter((s) => !isApiSource(s));
10849
+ const apiTargets = targets.filter(isApiSource);
10850
+ const listResults = await Promise.all(
10851
+ listTargets.map(async (source) => {
10852
+ const startedAt = Date.now();
10853
+ try {
10854
+ const res = await fetcher(source, {
10855
+ timeoutMs: options.timeoutMs,
10856
+ maxBytes: options.maxBytes,
10857
+ allowHttp: options.allowHttp
10858
+ });
10859
+ const outcome = {
10860
+ sourceId: source.id,
10861
+ ok: true,
10862
+ added: 0,
10863
+ updated: 0,
10864
+ rejected: 0,
10865
+ reasons: {},
10866
+ notModified: res.notModified,
10867
+ error: "",
10868
+ durationMs: Date.now() - startedAt,
10869
+ url: res.url
10870
+ };
10871
+ if (res.notModified) {
10872
+ return { source, outcome, inputs: [], etag: res.etag, lastModified: res.lastModified };
10873
+ }
10874
+ const parsed = parseSourcePayload(res.text);
10875
+ let inputs = toCandidateInputs(parsed, source.id);
10876
+ if (options.lightCheck && inputs.length > 0) inputs = await options.lightCheck(inputs);
10877
+ return { source, outcome, inputs, etag: res.etag, lastModified: res.lastModified };
10878
+ } catch (err) {
10879
+ return failure(source, err instanceof Error ? err.message : String(err), startedAt);
10880
+ }
10881
+ })
10882
+ );
10883
+ fetched.push(...listResults);
10884
+ if (apiTargets.length > 0) {
10885
+ let lastAt = 0;
10886
+ let lastType = "";
10887
+ for (const source of apiTargets) {
10888
+ const spec = PROVIDERS[source.type];
10889
+ if (spec && lastType === source.type) {
10890
+ const wait = spec.minIntervalMs - (Date.now() - lastAt);
10891
+ if (wait > 0) await new Promise((resolve4) => setTimeout(resolve4, wait));
10892
+ }
10893
+ lastType = source.type;
10894
+ lastAt = Date.now();
10895
+ const startedAt = Date.now();
10896
+ try {
10897
+ const result = await runProvider({
10898
+ source,
10899
+ timeoutMs: options.timeoutMs,
10900
+ maxBytes: options.maxBytes,
10901
+ fetchImpl: options.providerFetch
10902
+ });
10903
+ let inputs = toCandidateInputs(result.candidates, source.id);
10904
+ if (options.lightCheck && inputs.length > 0) inputs = await options.lightCheck(inputs);
10905
+ fetched.push({
10906
+ source,
10907
+ outcome: {
10908
+ sourceId: source.id,
10909
+ ok: true,
10910
+ added: 0,
10911
+ updated: 0,
10912
+ rejected: 0,
10913
+ reasons: {},
10914
+ notModified: false,
10915
+ error: "",
10916
+ durationMs: Date.now() - startedAt,
10917
+ // note 已经脱敏(不含 dork / key),可安全展示
10918
+ url: result.note
10919
+ },
10920
+ inputs,
10921
+ etag: "",
10922
+ lastModified: ""
10923
+ });
10924
+ } catch (err) {
10925
+ fetched.push(failure(source, err instanceof Error ? err.message : String(err), startedAt));
10926
+ }
10927
+ }
10928
+ }
10929
+ let poolCandidates = 0;
10930
+ await withConfigDirLock(async () => {
10931
+ const poolBefore = readPoolRaw();
10932
+ const pool2 = parsePool(poolBefore);
10933
+ const cfgBefore = readSourcesRaw();
10934
+ const cfg = parseSources(cfgBefore);
10935
+ for (const item of fetched) {
10936
+ const current = cfg.sources.find((s) => s.id === item.source.id);
10937
+ const outcome = item.outcome;
10938
+ if (current) {
10939
+ current.lastSyncAt = now;
10940
+ if (outcome.ok) {
10941
+ current.etag = item.etag;
10942
+ current.lastModified = item.lastModified;
10943
+ current.failCount = 0;
10944
+ current.lastError = "";
10945
+ } else {
10946
+ current.failCount += 1;
10947
+ current.lastError = outcome.error;
10948
+ }
10949
+ }
10950
+ if (outcome.ok && !outcome.notModified && item.inputs.length > 0) {
10951
+ const r = upsertCandidates(pool2, item.inputs, now);
10952
+ outcome.added = r.added;
10953
+ outcome.updated = r.updated;
10954
+ outcome.rejected = r.rejected;
10955
+ outcome.reasons = r.reasons;
10956
+ }
10957
+ const run = {
10958
+ at: now,
10959
+ sourceId: outcome.sourceId,
10960
+ ok: outcome.ok,
10961
+ added: outcome.added,
10962
+ updated: outcome.updated,
10963
+ rejected: outcome.rejected,
10964
+ error: outcome.error,
10965
+ durationMs: outcome.durationMs,
10966
+ notModified: outcome.notModified
10967
+ };
10968
+ appendRun(cfg, run);
10969
+ }
10970
+ const poolAfter = serializePool(pool2);
10971
+ if (poolAfter !== poolBefore) writePoolAtomic(poolAfter);
10972
+ const cfgAfter = serializeSources(cfg);
10973
+ if (cfgAfter !== cfgBefore) writeSourcesAtomic(cfgAfter);
10974
+ poolCandidates = pool2.candidates.length;
10975
+ });
10976
+ return { at: now, outcomes: fetched.map((f) => f.outcome), poolCandidates };
10977
+ }
10978
+ async function testSource(source, options = {}) {
10979
+ const startedAt = Date.now();
10980
+ const baseOutcome = (ok, added, url, error) => ({
10981
+ sourceId: source.id,
10982
+ ok,
10983
+ added,
10984
+ updated: 0,
10985
+ rejected: 0,
10986
+ reasons: {},
10987
+ notModified: false,
10988
+ error,
10989
+ durationMs: Date.now() - startedAt,
10990
+ url
10991
+ });
10992
+ if (isApiSource(source)) {
10993
+ try {
10994
+ const result = await runProvider({
10995
+ source,
10996
+ timeoutMs: options.timeoutMs,
10997
+ maxBytes: options.maxBytes,
10998
+ fetchImpl: options.providerFetch
10999
+ });
11000
+ return baseOutcome(true, result.candidates.length, result.note, "");
11001
+ } catch (err) {
11002
+ const msg = err instanceof Error ? err.message : String(err);
11003
+ return baseOutcome(false, 0, "", msg.slice(0, 300));
11004
+ }
11005
+ }
11006
+ const fetcher = options.fetcher ?? fetchSourceText;
11007
+ try {
11008
+ const res = await fetcher(source, {
11009
+ timeoutMs: options.timeoutMs,
11010
+ maxBytes: options.maxBytes,
11011
+ allowHttp: options.allowHttp
11012
+ });
11013
+ const parsed = res.notModified ? [] : parseSourcePayload(res.text);
11014
+ return {
11015
+ sourceId: source.id,
11016
+ ok: true,
11017
+ added: parsed.length,
11018
+ updated: 0,
11019
+ rejected: 0,
11020
+ reasons: {},
11021
+ notModified: res.notModified,
11022
+ error: "",
11023
+ durationMs: Date.now() - startedAt,
11024
+ url: res.url
11025
+ };
11026
+ } catch (err) {
11027
+ return {
11028
+ sourceId: source.id,
11029
+ ok: false,
11030
+ added: 0,
11031
+ updated: 0,
11032
+ rejected: 0,
11033
+ reasons: {},
11034
+ notModified: false,
11035
+ error: (err instanceof Error ? err.message : String(err)).slice(0, 300),
11036
+ durationMs: Date.now() - startedAt,
11037
+ url: sanitizeUrl(source.url)
11038
+ };
11039
+ }
11040
+ }
11041
+ var init_manager = __esm({
11042
+ "src/sources/manager.ts"() {
11043
+ "use strict";
11044
+ init_config2();
11045
+ init_fetch();
11046
+ init_normalizer();
11047
+ init_providers();
11048
+ init_pool();
11049
+ }
11050
+ });
11051
+
11052
+ // src/sources/light.ts
11053
+ var light_exports = {};
11054
+ __export(light_exports, {
11055
+ LIGHT_CONCURRENCY: () => LIGHT_CONCURRENCY,
11056
+ LIGHT_CONNECT_TIMEOUT_MS: () => LIGHT_CONNECT_TIMEOUT_MS,
11057
+ LIGHT_MAX_PER_SYNC: () => LIGHT_MAX_PER_SYNC,
11058
+ LIGHT_REFRESH_MS: () => LIGHT_REFRESH_MS,
11059
+ LIGHT_TOTAL_TIMEOUT_MS: () => LIGHT_TOTAL_TIMEOUT_MS,
11060
+ lightCheckCandidates: () => lightCheckCandidates,
11061
+ tcpProbeOnce: () => tcpProbeOnce
11062
+ });
11063
+ import { Socket as Socket3 } from "node:net";
11064
+ function tcpProbeOnce(ip, port, timeoutMs) {
11065
+ return new Promise((resolve4) => {
11066
+ const socket = new Socket3();
11067
+ let settled = false;
11068
+ const done = (ok) => {
11069
+ if (settled) return;
11070
+ settled = true;
11071
+ socket.destroy();
11072
+ resolve4(ok);
11073
+ };
11074
+ socket.setTimeout(timeoutMs, () => done(false));
11075
+ socket.once("error", () => done(false));
11076
+ socket.once("connect", () => done(true));
11077
+ try {
11078
+ socket.connect(port, ip);
11079
+ } catch {
11080
+ done(false);
11081
+ }
11082
+ });
11083
+ }
11084
+ async function defaultTlsProbe(ip, port, host, timeoutMs) {
11085
+ const r = await probeTlsHandshake(ip, port, host, timeoutMs);
11086
+ return { ok: !r.error, tlsMs: r.tlsMs };
11087
+ }
11088
+ function needsCheck(key, now, existing) {
11089
+ const found = existing.candidates.find((c2) => c2.key === key);
11090
+ if (!found || !found.lightCheck) return true;
11091
+ return now - found.lightCheck.at > LIGHT_REFRESH_MS;
11092
+ }
11093
+ async function lightCheckCandidates(inputs, options = {}) {
11094
+ const now = options.now ?? Date.now();
11095
+ const max = options.maxPerSync ?? LIGHT_MAX_PER_SYNC;
11096
+ const concurrency = Math.max(1, options.concurrency ?? LIGHT_CONCURRENCY);
11097
+ const connectTimeout = options.connectTimeoutMs ?? LIGHT_CONNECT_TIMEOUT_MS;
11098
+ const totalTimeout = options.totalTimeoutMs ?? LIGHT_TOTAL_TIMEOUT_MS;
11099
+ const sni = options.sni || loadConfig().dataHost || "cloudflare.com";
11100
+ const tcpProbe = options.tcpProbe ?? tcpProbeOnce;
11101
+ const tlsProbe = options.tlsProbe ?? defaultTlsProbe;
11102
+ const pool2 = parsePool(readPoolRaw());
11103
+ const out2 = inputs.map((i) => ({ ...i }));
11104
+ const pending = [];
11105
+ for (let i = 0; i < out2.length && pending.length < max; i++) {
11106
+ const input = out2[i];
11107
+ const key = normalizeCandidateKey(input.ip, input.port ?? 443);
11108
+ if (!key) continue;
11109
+ if (needsCheck(key, now, pool2)) pending.push(i);
11110
+ }
11111
+ const deadline = Date.now() + totalTimeout;
11112
+ let cursor = 0;
11113
+ const worker = async () => {
11114
+ for (; ; ) {
11115
+ if (Date.now() >= deadline) return;
11116
+ const idx = cursor++;
11117
+ if (idx >= pending.length) return;
11118
+ const input = out2[pending[idx]];
11119
+ const port = input.port ?? 443;
11120
+ const tcpOk = await tcpProbe(input.ip, port, connectTimeout);
11121
+ let tlsOk = false;
11122
+ let tlsMs = 0;
11123
+ if (tcpOk) {
11124
+ const tls7 = await tlsProbe(input.ip, port, sni, connectTimeout);
11125
+ tlsOk = tls7.ok;
11126
+ tlsMs = tls7.tlsMs;
11127
+ }
11128
+ const check = {
11129
+ tcpOk,
11130
+ tlsOk,
11131
+ // 字段顺序必须与 Go struct 一致:tlsMs 排在 at 之前
11132
+ ...tlsOk && tlsMs > 0 ? { tlsMs } : {},
11133
+ at: now
11134
+ };
11135
+ input.lightCheck = check;
11136
+ }
11137
+ };
11138
+ await Promise.all(Array.from({ length: Math.min(concurrency, pending.length) }, worker));
11139
+ return out2;
11140
+ }
11141
+ var LIGHT_MAX_PER_SYNC, LIGHT_CONCURRENCY, LIGHT_CONNECT_TIMEOUT_MS, LIGHT_TOTAL_TIMEOUT_MS, LIGHT_REFRESH_MS;
11142
+ var init_light = __esm({
11143
+ "src/sources/light.ts"() {
11144
+ "use strict";
11145
+ init_store();
11146
+ init_true_probe();
11147
+ init_pool();
11148
+ LIGHT_MAX_PER_SYNC = 100;
11149
+ LIGHT_CONCURRENCY = 8;
11150
+ LIGHT_CONNECT_TIMEOUT_MS = 2e3;
11151
+ LIGHT_TOTAL_TIMEOUT_MS = 3e4;
11152
+ LIGHT_REFRESH_MS = 7 * 24 * 60 * 60 * 1e3;
11153
+ }
11154
+ });
11155
+
11156
+ // src/sources/command.ts
11157
+ var command_exports3 = {};
11158
+ __export(command_exports3, {
11159
+ runSourceCommand: () => runSourceCommand
11160
+ });
11161
+ function out(text2) {
11162
+ process.stdout.write(`${text2}
11163
+ `);
11164
+ }
11165
+ function fail(text2) {
11166
+ process.stderr.write(`\u2717 ${text2}
11167
+ `);
11168
+ process.exit(1);
11169
+ }
11170
+ function parseType(raw) {
11171
+ if (raw === "github-raw" || raw === "custom-url" || raw === "ripe-stat") return raw;
11172
+ return fail(`--type \u53EA\u63A5\u53D7 github-raw / custom-url / ripe-stat\uFF0C\u6536\u5230\u300C${raw}\u300D`);
11173
+ }
11174
+ function isApiType(type) {
11175
+ return type === "ripe-stat";
11176
+ }
11177
+ function printList(file, asJson) {
11178
+ if (asJson) {
11179
+ out(JSON.stringify(file, null, 2));
11180
+ return;
11181
+ }
11182
+ if (file.sources.length === 0) {
11183
+ out("\u8FD8\u6CA1\u6709\u6570\u636E\u6E90\u3002\u7528 `cfpilot source add <id> --url <\u94FE\u63A5>` \u6DFB\u52A0\u3002");
11184
+ return;
11185
+ }
11186
+ out("\u5916\u90E8 IP \u6570\u636E\u6E90\uFF1A");
11187
+ for (const s of file.sources) {
11188
+ const status2 = s.enabled ? "\u542F\u7528" : "\u7981\u7528";
11189
+ const last = s.lastSyncAt ? new Date(s.lastSyncAt).toLocaleString() : "\u4ECE\u672A";
11190
+ out(` [${status2}] ${s.id} ${s.type} ${sanitizeUrl(s.url)}`);
11191
+ out(` \u95F4\u9694 ${s.intervalHours}h \xB7 \u4E0A\u6B21 ${last} \xB7 \u5931\u8D25 ${s.failCount}${s.lastError ? ` \xB7 ${s.lastError}` : ""}`);
11192
+ }
11193
+ if (file.runs.length > 0) {
11194
+ out("\n\u6700\u8FD1\u91C7\u96C6\u8BB0\u5F55\uFF1A");
11195
+ for (const r of file.runs.slice(-5).reverse()) {
11196
+ const tag = r.ok ? r.notModified ? "\u672A\u53D8\u66F4" : `+${r.added}/~${r.updated}/\xD7${r.rejected}` : `\u5931\u8D25\uFF1A${r.error}`;
11197
+ out(` ${new Date(r.at).toLocaleString()} ${r.sourceId} ${tag} ${r.durationMs}ms`);
11198
+ }
11199
+ }
11200
+ }
11201
+ function printSync(report, asJson) {
11202
+ if (asJson) {
11203
+ out(JSON.stringify(report, null, 2));
11204
+ return;
11205
+ }
11206
+ for (const r of report.outcomes) {
11207
+ if (!r.ok) {
11208
+ out(` \u2717 ${r.sourceId}\uFF1A${r.error}`);
11209
+ } else if (r.notModified) {
11210
+ out(` = ${r.sourceId}\uFF1A\u672A\u53D8\u66F4\uFF08304\uFF09`);
11211
+ } else {
11212
+ out(` \u2713 ${r.sourceId}\uFF1A\u65B0\u589E ${r.added} \xB7 \u5237\u65B0 ${r.updated} \xB7 \u62D2\u7EDD ${r.rejected}`);
11213
+ }
11214
+ }
11215
+ out(`\u672C\u5730\u5019\u9009\u6C60\u73B0\u6709 ${report.poolCandidates} \u6761\uFF08\u672A\u5199 KV\u3001\u672A\u56DE\u586B\u8BA2\u9605\uFF09`);
11216
+ }
11217
+ async function removeSource(id) {
11218
+ return withConfigDirLock(async () => {
11219
+ const cfgBefore = readSourcesRaw();
11220
+ const cfg = parseSources(cfgBefore);
11221
+ const before = cfg.sources.length;
11222
+ cfg.sources = cfg.sources.filter((s) => s.id !== id);
11223
+ if (cfg.sources.length === before) throw new Error(`\u6570\u636E\u6E90\u4E0D\u5B58\u5728\uFF1A${id}`);
11224
+ cfg.runs = cfg.runs.filter((r) => r.sourceId !== id);
11225
+ cfg.updatedAt = Date.now();
11226
+ const poolBefore = readPoolRaw();
11227
+ const pool2 = parsePool(poolBefore);
11228
+ let removed = 0;
11229
+ pool2.candidates = pool2.candidates.filter((c2) => {
11230
+ if (!c2.sources.includes(id)) return true;
11231
+ c2.sources = c2.sources.filter((s) => s !== id);
11232
+ if (c2.sources.length > 0 || c2.status === "disabled") return true;
11233
+ removed++;
11234
+ return false;
11235
+ });
11236
+ const cfgAfter = serializeSources(cfg);
11237
+ if (cfgAfter !== cfgBefore) writeSourcesAtomic(cfgAfter);
11238
+ const poolAfter = serializePool(pool2);
11239
+ if (poolAfter !== poolBefore) writePoolAtomic(poolAfter);
11240
+ return { removedCandidates: removed, keptCandidates: pool2.candidates.length };
11241
+ });
11242
+ }
11243
+ async function runSourceCommand(args) {
11244
+ const action = (args.positionals[0] ?? "list").toLowerCase();
11245
+ const asJson = flagBool(args, "json");
11246
+ if (flagBool(args, "h") || flagBool(args, "help") || action === "help") {
11247
+ out(HELP);
11248
+ return;
11249
+ }
11250
+ switch (action) {
11251
+ case "list": {
11252
+ printList(loadSources(), asJson);
11253
+ return;
11254
+ }
11255
+ case "add": {
11256
+ const id = (args.positionals[1] ?? "").trim();
11257
+ if (!id) fail("\u7528\u6CD5\uFF1Acfpilot source add <id> --type <\u7C7B\u578B> [--url <\u94FE\u63A5> | --query <\u4E32>]");
11258
+ const type = parseType(flagString(args, "type") || "custom-url");
11259
+ const url = flagString(args, "url").trim();
11260
+ if (!isApiType(type) && !url) fail("list \u578B\u6570\u636E\u6E90\u7F3A\u5C11 --url");
11261
+ if (isApiType(type) && url) fail("API \u578B\u6570\u636E\u6E90\u4E0D\u9700\u8981 --url\uFF0C\u8BF7\u7528 --query");
11262
+ if (url) {
11263
+ try {
11264
+ validateSourceUrl(url);
11265
+ } catch (err) {
11266
+ fail(err instanceof Error ? err.message : String(err));
11267
+ }
11268
+ }
11269
+ const spec = isApiType(type) ? PROVIDERS[type] : void 0;
11270
+ const query = flagString(args, "query").trim() || (spec ? spec.defaultQuery : "");
11271
+ if (type === "ripe-stat" && !/^AS\d{1,10}$/i.test(query)) {
11272
+ fail(`ripe-stat \u7684 --query \u5FC5\u987B\u662F ASN\uFF08\u5982 AS13335\uFF09\uFF0C\u6536\u5230\u300C${query}\u300D`);
11273
+ }
11274
+ const source = makeSource({
11275
+ id,
11276
+ name: flagString(args, "name") || id,
11277
+ type,
11278
+ url,
11279
+ mirrors: flagList(args, "mirror"),
11280
+ enabled: !flagBool(args, "disabled"),
11281
+ intervalHours: flagNumber(args, "interval-hours", 0) || void 0,
11282
+ query,
11283
+ maxResults: flagNumber(args, "max-results", spec?.defaultMaxResults ?? 200)
11284
+ });
11285
+ await withConfigDirLock(async () => {
11286
+ const before = readSourcesRaw();
11287
+ const file = parseSources(before);
11288
+ if (file.sources.some((s) => s.id === id)) fail(`\u6570\u636E\u6E90\u5DF2\u5B58\u5728\uFF1A${id}`);
11289
+ file.sources.push(source);
11290
+ file.updatedAt = Date.now();
11291
+ const after = serializeSources(file);
11292
+ if (after !== before) writeSourcesAtomic(after);
11293
+ });
11294
+ out(asJson ? JSON.stringify(source, null, 2) : `\u2713 \u5DF2\u6DFB\u52A0\u6570\u636E\u6E90 ${id}\uFF08${source.type}\uFF09`);
11295
+ return;
11296
+ }
11297
+ case "remove": {
11298
+ const id = (args.positionals[1] ?? "").trim();
11299
+ if (!id) fail("\u7528\u6CD5\uFF1Acfpilot source remove <id>");
11300
+ const r = await removeSource(id);
11301
+ out(asJson ? JSON.stringify({ id, ...r }, null, 2) : `\u2713 \u5DF2\u5220\u9664\u6570\u636E\u6E90 ${id}\uFF1B\u6E05\u7406\u65E0\u6765\u6E90\u5019\u9009 ${r.removedCandidates} \u6761\uFF0C\u6C60\u5185\u4FDD\u7559 ${r.keptCandidates} \u6761`);
11302
+ return;
11303
+ }
11304
+ case "test": {
11305
+ const id = (args.positionals[1] ?? "").trim();
11306
+ if (!id) fail("\u7528\u6CD5\uFF1Acfpilot source test <id>");
11307
+ const source = loadSources().sources.find((s) => s.id === id);
11308
+ if (!source) fail(`\u6570\u636E\u6E90\u4E0D\u5B58\u5728\uFF1A${id}`);
11309
+ const probe = { ...source, etag: "", lastModified: "" };
11310
+ const r = await testSource(probe, {
11311
+ allowHttp: flagBool(args, "allow-http"),
11312
+ timeoutMs: flagNumber(args, "timeout-ms", SOURCE_TIMEOUT_MS)
11313
+ });
11314
+ if (asJson) {
11315
+ out(JSON.stringify(r, null, 2));
11316
+ } else if (r.ok) {
11317
+ out(`\u2713 ${source.id} \u53EF\u7528\uFF1A\u89E3\u6790\u51FA ${r.added} \u6761\u5019\u9009\uFF08${r.durationMs}ms\uFF09
11318
+ \u6765\u81EA ${r.url}`);
11319
+ } else {
11320
+ out(`\u2717 ${source.id} \u4E0D\u53EF\u7528\uFF1A${r.error}`);
11321
+ }
11322
+ if (!r.ok) process.exitCode = 1;
11323
+ return;
11324
+ }
11325
+ case "sync": {
11326
+ const ids = args.positionals.slice(1).filter(Boolean);
11327
+ const options = {
11328
+ sourceIds: ids,
11329
+ allowHttp: flagBool(args, "allow-http"),
11330
+ timeoutMs: flagNumber(args, "timeout-ms", SOURCE_TIMEOUT_MS)
11331
+ };
11332
+ if (flagBool(args, "light")) {
11333
+ const { lightCheckCandidates: lightCheckCandidates2 } = await Promise.resolve().then(() => (init_light(), light_exports));
11334
+ options.lightCheck = lightCheckCandidates2;
11335
+ }
11336
+ const report = await syncSources(options);
11337
+ printSync(report, asJson);
11338
+ if (report.outcomes.some((r) => !r.ok)) process.exitCode = 1;
11339
+ return;
11340
+ }
11341
+ default:
11342
+ fail(`\u672A\u77E5\u52A8\u4F5C\uFF1A${action}
11343
+ ${HELP}`);
11344
+ }
11345
+ }
11346
+ var HELP;
11347
+ var init_command3 = __esm({
11348
+ "src/sources/command.ts"() {
11349
+ "use strict";
11350
+ init_args();
11351
+ init_config2();
11352
+ init_fetch();
11353
+ init_providers();
11354
+ init_manager();
11355
+ init_pool();
11356
+ HELP = `
11357
+ cfpilot source <\u52A8\u4F5C> [\u9009\u9879] \u5916\u90E8 IP \u6570\u636E\u6E90\u7BA1\u7406\uFF08\u672C\u5730\u6C60\uFF0C\u4E0D\u5199 KV\uFF09
11358
+
11359
+ \u52A8\u4F5C:
11360
+ list \u5217\u51FA\u6570\u636E\u6E90\u4E0E\u6700\u8FD1\u91C7\u96C6\u8BB0\u5F55
11361
+ add <id> \u65B0\u589E\u6570\u636E\u6E90\uFF08\u9ED8\u8BA4\u542F\u7528\uFF09
11362
+ remove <id> \u5220\u9664\u6570\u636E\u6E90\u5E76\u6E05\u7406\u6765\u6E90\u5173\u8054
11363
+ test <id> \u6D4B\u8BD5\u8FDE\u63A5\uFF08\u53EA\u62C9\u4E0D\u5199\u6C60\uFF09
11364
+ sync [id...] \u540C\u6B65\u5230 ~/.cfpilot/external-candidates.json
11365
+
11366
+ \u6765\u6E90\u7C7B\u578B\uFF08--type\uFF09:
11367
+ github-raw / custom-url GET \u4E00\u4EFD\u6E05\u5355\u6587\u672C\uFF08\u9700 --url\uFF09
11368
+ ripe-stat RIPEstat AS \u5BA3\u544A\u524D\u7F00\uFF0C\u96F6 Key\uFF08\u9ED8\u8BA4 AS13335\uFF09
11369
+
11370
+ \u9009\u9879:
11371
+ --type <\u7C7B\u578B> \u6765\u6E90\u7C7B\u578B\uFF08\u9ED8\u8BA4 custom-url\uFF09
11372
+ --url <\u94FE\u63A5> \u6E05\u5355 URL\uFF08list \u578B\u5FC5\u586B\uFF0CAPI \u578B\u4E0D\u7528\uFF09
11373
+ --query <\u4E32> API \u578B\u67E5\u8BE2\uFF1Aripe-stat \u7528 ASN\uFF08\u7F3A\u7701 AS13335\uFF09
11374
+ --max-results <n> API \u578B\u5355\u6B21\u6700\u591A\u5165\u6C60\u5019\u9009\uFF08\u9ED8\u8BA4 200\uFF09
11375
+ --name <\u540D\u79F0> \u663E\u793A\u540D\u79F0\uFF08\u9ED8\u8BA4\u540C id\uFF09
11376
+ --mirror <\u94FE\u63A5> \u955C\u50CF URL\uFF0C\u53EF\u91CD\u590D\uFF08\u4EC5 list \u578B\uFF09
11377
+ --interval-hours <\u5C0F\u65F6> \u5EFA\u8BAE\u540C\u6B65\u95F4\u9694
11378
+ --disabled \u65B0\u589E\u540E\u4FDD\u6301\u7981\u7528
11379
+ --allow-http \u5141\u8BB8 http\uFF08\u4EC5\u672C\u5730\u81EA\u5EFA\u6D4B\u8BD5\u6E90\uFF0C\u751F\u4EA7\u8BF7\u7528 HTTPS\uFF09
11380
+ --timeout-ms <\u6BEB\u79D2> \u5355\u6E90\u8D85\u65F6\uFF08\u9ED8\u8BA4 ${SOURCE_TIMEOUT_MS}\uFF09
11381
+ --light \u540C\u6B65\u540E\u5BF9\u65B0\u589E\u5019\u9009\u505A TCP/TLS \u8F7B\u91CF\u6821\u9A8C
11382
+ --json \u4EE5 JSON \u8F93\u51FA
11383
+ -h, --help \u663E\u793A\u672C\u5E2E\u52A9
11384
+
11385
+ \u793A\u4F8B:
11386
+ cfpilot source add ripe --type ripe-stat --query AS13335 --max-results 200
11387
+ cfpilot source sync ripe --json
11388
+
11389
+ \u26A0\uFE0F \u540C\u6B65\u53EA\u5199\u672C\u5730\u78C1\u76D8\uFF1A\u4E0D\u89E6\u53D1 WS \u6821\u9A8C\u3001\u4E0D\u6D4B\u901F\u3001\u4E0D\u56DE\u586B\u8BA2\u9605\u3002
11390
+ \u8981\u66F4\u65B0\u8BA2\u9605\u8BF7\u7528 cfpilot scan --from-pool\uFF08\u5B8C\u6574\u4F18\u9009 + \u56DE\u586B\uFF09\u3002
11391
+ `;
11392
+ }
11393
+ });
11394
+
9789
11395
  // src/scan/single.ts
9790
11396
  import * as net6 from "node:net";
9791
11397
  function probeTcp(ip, port, timeoutMs) {
@@ -9927,13 +11533,13 @@ function printStage(result) {
9927
11533
  }
9928
11534
  async function runTestCommand(args) {
9929
11535
  if (flagBool(args, "h") || flagBool(args, "help")) {
9930
- process.stdout.write(HELP);
11536
+ process.stdout.write(HELP2);
9931
11537
  return;
9932
11538
  }
9933
11539
  const host = flagString(args, "host").trim();
9934
11540
  const ip = flagString(args, "ip").trim();
9935
11541
  if (!host || !ip) {
9936
- process.stderr.write("\u7F3A\u5C11\u53C2\u6570\uFF1A--host \u4E0E --ip \u90FD\u662F\u5FC5\u586B\n\n" + HELP);
11542
+ process.stderr.write("\u7F3A\u5C11\u53C2\u6570\uFF1A--host \u4E0E --ip \u90FD\u662F\u5FC5\u586B\n\n" + HELP2);
9937
11543
  process.exitCode = 1;
9938
11544
  return;
9939
11545
  }
@@ -9981,14 +11587,14 @@ async function runTestCommand(args) {
9981
11587
  }
9982
11588
  if (results.some((r) => !r.ok)) process.exitCode = 1;
9983
11589
  }
9984
- var HELP;
11590
+ var HELP2;
9985
11591
  var init_single_command = __esm({
9986
11592
  "src/scan/single-command.ts"() {
9987
11593
  "use strict";
9988
11594
  init_args();
9989
11595
  init_version();
9990
11596
  init_single();
9991
- HELP = `
11597
+ HELP2 = `
9992
11598
  ${NAME} test \u2014\u2014 \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u8DEF
9993
11599
 
9994
11600
  \u7528\u6CD5:
@@ -10025,7 +11631,7 @@ ${NAME} test \u2014\u2014 \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u
10025
11631
  import * as net7 from "node:net";
10026
11632
  import * as tls5 from "node:tls";
10027
11633
  import * as https from "node:https";
10028
- function fail(code, error) {
11634
+ function fail2(code, error) {
10029
11635
  return { ok: false, code, error };
10030
11636
  }
10031
11637
  function isPublicIp(value) {
@@ -10165,7 +11771,7 @@ function identifyEgress(options) {
10165
11771
  if (Buffer.byteLength(user) > 255 || Buffer.byteLength(password) > 255 || !user && password) throw new Error();
10166
11772
  }
10167
11773
  } catch {
10168
- 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"));
11774
+ return Promise.resolve(fail2("config", "\u8BC6\u522B\u914D\u7F6E\u65E0\u6548\uFF1A\u9700\u8981 HTTPS\u3001\u6709\u6548\u77ED\u671F\u4EE4\u724C\u548C\u53EF\u9009 SOCKS5 \u5730\u5740"));
10169
11775
  }
10170
11776
  return new Promise((resolve4) => {
10171
11777
  let settled = false;
@@ -10181,12 +11787,12 @@ function identifyEgress(options) {
10181
11787
  agent.destroy();
10182
11788
  resolve4(result);
10183
11789
  };
10184
- const timer = setTimeout(() => finish(fail("timeout", "\u51FA\u53E3\u8BC6\u522B\u8D85\u8FC7\u603B\u8D85\u65F6\u9884\u7B97")), timeoutMs);
11790
+ const timer = setTimeout(() => finish(fail2("timeout", "\u51FA\u53E3\u8BC6\u522B\u8D85\u8FC7\u603B\u8D85\u65F6\u9884\u7B97")), timeoutMs);
10185
11791
  if (proxy) {
10186
11792
  const selectedProxy = proxy;
10187
11793
  agent.createConnection = (_connectionOptions, callback) => {
10188
11794
  socket = net7.connect({ host: selectedProxy.hostname.replace(/^\[|\]$/g, ""), port: Number(selectedProxy.port || 1080) });
10189
- socket.once("error", () => finish(fail("transport", "SOCKS5 \u8FDE\u63A5\u5931\u8D25")));
11795
+ socket.once("error", () => finish(fail2("transport", "SOCKS5 \u8FDE\u63A5\u5931\u8D25")));
10190
11796
  socket.once("connect", () => {
10191
11797
  const raw = socket;
10192
11798
  void negotiateSocks(raw, selectedProxy, target).then(() => {
@@ -10194,9 +11800,9 @@ function identifyEgress(options) {
10194
11800
  const hostname = target.hostname.replace(/^\[|\]$/g, "");
10195
11801
  const secure = tls5.connect({ socket: raw, host: hostname, servername: net7.isIP(hostname) ? void 0 : hostname, rejectUnauthorized: true });
10196
11802
  socket = secure;
10197
- secure.once("error", () => finish(fail("transport", "\u8BC6\u522B\u670D\u52A1 TLS \u8FDE\u63A5\u5931\u8D25")));
11803
+ secure.once("error", () => finish(fail2("transport", "\u8BC6\u522B\u670D\u52A1 TLS \u8FDE\u63A5\u5931\u8D25")));
10198
11804
  callback?.(null, secure);
10199
- }).catch(() => finish(fail("transport", "SOCKS5 \u63E1\u624B\u5931\u8D25")));
11805
+ }).catch(() => finish(fail2("transport", "SOCKS5 \u63E1\u624B\u5931\u8D25")));
10200
11806
  });
10201
11807
  return void 0;
10202
11808
  };
@@ -10208,16 +11814,16 @@ function identifyEgress(options) {
10208
11814
  headers: { Accept: "application/json", "Accept-Encoding": "identity", "Cache-Control": "no-store", ...options.token ? { Authorization: `Bearer ${options.token}` } : {} }
10209
11815
  }, (response) => {
10210
11816
  if (response.statusCode !== 200) {
10211
- finish(fail("http", `\u8BC6\u522B\u670D\u52A1\u8FD4\u56DE HTTP ${response.statusCode ?? 0}`));
11817
+ finish(fail2("http", `\u8BC6\u522B\u670D\u52A1\u8FD4\u56DE HTTP ${response.statusCode ?? 0}`));
10212
11818
  return;
10213
11819
  }
10214
11820
  if (!/^application\/json(?:\s*;|$)/i.test(response.headers["content-type"] ?? "") || response.headers["content-encoding"] && response.headers["content-encoding"] !== "identity") {
10215
- finish(fail("response", "\u8BC6\u522B\u670D\u52A1\u5FC5\u987B\u8FD4\u56DE\u672A\u538B\u7F29\u7684 JSON"));
11821
+ finish(fail2("response", "\u8BC6\u522B\u670D\u52A1\u5FC5\u987B\u8FD4\u56DE\u672A\u538B\u7F29\u7684 JSON"));
10216
11822
  return;
10217
11823
  }
10218
11824
  const declared = response.headers["content-length"];
10219
11825
  if (declared && (!/^\d+$/.test(declared) || Number(declared) > MAX_IDENTITY_BYTES)) {
10220
- finish(fail("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
11826
+ finish(fail2("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
10221
11827
  return;
10222
11828
  }
10223
11829
  const chunks = [];
@@ -10225,28 +11831,28 @@ function identifyEgress(options) {
10225
11831
  response.on("data", (chunk) => {
10226
11832
  bytes += chunk.length;
10227
11833
  if (bytes > MAX_IDENTITY_BYTES) {
10228
- finish(fail("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
11834
+ finish(fail2("size", "\u8BC6\u522B\u54CD\u5E94\u8D85\u8FC7 16 KiB"));
10229
11835
  return;
10230
11836
  }
10231
11837
  chunks.push(chunk);
10232
11838
  });
10233
- response.once("error", () => finish(fail("transport", "\u8BC6\u522B\u54CD\u5E94\u4F20\u8F93\u5931\u8D25")));
11839
+ response.once("error", () => finish(fail2("transport", "\u8BC6\u522B\u54CD\u5E94\u4F20\u8F93\u5931\u8D25")));
10234
11840
  response.once("end", () => {
10235
11841
  if (settled) return;
10236
11842
  try {
10237
11843
  const value = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
10238
11844
  const observation = validateIdentityResponse(value, Date.now());
10239
11845
  if (!observation) {
10240
- finish(fail("response", "\u8BC6\u522B\u7ED3\u679C\u5B57\u6BB5\u6216\u516C\u7F51\u5730\u5740\u65E0\u6548"));
11846
+ finish(fail2("response", "\u8BC6\u522B\u7ED3\u679C\u5B57\u6BB5\u6216\u516C\u7F51\u5730\u5740\u65E0\u6548"));
10241
11847
  return;
10242
11848
  }
10243
11849
  finish({ ok: true, observation: { ...observation, sourceUrl: target.origin + target.pathname, transport: proxy ? "socks5" : "direct" } });
10244
11850
  } catch {
10245
- finish(fail("response", "\u8BC6\u522B\u54CD\u5E94\u4E0D\u662F\u6709\u6548 UTF-8 JSON"));
11851
+ finish(fail2("response", "\u8BC6\u522B\u54CD\u5E94\u4E0D\u662F\u6709\u6548 UTF-8 JSON"));
10246
11852
  }
10247
11853
  });
10248
11854
  });
10249
- request3.once("error", () => finish(fail("transport", "\u8BC6\u522B\u8BF7\u6C42\u8FDE\u63A5\u5931\u8D25")));
11855
+ request3.once("error", () => finish(fail2("transport", "\u8BC6\u522B\u8BF7\u6C42\u8FDE\u63A5\u5931\u8D25")));
10250
11856
  request3.end();
10251
11857
  });
10252
11858
  }
@@ -10268,7 +11874,7 @@ __export(egress_command_exports, {
10268
11874
  });
10269
11875
  async function runEgressIdentityCommand(args) {
10270
11876
  if (flagBool(args, "help") || flagBool(args, "h")) {
10271
- process.stdout.write(HELP2);
11877
+ process.stdout.write(HELP3);
10272
11878
  return;
10273
11879
  }
10274
11880
  const url = flagString(args, "url");
@@ -10288,13 +11894,13 @@ async function runEgressIdentityCommand(args) {
10288
11894
  `);
10289
11895
  if (!result.ok) process.exitCode = 1;
10290
11896
  }
10291
- var HELP2;
11897
+ var HELP3;
10292
11898
  var init_egress_command = __esm({
10293
11899
  "src/experimental/egress-command.ts"() {
10294
11900
  "use strict";
10295
11901
  init_args();
10296
11902
  init_egress_identity();
10297
- HELP2 = `
11903
+ HELP3 = `
10298
11904
  \u5B9E\u9A8C\u6027\u51FA\u53E3\u8BC6\u522B\uFF08\u4E0D\u53C2\u4E0E\u9ED8\u8BA4 scan \u6216\u5019\u9009\u6392\u5E8F\uFF09
10299
11905
 
10300
11906
  \u7528\u6CD5\uFF1Acfpilot egress-identify --url https://\u81EA\u6709\u670D\u52A1/identify [--proxy socks5://127.0.0.1:10808]
@@ -10499,7 +12105,7 @@ __export(website_command_exports, {
10499
12105
  });
10500
12106
  async function runWebsiteCommand(args) {
10501
12107
  if (flagBool(args, "help") || flagBool(args, "h")) {
10502
- process.stdout.write(HELP3);
12108
+ process.stdout.write(HELP4);
10503
12109
  return;
10504
12110
  }
10505
12111
  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") {
@@ -10516,13 +12122,13 @@ async function runWebsiteCommand(args) {
10516
12122
  `);
10517
12123
  if (targets.some((result) => result.status !== "ok")) process.exitCode = 1;
10518
12124
  }
10519
- var HELP3;
12125
+ var HELP4;
10520
12126
  var init_website_command = __esm({
10521
12127
  "src/experimental/website-command.ts"() {
10522
12128
  "use strict";
10523
12129
  init_args();
10524
12130
  init_website_compatibility();
10525
- HELP3 = `
12131
+ HELP4 = `
10526
12132
  \u5B9E\u9A8C\u6027\u7F51\u7AD9\u517C\u5BB9\u6027\u68C0\u6D4B\uFF08\u4E0D\u53C2\u4E0E\u9ED8\u8BA4 scan \u6216\u6392\u5E8F\uFF09
10527
12133
 
10528
12134
  \u7528\u6CD5\uFF1Acfpilot website-check --url https://\u7528\u6237\u6307\u5B9A\u7F51\u7AD9/ [--proxy socks5://127.0.0.1:10808]
@@ -10603,12 +12209,12 @@ var init_token_command = __esm({
10603
12209
  });
10604
12210
 
10605
12211
  // src/vps/command.ts
10606
- var command_exports3 = {};
10607
- __export(command_exports3, {
12212
+ var command_exports4 = {};
12213
+ __export(command_exports4, {
10608
12214
  runVpsCommand: () => runVpsCommand
10609
12215
  });
10610
12216
  import { spawn } from "node:child_process";
10611
- import { existsSync as existsSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "node:fs";
12217
+ import { existsSync as existsSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";
10612
12218
  import { dirname as dirname4, resolve as resolve3 } from "node:path";
10613
12219
  import { fileURLToPath as fileURLToPath3 } from "node:url";
10614
12220
  function loadScript() {
@@ -10618,7 +12224,7 @@ function loadScript() {
10618
12224
  resolve3(here, "../../assets/vps-socks5.sh")
10619
12225
  ];
10620
12226
  for (const path of candidates) {
10621
- if (existsSync2(path)) return readFileSync5(path, "utf8");
12227
+ if (existsSync4(path)) return readFileSync7(path, "utf8");
10622
12228
  }
10623
12229
  throw new Error("\u5185\u7F6E\u811A\u672C\u7F3A\u5931\uFF08assets/vps-socks5.sh\uFF09\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5\u6216\u5347\u7EA7 cfpilot");
10624
12230
  }
@@ -10650,7 +12256,7 @@ ssh \u542F\u52A8\u5931\u8D25\uFF1A${err.message}
10650
12256
  }
10651
12257
  async function runVpsCommand(args) {
10652
12258
  if (flagBool(args, "h") || flagBool(args, "help")) {
10653
- process.stdout.write(HELP4);
12259
+ process.stdout.write(HELP5);
10654
12260
  return;
10655
12261
  }
10656
12262
  const port = flagNumber(args, "port", 0);
@@ -10674,11 +12280,11 @@ async function runVpsCommand(args) {
10674
12280
  }
10675
12281
  return;
10676
12282
  }
10677
- const out = resolve3(process.cwd(), flagString(args, "out") ?? "cfpilot-vps-socks5.sh");
10678
- writeFileSync3(out, script, { mode: 493 });
12283
+ const out2 = resolve3(process.cwd(), flagString(args, "out") ?? "cfpilot-vps-socks5.sh");
12284
+ writeFileSync5(out2, script, { mode: 493 });
10679
12285
  process.stdout.write(
10680
12286
  `
10681
- \u5DF2\u751F\u6210\u811A\u672C\uFF1A${out}
12287
+ \u5DF2\u751F\u6210\u811A\u672C\uFF1A${out2}
10682
12288
 
10683
12289
  \u63A5\u4E0B\u6765\u4E8C\u9009\u4E00\uFF1A
10684
12290
 
@@ -10697,13 +12303,13 @@ async function runVpsCommand(args) {
10697
12303
  `
10698
12304
  );
10699
12305
  }
10700
- var HELP4;
10701
- var init_command3 = __esm({
12306
+ var HELP5;
12307
+ var init_command4 = __esm({
10702
12308
  "src/vps/command.ts"() {
10703
12309
  "use strict";
10704
12310
  init_args();
10705
12311
  init_version();
10706
- HELP4 = `
12312
+ HELP5 = `
10707
12313
  ${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5 \u843D\u5730\u4EE3\u7406
10708
12314
 
10709
12315
  \u7528\u6CD5:
@@ -10736,7 +12342,7 @@ ${NAME} vps \u2014\u2014 \u5728\u81EA\u5DF1\u7684 VPS \u4E0A\u90E8\u7F72 SOCKS5
10736
12342
  // src/cli.ts
10737
12343
  init_args();
10738
12344
  init_version();
10739
- var HELP5 = `
12345
+ var HELP6 = `
10740
12346
  ${NAME} v${VERSION}
10741
12347
  Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
10742
12348
 
@@ -10744,6 +12350,7 @@ Cloudflare Pages \u4EE3\u7406\u90E8\u7F72\u4E0E\u4F18\u9009\u5DE5\u5177
10744
12350
  ${NAME} \u4EA4\u4E92\u83DC\u5355\uFF08\u63A8\u8350\u9996\u6B21\u4F7F\u7528\uFF09
10745
12351
  ${NAME} deploy [\u9009\u9879] \u90E8\u7F72 Pages \u53CC\u9879\u76EE
10746
12352
  ${NAME} scan [\u9009\u9879] \u672C\u5730\u771F\u8FDE\u63A5\u4F18\u9009
12353
+ ${NAME} source <\u52A8\u4F5C> \u5916\u90E8 IP \u6570\u636E\u6E90\u4E0E\u672C\u5730\u5019\u9009\u6C60\u7BA1\u7406
10747
12354
  ${NAME} test [\u9009\u9879] \u6D4B\u8BD5\u5355\u4E2A IP \u7684\u5B8C\u6574\u94FE\u8DEF
10748
12355
  ${NAME} egress-identify \u5B9E\u9A8C\u6027\u6307\u5B9A\u4F20\u8F93\u8DEF\u5F84\u51FA\u53E3\u8BC6\u522B
10749
12356
  ${NAME} website-check \u5B9E\u9A8C\u6027\u7F51\u7AD9\u517C\u5BB9\u6027\u68C0\u6D4B
@@ -10772,11 +12379,11 @@ async function main() {
10772
12379
  return;
10773
12380
  }
10774
12381
  if (!command && (flagBool(args, "h") || flagBool(args, "help"))) {
10775
- process.stdout.write(HELP5);
12382
+ process.stdout.write(HELP6);
10776
12383
  return;
10777
12384
  }
10778
12385
  if (command === "help") {
10779
- process.stdout.write(HELP5);
12386
+ process.stdout.write(HELP6);
10780
12387
  return;
10781
12388
  }
10782
12389
  switch (command) {
@@ -10796,6 +12403,11 @@ async function main() {
10796
12403
  await runScanCommand2(args);
10797
12404
  return;
10798
12405
  }
12406
+ case "source": {
12407
+ const { runSourceCommand: runSourceCommand2 } = await Promise.resolve().then(() => (init_command3(), command_exports3));
12408
+ await runSourceCommand2(args);
12409
+ return;
12410
+ }
10799
12411
  case "test": {
10800
12412
  const { runTestCommand: runTestCommand2 } = await Promise.resolve().then(() => (init_single_command(), single_command_exports));
10801
12413
  await runTestCommand2(args);
@@ -10827,7 +12439,7 @@ async function main() {
10827
12439
  return;
10828
12440
  }
10829
12441
  case "vps": {
10830
- const { runVpsCommand: runVpsCommand2 } = await Promise.resolve().then(() => (init_command3(), command_exports3));
12442
+ const { runVpsCommand: runVpsCommand2 } = await Promise.resolve().then(() => (init_command4(), command_exports4));
10831
12443
  await runVpsCommand2(args);
10832
12444
  return;
10833
12445
  }
@@ -10835,7 +12447,7 @@ async function main() {
10835
12447
  process.stderr.write(`\u672A\u77E5\u547D\u4EE4\uFF1A${command}
10836
12448
 
10837
12449
  `);
10838
- process.stderr.write(HELP5);
12450
+ process.stderr.write(HELP6);
10839
12451
  process.exitCode = 1;
10840
12452
  }
10841
12453
  }