fix(user-secret): 白名单「获取当前 IP」改走服务端回显,第三方回显只作兜底
无影云桌面等受限网络里 myip.ipip.net 不可达,页面却能正常调自家接口, 导致青果白名单拿不到本机出口 IP。新增 /api/user-secrets/client-ip 回显服务端看到的来源 IP(XFF 逐跳取首个公网地址),前端优先用它, 失败再退回第三方回显。
This commit is contained in:
+15
@@ -1,6 +1,7 @@
|
||||
package com.nanri.aiimage.modules.usersecret.controller;
|
||||
|
||||
import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretCheckRequest;
|
||||
@@ -13,11 +14,13 @@ import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyWhitelistVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBundleVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretCheckResultVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretItemVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserClientIpVo;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserProxyBalanceService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserProxyPlanService;
|
||||
import com.nanri.aiimage.modules.usersecret.service.UserProxyWhitelistService;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ClientIpResolver;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -116,6 +119,18 @@ public class UserApiSecretController {
|
||||
return ApiResponse.success(userProxyPlanService.get(currentUserId(request)));
|
||||
}
|
||||
|
||||
@GetMapping("/client-ip")
|
||||
@Operation(summary = "回显调用方公网 IP",
|
||||
description = "受限网络(如阿里云无影桌面)连不上第三方回显服务时,用服务端看到的来源 IP 回填白名单输入框;仍需用户点击加入白名单。")
|
||||
public ApiResponse<UserClientIpVo> clientIp(HttpServletRequest request) {
|
||||
currentUserId(request);
|
||||
String ip = ClientIpResolver.resolve(request);
|
||||
if (ip == null) {
|
||||
throw new BusinessException("无法识别当前出口 IP,请手动填写");
|
||||
}
|
||||
return ApiResponse.success(new UserClientIpVo(ip));
|
||||
}
|
||||
|
||||
@PutMapping("/proxy-plan")
|
||||
@Operation(summary = "保存当前用户的 jikip 套餐配置",
|
||||
description = "套餐 ID / 用户 ID 用于查询余量;套餐 key 加密保存,仅用于白名单添加(留空=保留已存值)。")
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@Schema(description = "服务端看到的调用方公网 IP")
|
||||
public class UserClientIpVo {
|
||||
|
||||
@Schema(description = "公网 IP(IPv4/IPv6 字面量)")
|
||||
private String ip;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 从请求头还原调用方公网 IP:白名单要加的是本机出口 IP,服务端能看到的来源就是它。
|
||||
*
|
||||
* <p>优先级 X-Forwarded-For(逐跳取第一个合法公网地址)→ X-Real-IP → remoteAddr。
|
||||
* 只认 {@link PublicIpValidator} 认可的地址,回环/内网/域名一律跳过——nginx 会在
|
||||
* X-Forwarded-For 末尾追加自己的 127.0.0.1,直接取首段也可能拿到伪造值,
|
||||
* 但这段值只用于回填输入框,真正加白名单仍由用户确认后单独提交。</p>
|
||||
*/
|
||||
public final class ClientIpResolver {
|
||||
|
||||
private ClientIpResolver() {
|
||||
}
|
||||
|
||||
public static String resolve(HttpServletRequest request) {
|
||||
String forwarded = request.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null) {
|
||||
for (String part : forwarded.split(",")) {
|
||||
String ip = PublicIpValidator.normalize(part);
|
||||
if (ip != null) {
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
String realIp = PublicIpValidator.normalize(request.getHeader("X-Real-IP"));
|
||||
if (realIp != null) {
|
||||
return realIp;
|
||||
}
|
||||
return PublicIpValidator.normalize(request.getRemoteAddr());
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 服务端回显调用方 IP 的取数口径:无影一类受限网络里第三方回显不可达时,
|
||||
* 白名单输入框靠这条兜底,取错段会把代理出口写进白名单(配了也不通)。
|
||||
*/
|
||||
class ClientIpResolverTest {
|
||||
|
||||
private HttpServletRequest request(String forwardedFor, String realIp, String remoteAddr) {
|
||||
HttpServletRequest request = mock(HttpServletRequest.class);
|
||||
when(request.getHeader("X-Forwarded-For")).thenReturn(forwardedFor);
|
||||
when(request.getHeader("X-Real-IP")).thenReturn(realIp);
|
||||
when(request.getRemoteAddr()).thenReturn(remoteAddr);
|
||||
return request;
|
||||
}
|
||||
|
||||
@Test
|
||||
void takesFirstPublicHopAndSkipsNginxAppendedLoopback() {
|
||||
assertThat(ClientIpResolver.resolve(request("8.149.69.98, 127.0.0.1", null, "172.19.0.1")))
|
||||
.isEqualTo("8.149.69.98");
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipsSpoofedHostnameAndPrivateHops() {
|
||||
assertThat(ClientIpResolver.resolve(request("evil.example, 10.0.0.8, 36.251.68.43", null, "127.0.0.1")))
|
||||
.isEqualTo("36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToRealIpWhenForwardedChainHasNoPublicAddress() {
|
||||
assertThat(ClientIpResolver.resolve(request("192.168.1.5, 127.0.0.1", "36.251.68.43", "10.1.2.3")))
|
||||
.isEqualTo("36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fallsBackToRemoteAddrWithoutProxyHeaders() {
|
||||
assertThat(ClientIpResolver.resolve(request(null, null, "36.251.68.43")))
|
||||
.isEqualTo("36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullWhenOnlyPrivateAddressesAreVisible() {
|
||||
assertThat(ClientIpResolver.resolve(request("10.0.0.8, 127.0.0.1", null, "172.19.0.1")))
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
@@ -213,6 +213,7 @@ export const API_ENDPOINTS = {
|
||||
proxyBalance: '/api/user-secrets/proxy-balance',
|
||||
proxyPlan: '/api/user-secrets/proxy-plan',
|
||||
proxyWhitelist: '/api/user-secrets/proxy-whitelist',
|
||||
clientIp: '/api/user-secrets/client-ip',
|
||||
},
|
||||
costGuard: {
|
||||
status: '/api/user/cost-guard/status',
|
||||
|
||||
@@ -165,3 +165,10 @@ export function addProxyWhitelist(ip: string) {
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** 服务端看到的调用方公网 IP:受限网络(无影桌面等)连不上第三方回显时的主通道。 */
|
||||
export function fetchClientIp() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<{ ip: string }>>(buildJavaUrl(API_ENDPOINTS.userSecret.clientIp)),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ import { computed, ref, type ComputedRef, type Ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import {
|
||||
addProxyWhitelist,
|
||||
fetchClientIp,
|
||||
type UserProxyWhitelistResult,
|
||||
} from '@/shared/api/types/modules/user-secret'
|
||||
import { fetchPublicIp } from '@/shared/utils/public-ip'
|
||||
import { resolvePublicIp } from '@/shared/utils/public-ip'
|
||||
import type { ProxyMode } from '@/shared/bridges/pywebview'
|
||||
import type { ProxyProviderKey } from '@/shared/utils/api-secret-channel'
|
||||
|
||||
@@ -86,7 +87,8 @@ export function useProxyWhitelist(deps: ProxyWhitelistDeps) {
|
||||
whitelistFetching.value = true
|
||||
whitelistError.value = ''
|
||||
whitelistResult.value = null
|
||||
fetchPublicIp()
|
||||
// 服务端回显优先:无影一类受限网络里第三方回显不可达,页面本身却能正常调自家接口
|
||||
resolvePublicIp(async () => (await fetchClientIp()).ip)
|
||||
.then((ip) => {
|
||||
whitelistIp.value = ip
|
||||
})
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* 客户端公网 IP 获取:用户在「代理 → 白名单」里点「获取当前 IP」时使用。
|
||||
*
|
||||
* 口径:myip.ipip.net 是极客帮助文档里的测试目标,且带 CORS(Access-Control-Allow-Origin: *),
|
||||
* 浏览器/pywebview 可直接请求;解析失败时返回 null 由用户手填,绝不静默写一个猜的 IP。
|
||||
* 口径:先问自家服务端要它看到的来源 IP(受限网络里第三方回显常被拦,例如阿里云无影桌面),
|
||||
* 拿不到再退回 myip.ipip.net(带 CORS,Access-Control-Allow-Origin: *);
|
||||
* 解析失败时返回 null 由用户手填,绝不静默写一个猜的 IP。
|
||||
*/
|
||||
const PUBLIC_IP_ENDPOINT = 'https://myip.ipip.net'
|
||||
const IPV4_TOKEN = /(?:^|[^\d.])(\d{1,3}(?:\.\d{1,3}){3})(?![\d.])/
|
||||
@@ -22,6 +23,18 @@ export function parsePublicIp(text: unknown): string | null {
|
||||
return candidate
|
||||
}
|
||||
|
||||
/** 先取服务端回显,失败或拿不到合法 IPv4 时再走公网回显;两个出口都失败才抛错。 */
|
||||
export async function resolvePublicIp(
|
||||
fetchFromServer: () => Promise<string | null>,
|
||||
fetchFromEcho: () => Promise<string> = () => fetchPublicIp(),
|
||||
): Promise<string> {
|
||||
// 服务端通道失败(未登录 / 网关拦截)不是终点:只把结果折成 null,交给公网回显兜底
|
||||
const serverIp = await fetchFromServer()
|
||||
.then((value) => parsePublicIp(value))
|
||||
.catch(() => null)
|
||||
return serverIp ?? fetchFromEcho()
|
||||
}
|
||||
|
||||
/** 请求公网 IP 回显服务;超时/网络/解析失败都会抛错,由调用方给出可见提示。 */
|
||||
export async function fetchPublicIp(timeoutMs = 8000): Promise<string> {
|
||||
if (typeof fetch !== 'function') {
|
||||
|
||||
@@ -320,7 +320,8 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
"migrate": "/api/user-secrets/migrate",
|
||||
"proxyBalance": "/api/user-secrets/proxy-balance",
|
||||
"proxyPlan": "/api/user-secrets/proxy-plan",
|
||||
"proxyWhitelist": "/api/user-secrets/proxy-whitelist"
|
||||
"proxyWhitelist": "/api/user-secrets/proxy-whitelist",
|
||||
"clientIp": "/api/user-secrets/client-ip"
|
||||
},
|
||||
"costGuard": {
|
||||
"status": "/api/user/cost-guard/status",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { parsePublicIp } from '../src/shared/utils/public-ip.ts'
|
||||
import { parsePublicIp, resolvePublicIp } from '../src/shared/utils/public-ip.ts'
|
||||
|
||||
test('test_public_ip_parses_ipip_response', () => {
|
||||
assert.equal(parsePublicIp('当前 IP:36.251.68.43 来自于:中国 福建 福州 联通'), '36.251.68.43')
|
||||
@@ -22,3 +22,41 @@ test('test_public_ip_rejects_invalid_values', () => {
|
||||
assert.equal(parsePublicIp(null), null)
|
||||
assert.equal(parsePublicIp(123), null)
|
||||
})
|
||||
|
||||
test('test_public_ip_prefers_server_echo', async () => {
|
||||
const ip = await resolvePublicIp(
|
||||
async () => '8.149.69.98',
|
||||
async () => {
|
||||
throw new Error('第三方回显不该被调用')
|
||||
},
|
||||
)
|
||||
assert.equal(ip, '8.149.69.98')
|
||||
})
|
||||
|
||||
test('test_public_ip_falls_back_when_server_echo_fails', async () => {
|
||||
const ip = await resolvePublicIp(
|
||||
async () => {
|
||||
throw new Error('401')
|
||||
},
|
||||
async () => '36.251.68.43',
|
||||
)
|
||||
assert.equal(ip, '36.251.68.43')
|
||||
})
|
||||
|
||||
test('test_public_ip_falls_back_when_server_echo_is_not_ipv4', async () => {
|
||||
// 服务端可能回显 IPv6:青果白名单要的是 IPv4,仍交给公网回显兜底
|
||||
const ip = await resolvePublicIp(async () => '2408:8207:1234::1', async () => '36.251.68.43')
|
||||
assert.equal(ip, '36.251.68.43')
|
||||
})
|
||||
|
||||
test('test_public_ip_reports_error_only_when_both_channels_fail', async () => {
|
||||
await assert.rejects(
|
||||
resolvePublicIp(
|
||||
async () => null,
|
||||
async () => {
|
||||
throw new Error('获取当前 IP 失败,请手动填写')
|
||||
},
|
||||
),
|
||||
/获取当前 IP 失败/,
|
||||
)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user