diff --git a/src/services/api.ts b/src/services/api.ts index 1cac913d7..b68f4fa39 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -1,9 +1,20 @@ +import { getName, getVersion } from "@tauri-apps/api/app"; import { fetch } from "@tauri-apps/plugin-http"; import { asyncRetry } from "foxts/async-retry"; import { extractErrorMessage } from "foxts/extract-error-message"; +import { once } from "foxts/once"; import { debugLog } from "@/utils/debug"; +const getUserAgentPromise = once(async () => { + try { + const [name, version] = await Promise.all([getName(), getVersion()]); + return `${name}/${version}`; + } catch (error) { + console.debug("Failed to build User-Agent, fallback to default", error); + return "clash-verge-rev"; + } +}); // Get current IP and geolocation information (refactored IP detection with service-specific mappings) interface IpInfo { ip: string; @@ -192,6 +203,8 @@ export const getIpInfo = async (): Promise< const shuffledServices = shuffleServices(); let lastError: unknown | null = null; + const userAgent = await getUserAgentPromise(); + console.debug("User-Agent for IP detection:", userAgent); for (const service of shuffledServices) { debugLog(`尝试IP检测服务: ${service.url}`); @@ -210,6 +223,9 @@ export const getIpInfo = async (): Promise< method: "GET", signal: timeoutController.signal, // AbortSignal.timeout(service.timeout || serviceTimeout), connectTimeout: service.timeout || serviceTimeout, + headers: { + "User-Agent": userAgent, + }, }); if (!response.ok) {