cfpilot 0.13.7 → 0.13.9

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.13.7";
90
+ VERSION = "0.13.9";
91
91
  NAME = "cfpilot";
92
92
  }
93
93
  });
@@ -5014,11 +5014,21 @@ async function runScan(options) {
5014
5014
  for (const entry of entries) {
5015
5015
  report({ type: "result", entry });
5016
5016
  }
5017
- const observations = probeResults.map((r) => ({
5018
- ip: r.ip,
5019
- ok: r.probe.ok && r.probe.pongVerified !== false,
5020
- latencyMs: r.latency
5021
- }));
5017
+ const observations = [];
5018
+ for (const item of tcpResults) {
5019
+ observations.push({ ip: item.ip, ok: item.ok, stage: "tcp", latencyMs: item.latency });
5020
+ }
5021
+ for (const item of tlsResults) {
5022
+ observations.push({ ip: item.ip, ok: item.tls.tlsMs > 0, stage: "tls", latencyMs: item.tls.tlsMs });
5023
+ }
5024
+ for (const item of probeResults) {
5025
+ observations.push({
5026
+ ip: item.ip,
5027
+ ok: item.probe.ok && item.probe.pongVerified !== false,
5028
+ stage: "ws",
5029
+ latencyMs: item.latency
5030
+ });
5031
+ }
5022
5032
  const speedByIp = /* @__PURE__ */ new Map();
5023
5033
  for (const item of speedResults) {
5024
5034
  if (item.speed && item.speed > 0) speedByIp.set(item.ip, item.speed);
@@ -5701,11 +5711,289 @@ var init_net_env = __esm({
5701
5711
  }
5702
5712
  });
5703
5713
 
5714
+ // src/scan/candidates_adaptive.ts
5715
+ function effectiveSegmentWeight(staticWeight, observation) {
5716
+ if (staticWeight <= 0) return 0;
5717
+ if (!observation) return staticWeight;
5718
+ const numerator = staticWeight * LEARN_PRIOR_TOTAL + observation.successes * observation.decay;
5719
+ const denominator = LEARN_PRIOR_TOTAL + observation.attempts * observation.decay;
5720
+ if (denominator <= 0) return staticWeight;
5721
+ return Math.max(MIN_WEIGHT, Math.min(1, numerator / denominator));
5722
+ }
5723
+ function exploreBudget(count2, explorationRate) {
5724
+ const rate = Math.min(1, Math.max(0, explorationRate));
5725
+ return Math.ceil(count2 * rate);
5726
+ }
5727
+ function prefixCap(count2, share = MAX_PREFIX_SHARE) {
5728
+ const ratio = Math.min(1, Math.max(0, share));
5729
+ return Math.max(1, Math.ceil(count2 * ratio));
5730
+ }
5731
+ function adaptivePool(cidrs, limit, includeZero, neutral, random, store, options) {
5732
+ const count2 = Math.max(0, Math.floor(limit));
5733
+ if (count2 === 0) return [];
5734
+ const ranges = cidrs.map(parseCidr).filter((item) => item !== null).map((item) => ({ family: item.family, start: item.base, end: item.base + item.size })).sort((a, b) => a.family - b.family || (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));
5735
+ const merged = [];
5736
+ for (const range of ranges) {
5737
+ const previous = merged.at(-1);
5738
+ if (previous && previous.family === range.family && range.start <= previous.end) previous.end = previous.end > range.end ? previous.end : range.end;
5739
+ else merged.push({ ...range });
5740
+ }
5741
+ const format = (value, family) => family === 4 ? [24n, 16n, 8n, 0n].map((shift) => (value >> shift & 255n).toString()).join(".") : Array.from({ length: 8 }, (_, index) => (value >> BigInt(112 - index * 16) & 65535n).toString(16)).join(":");
5742
+ const now = options?.now ?? Date.now();
5743
+ const halfLife2 = options?.halfLifeMs ?? 7 * 24 * 60 * 60 * 1e3;
5744
+ const profileId = options?.profileId ?? "";
5745
+ const buckets = [];
5746
+ for (const range of merged) {
5747
+ const align = range.family === 4 ? 256n : 0n;
5748
+ for (let start = range.start; start < range.end; ) {
5749
+ const size = align === 0n ? range.end - start : (() => {
5750
+ const chunk = align - start % align;
5751
+ return chunk > range.end - start ? range.end - start : chunk;
5752
+ })();
5753
+ const staticWeight = range.family === 4 ? cidrWeight(`${format(start, 4)}/32`) : 1;
5754
+ if (staticWeight === 0 && !includeZero) {
5755
+ start += size;
5756
+ continue;
5757
+ }
5758
+ const prefix = range.family === 4 ? `${format(start & ~255n, 4)}/24` : format(start, 6);
5759
+ const observation = bucketObservation(prefix, range.family, store, profileId, now, halfLife2);
5760
+ const weight = neutral && staticWeight > 0 ? 1 : effectiveSegmentWeight(staticWeight, observation);
5761
+ let capacity = Number(size);
5762
+ if (size > 2n) {
5763
+ if (start % 256n === 0n) capacity--;
5764
+ const last = start + size - 1n;
5765
+ if (last % 256n === 255n) capacity--;
5766
+ }
5767
+ if (!Number.isFinite(capacity) || capacity > MAX_BUCKET_CAPACITY) capacity = MAX_BUCKET_CAPACITY;
5768
+ buckets.push({
5769
+ family: range.family,
5770
+ start,
5771
+ end: start + size,
5772
+ staticWeight,
5773
+ weight,
5774
+ capacity: Math.max(0, capacity),
5775
+ used: 0,
5776
+ usedOffsets: /* @__PURE__ */ new Set(),
5777
+ family24: range.family === 4 ? start & ~255n : start
5778
+ });
5779
+ start += size;
5780
+ }
5781
+ }
5782
+ if (buckets.length === 0) return [];
5783
+ const explorationRate = Math.min(1, Math.max(0, options?.explorationRate ?? 0.2));
5784
+ const exploreBudgetCount = exploreBudget(count2, explorationRate);
5785
+ let capPerPrefix = prefixCap(count2);
5786
+ const byPrefix = /* @__PURE__ */ new Map();
5787
+ const out = [];
5788
+ const capacityOf = (bucket) => bucket.capacity - bucket.used;
5789
+ while (out.length < count2) {
5790
+ const isExplore = out.length < exploreBudgetCount;
5791
+ const weights = [];
5792
+ let totalWeight = 0;
5793
+ for (const bucket2 of buckets) {
5794
+ const prefixKey2 = `${bucket2.family}:${bucket2.family24}`;
5795
+ const used = byPrefix.get(prefixKey2) ?? 0;
5796
+ if (capacityOf(bucket2) <= 0 || used >= capPerPrefix) {
5797
+ weights.push(0);
5798
+ continue;
5799
+ }
5800
+ const weight = isExplore ? 1 : bucket2.weight;
5801
+ const value = capacityOf(bucket2) * weight;
5802
+ weights.push(value);
5803
+ totalWeight += value;
5804
+ }
5805
+ if (totalWeight <= 0) {
5806
+ const available = buckets.some((bucket2) => capacityOf(bucket2) > 0 && (isExplore || bucket2.weight > 0));
5807
+ if (!available) break;
5808
+ capPerPrefix++;
5809
+ continue;
5810
+ }
5811
+ let draw = random() * totalWeight;
5812
+ let chosen = -1;
5813
+ for (let index = 0; index < weights.length; index++) {
5814
+ const weight = weights[index];
5815
+ if (weight <= 0) continue;
5816
+ chosen = index;
5817
+ draw -= weight;
5818
+ if (draw < 0) break;
5819
+ }
5820
+ if (chosen < 0) break;
5821
+ const bucket = buckets[chosen];
5822
+ let address;
5823
+ const bucketSize = bucket.end - bucket.start;
5824
+ if (bucketSize <= ENUMERABLE_BUCKET_SIZE) {
5825
+ if (!bucket.order) {
5826
+ const order = [];
5827
+ for (let offset = 0n; offset < bucketSize; offset++) {
5828
+ const candidate = bucket.start + offset;
5829
+ if (bucketSize > 2n && (candidate % 256n === 0n || candidate % 256n === 255n)) continue;
5830
+ order.push(candidate);
5831
+ }
5832
+ for (let index = order.length - 1; index > 0; index--) {
5833
+ const other = Math.floor(random() * (index + 1));
5834
+ const swap = order[index];
5835
+ order[index] = order[other];
5836
+ order[other] = swap;
5837
+ }
5838
+ bucket.order = order;
5839
+ }
5840
+ address = bucket.order[bucket.used];
5841
+ } else {
5842
+ const span = Number(bucketSize > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : bucketSize);
5843
+ for (let attempt = 0; attempt < 64 && address === void 0; attempt++) {
5844
+ const offset = BigInt(Math.floor(random() * span));
5845
+ if (bucket.usedOffsets.has(offset)) continue;
5846
+ bucket.usedOffsets.add(offset);
5847
+ address = bucket.start + offset;
5848
+ }
5849
+ }
5850
+ if (address === void 0) break;
5851
+ bucket.used++;
5852
+ const prefixKey = `${bucket.family}:${bucket.family24}`;
5853
+ byPrefix.set(prefixKey, (byPrefix.get(prefixKey) ?? 0) + 1);
5854
+ out.push({ ip: format(address, bucket.family), staticWeight: bucket.staticWeight });
5855
+ }
5856
+ return out;
5857
+ }
5858
+ function bucketObservation(prefix, family, store, profileId, now, halfLifeMs) {
5859
+ if (!store || !profileId) return void 0;
5860
+ const rank = (stage) => stage === "ws" ? 3 : stage === "tls" ? 2 : stage === "tcp" ? 1 : 0;
5861
+ let best;
5862
+ for (const observation of Object.values(store.observations)) {
5863
+ if (observation.profileId !== profileId) continue;
5864
+ if (family === 4) {
5865
+ if (observation.prefix !== prefix) continue;
5866
+ } else if (!observation.prefix.startsWith(prefix)) {
5867
+ continue;
5868
+ }
5869
+ const current = rank(observation.stage);
5870
+ if (!best || current > best.rank || current === best.rank && observation.updatedAt > best.updatedAt) {
5871
+ best = {
5872
+ attempts: observation.attempts,
5873
+ successes: observation.successes,
5874
+ updatedAt: observation.updatedAt,
5875
+ rank: current
5876
+ };
5877
+ }
5878
+ }
5879
+ if (!best || best.attempts <= 0) return void 0;
5880
+ const age = Math.max(0, now - best.updatedAt);
5881
+ return { attempts: best.attempts, successes: best.successes, decay: 2 ** (-age / Math.max(1, halfLifeMs)) };
5882
+ }
5883
+ var LEARN_PRIOR_ALPHA, LEARN_PRIOR_BETA, LEARN_PRIOR_TOTAL, MIN_WEIGHT, MAX_PREFIX_SHARE, ENUMERABLE_BUCKET_SIZE, MAX_BUCKET_CAPACITY;
5884
+ var init_candidates_adaptive = __esm({
5885
+ "src/scan/candidates_adaptive.ts"() {
5886
+ "use strict";
5887
+ init_ip_ranges();
5888
+ LEARN_PRIOR_ALPHA = 5.6;
5889
+ LEARN_PRIOR_BETA = 2.4;
5890
+ LEARN_PRIOR_TOTAL = LEARN_PRIOR_ALPHA + LEARN_PRIOR_BETA;
5891
+ MIN_WEIGHT = 0.02;
5892
+ MAX_PREFIX_SHARE = 0.05;
5893
+ ENUMERABLE_BUCKET_SIZE = 65536n;
5894
+ MAX_BUCKET_CAPACITY = 1e9;
5895
+ }
5896
+ });
5897
+
5898
+ // src/scan/candidates.ts
5899
+ function normalizeCidrInput(cidr) {
5900
+ if (cidr === void 0) return [];
5901
+ const list = Array.isArray(cidr) ? cidr : [cidr];
5902
+ const out = [];
5903
+ for (const item of list) {
5904
+ if (typeof item !== "string") continue;
5905
+ for (const part of item.split(/[\n,]+/)) {
5906
+ const value = part.trim();
5907
+ if (value) out.push(value);
5908
+ }
5909
+ }
5910
+ return out;
5911
+ }
5912
+ function isIpv6Cidr(cidr) {
5913
+ return cidr.includes(":");
5914
+ }
5915
+ function filterByFamily(cidrs, family) {
5916
+ if (family === "both") return cidrs;
5917
+ const wantIpv6 = family === "v6";
5918
+ return cidrs.filter((cidr) => isIpv6Cidr(cidr) === wantIpv6);
5919
+ }
5920
+ async function loadCloudflareCidrs(family) {
5921
+ let ipv4 = BUILTIN_IPV4_CIDRS;
5922
+ let ipv6 = BUILTIN_IPV6_CIDRS;
5923
+ try {
5924
+ const ranges = await fetchCloudflareCidrs();
5925
+ if (ranges.ipv4.length > 0) ipv4 = ranges.ipv4;
5926
+ if (ranges.ipv6.length > 0) ipv6 = ranges.ipv6;
5927
+ } catch {
5928
+ }
5929
+ if (family === "v4") return [...ipv4];
5930
+ if (family === "v6") return [...ipv6];
5931
+ return [...ipv4, ...ipv6];
5932
+ }
5933
+ async function resolveCandidates(opts = {}) {
5934
+ const sample = opts.sample ?? DEFAULT_CANDIDATE_SAMPLE;
5935
+ const seed = opts.seed ?? randomSeed();
5936
+ const family = opts.family ?? "both";
5937
+ const neutral = opts.neutral === true;
5938
+ const customCidrs = normalizeCidrInput(opts.cidr);
5939
+ const cidrs = customCidrs.length > 0 ? filterByFamily(customCidrs, family) : await loadCloudflareCidrs(family);
5940
+ if (!opts.profile) return expandCidrs(cidrs, { sample, seed, neutral });
5941
+ const random = seededRandom(seed);
5942
+ const adaptive = { limit: sample > 0 ? sample : DEFAULT_CANDIDATE_SAMPLE, random, ...opts.adaptiveSampling };
5943
+ return adaptivePool(cidrs, adaptive.limit, adaptive.includeZeroWeight === true, neutral, random, opts.profile, {
5944
+ explorationRate: adaptive.explorationRate,
5945
+ now: adaptive.now,
5946
+ halfLifeMs: adaptive.halfLifeMs,
5947
+ profileId: adaptive.profileId
5948
+ }).map((item) => item.ip);
5949
+ }
5950
+ function seededRandom(seed) {
5951
+ let state = seed >>> 0;
5952
+ return () => {
5953
+ state = state + 1831565813 | 0;
5954
+ let value = Math.imul(state ^ state >>> 15, 1 | state);
5955
+ value = value + Math.imul(value ^ value >>> 7, 61 | value) ^ value;
5956
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
5957
+ };
5958
+ }
5959
+ function randomSeed() {
5960
+ return (Date.now() ^ Math.floor(Math.random() * 4294967296)) >>> 0;
5961
+ }
5962
+ function normalizeCandidateList(input) {
5963
+ if (!Array.isArray(input) || input.length === 0) return [];
5964
+ const lines = input.filter((item) => typeof item === "string");
5965
+ if (lines.length === 0) return [];
5966
+ const seen = /* @__PURE__ */ new Set();
5967
+ const out = [];
5968
+ for (const ip of readIpFile(lines.join("\n"))) {
5969
+ if (seen.has(ip)) continue;
5970
+ seen.add(ip);
5971
+ const isIpv4Literal = /^\d{1,3}(\.\d{1,3}){3}$/.test(ip);
5972
+ const isIpv6Literal = ip.includes(":");
5973
+ if (isIpv4Literal || isIpv6Literal) {
5974
+ if (!isPublicAddress(ip)) continue;
5975
+ }
5976
+ out.push(ip);
5977
+ }
5978
+ return out;
5979
+ }
5980
+ var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE;
5981
+ var init_candidates = __esm({
5982
+ "src/scan/candidates.ts"() {
5983
+ "use strict";
5984
+ init_ip_ranges();
5985
+ init_net_env();
5986
+ init_candidates_adaptive();
5987
+ DEFAULT_CANDIDATE_SAMPLE = 2e4;
5988
+ DEFAULT_BRIDGE_SAMPLE = 6556;
5989
+ }
5990
+ });
5991
+
5704
5992
  // src/scan/network-profile.ts
5705
5993
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
5706
5994
  import { mkdir as mkdir2, open, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
5707
5995
  import { isIP } from "node:net";
5708
- import { dirname as dirname2 } from "node:path";
5996
+ import { dirname as dirname2, join as join3 } from "node:path";
5709
5997
  function classifyFailureDetailed(error, status2) {
5710
5998
  const value = String(error ?? "").trim();
5711
5999
  if (status2 && status2 >= 400) return { kind: "http", status: status2, retryable: status2 >= 500 || status2 === 408 || status2 === 429, message: `HTTP ${status2}` };
@@ -5737,8 +6025,19 @@ function canonicalPrefix(value) {
5737
6025
  const prefix = networkBucket(parts[0]);
5738
6026
  return prefix.endsWith(`/${parts[1]}`) ? prefix : "";
5739
6027
  }
6028
+ function normalizeRegion(raw) {
6029
+ let value = text(raw).replace(/[\u3000\s]+/g, "");
6030
+ if (!value) return "";
6031
+ for (const suffix of ["\u7279\u522B\u884C\u653F\u533A", "\u81EA\u6CBB\u533A", "\u7701", "\u5E02"]) {
6032
+ if (value.length > suffix.length && value.endsWith(suffix)) {
6033
+ value = value.slice(0, -suffix.length);
6034
+ break;
6035
+ }
6036
+ }
6037
+ return REGION_ALIASES[value] ?? value;
6038
+ }
5740
6039
  function normalizeNetworkProfile(input, now = Date.now()) {
5741
- const isp = text(input.isp), region = text(input.region), access = text(input.access).toLowerCase(), family = text(input.family).toLowerCase() || "ipv4";
6040
+ const isp = text(input.isp), region = normalizeRegion(text(input.region)), access = text(input.access).toLowerCase(), family = text(input.family).toLowerCase() || "ipv4";
5742
6041
  const id = createHash3("sha256").update(JSON.stringify([isp.toLowerCase(), region.toLowerCase(), access, family])).digest("hex").slice(0, 32);
5743
6042
  return { id, isp, region, access, family, source: text(input.source), confidence: Math.min(1, count(input.confidence)), updatedAt: time(input.updatedAt, time(now)) };
5744
6043
  }
@@ -5784,52 +6083,6 @@ function updateNetworkProfile(store, observations, now = Date.now(), duration =
5784
6083
  }
5785
6084
  return capStore(next);
5786
6085
  }
5787
- function sampleExploreExploit(candidates, store, options) {
5788
- const limit = finite(options.limit) ? Math.max(0, Math.floor(options.limit)) : 0;
5789
- if (!limit) return [];
5790
- const draw = () => Math.min(1 - Number.EPSILON, Math.max(0, (options.random ?? Math.random)()));
5791
- const pool2 = [...new Map(candidates.filter((item) => item.staticWeight !== 0 || options.includeZeroWeight === true).map((item) => [item.ip, item])).values()];
5792
- const rate = finite(options.explorationRate) ? Math.min(1, Math.max(0, options.explorationRate)) : 0.2;
5793
- const exploreCount = Math.min(pool2.length, limit, Math.ceil(limit * rate));
5794
- const byBucket = /* @__PURE__ */ new Map();
5795
- for (const candidate of pool2) {
5796
- const key = networkBucket(candidate.ip) || candidate.ip;
5797
- byBucket.set(key, [...byBucket.get(key) ?? [], candidate]);
5798
- }
5799
- const selected = [], used = /* @__PURE__ */ new Set();
5800
- const take = (item) => {
5801
- if (!used.has(item.ip)) {
5802
- selected.push(item);
5803
- used.add(item.ip);
5804
- }
5805
- };
5806
- if (options.includeZeroWeight && exploreCount > 0) {
5807
- const zero = pool2.filter((item) => item.staticWeight === 0);
5808
- if (zero.length) take(zero[Math.floor(draw() * zero.length)]);
5809
- }
5810
- const buckets = [...byBucket.keys()];
5811
- for (let index = buckets.length - 1; index > 0; index--) {
5812
- const other = Math.floor(draw() * (index + 1));
5813
- [buckets[index], buckets[other]] = [buckets[other], buckets[index]];
5814
- }
5815
- while (selected.length < exploreCount && buckets.length) {
5816
- const key = buckets.shift(), list = byBucket.get(key).filter((item) => !used.has(item.ip));
5817
- if (!list.length) continue;
5818
- take(list[Math.floor(draw() * list.length)]);
5819
- if (list.length > 1) buckets.push(key);
5820
- }
5821
- const profileId = selectedProfile(store, options.profileId), now = time(options.now, Date.now());
5822
- const scored = pool2.filter((item) => !used.has(item.ip) && item.staticWeight !== 0).map((candidate) => {
5823
- const prefix = networkBucket(candidate.ip);
5824
- const stages = profileId ? STAGES.map((stage) => store.observations[observationKey(profileId, prefix, stage)]).filter((item) => !!item && item.attempts > 0) : [];
5825
- const observation = stages.at(-1);
5826
- const prior = finite(candidate.staticWeight) ? Math.min(1, Math.max(0.02, candidate.staticWeight)) : 0.2;
5827
- const decay = observation ? decayAt(observation.updatedAt, now, options.halfLifeMs ?? DEFAULT_HALF_LIFE) : 0;
5828
- const score = (prior * 2 + (observation?.successes ?? 0) * decay) / (2 + (observation?.attempts ?? 0) * decay);
5829
- return { candidate, score: score + (finite(candidate.score) ? candidate.score * 1e-3 : 0) };
5830
- }).sort((a, b) => b.score - a.score);
5831
- return [...selected, ...scored.map((item) => item.candidate)].slice(0, limit);
5832
- }
5833
6086
  function sanitizeObservation(raw, profiles) {
5834
6087
  if (!record(raw)) return void 0;
5835
6088
  const profileId = text(raw.profileId), prefix = canonicalPrefix(raw.prefix);
@@ -5924,7 +6177,24 @@ async function saveNetworkProfile(file, store) {
5924
6177
  });
5925
6178
  }
5926
6179
  }
