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:
+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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user