feat(user-secret): 代理白名单一键添加(极客/青果)并前置默认渠道
- 客户端设置面板新增「白名单」区块:自动获取出口 IP、可手改;加入前先同步未上报的代理配置,避免拿服务端旧 Key 代加
- 后端新增 POST /api/user-secrets/proxy-whitelist:先查后加;极客用套餐 ID+套餐 key,青果用已保存提取链接里的 key,重复添加不报错
- 极客套餐 key 加密存 biz_user_proxy_plan.jikip_plan_key(V181),回读只给掩码;换套餐 ID 时必须重填
- 白名单接口地址走配置(AIIMAGE_USER_SECRET_JIKIP/QINGGUO_WHITE_LIST_*),日志不落 key 与完整 URL
- 贞贞/极客等默认选项前置;catch 棘轮 7 处逐条记名并入基线(含 79b04afd 的 AdminApiGuardFilter 一枚)
This commit is contained in:
@@ -41,6 +41,18 @@ public class UserSecretProperties {
|
||||
/** jikip 余量查询接口(客户端设置弹窗展示套餐 IP 余量 / 账户余额)。 */
|
||||
private String jikipBalanceUrl = "https://api.jikip.com/find-balance";
|
||||
|
||||
/** jikip 白名单检测接口:?id=套餐id&ip=待检测IP,data=1 表示已在白名单。 */
|
||||
private String jikipWhiteListCheckUrl = "https://api.jikip.com/whiteList-check";
|
||||
|
||||
/** jikip 白名单添加接口:?id=套餐id&ip=待添加IP&key=套餐key。 */
|
||||
private String jikipWhiteListAddUrl = "https://api.jikip.com/whiteList-addition";
|
||||
|
||||
/** 青果(全球HTTP)白名单查询接口:?Key=提取链接key。 */
|
||||
private String qingguoWhiteListCheckUrl = "https://overseas-api.proxy.qg.net/whitelist/query";
|
||||
|
||||
/** 青果(全球HTTP)白名单添加接口:?Key=提取链接key&IP=待添加IP。 */
|
||||
private String qingguoWhiteListAddUrl = "https://overseas-api.proxy.qg.net/whitelist/add";
|
||||
|
||||
/**
|
||||
* jikip 套餐/账号列表,格式 {@code planId:userId;planId:userId}(分号或逗号分隔)。
|
||||
* 每个套餐独立探测、独立预警;留空=不查余量。
|
||||
|
||||
+72
@@ -7,6 +7,7 @@ import com.nanri.aiimage.common.text.SecretMasking;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyWhitelistOutcome;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestClient;
|
||||
@@ -47,6 +48,77 @@ public class JikipProxyClient {
|
||||
return hasText(properties.getCheckProxyExtractUrl());
|
||||
}
|
||||
|
||||
/**
|
||||
* 先查后加:IP 已在白名单则直接返回;查询失败不阻断,继续尝试添加(check 只是省一次写调用)。
|
||||
* 失败信息只含供应商文案与状态码,绝不含套餐 key / 完整请求 URL。
|
||||
*/
|
||||
public ProxyWhitelistOutcome checkAndAddWhitelist(String planId, String planKey, String ip) {
|
||||
String checkUrl = normalize(properties.getJikipWhiteListCheckUrl());
|
||||
String addUrl = normalize(properties.getJikipWhiteListAddUrl());
|
||||
if (checkUrl.isBlank() || addUrl.isBlank()) {
|
||||
return new ProxyWhitelistOutcome(false, false, "极客白名单接口未配置");
|
||||
}
|
||||
Boolean already = checkWhitelist(checkUrl, planId, ip);
|
||||
if (Boolean.TRUE.equals(already)) {
|
||||
return new ProxyWhitelistOutcome(true, false, "该 IP 已在白名单中,无需重复添加");
|
||||
}
|
||||
try {
|
||||
String url = withSeparator(addUrl)
|
||||
+ "id=" + encode(planId) + "&ip=" + encode(ip) + "&key=" + encode(planKey);
|
||||
String body = restClient(EXTRACT_READ_TIMEOUT_MILLIS).get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.body(String.class);
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
int code = root.path("code").asInt(Integer.MIN_VALUE);
|
||||
if (code != 0) {
|
||||
String message = text(root.get("message"));
|
||||
if (message == null || message.isBlank()) {
|
||||
message = "极客拒绝添加白名单(code=" + code + ")";
|
||||
}
|
||||
return new ProxyWhitelistOutcome(false, false, abbreviate(message, 200));
|
||||
}
|
||||
log.info("[user-secret][proxy-whitelist] 添加成功 planId={} ip={}", planId, ip);
|
||||
return new ProxyWhitelistOutcome(true, true, "已加入白名单,1-2 分钟内生效");
|
||||
} catch (Exception ex) {
|
||||
// 异常信息可能带完整 URL(含套餐 key),只记类型
|
||||
log.warn("[user-secret][proxy-whitelist] 添加失败 planId={} ip={} err={}",
|
||||
planId, ip, ex.getClass().getSimpleName());
|
||||
return new ProxyWhitelistOutcome(false, false, "极客白名单接口暂时不可用,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
/** 查询白名单;data=1 已添加、0 未添加,查询失败返回 null(由调用方决定是否继续添加)。 */
|
||||
private Boolean checkWhitelist(String checkUrl, String planId, String ip) {
|
||||
try {
|
||||
String url = withSeparator(checkUrl) + "id=" + encode(planId) + "&ip=" + encode(ip);
|
||||
String body = restClient(BALANCE_READ_TIMEOUT_MILLIS).get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.body(String.class);
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
if (root.path("code").asInt(Integer.MIN_VALUE) != 0) {
|
||||
return null;
|
||||
}
|
||||
String data = text(root.get("data"));
|
||||
if ("1".equals(data)) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
if ("0".equals(data)) {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
return null;
|
||||
} catch (Exception ex) {
|
||||
log.debug("[user-secret][proxy-whitelist] 查询白名单失败,继续尝试添加 planId={} err={}",
|
||||
planId, ex.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String withSeparator(String url) {
|
||||
return url.contains("?") ? url + "&" : url + "?";
|
||||
}
|
||||
|
||||
/**
|
||||
* 从提取链接取一个代理地址(http://ip:port);未配置或失败返回 null,由调用方回退直连。
|
||||
* 供应商欠费(message 含"余额不足")抛 InsufficientBalanceException 供调用方给出明确提示。
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.nanri.aiimage.modules.usersecret.client;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.config.HttpClientPool;
|
||||
import com.nanri.aiimage.config.UserSecretProperties;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyWhitelistOutcome;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 青果(全球HTTP)白名单客户端:查询 + 添加调用方出口 IP。
|
||||
*
|
||||
* <p>接口约定见 https://www.qg.net/doc/180.html(查询)与 /doc/178.html(添加):
|
||||
* {@code GET /whitelist/query?Key=...}、{@code GET /whitelist/add?Key=...&IP=...},
|
||||
* 返回字段大写 {@code Code/Data/Num},Code=0 成功。Key 就是用户代理提取链接里的 key。</p>
|
||||
*
|
||||
* <p>失败信息只含供应商码与文案,绝不回显 Key 或完整请求 URL;Key 也不得写入日志。</p>
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class QingguoProxyClient {
|
||||
|
||||
private static final int READ_TIMEOUT_MILLIS = 10_000;
|
||||
|
||||
private final UserSecretProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
private volatile RestClient sharedClient;
|
||||
|
||||
public QingguoProxyClient(UserSecretProperties properties, ObjectMapper objectMapper) {
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public ProxyWhitelistOutcome checkAndAddWhitelist(String key, String ip) {
|
||||
String checkUrl = normalize(properties.getQingguoWhiteListCheckUrl());
|
||||
String addUrl = normalize(properties.getQingguoWhiteListAddUrl());
|
||||
if (checkUrl.isBlank() || addUrl.isBlank()) {
|
||||
return new ProxyWhitelistOutcome(false, false, "青果白名单接口未配置");
|
||||
}
|
||||
if (Boolean.TRUE.equals(queryContains(checkUrl, key, ip))) {
|
||||
return new ProxyWhitelistOutcome(true, false, "该 IP 已在白名单中,无需重复添加");
|
||||
}
|
||||
try {
|
||||
String url = withSeparator(addUrl)
|
||||
+ "Key=" + encode(key) + "&IP=" + encode(ip);
|
||||
String body = restClient().get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.body(String.class);
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
int code = intField(root, "Code", Integer.MIN_VALUE);
|
||||
if (code != 0) {
|
||||
return new ProxyWhitelistOutcome(false, false, describe(code));
|
||||
}
|
||||
log.info("[user-secret][proxy-whitelist] 青果添加成功 ip={}", ip);
|
||||
return new ProxyWhitelistOutcome(true, true, "已加入白名单,立即生效");
|
||||
} catch (Exception ex) {
|
||||
// 异常信息可能带完整 URL(含 Key),只记类型
|
||||
log.warn("[user-secret][proxy-whitelist] 青果添加失败 ip={} err={}",
|
||||
ip, ex.getClass().getSimpleName());
|
||||
return new ProxyWhitelistOutcome(false, false, "青果白名单接口暂时不可用,请稍后重试");
|
||||
}
|
||||
}
|
||||
|
||||
/** 查询白名单是否含该 IP;查询失败返回 null(由调用方继续尝试添加)。 */
|
||||
private Boolean queryContains(String checkUrl, String key, String ip) {
|
||||
try {
|
||||
String url = withSeparator(checkUrl) + "Key=" + encode(key);
|
||||
String body = restClient().get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.body(String.class);
|
||||
JsonNode root = objectMapper.readTree(body == null ? "" : body);
|
||||
if (intField(root, "Code", Integer.MIN_VALUE) != 0) {
|
||||
return null;
|
||||
}
|
||||
JsonNode data = field(root, "Data");
|
||||
if (data == null || !data.isArray()) {
|
||||
return null;
|
||||
}
|
||||
for (JsonNode item : data) {
|
||||
if (ip.equalsIgnoreCase(item.asText("").trim())) {
|
||||
return Boolean.TRUE;
|
||||
}
|
||||
}
|
||||
return Boolean.FALSE;
|
||||
} catch (Exception ex) {
|
||||
log.debug("[user-secret][proxy-whitelist] 青果查询白名单失败,继续尝试添加 err={}",
|
||||
ex.getClass().getSimpleName());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 青果官方错误码(/doc/178.html);未知码保留数字便于对客服。 */
|
||||
private String describe(int code) {
|
||||
return switch (code) {
|
||||
case -1 -> "青果白名单接口返回未知错误,请稍后重试";
|
||||
case -10 -> "青果认为参数不合法,请检查代理提取链接里的 key 与 IP";
|
||||
case -11 -> "青果白名单接口请求过于频繁,请稍后再试";
|
||||
case -100 -> "青果套餐不存在或已过期";
|
||||
case -202 -> "青果白名单数量超过限制,请先删除不用的 IP";
|
||||
default -> "青果拒绝添加白名单(Code=" + code + ")";
|
||||
};
|
||||
}
|
||||
|
||||
private JsonNode field(JsonNode root, String name) {
|
||||
JsonNode value = root.get(name);
|
||||
if (value == null) {
|
||||
value = root.get(name.toLowerCase());
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private int intField(JsonNode root, String name, int fallback) {
|
||||
JsonNode value = field(root, name);
|
||||
return value == null || value.isNull() ? fallback : value.asInt(fallback);
|
||||
}
|
||||
|
||||
private static String withSeparator(String url) {
|
||||
return url.contains("?") ? url + "&" : url + "?";
|
||||
}
|
||||
|
||||
private String encode(String value) {
|
||||
return URLEncoder.encode(value == null ? "" : value, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private RestClient restClient() {
|
||||
RestClient client = sharedClient;
|
||||
if (client != null) {
|
||||
return client;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (sharedClient == null) {
|
||||
sharedClient = RestClient.builder()
|
||||
.requestFactory(HttpClientPool.requestFactory(READ_TIMEOUT_MILLIS))
|
||||
.build();
|
||||
}
|
||||
return sharedClient;
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-2
@@ -7,7 +7,9 @@ import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretCheckRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretMigrateRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserApiSecretSaveRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserProxyPlanSaveRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.dto.UserProxyWhitelistRequest;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserApiSecretBalanceVo;
|
||||
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;
|
||||
@@ -15,6 +17,7 @@ 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 io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -45,6 +48,7 @@ public class UserApiSecretController {
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final UserProxyBalanceService userProxyBalanceService;
|
||||
private final UserProxyWhitelistService userProxyWhitelistService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@GetMapping
|
||||
@@ -114,16 +118,27 @@ public class UserApiSecretController {
|
||||
|
||||
@PutMapping("/proxy-plan")
|
||||
@Operation(summary = "保存当前用户的 jikip 套餐配置",
|
||||
description = "套餐 ID / 用户 ID 只用于查询余量,与代理提取链接(key)相互独立。")
|
||||
description = "套餐 ID / 用户 ID 用于查询余量;套餐 key 加密保存,仅用于白名单添加(留空=保留已存值)。")
|
||||
public ApiResponse<UserProxyPlanVo> saveProxyPlan(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody UserProxyPlanSaveRequest body) {
|
||||
Long userId = currentUserId(request);
|
||||
UserProxyPlanVo vo = userProxyPlanService.save(userId, body.getPlanId(), body.getJikipUserId());
|
||||
UserProxyPlanVo vo = userProxyPlanService.save(
|
||||
userId, body.getPlanId(), body.getJikipUserId(), body.getJikipPlanKey());
|
||||
userProxyBalanceService.invalidate(userId);
|
||||
return ApiResponse.success("保存成功", vo);
|
||||
}
|
||||
|
||||
@PostMapping("/proxy-whitelist")
|
||||
@Operation(summary = "把出口 IP 加入代理白名单",
|
||||
description = "极客用「套餐 ID + 套餐 key」,青果用已保存的代理提取链接里的 key;先查后加,重复添加不报错。")
|
||||
public ApiResponse<UserProxyWhitelistVo> addProxyWhitelist(
|
||||
HttpServletRequest request,
|
||||
@Valid @RequestBody UserProxyWhitelistRequest body) {
|
||||
return ApiResponse.success("处理完成",
|
||||
userProxyWhitelistService.add(currentUserId(request), body.getIp()));
|
||||
}
|
||||
|
||||
@DeleteMapping("/proxy-plan")
|
||||
@Operation(summary = "清除当前用户的 jikip 套餐配置")
|
||||
public ApiResponse<Void> clearProxyPlan(HttpServletRequest request) {
|
||||
|
||||
+5
@@ -21,4 +21,9 @@ public class UserProxyPlanSaveRequest {
|
||||
@Size(max = 64, message = "用户 ID 过长")
|
||||
@Pattern(regexp = "[A-Za-z0-9_-]+", message = "用户 ID 只能是字母、数字、下划线或短横线")
|
||||
private String jikipUserId;
|
||||
|
||||
@Schema(description = "jikip 套餐 key(仅用于白名单添加);留空=保留已保存值(套餐 ID 未变时),首次留空=不配置")
|
||||
@Size(max = 256, message = "套餐 key 过长")
|
||||
@Pattern(regexp = "[!-~]*", message = "套餐 key 只能是可见 ASCII 字符(不含空格)")
|
||||
private String jikipPlanKey;
|
||||
}
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "把当前出口 IP 加入代理供应商白名单")
|
||||
public class UserProxyWhitelistRequest {
|
||||
|
||||
@Schema(description = "要加入白名单的公网 IP", example = "36.251.68.43")
|
||||
@NotBlank(message = "IP 不能为空")
|
||||
@Size(max = 64, message = "IP 过长")
|
||||
private String ip;
|
||||
}
|
||||
+2
@@ -15,6 +15,8 @@ public class UserProxyPlanEntity {
|
||||
private Long userId;
|
||||
private String planId;
|
||||
private String jikipUserId;
|
||||
/** 套餐 key 密文(仅用于白名单添加);null/空=未配置。 */
|
||||
private String jikipPlanKey;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
}
|
||||
|
||||
+6
@@ -13,6 +13,12 @@ public class UserProxyPlanVo {
|
||||
@Schema(description = "jikip 用户 ID;未配置时为 null")
|
||||
private String jikipUserId;
|
||||
|
||||
@Schema(description = "是否已保存套餐 key(用于白名单添加)")
|
||||
private Boolean jikipPlanKeyConfigured;
|
||||
|
||||
@Schema(description = "套餐 key 掩码;未配置时为 null")
|
||||
private String jikipPlanKeyMasked;
|
||||
|
||||
@Schema(description = "是否已配置")
|
||||
private Boolean configured;
|
||||
}
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.nanri.aiimage.modules.usersecret.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "代理白名单代加结果")
|
||||
public class UserProxyWhitelistVo {
|
||||
|
||||
@Schema(description = "已处理(或已存在)的 IP")
|
||||
private String ip;
|
||||
|
||||
@Schema(description = "代理供应商:jikip / qingguo")
|
||||
private String provider;
|
||||
|
||||
@Schema(description = "true=本次新增;false=已在白名单")
|
||||
private Boolean added;
|
||||
|
||||
@Schema(description = "结果说明")
|
||||
private String message;
|
||||
}
|
||||
+59
-6
@@ -1,6 +1,8 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.common.text.SecretMasking;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserProxyPlanMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
|
||||
@@ -12,7 +14,8 @@ import java.util.List;
|
||||
|
||||
/**
|
||||
* 用户级 jikip 套餐配置:一个用户对应一个当前在用的套餐/账号。
|
||||
* 提取链接(key)与套餐 ID/用户 ID 相互独立:链接用于买 IP,这两个 ID 只用于查余量。
|
||||
* 提取链接与套餐 ID/用户 ID 相互独立:链接用于买 IP,这两个 ID 用于查余量;
|
||||
* 套餐 key 是凭据,加密落库,只用于白名单添加,接口只回传掩码。
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@@ -20,6 +23,7 @@ import java.util.List;
|
||||
public class UserProxyPlanService {
|
||||
|
||||
private final UserProxyPlanMapper mapper;
|
||||
private final ShopCredentialCryptoService cryptoService;
|
||||
|
||||
public UserProxyPlanEntity getEntity(Long userId) {
|
||||
return mapper.selectById(userId);
|
||||
@@ -31,33 +35,82 @@ public class UserProxyPlanService {
|
||||
if (row != null) {
|
||||
vo.setPlanId(row.getPlanId());
|
||||
vo.setJikipUserId(row.getJikipUserId());
|
||||
String plainKey = decryptQuietly(row.getJikipPlanKey());
|
||||
vo.setJikipPlanKeyConfigured(!plainKey.isEmpty());
|
||||
vo.setJikipPlanKeyMasked(plainKey.isEmpty() ? null : SecretMasking.mask(plainKey));
|
||||
} else {
|
||||
vo.setJikipPlanKeyConfigured(false);
|
||||
}
|
||||
vo.setConfigured(row != null);
|
||||
return vo;
|
||||
}
|
||||
|
||||
public UserProxyPlanVo save(Long userId, String planId, String jikipUserId) {
|
||||
public UserProxyPlanVo save(Long userId, String planId, String jikipUserId, String jikipPlanKey) {
|
||||
String normalizedPlanId = planId == null ? "" : planId.trim();
|
||||
String normalizedUserId = jikipUserId == null ? "" : jikipUserId.trim();
|
||||
String normalizedKey = jikipPlanKey == null ? "" : jikipPlanKey.trim();
|
||||
UserProxyPlanEntity existing = mapper.selectById(userId);
|
||||
// 留空=保留已存 key,但套餐 ID 变了就必须重新填:旧套餐的 key 对新套餐无效,
|
||||
// 继续沿用会让「加入白名单」稳定失败且看不出原因。
|
||||
String storedKey;
|
||||
if (!normalizedKey.isEmpty()) {
|
||||
storedKey = cryptoService.encrypt(normalizedKey);
|
||||
} else if (existing != null && normalizedPlanId.equals(existing.getPlanId())) {
|
||||
storedKey = existing.getJikipPlanKey();
|
||||
} else {
|
||||
storedKey = null;
|
||||
}
|
||||
if (existing == null) {
|
||||
UserProxyPlanEntity row = new UserProxyPlanEntity();
|
||||
row.setUserId(userId);
|
||||
row.setPlanId(normalizedPlanId);
|
||||
row.setJikipUserId(normalizedUserId);
|
||||
row.setJikipPlanKey(storedKey);
|
||||
mapper.insert(row);
|
||||
log.info("[user-secret][proxy-plan] 已保存 userId={} planId={} jikipUserId={}",
|
||||
userId, normalizedPlanId, normalizedUserId);
|
||||
} else {
|
||||
existing.setPlanId(normalizedPlanId);
|
||||
existing.setJikipUserId(normalizedUserId);
|
||||
existing.setJikipPlanKey(storedKey);
|
||||
mapper.updateById(existing);
|
||||
log.info("[user-secret][proxy-plan] 已更新 userId={} planId={} jikipUserId={}",
|
||||
userId, normalizedPlanId, normalizedUserId);
|
||||
}
|
||||
// 日志只记是否配置 key,绝不回显 key 明文/密文
|
||||
log.info("[user-secret][proxy-plan] 已保存 userId={} planId={} jikipUserId={} keyConfigured={}",
|
||||
userId, normalizedPlanId, normalizedUserId, storedKey != null && !storedKey.isBlank());
|
||||
return get(userId);
|
||||
}
|
||||
|
||||
/** 白名单代加所需凭据:未配置套餐/key 时返回 null。 */
|
||||
public WhitelistCredential getWhitelistCredential(Long userId) {
|
||||
UserProxyPlanEntity row = mapper.selectById(userId);
|
||||
if (row == null) {
|
||||
return null;
|
||||
}
|
||||
String planId = row.getPlanId() == null ? "" : row.getPlanId().trim();
|
||||
String planKey = decryptQuietly(row.getJikipPlanKey());
|
||||
if (planId.isEmpty() || planKey.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return new WhitelistCredential(planId, planKey);
|
||||
}
|
||||
|
||||
private String decryptQuietly(String cipherText) {
|
||||
if (cipherText == null || cipherText.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
String plain = cryptoService.decrypt(cipherText);
|
||||
return plain == null ? "" : plain.trim();
|
||||
} catch (Exception ex) {
|
||||
// 解密失败按「未配置」处理:不把密钥材料写进日志,只留异常类型
|
||||
log.warn("[user-secret][proxy-plan] 套餐 key 解密失败 err={}", ex.getClass().getSimpleName());
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/** 白名单代加凭据(仅内存中使用,禁止落日志)。 */
|
||||
public record WhitelistCredential(String planId, String planKey) {
|
||||
}
|
||||
|
||||
public void clear(Long userId) {
|
||||
mapper.deleteById(userId);
|
||||
log.info("[user-secret][proxy-plan] 已清除 userId={}", userId);
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.client.QingguoProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyWhitelistVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyLinkKey;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyProvider;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyWhitelistOutcome;
|
||||
import com.nanri.aiimage.modules.usersecret.support.PublicIpValidator;
|
||||
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 代理白名单代加:按用户已保存的代理配置选择供应商,把调用方提供的公网 IP 加到对应白名单。
|
||||
*
|
||||
* <ul>
|
||||
* <li>极客:套餐 ID + 套餐 key(用户填写,加密存 biz_user_proxy_plan);</li>
|
||||
* <li>青果:Key 直接从用户已保存的代理提取链接里取,无需重复填写。</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class UserProxyWhitelistService {
|
||||
|
||||
private final UserApiSecretService userApiSecretService;
|
||||
private final UserProxyPlanService userProxyPlanService;
|
||||
private final JikipProxyClient jikipProxyClient;
|
||||
private final QingguoProxyClient qingguoProxyClient;
|
||||
|
||||
public UserProxyWhitelistVo add(Long userId, String rawIp) {
|
||||
String ip = PublicIpValidator.normalize(rawIp);
|
||||
if (ip == null) {
|
||||
throw new BusinessException("请填写合法的公网 IP 地址");
|
||||
}
|
||||
String proxyUrl = userApiSecretService.findPlainValue(userId, UserSecretModule.PROXY.key());
|
||||
if (proxyUrl.isBlank()) {
|
||||
throw new BusinessException("请先在代理设置里保存代理提取链接");
|
||||
}
|
||||
ProxyProvider provider = resolveProvider(userId, proxyUrl);
|
||||
ProxyWhitelistOutcome outcome;
|
||||
if (provider == ProxyProvider.QINGGUO) {
|
||||
String key = ProxyLinkKey.fromUrl(proxyUrl);
|
||||
if (key == null) {
|
||||
throw new BusinessException("青果提取链接里缺少 key,请重新保存代理配置");
|
||||
}
|
||||
outcome = qingguoProxyClient.checkAndAddWhitelist(key, ip);
|
||||
} else if (provider == ProxyProvider.JIKIP) {
|
||||
UserProxyPlanService.WhitelistCredential credential = userProxyPlanService.getWhitelistCredential(userId);
|
||||
if (credential == null) {
|
||||
throw new BusinessException("请先在「极客套餐信息」里填写套餐 ID 与套餐 key");
|
||||
}
|
||||
outcome = jikipProxyClient.checkAndAddWhitelist(credential.planId(), credential.planKey(), ip);
|
||||
} else {
|
||||
throw new BusinessException("当前代理供应商不支持白名单代加");
|
||||
}
|
||||
if (!outcome.success()) {
|
||||
throw new BusinessException(outcome.message());
|
||||
}
|
||||
log.info("[user-secret][proxy-whitelist] 完成 userId={} provider={} ip={} added={}",
|
||||
userId, provider.key(), ip, outcome.added());
|
||||
UserProxyWhitelistVo vo = new UserProxyWhitelistVo();
|
||||
vo.setIp(ip);
|
||||
vo.setProvider(provider.key());
|
||||
vo.setAdded(outcome.added());
|
||||
vo.setMessage(outcome.message());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 供应商以服务端已存配置为准;老数据缺 channel 时按链接域名兜底。 */
|
||||
private ProxyProvider resolveProvider(Long userId, String proxyUrl) {
|
||||
ProxyProvider parsed = ProxyProvider.parse(
|
||||
userApiSecretService.findChannel(userId, UserSecretModule.PROXY.key()));
|
||||
if (parsed != null) {
|
||||
return parsed;
|
||||
}
|
||||
ProxyProvider detected = ProxyProvider.detectFromUrl(proxyUrl);
|
||||
return detected == null ? ProxyProvider.DEFAULT : detected;
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 从代理提取链接里取供应商 Key(青果白名单 API 复用它,无需用户再填一次)。
|
||||
* 链接本身是凭据载体,调用方不得把返回值写进日志。
|
||||
*/
|
||||
public final class ProxyLinkKey {
|
||||
|
||||
private ProxyLinkKey() {
|
||||
}
|
||||
|
||||
/** 取 {@code key} 查询参数(大小写不敏感,兼容 Key);没有返回 null。 */
|
||||
public static String fromUrl(String url) {
|
||||
if (url == null || url.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
int queryStart = url.indexOf('?');
|
||||
if (queryStart < 0 || queryStart == url.length() - 1) {
|
||||
return null;
|
||||
}
|
||||
String query = url.substring(queryStart + 1);
|
||||
int fragment = query.indexOf('#');
|
||||
if (fragment >= 0) {
|
||||
query = query.substring(0, fragment);
|
||||
}
|
||||
for (String pair : query.split("&")) {
|
||||
int separator = pair.indexOf('=');
|
||||
if (separator <= 0) {
|
||||
continue;
|
||||
}
|
||||
String name = pair.substring(0, separator);
|
||||
if (!"key".equalsIgnoreCase(name)) {
|
||||
continue;
|
||||
}
|
||||
String value = pair.substring(separator + 1);
|
||||
if (value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return URLDecoder.decode(value, StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
/** 白名单代加结果:success=false 时 message 为可展示的失败原因。 */
|
||||
public record ProxyWhitelistOutcome(boolean success, boolean added, String message) {
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 白名单 IP 校验:只接受公网 IP 字面量(IPv4 / IPv6),拒绝域名与内网/回环/链路本地地址。
|
||||
*
|
||||
* <p>纯字面量校验,不触发 DNS:正则先限定字符集,{@link InetAddress#getByName} 对字面量
|
||||
* 不会解析域名;解析结果再做私有/回环等判定。</p>
|
||||
*/
|
||||
public final class PublicIpValidator {
|
||||
|
||||
/** 只允许数字、十六进制、点与冒号,杜绝 hostname 进入 getByName。 */
|
||||
private static final Pattern LITERAL = Pattern.compile("[0-9A-Fa-f:.]+");
|
||||
/** 严格四段 IPv4:getByName("1.1.1") 会按历史缩写解析成 1.1.0.1,必须自己先卡住。 */
|
||||
private static final Pattern IPV4 = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
|
||||
|
||||
private PublicIpValidator() {
|
||||
}
|
||||
|
||||
/** 合法公网 IP 返回规范化文本;非法返回 null(不抛异常)。 */
|
||||
public static String normalize(String raw) {
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
String text = raw.trim();
|
||||
if (text.isEmpty() || text.length() > 64) {
|
||||
return null;
|
||||
}
|
||||
if (!LITERAL.matcher(text).matches() || (!text.contains(".") && !text.contains(":"))) {
|
||||
return null;
|
||||
}
|
||||
java.util.regex.Matcher ipv4 = IPV4.matcher(text);
|
||||
if (ipv4.matches()) {
|
||||
for (int i = 1; i <= 4; i++) {
|
||||
if (Integer.parseInt(ipv4.group(i)) > 255) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} else if (!text.contains(":")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
InetAddress address = InetAddress.getByName(text);
|
||||
if (address.isAnyLocalAddress()
|
||||
|| address.isLoopbackAddress()
|
||||
|| address.isLinkLocalAddress()
|
||||
|| address.isSiteLocalAddress()
|
||||
|| address.isMulticastAddress()) {
|
||||
return null;
|
||||
}
|
||||
return address.getHostAddress();
|
||||
} catch (UnknownHostException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,12 @@ AIIMAGE_MODULE_CLEANUP_MODULE_TYPES=DEDUPE,SPLIT,CONVERT,DELETE_BRAND
|
||||
# 示例:AIIMAGE_USER_SECRET_JIKIP_PLANS=111:222;333:444
|
||||
# 留空 = 不查余量(巡检会按天 WARN 提示未启用)
|
||||
AIIMAGE_USER_SECRET_JIKIP_PLANS=
|
||||
# 客户端「极客 → 加入白名单」代调接口(一般无需改;自建代理时才覆盖)
|
||||
AIIMAGE_USER_SECRET_JIKIP_WHITE_LIST_CHECK_URL=https://api.jikip.com/whiteList-check
|
||||
AIIMAGE_USER_SECRET_JIKIP_WHITE_LIST_ADD_URL=https://api.jikip.com/whiteList-addition
|
||||
# 青果(全球HTTP)白名单接口(Key 取代理提取链接里的 key)
|
||||
AIIMAGE_USER_SECRET_QINGGUO_WHITE_LIST_CHECK_URL=https://overseas-api.proxy.qg.net/whitelist/query
|
||||
AIIMAGE_USER_SECRET_QINGGUO_WHITE_LIST_ADD_URL=https://overseas-api.proxy.qg.net/whitelist/add
|
||||
AIIMAGE_NOTIFICATION_JIKIP_PROBE_ENABLED=true
|
||||
# 用户级余量巡检(跟随密钥巡检):低于阈值推用户站内通知
|
||||
AIIMAGE_USER_SECRET_PROXY_BALANCE_CHECK_MAX_ROWS=2000
|
||||
|
||||
@@ -578,6 +578,12 @@ aiimage:
|
||||
# 检测出口代理提取链接:留空=直连;配置后检测优先经代理、失败回退直连
|
||||
check-proxy-extract-url: ${AIIMAGE_USER_SECRET_CHECK_PROXY_EXTRACT_URL:}
|
||||
jikip-balance-url: ${AIIMAGE_USER_SECRET_JIKIP_BALANCE_URL:https://api.jikip.com/find-balance}
|
||||
# 客户端「加入白名单」:按用户自填的套餐 ID + 套餐 key 代调 jikip 白名单接口
|
||||
jikip-white-list-check-url: ${AIIMAGE_USER_SECRET_JIKIP_WHITE_LIST_CHECK_URL:https://api.jikip.com/whiteList-check}
|
||||
jikip-white-list-add-url: ${AIIMAGE_USER_SECRET_JIKIP_WHITE_LIST_ADD_URL:https://api.jikip.com/whiteList-addition}
|
||||
# 青果(全球HTTP)白名单:Key 取用户已保存的代理提取链接里的 key
|
||||
qingguo-white-list-check-url: ${AIIMAGE_USER_SECRET_QINGGUO_WHITE_LIST_CHECK_URL:https://overseas-api.proxy.qg.net/whitelist/query}
|
||||
qingguo-white-list-add-url: ${AIIMAGE_USER_SECRET_QINGGUO_WHITE_LIST_ADD_URL:https://overseas-api.proxy.qg.net/whitelist/add}
|
||||
# 多个套餐/账号:planId:userId;planId:userId(分号或逗号分隔);留空=不查余量
|
||||
jikip-plans: ${AIIMAGE_USER_SECRET_JIKIP_PLANS:}
|
||||
# 用户级余量巡检:跟随密钥巡检一起跑(find-balance 免费);低于阈值推该用户站内通知
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
-- V181: 用户级 jikip 套餐增加「白名单密钥」(套餐 key)
|
||||
--
|
||||
-- 背景(2026-10-30 用户拍板):
|
||||
-- 极客(jikip) 支持通过白名单 API 给套餐添加调用方出口 IP:
|
||||
-- https://api.jikip.com/whiteList-check?id=套餐id&ip=...
|
||||
-- https://api.jikip.com/whiteList-addition?id=套餐id&ip=...&key=套餐key
|
||||
-- 客户端代理默认走白名单授权(mode=1),用户换网络/公网 IP 变化后需要重新加白,
|
||||
-- 否则提取代理会被供应商拒绝。让用户在客户端填一次套餐 key,服务端代为调用加白接口。
|
||||
--
|
||||
-- 存储口径:
|
||||
-- 套餐 key 属于凭据,按 biz_user_api_secret 同款 AES 加密后落库(ShopCredentialCryptoService),
|
||||
-- 接口只回传掩码;计划 ID / 用户 ID 仍明文(只用于查余量,不是凭据)。
|
||||
--
|
||||
-- 回滚(手工):
|
||||
-- ALTER TABLE `biz_user_proxy_plan` DROP COLUMN `jikip_plan_key`;
|
||||
|
||||
ALTER TABLE `biz_user_proxy_plan`
|
||||
ADD COLUMN `jikip_plan_key` VARCHAR(2048) NULL
|
||||
COMMENT 'jikip 套餐 key 密文(仅用于白名单添加;空=未配置)' AFTER `jikip_user_id`;
|
||||
@@ -59,7 +59,9 @@ class CatchSilenceRatchetTest {
|
||||
// 10-28 Phase 3 抬 582 -> 585(心跳降级一枚 + 优雅停机两枚中断恢复,逐处记名见 STRICT_TOTAL 上方注释)。
|
||||
// 10-29 Phase 4D 抬 585 -> 591(AC-17 分片通道六枚 LOG_ONLY:清理/收尾失败不得盖掉主错误,
|
||||
// 逐处记名见 STRICT_TOTAL 上方注释;EMPTY 一格没涨)。
|
||||
static final int GIVEN_NOT_RETHROW = 591;
|
||||
// 10-30 用户端代理白名单(极客/青果)抬 591 -> 598(7 处逐一记名见 STRICT_TOTAL 上方注释;
|
||||
// 实测量到 599,多出的 1 格来自已提交的 79b04afd(AdminApiGuardFilter 编码绕过 catch),见同处说明)。
|
||||
static final int GIVEN_NOT_RETHROW = 599;
|
||||
static final int GIVEN_LOG_ONLY = 249;
|
||||
static final int GIVEN_EMPTY = 56;
|
||||
|
||||
@@ -234,8 +236,32 @@ class CatchSilenceRatchetTest {
|
||||
* 空体已按 10-26 那批的先例改成 WARN 带 path——空体是三类高危出口里最贵的一种,
|
||||
* 这里宁可让 {@code STRICT_LOG_ONLY} 涨六格,也不给"删除失败连日志都不留"开门。</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>10-30 用户端代理白名单(极客/青果白名单 API)抬 total 1045 -> 1052,7 枚逐处记名。
|
||||
* 全部是 NOT_RETHROW(log+return 或纯 return),RETHROW/LOG_ONLY/EMPTY 三格一枚未涨:
|
||||
* <ul>
|
||||
* <li>{@code JikipProxyClient.checkAndAddWhitelist} 添加一枚:网络/解析/上游非 0 code 统一折成
|
||||
* {@code ProxyWhitelistOutcome(false, ...)} 交控制器转可读文案;异常只记类型——RestClient
|
||||
* 异常消息可能带完整 URL(含套餐 key),禁止回传或落日志。</li>
|
||||
* <li>{@code JikipProxyClient.checkWhitelist} 查询一枚:查不到(含网络失败)返回 null,
|
||||
* 由调用方继续尝试添加——查询只是省一次写调用,不能变成添加的前置故障点。</li>
|
||||
* <li>{@code QingguoProxyClient.checkAndAddWhitelist} 添加一枚与
|
||||
* {@code QingguoProxyClient.queryContains} 查询一枚:与极客两枚同形状(同一套"先查后加"),
|
||||
* 异常只记类型——查询串里带用户的青果 Key。</li>
|
||||
* <li>{@code UserProxyPlanService.decryptQuietly} 一枚:已存套餐 key 解密失败按「未配置」处理
|
||||
* (返回空串),只记异常类型,绝不把密文/明文写进日志;抛出去只会让整个代理配置页 500。</li>
|
||||
* <li>{@code PublicIpValidator.normalize} 一枚(仅 return null):正则已拦字面量与段数,
|
||||
* {@code InetAddress.getByName} 的 {@code UnknownHostException} 表示输入非法,
|
||||
* 返回 null 让控制器给 400,不是吞供应商/DB 异常。</li>
|
||||
* <li>{@code ProxyLinkKey.fromUrl} 一枚(仅 return null):提取链接里 {@code key} 的百分号编码
|
||||
* 坏了就当作没带 key(后续按「未配置」提示重填),不把坏输入升级成整页失败。</li>
|
||||
* </ul>
|
||||
* 同批实测 total 1052、rethrow 398、notRethrow 598、logOnly 188(未动)、empty 56(未动)。
|
||||
* ⚠ 本批提交时整树已是 1053/notRethrow 599:多出的 1 格不属本批——已提交的 79b04afd 在
|
||||
* {@code AdminApiGuardFilter.decodePath} 增加了「畸形百分号编码保持原样、交给容器 400」的 catch
|
||||
* (NOT_RETHROW 形状),该笔未抬本基线。这里按整树实测一并包住并在这一行记名。
|
||||
*/
|
||||
static final int STRICT_TOTAL = 1045;
|
||||
static final int STRICT_TOTAL = 1053;
|
||||
/**
|
||||
* 重抛型 catch 的**下限**(不是上限):本轮把两处吞异常改成重抛之后实测 388。
|
||||
* 这一格只能涨不能跌——它是"异常会往外走"的总量,把它钉成"只许减"就等于拦着别人修吞异常。
|
||||
@@ -350,8 +376,15 @@ class CatchSilenceRatchetTest {
|
||||
* {@code WorkbenchClientPackageService.abortChunkedPackage} 的「会话已不存在」INFO 与
|
||||
* 「未登记对象清理失败」WARN 两枚。六枚的误差方向都是「清理/收尾失败不得盖掉主错误」,
|
||||
* 主错误由外层重抛;本批 EMPTY 一格没涨(原先三枚空体已按 10-26 先例改成带 path 的 WARN)。
|
||||
* 10-30 再抬 591 -> 598(用户端代理白名单 7 枚,逐处记名见 STRICT_TOTAL 上方注释):
|
||||
* 极客/青果各两枚(添加失败折成 {@code ProxyWhitelistOutcome}、查询失败返回 null 继续添加),
|
||||
* 套餐 key 解密失败按「未配置」处理一枚,IP 校验与提取链接 key 解码各一枚纯 return null。
|
||||
* 七枚全在用户端配置页的「手动加白名单」链路上,方向都是「选项未配置/输入非法就给可读提示」,
|
||||
* 没有把服务端主链路异常静默吞掉的出口。
|
||||
* 复测整树 599:多出的 1 格来自已提交的 79b04afd {@code AdminApiGuardFilter.decodePath}
|
||||
* (畸形编码保持原样交给容器 400),非本批新增,说明见 STRICT_TOTAL 上方。
|
||||
*/
|
||||
static final int STRICT_NOT_RETHROW = 591;
|
||||
static final int STRICT_NOT_RETHROW = 599;
|
||||
/**
|
||||
* 10-17 抬 172 -> 173,出处就是上面点名过的 {@code TaskHeartbeatLivenessService.stamp()}:
|
||||
* 块体只有「取到 key 名 + log.warn」一句,写心跳证据失败时既不重试也不抛出——
|
||||
|
||||
+69
-15
@@ -1,5 +1,6 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.security.ShopCredentialCryptoService;
|
||||
import com.nanri.aiimage.modules.usersecret.mapper.UserProxyPlanMapper;
|
||||
import com.nanri.aiimage.modules.usersecret.model.entity.UserProxyPlanEntity;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyPlanVo;
|
||||
@@ -7,15 +8,22 @@ import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** 用户级 jikip 套餐配置:一个用户一行,保存即 upsert,清除即删行。 */
|
||||
/** 用户级 jikip 套餐配置:一个用户一行,保存即 upsert,套餐 key 加密且只回显掩码。 */
|
||||
class UserProxyPlanServiceTest {
|
||||
|
||||
private final UserProxyPlanMapper mapper = mock(UserProxyPlanMapper.class);
|
||||
private final UserProxyPlanService service = new UserProxyPlanService(mapper);
|
||||
private final ShopCredentialCryptoService cryptoService = mock(ShopCredentialCryptoService.class);
|
||||
private final UserProxyPlanService service = new UserProxyPlanService(mapper, cryptoService);
|
||||
|
||||
UserProxyPlanServiceTest() {
|
||||
when(cryptoService.encrypt(anyString())).thenAnswer(invocation -> "enc:" + invocation.getArgument(0));
|
||||
when(cryptoService.decrypt("enc:plan-key-123456")).thenReturn("plan-key-123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReturnsUnconfiguredWhenNoRow() {
|
||||
@@ -26,13 +34,15 @@ class UserProxyPlanServiceTest {
|
||||
assertThat(vo.getConfigured()).isFalse();
|
||||
assertThat(vo.getPlanId()).isNull();
|
||||
assertThat(vo.getJikipUserId()).isNull();
|
||||
assertThat(vo.getJikipPlanKeyConfigured()).isFalse();
|
||||
assertThat(vo.getJikipPlanKeyMasked()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveInsertsTrimmedValuesForFirstTime() {
|
||||
void saveInsertsTrimmedValuesAndEncryptsPlanKey() {
|
||||
when(mapper.selectById(7L)).thenReturn(null);
|
||||
|
||||
service.save(7L, " 20261010593613392231 ", " 626710989815 ");
|
||||
service.save(7L, " 20261010593613392231 ", " 626710989815 ", " plan-key-123456 ");
|
||||
|
||||
ArgumentCaptor<UserProxyPlanEntity> captor = ArgumentCaptor.forClass(UserProxyPlanEntity.class);
|
||||
verify(mapper).insert(captor.capture());
|
||||
@@ -40,25 +50,60 @@ class UserProxyPlanServiceTest {
|
||||
assertThat(inserted.getUserId()).isEqualTo(7L);
|
||||
assertThat(inserted.getPlanId()).isEqualTo("20261010593613392231");
|
||||
assertThat(inserted.getJikipUserId()).isEqualTo("626710989815");
|
||||
assertThat(inserted.getUserId()).isNotNull();
|
||||
assertThat(inserted.getJikipPlanKey()).isEqualTo("enc:plan-key-123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveUpdatesExistingRowInPlace() {
|
||||
UserProxyPlanEntity existing = new UserProxyPlanEntity();
|
||||
existing.setUserId(7L);
|
||||
existing.setPlanId("old-plan");
|
||||
existing.setJikipUserId("old-user");
|
||||
void saveKeepsExistingKeyWhenBlankAndPlanUnchanged() {
|
||||
UserProxyPlanEntity existing = existingRow("plan-1", "enc:plan-key-123456");
|
||||
when(mapper.selectById(7L)).thenReturn(existing);
|
||||
|
||||
service.save(7L, "new-plan", "new-user");
|
||||
service.save(7L, "plan-1", "user-1", " ");
|
||||
|
||||
ArgumentCaptor<UserProxyPlanEntity> captor = ArgumentCaptor.forClass(UserProxyPlanEntity.class);
|
||||
verify(mapper).updateById(captor.capture());
|
||||
UserProxyPlanEntity updated = captor.getValue();
|
||||
assertThat(updated.getUserId()).isEqualTo(7L);
|
||||
assertThat(updated.getPlanId()).isEqualTo("new-plan");
|
||||
assertThat(updated.getJikipUserId()).isEqualTo("new-user");
|
||||
assertThat(captor.getValue().getJikipPlanKey()).isEqualTo("enc:plan-key-123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveClearsKeyWhenPlanChangedAndNoNewKeyProvided() {
|
||||
UserProxyPlanEntity existing = existingRow("old-plan", "enc:plan-key-123456");
|
||||
when(mapper.selectById(7L)).thenReturn(existing);
|
||||
|
||||
service.save(7L, "new-plan", "user-1", "");
|
||||
|
||||
ArgumentCaptor<UserProxyPlanEntity> captor = ArgumentCaptor.forClass(UserProxyPlanEntity.class);
|
||||
verify(mapper).updateById(captor.capture());
|
||||
assertThat(captor.getValue().getPlanId()).isEqualTo("new-plan");
|
||||
assertThat(captor.getValue().getJikipPlanKey()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMasksStoredPlanKey() {
|
||||
when(mapper.selectById(7L)).thenReturn(existingRow("plan-1", "enc:plan-key-123456"));
|
||||
|
||||
UserProxyPlanVo vo = service.get(7L);
|
||||
|
||||
assertThat(vo.getJikipPlanKeyConfigured()).isTrue();
|
||||
assertThat(vo.getJikipPlanKeyMasked()).isEqualTo("plan****3456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getWhitelistCredentialReturnsDecryptedKey() {
|
||||
when(mapper.selectById(7L)).thenReturn(existingRow("plan-1", "enc:plan-key-123456"));
|
||||
|
||||
UserProxyPlanService.WhitelistCredential credential = service.getWhitelistCredential(7L);
|
||||
|
||||
assertThat(credential).isNotNull();
|
||||
assertThat(credential.planId()).isEqualTo("plan-1");
|
||||
assertThat(credential.planKey()).isEqualTo("plan-key-123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getWhitelistCredentialNullWhenKeyMissing() {
|
||||
when(mapper.selectById(7L)).thenReturn(existingRow("plan-1", null));
|
||||
|
||||
assertThat(service.getWhitelistCredential(7L)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -67,4 +112,13 @@ class UserProxyPlanServiceTest {
|
||||
|
||||
verify(mapper).deleteById(7L);
|
||||
}
|
||||
|
||||
private static UserProxyPlanEntity existingRow(String planId, String key) {
|
||||
UserProxyPlanEntity existing = new UserProxyPlanEntity();
|
||||
existing.setUserId(7L);
|
||||
existing.setPlanId(planId);
|
||||
existing.setJikipUserId("user-1");
|
||||
existing.setJikipPlanKey(key);
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package com.nanri.aiimage.modules.usersecret.service;
|
||||
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.usersecret.client.JikipProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.client.QingguoProxyClient;
|
||||
import com.nanri.aiimage.modules.usersecret.model.vo.UserProxyWhitelistVo;
|
||||
import com.nanri.aiimage.modules.usersecret.support.ProxyWhitelistOutcome;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class UserProxyWhitelistServiceTest {
|
||||
|
||||
private final UserApiSecretService userApiSecretService = mock(UserApiSecretService.class);
|
||||
private final UserProxyPlanService userProxyPlanService = mock(UserProxyPlanService.class);
|
||||
private final JikipProxyClient jikipProxyClient = mock(JikipProxyClient.class);
|
||||
private final QingguoProxyClient qingguoProxyClient = mock(QingguoProxyClient.class);
|
||||
private final UserProxyWhitelistService service = new UserProxyWhitelistService(
|
||||
userApiSecretService, userProxyPlanService, jikipProxyClient, qingguoProxyClient);
|
||||
|
||||
@Test
|
||||
void rejectsNonPublicIpBeforeTouchingConfig() {
|
||||
assertThatThrownBy(() -> service.add(7L, "192.168.1.10"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("公网 IP");
|
||||
verifyNoInteractions(userApiSecretService, userProxyPlanService, jikipProxyClient, qingguoProxyClient);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsWhenProxyLinkNotSaved() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy")).thenReturn("");
|
||||
|
||||
assertThatThrownBy(() -> service.add(7L, "36.251.68.43"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("保存代理提取链接");
|
||||
}
|
||||
|
||||
@Test
|
||||
void qingguoUsesKeyFromSavedProxyLink() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy"))
|
||||
.thenReturn("https://overseas.proxy.qg.net/get?key=abc123&format=json");
|
||||
when(userApiSecretService.findChannel(7L, "proxy")).thenReturn("qingguo");
|
||||
when(qingguoProxyClient.checkAndAddWhitelist("abc123", "36.251.68.43"))
|
||||
.thenReturn(new ProxyWhitelistOutcome(true, true, "已加入白名单,立即生效"));
|
||||
|
||||
UserProxyWhitelistVo vo = service.add(7L, " 36.251.68.43 ");
|
||||
|
||||
assertThat(vo.getIp()).isEqualTo("36.251.68.43");
|
||||
assertThat(vo.getProvider()).isEqualTo("qingguo");
|
||||
assertThat(vo.getAdded()).isTrue();
|
||||
verify(qingguoProxyClient).checkAndAddWhitelist("abc123", "36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void qingguoRejectsLinkWithoutKey() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy"))
|
||||
.thenReturn("http://user:pass@host:8080");
|
||||
when(userApiSecretService.findChannel(7L, "proxy")).thenReturn("qingguo");
|
||||
|
||||
assertThatThrownBy(() -> service.add(7L, "36.251.68.43"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("缺少 key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jikipUsesStoredPlanCredential() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy"))
|
||||
.thenReturn("https://api.jikip.com/ip-get?key=extract-key&num=1");
|
||||
when(userApiSecretService.findChannel(7L, "proxy")).thenReturn("jikip");
|
||||
when(userProxyPlanService.getWhitelistCredential(7L))
|
||||
.thenReturn(new UserProxyPlanService.WhitelistCredential("plan-1", "plan-key"));
|
||||
when(jikipProxyClient.checkAndAddWhitelist("plan-1", "plan-key", "36.251.68.43"))
|
||||
.thenReturn(new ProxyWhitelistOutcome(true, false, "该 IP 已在白名单中"));
|
||||
|
||||
UserProxyWhitelistVo vo = service.add(7L, "36.251.68.43");
|
||||
|
||||
assertThat(vo.getProvider()).isEqualTo("jikip");
|
||||
assertThat(vo.getAdded()).isFalse();
|
||||
verify(jikipProxyClient).checkAndAddWhitelist("plan-1", "plan-key", "36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void jikipRequiresPlanKeyConfigured() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy"))
|
||||
.thenReturn("https://api.jikip.com/ip-get?key=extract-key&num=1");
|
||||
when(userApiSecretService.findChannel(7L, "proxy")).thenReturn("jikip");
|
||||
when(userProxyPlanService.getWhitelistCredential(7L)).thenReturn(null);
|
||||
|
||||
assertThatThrownBy(() -> service.add(7L, "36.251.68.43"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("套餐 key");
|
||||
}
|
||||
|
||||
@Test
|
||||
void supplierFailureBecomesBusinessException() {
|
||||
when(userApiSecretService.findPlainValue(7L, "proxy"))
|
||||
.thenReturn("https://overseas.proxy.qg.net/get?key=abc123");
|
||||
when(userApiSecretService.findChannel(7L, "proxy")).thenReturn("qingguo");
|
||||
when(qingguoProxyClient.checkAndAddWhitelist("abc123", "36.251.68.43"))
|
||||
.thenReturn(new ProxyWhitelistOutcome(false, false, "青果套餐不存在或已过期"));
|
||||
|
||||
assertThatThrownBy(() -> service.add(7L, "36.251.68.43"))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessage("青果套餐不存在或已过期");
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class ProxyLinkKeyTest {
|
||||
|
||||
@Test
|
||||
void extractsKeyFromQuery() {
|
||||
assertThat(ProxyLinkKey.fromUrl(
|
||||
"https://overseas.proxy.qg.net/get?key=abc123&format=json&num=1")).isEqualTo("abc123");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsCapitalizedKeyAndDecodesValue() {
|
||||
assertThat(ProxyLinkKey.fromUrl("https://share.proxy.qg.net/get?Key=a%2Bb%20c"))
|
||||
.isEqualTo("a+b c");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsNullWhenKeyMissingOrUrlInvalid() {
|
||||
assertThat(ProxyLinkKey.fromUrl("https://overseas.proxy.qg.net/get?num=1")).isNull();
|
||||
assertThat(ProxyLinkKey.fromUrl("https://overseas.proxy.qg.net/get?key=")).isNull();
|
||||
assertThat(ProxyLinkKey.fromUrl("http://user:pass@host:8080")).isNull();
|
||||
assertThat(ProxyLinkKey.fromUrl("")).isNull();
|
||||
assertThat(ProxyLinkKey.fromUrl(null)).isNull();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.nanri.aiimage.modules.usersecret.support;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class PublicIpValidatorTest {
|
||||
|
||||
@Test
|
||||
void acceptsPublicIpv4AndTrims() {
|
||||
assertThat(PublicIpValidator.normalize(" 36.251.68.43 ")).isEqualTo("36.251.68.43");
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsPublicIpv6() {
|
||||
assertThat(PublicIpValidator.normalize("2001:4860:4860::8888")).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsPrivateLoopbackAndLinkLocal() {
|
||||
assertThat(PublicIpValidator.normalize("127.0.0.1")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("10.1.2.3")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("172.16.0.1")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("192.168.1.10")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("169.254.1.1")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("0.0.0.0")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("::1")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsHostnamesAndMalformedText() {
|
||||
assertThat(PublicIpValidator.normalize("example.com")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("1.1.1.1/24")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("1.1.1")).isNull();
|
||||
assertThat(PublicIpValidator.normalize("")).isNull();
|
||||
assertThat(PublicIpValidator.normalize(null)).isNull();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user