5927
- var PROFILE_CAPACITY, OBSERVATION_CAPACITY, MAX_COUNTER, MAX_FILE_BYTES, DEFAULT_HALF_LIFE, STAGES, FAILURE_CLASSES, record, finite, count, time, halfLife, decayAt, text, observationKey;
6180
+ function mergeProfileStores(base, extra) {
6181
+ const profiles = { ...base.profiles };
6182
+ for (const [id, profile] of Object.entries(extra.profiles)) {
6183
+ if (!profiles[id]) profiles[id] = profile;
6184
+ }
6185
+ const observations = { ...base.observations };
6186
+ for (const [key, item] of Object.entries(extra.observations)) {
6187
+ const previous = observations[key];
6188
+ if (!previous || item.updatedAt > previous.updatedAt) observations[key] = item;
6189
+ }
6190
+ return capStore({ version: 1, profiles, observations });
6191
+ }
6192
+ function desktopProfileStorePath() {
6193
+ const home = process.env.USERPROFILE || process.env.HOME || "";
6194
+ if (!home) return "";
6195
+ return join3(home, ".cfpilot-gui", "scan-profiles.json");
6196
+ }
6197
+ var PROFILE_CAPACITY, OBSERVATION_CAPACITY, MAX_COUNTER, MAX_FILE_BYTES, DEFAULT_HALF_LIFE, STAGES, FAILURE_CLASSES, record, finite, count, time, halfLife, decayAt, text, observationKey, REGION_ALIASES;
5928
6198
  var init_network_profile = __esm({
5929
6199
  "src/scan/network-profile.ts"() {
5930
6200
  "use strict";
@@ -5944,211 +6214,38 @@ var init_network_profile = __esm({
5944
6214
  decayAt = (from, to, duration) => 2 ** (-Math.max(0, to - from) / halfLife(duration));
5945
6215
  text = (value) => typeof value === "string" ? value.trim().slice(0, 128) : "";
5946
6216
  observationKey = (profileId, prefix, stage) => `${profileId}|${prefix}|${stage}`;
5947
- }
5948
- });
5949
-
5950
- // src/scan/candidates.ts
5951
- function normalizeCidrInput(cidr) {
5952
- if (cidr === void 0) return [];
5953
- const list = Array.isArray(cidr) ? cidr : [cidr];
5954
- const out = [];
5955
- for (const item of list) {
5956
- if (typeof item !== "string") continue;
5957
- for (const part of item.split(/[\n,]+/)) {
5958
- const value = part.trim();
5959
- if (value) out.push(value);
5960
- }
5961
- }
5962
- return out;
5963
- }
5964
- function isIpv6Cidr(cidr) {
5965
- return cidr.includes(":");
5966
- }
5967
- function filterByFamily(cidrs, family) {
5968
- if (family === "both") return cidrs;
5969
- const wantIpv6 = family === "v6";
5970
- return cidrs.filter((cidr) => isIpv6Cidr(cidr) === wantIpv6);
5971
- }
5972
- async function loadCloudflareCidrs(family) {
5973
- let ipv4 = BUILTIN_IPV4_CIDRS;
5974
- let ipv6 = BUILTIN_IPV6_CIDRS;
5975
- try {
5976
- const ranges = await fetchCloudflareCidrs();
5977
- if (ranges.ipv4.length > 0) ipv4 = ranges.ipv4;
5978
- if (ranges.ipv6.length > 0) ipv6 = ranges.ipv6;
5979
- } catch {
5980
- }
5981
- if (family === "v4") return [...ipv4];
5982
- if (family === "v6") return [...ipv6];
5983
- return [...ipv4, ...ipv6];
5984
- }
5985
- async function resolveCandidates(opts = {}) {
5986
- const sample = opts.sample ?? DEFAULT_CANDIDATE_SAMPLE;
5987
- const seed = opts.seed ?? randomSeed();
5988
- const family = opts.family ?? "both";
5989
- const neutral = opts.neutral === true;
5990
- const customCidrs = normalizeCidrInput(opts.cidr);
5991
- const cidrs = customCidrs.length > 0 ? filterByFamily(customCidrs, family) : await loadCloudflareCidrs(family);
5992
- if (!opts.profile) return expandCidrs(cidrs, { sample, seed, neutral });
5993
- const random = seededRandom(seed);
5994
- const adaptive = { limit: sample > 0 ? sample : DEFAULT_CANDIDATE_SAMPLE, random, ...opts.adaptiveSampling };
5995
- const candidates = adaptivePool(cidrs, adaptive.limit, adaptive.includeZeroWeight === true, neutral, random, opts.profile, {
5996
- explorationRate: adaptive.explorationRate,
5997
- now: adaptive.now,
5998
- halfLifeMs: adaptive.halfLifeMs,
5999
- profileId: adaptive.profileId
6000
- });
6001
- return sampleExploreExploit(candidates, opts.profile, adaptive).map((item) => item.ip);
6002
- }
6003
- function seededRandom(seed) {
6004
- let state = seed >>> 0;
6005
- return () => {
6006
- state = state + 1831565813 | 0;
6007
- let value = Math.imul(state ^ state >>> 15, 1 | state);
6008
- value = value + Math.imul(value ^ value >>> 7, 61 | value) ^ value;
6009
- return ((value ^ value >>> 14) >>> 0) / 4294967296;
6010
- };
6011
- }
6012
- function segmentObservation(segment, store, profileId, now, halfLifeMs) {
6013
- if (!store || segment.family !== 4 || !profileId) return void 0;
6014
- const best = /* @__PURE__ */ new Map();
6015
- for (const observation of Object.values(store.observations)) {
6016
- if (observation.profileId !== profileId) continue;
6017
- const parsed = parseCidr(observation.prefix);
6018
- if (!parsed || parsed.family !== 4) continue;
6019
- if (parsed.base < segment.start || parsed.base + parsed.size > segment.end) continue;
6020
- const current = best.get(observation.prefix);
6021
- const rank = (stage) => stage === "ws" ? 3 : stage === "tls" ? 2 : 1;
6022
- if (!current || observation.attempts > current.attempts || observation.attempts === current.attempts && rank(observation.stage) > rank(current.stage)) {
6023
- best.set(observation.prefix, { stage: observation.stage, attempts: observation.attempts });
6024
- }
6025
- }
6026
- if (best.size === 0) return void 0;
6027
- let attempts = 0;
6028
- let successes = 0;
6029
- let updated = 0;
6030
- for (const observation of Object.values(store.observations)) {
6031
- if (observation.profileId !== profileId) continue;
6032
- const picked = best.get(observation.prefix);
6033
- if (!picked || picked.stage !== observation.stage) continue;
6034
- const parsed = parseCidr(observation.prefix);
6035
- if (!parsed || parsed.family !== 4) continue;
6036
- if (parsed.base < segment.start || parsed.base + parsed.size > segment.end) continue;
6037
- attempts += observation.attempts;
6038
- successes += observation.successes;
6039
- if (observation.updatedAt > updated) updated = observation.updatedAt;
6040
- }
6041
- if (attempts <= 0) return void 0;
6042
- const age = Math.max(0, now - updated);
6043
- const decay = 2 ** (-age / Math.max(1, halfLifeMs));
6044
- return { attempts, successes, decay };
6045
- }
6046
- function effectiveSegmentWeight(staticWeight, observation) {
6047
- if (staticWeight <= 0) return 0;
6048
- if (!observation) return staticWeight;
6049
- const numerator = staticWeight * LEARN_PRIOR_TOTAL + observation.successes * observation.decay;
6050
- const denominator = LEARN_PRIOR_TOTAL + observation.attempts * observation.decay;
6051
- if (denominator <= 0) return staticWeight;
6052
- return Math.max(0.02, Math.min(1, numerator / denominator));
6053
- }
6054
- function adaptivePool(cidrs, limit, includeZero, neutral, random, store, options) {
6055
- const ranges = cidrs.map(parseCidr).filter((item) => item !== null).map((item) => ({ family: item.family, start: item.base, end: item.base + item.size })).sort((a, b) => a.family - b.family || (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));
6056
- const merged = [];
6057
- for (const range of ranges) {
6058
- const previous = merged.at(-1);
6059
- if (previous && previous.family === range.family && range.start <= previous.end) previous.end = previous.end > range.end ? previous.end : range.end;
6060
- else merged.push({ ...range });
6061
- }
6062
- const format = (value, family) => family === 4 ? [24n, 16n, 8n, 0n].map((shift) => (value >> shift & 255n).toString()).join(".") : Array.from({ length: 8 }, (_, index) => (value >> BigInt(112 - index * 16) & 65535n).toString(16)).join(":");
6063
- const boundaries = Object.keys(IPV4_CIDR_WEIGHTS).map(parseCidr).filter((item) => item !== null).flatMap((item) => [item.base, item.base + item.size]);
6064
- const now = options?.now ?? Date.now();
6065
- const halfLife2 = options?.halfLifeMs ?? 7 * 24 * 60 * 60 * 1e3;
6066
- const segments = [];
6067
- for (const range of merged) {
6068
- const cuts = [.../* @__PURE__ */ new Set([range.start, ...range.family === 4 ? boundaries.filter((point) => point > range.start && point < range.end) : [], range.end])].sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
6069
- for (let index = 0; index < cuts.length - 1; index++) {
6070
- const start = cuts[index], end = cuts[index + 1];
6071
- const staticWeight = range.family === 4 ? cidrWeight(`${format(start, 4)}/32`) : 1;
6072
- if (staticWeight === 0 && !includeZero) continue;
6073
- const observation = segmentObservation({ family: range.family, start, end }, store, options?.profileId ?? "", now, halfLife2);
6074
- const weight = neutral && staticWeight > 0 ? 1 : effectiveSegmentWeight(staticWeight, observation);
6075
- segments.push({ family: range.family, start, end, staticWeight, weight, used: /* @__PURE__ */ new Set() });
6076
- }
6077
- }
6078
- if (segments.length === 0) return [];
6079
- const target = Math.max(0, Math.min(DEFAULT_CANDIDATE_SAMPLE * 4, Math.ceil(limit) * 4));
6080
- const explorationRate = Math.min(1, Math.max(0, options?.explorationRate ?? 0.2));
6081
- const exploreBudget = Math.min(target, Math.round(target * explorationRate));
6082
- const exploitBudget = target - exploreBudget;
6083
- const out = [];
6084
- const drawFrom = (segment, count2) => {
6085
- const size = segment.end - segment.start;
6086
- if (size <= 0n) return;
6087
- let taken = 0;
6088
- for (let attempt = 0; attempt < count2 * 8 && taken < count2; attempt++) {
6089
- if (BigInt(segment.used.size) >= size) break;
6090
- let value = 0n;
6091
- for (let word = 0; word < (segment.family === 4 ? 1 : 4); word++) value = value << 32n | BigInt(Math.floor(random() * 4294967296));
6092
- let offset = value % size;
6093
- for (let probe = 0n; probe < size && segment.used.has(offset); probe++) {
6094
- offset = (offset + 1n) % size;
6095
- }
6096
- if (segment.used.has(offset)) break;
6097
- segment.used.add(offset);
6098
- out.push({ ip: format(segment.start + offset, segment.family), staticWeight: segment.staticWeight });
6099
- taken++;
6100
- }
6101
- };
6102
- const totalSize = segments.reduce((sum, segment) => sum + (segment.end - segment.start), 0n);
6103
- if (exploreBudget > 0 && totalSize > 0n) {
6104
- for (const segment of segments) {
6105
- const share = Number((segment.end - segment.start) * BigInt(exploreBudget) / totalSize);
6106
- if (share > 0) drawFrom(segment, share);
6107
- }
6108
- }
6109
- const totalWeight = segments.reduce((sum, segment) => sum + Number(segment.end - segment.start) * segment.weight, 0);
6110
- if (exploitBudget > 0 && totalWeight > 0) {
6111
- for (const segment of segments) {
6112
- if (segment.weight <= 0) continue;
6113
- const share = Math.floor(Number(segment.end - segment.start) * segment.weight * exploitBudget / totalWeight);
6114
- if (share > 0) drawFrom(segment, share);
6115
- }
6116
- }
6117
- return out;
6118
- }
6119
- function randomSeed() {
6120
- return (Date.now() ^ Math.floor(Math.random() * 4294967296)) >>> 0;
6121
- }
6122
- function normalizeCandidateList(input) {
6123
- if (!Array.isArray(input) || input.length === 0) return [];
6124
- const lines = input.filter((item) => typeof item === "string");
6125
- if (lines.length === 0) return [];
6126
- const seen = /* @__PURE__ */ new Set();
6127
- const out = [];
6128
- for (const ip of readIpFile(lines.join("\n"))) {
6129
- if (seen.has(ip)) continue;
6130
- seen.add(ip);
6131
- const isIpv4Literal = /^\d{1,3}(\.\d{1,3}){3}$/.test(ip);
6132
- const isIpv6Literal = ip.includes(":");
6133
- if (isIpv4Literal || isIpv6Literal) {
6134
- if (!isPublicAddress(ip)) continue;
6135
- }
6136
- out.push(ip);
6137
- }
6138
- return out;
6139
- }
6140
- var DEFAULT_CANDIDATE_SAMPLE, DEFAULT_BRIDGE_SAMPLE, LEARN_PRIOR_ALPHA, LEARN_PRIOR_BETA, LEARN_PRIOR_TOTAL;
6141
- var init_candidates = __esm({
6142
- "src/scan/candidates.ts"() {
6143
- "use strict";
6144
- init_ip_ranges();
6145
- init_net_env();
6146
- init_network_profile();
6147
- DEFAULT_CANDIDATE_SAMPLE = 2e4;
6148
- DEFAULT_BRIDGE_SAMPLE = 6556;
6149
- LEARN_PRIOR_ALPHA = 5.6;
6150
- LEARN_PRIOR_BETA = 2.4;
6151
- LEARN_PRIOR_TOTAL = LEARN_PRIOR_ALPHA + LEARN_PRIOR_BETA;
6217
+ REGION_ALIASES = {
6218
+ \u95FD: "\u798F\u5EFA",
6219
+ \u7CA4: "\u5E7F\u4E1C",
6220
+ \u4EAC: "\u5317\u4EAC",
6221
+ \u6CAA: "\u4E0A\u6D77",
6222
+ \u6D25: "\u5929\u6D25",
6223
+ \u6E1D: "\u91CD\u5E86",
6224
+ \u6D59: "\u6D59\u6C5F",
6225
+ \u82CF: "\u6C5F\u82CF",
6226
+ \u9C81: "\u5C71\u4E1C",
6227
+ \u8C6B: "\u6CB3\u5357",
6228
+ \u5180: "\u6CB3\u5317",
6229
+ \u6E58: "\u6E56\u5357",
6230
+ \u9102: "\u6E56\u5317",
6231
+ \u7696: "\u5B89\u5FBD",
6232
+ \u8D63: "\u6C5F\u897F",
6233
+ \u6842: "\u5E7F\u897F",
6234
+ \u4E91: "\u4E91\u5357",
6235
+ \u8D35: "\u8D35\u5DDE",
6236
+ \u5DDD: "\u56DB\u5DDD",
6237
+ \u664B: "\u5C71\u897F",
6238
+ \u9655: "\u9655\u897F",
6239
+ \u7518: "\u7518\u8083",
6240
+ \u9752: "\u9752\u6D77",
6241
+ \u5B81: "\u5B81\u590F",
6242
+ \u65B0: "\u65B0\u7586",
6243
+ \u85CF: "\u897F\u85CF",
6244
+ \u8499: "\u5185\u8499\u53E4",
6245
+ \u6E2F: "\u9999\u6E2F",
6246
+ \u6FB3: "\u6FB3\u95E8",
6247
+ \u53F0: "\u53F0\u6E7E"
6248
+ };
6152
6249
  }
6153
6250
  });
6154
6251
 
@@ -6634,7 +6731,7 @@ __export(command_exports2, {
6634
6731
  runScanCommand: () => runScanCommand
6635
6732
  });
6636
6733
  import { readFileSync as readFileSync2 } from "node:fs";
6637
- import { join as join3 } from "node:path";
6734
+ import { join as join4 } from "node:path";
6638
6735
  function normalizeWsPath(raw, fallback) {
6639
6736
  const value = (raw ?? fallback).trim();
6640
6737
  if (!value) return fallback;
@@ -6676,11 +6773,21 @@ function normalizeAccess(raw) {
6676
6773
  return value === "mobile" ? "mobile" : "fixed";
6677
6774
  }
6678
6775
  async function loadAdaptiveContext(args) {
6679
- const file = join3(configDirPath(), "network-profiles.json");
6776
+ const file = join4(configDirPath(), "network-profiles.json");
6680
6777
  const isp = normalizeIsp(flagString(args, "isp"));
6681
- const region = (flagString(args, "region") ?? "").trim().slice(0, 32);
6778
+ const region = normalizeRegion(flagString(args, "region") ?? "").slice(0, 32);
6682
6779
  const access = normalizeAccess(flagString(args, "access"));
6683
- const store = await loadNetworkProfile(file, `${isp}-${region}-${access}`);
6780
+ let store = await loadNetworkProfile(file, `${isp}-${region}-${access}`);
6781
+ const desktopFile = desktopProfileStorePath();
6782
+ if (desktopFile) {
6783
+ try {
6784
+ const desktopStore = await loadNetworkProfile(desktopFile, "");
6785
+ if (Object.keys(desktopStore.observations).length > 0) {
6786
+ store = mergeProfileStores(store, desktopStore);
6787
+ }
6788
+ } catch {
6789
+ }
6790
+ }
6684
6791
  const profile = normalizeNetworkProfile({ isp, region, access, family: "ipv4", source: "manual" });
6685
6792
  store.profiles[profile.id] = { ...profile, updatedAt: Date.now() };
6686
6793
  return { file, store, profileId: profile.id };
@@ -6725,11 +6832,11 @@ async function saveAdaptiveObservations(args, observations) {
6725
6832
  observations.map((observation) => ({
6726
6833
  ip: observation.ip,
6727
6834
  ok: observation.ok,
6835
+ stage: observation.stage ?? "ws",
6728
6836
  latencyMs: observation.latencyMs,
6729
6837
  speedMBps: observation.speedMBps,
6730
6838
  at: now,
6731
- profileId: context.profileId,
6732
- stage: "ws"
6839
+ profileId: context.profileId
6733
6840
  })),
6734
6841
  now
6735
6842
  );