fix: isolate server-side donation credentials and rotate auth defaults (#320)

This commit is contained in:
qaiu authored and GitHub committed 2026-12-04 03:09:45 +08:00
1 parent 3047ba97a2
commit 76aaa7d214
19 files changed
+190 -125

No files matched your search

@@ -5,6 +5,7 @@ import cn.qaiu.db.pool.JDBCPoolInit;
import cn.qaiu.lz.common.cache.CacheConfigLoader;
import cn.qaiu.lz.common.cache.CacheManager;
import cn.qaiu.lz.common.interceptorImpl.RateLimiter;
import cn.qaiu.lz.common.util.AuthParamCodec;
import cn.qaiu.lz.web.config.PlaygroundConfig;
import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.lz.web.service.impl.ShoutServiceImpl;
@@ -90,6 +91,7 @@ public class AppMain {
* @param jsonObject 配置
*/
private static void exec(JsonObject jsonObject) {
AuthParamCodec.configure(jsonObject.getJsonObject(ConfigConstant.SERVER));
WebClientVertxInit.init(VertxHolder.getVertxInstance());
DatabindCodec.mapper().registerModule(new JavaTimeModule());
// 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。
@@ -3,13 +3,17 @@ package cn.qaiu.lz.common.util;
import cn.qaiu.lz.web.model.AuthParam;
import cn.qaiu.util.AESUtils;
import cn.qaiu.util.Base64Decoder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
/**
* 认证参数编解码工具类
@@ -24,34 +28,51 @@ import java.nio.charset.StandardCharsets;
@Slf4j
public class AuthParamCodec {
/**
* 默认加密密钥(16位)
*/
private static final String DEFAULT_ENCRYPT_KEY = "nfd_auth_key2026";
/**
* 配置中的密钥路径
*/
private static final String CONFIG_KEY_PATH = "authEncryptKey";
// 识别升级时保留下来的旧发行版配置;不再使用旧密钥。
private static final String RETIRED_KEY_SHA256 = "b2c23dd4619534db9831db32be8e699412f1de60138ac37234eaae827ff1bcf4";
private static final String PROCESS_RANDOM_KEY = generateKey();
private static volatile String encryptKey = PROCESS_RANDOM_KEY;
private AuthParamCodec() {
// 工具类禁止实例化
}
/**
* 获取加密密钥
* 优先从配置文件读取,如果未配置则使用默认密钥
*/
public static String getEncryptKey() {
try {
String configKey = SharedDataUtil.getJsonStringForServerConfig(CONFIG_KEY_PATH);
if (StringUtils.isNotBlank(configKey)) {
return configKey;
}
} catch (Exception e) {
log.debug("从配置读取加密密钥失败,使用默认密钥: {}", e.getMessage());
public static void configure(JsonObject serverConfig) {
String configuredKey = serverConfig.getString(CONFIG_KEY_PATH);
encryptKey = selectKey(configuredKey);
log.info("authEncryptKey: source={}, fingerprint(SHA-256)={}",
encryptKey == PROCESS_RANDOM_KEY ? "generated (this process only)" : "configured",
fingerprint(encryptKey).substring(0, 12));
}
static String selectKey(String configuredKey) {
if (StringUtils.isBlank(configuredKey) || RETIRED_KEY_SHA256.equals(fingerprint(configuredKey))) {
return PROCESS_RANDOM_KEY;
}
return DEFAULT_ENCRYPT_KEY;
int length = configuredKey.getBytes(StandardCharsets.UTF_8).length;
if (length != 16 && length != 24 && length != 32) {
throw new IllegalArgumentException("server.authEncryptKey must be 16, 24, or 32 UTF-8 bytes");
}
return configuredKey;
}
static String generateKey() {
byte[] random = new byte[24];
new SecureRandom().nextBytes(random);
return Base64.getUrlEncoder().withoutPadding().encodeToString(random);
}
private static String fingerprint(String value) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 unavailable", e);
}
}
public static String getEncryptKey() {
return encryptKey;
}
/**
@@ -69,7 +90,7 @@ public class AuthParamCodec {
* 解码认证参数(指定密钥)
*
* @param encryptedAuth 加密后的认证参数字符串
* @param key AES密钥(16位)
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
* @return AuthParam 对象,解码失败返回 null
*/
public static AuthParam decode(String encryptedAuth, String key) {
@@ -85,7 +106,6 @@ public class AuthParamCodec {
}
// 兼容 query 参数中 '+' 被还原为空格的情况
normalized = normalized.replace(' ', '+');
log.debug("认证参数规范化结果: {}", normalized);
// Step 2: Base64解码
byte[] base64Decoded = Base64Decoder.decode(normalized);
@@ -93,7 +113,6 @@ public class AuthParamCodec {
// Step 3: AES解密
String jsonStr = AESUtils.decryptByAES(base64Decoded, key);
log.debug("AES解密结果: {}", jsonStr);
// Step 4: JSON解析
JsonObject json = new JsonObject(jsonStr);
@@ -102,9 +121,9 @@ public class AuthParamCodec {
return authParam;
} catch (IllegalArgumentException e) {
log.warn("认证参数Base64解码失败: {}", e.getMessage());
log.warn("认证参数格式无效");
} catch (Exception e) {
log.warn("认证参数解码失败: {}", e.getMessage());
log.warn("认证参数解码失败");
}
return null;
}
@@ -124,7 +143,7 @@ public class AuthParamCodec {
* 编码认证参数(指定密钥)
*
* @param authParam 认证参数对象
* @param key AES密钥(16位)
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节)
* @return 加密后的字符串,编码失败返回 null
*/
public static String encode(AuthParam authParam, String key) {
@@ -135,15 +154,12 @@ public class AuthParamCodec {
try {
// Step 1: 转换为JSON
String jsonStr = authParam.toJsonObject().encode();
log.debug("JSON字符串: {}", jsonStr);
// Step 2: AES加密 + Base64编码
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, key);
log.debug("AES+Base64编码结果: {}", base64Encoded);
// Step 3: URL编码
String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
log.debug("URL编码结果: {}", urlEncoded);
return urlEncoded;
@@ -6,6 +6,7 @@ import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.parser.ParserCreate;
import cn.qaiu.vx.core.util.ConfigConstant;
import cn.qaiu.vx.core.util.VertxHolder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.Future;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest;
@@ -88,7 +89,7 @@ public class ParserAuthUtil {
public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam,
Throwable cause) {
if (!isLikelyAuthFailure(cause) || otherParam == null) {
if (otherParam == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
return;
}
String donatedAccountToken = otherParam.getString("donatedAccountToken");
@@ -101,7 +102,7 @@ public class ParserAuthUtil {
public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo,
Throwable cause) {
if (shareLinkInfo == null || !isLikelyAuthFailure(cause)) {
if (shareLinkInfo == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) {
return;
}
Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN);
@@ -112,14 +113,31 @@ public class ParserAuthUtil {
.onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e));
}
public static boolean isDonatedAccountsEnabled() {
return isDonatedAccountsEnabled(SharedDataUtil.getJsonConfig(ConfigConstant.SERVER));
}
static boolean isDonatedAccountsEnabled(JsonObject server) {
return server != null && Boolean.TRUE.equals(server.getValue("enableDonatedAccounts"))
&& Boolean.TRUE.equals(server.getValue("enableDatabase"));
}
// 只启用已检查解析结果不会携带捐赠账号下载请求头的网盘。
public static boolean supportsServerSideDonation(String type) {
return "ye".equalsIgnoreCase(type) || "fj".equalsIgnoreCase(type) || "iz".equalsIgnoreCase(type);
}
private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) {
if (!isDonatedAccountsEnabled()) {
return Future.succeededFuture();
}
ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo();
Map<String, Object> otherParam = shareLinkInfo.getOtherParam();
if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) {
return Future.succeededFuture();
}
String type = shareLinkInfo.getType();
if (StringUtils.isBlank(type) || hasUsableStaticAuthConfig(type)) {
if (!supportsServerSideDonation(type) || hasUsableStaticAuthConfig(type)) {
return Future.succeededFuture();
}
return dbService.getRandomDonatedAccount(type.toUpperCase())
@@ -770,11 +770,18 @@ public class ParserApi {
*/
@RouteMapping(value = "/donateAccount", method = RouteMethod.POST)
public Future<JsonObject> donateAccount(RoutingContext ctx) {
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
return Future.succeededFuture(JsonResult.error("捐赠账号功能未启用").toJsonObject());
}
JsonObject body = ctx.body().asJsonObject();
if (body == null || StringUtils.isBlank(body.getString("panType"))
|| StringUtils.isBlank(body.getString("authType"))) {
return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject());
}
if (!ParserAuthUtil.supportsServerSideDonation(body.getString("panType"))) {
return Future.succeededFuture(JsonResult.error("该网盘暂不支持服务端捐赠池").toJsonObject());
}
body.put("panType", body.getString("panType").toUpperCase(java.util.Locale.ROOT));
String ip = ctx.request().remoteAddress().host();
body.put("ip", ip);
return dbService.saveDonatedAccount(body);
@@ -785,23 +792,16 @@ public class ParserApi {
*/
@RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET)
public Future<JsonObject> getDonateAccountCounts() {
return dbService.getDonatedAccountCounts();
}
/**
* 随机获取指定网盘类型的捐赠账号(内部使用,返回加密后的 auth 参数)
*/
@RouteMapping(value = "/randomAuth", method = RouteMethod.GET)
public Future<JsonObject> getRandomAuth(String panType) {
return dbService.getRandomDonatedAccount(panType).map(res -> {
if (Integer.valueOf(200).equals(res.getInteger("code")) && res.getJsonObject("data") != null) {
JsonObject data = res.getJsonObject("data");
String encryptedAuth = AuthParamCodec.encode(data);
JsonObject safeData = new JsonObject();
safeData.put("encryptedAuth", encryptedAuth);
res.put("data", safeData);
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
return Future.succeededFuture(JsonResult.data(new JsonObject().put("enabled", false)).toJsonObject());
}
return dbService.getDonatedAccountCounts().map(result -> {
JsonObject data = result.getJsonObject("data");
if (data != null) {
data.put("enabled", true);
}
return res;
return result;
});
}
}
@@ -39,7 +39,7 @@ public class DbServiceImpl implements DbService {
private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L;
private static final String HMAC_ALGORITHM = "HmacSHA256";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_CONFIG = "donatedAccountFailureTokenSignKey";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = "nfd_donate_fail_token_sign_2026";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = java.util.UUID.randomUUID().toString() + java.util.UUID.randomUUID();
@Override
public Future<JsonObject> sayOk(String data) {
log.info("say ok1 -> wait...");
@@ -574,7 +574,7 @@ public class DbServiceImpl implements DbService {
return configKey;
}
} catch (Exception e) {
log.debug("读取捐赠账号失败计数签名密钥失败,使用默认值: {}", e.getMessage());
log.debug("读取捐赠账号失败计数签名密钥失败,使用进程随机值: {}", e.getMessage());
}
return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK;
}
+4 -2
View File
@@ -8,8 +8,10 @@ server:
# domainName: http://127.0.0.1:6401
# 预览服务URL
previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src=
# auth参数加密密钥(16位AES密钥)
authEncryptKey: 'nfd_auth_key2026'
# 未配置时每次启动自动生成随机密钥;多实例或外部客户端可配置共享密钥。
# authEncryptKey: ""
# 捐赠默认关闭;开启后凭据仅供服务端选用。
enableDonatedAccounts: false
# 反向代理服务器配置路径(不用加后缀)
proxyConf: server-proxy
@@ -21,7 +21,37 @@ import static org.junit.Assert.*;
public class AuthParamCodecTest {
// 测试用的固定密钥
private static final String TEST_KEY = "nfd_auth_key2026";
private static final String TEST_KEY = "dummy-test-key16";
@Test
public void usesOneRandomKeyPerProcessAndSupportsExplicitConfiguration() {
String generated = AuthParamCodec.selectKey(null);
assertEquals(32, generated.getBytes(StandardCharsets.UTF_8).length);
assertSame(generated, AuthParamCodec.selectKey(""));
assertSame(generated, AuthParamCodec.selectKey(" "));
assertNotEquals(AuthParamCodec.generateKey(), AuthParamCodec.generateKey());
assertEquals(TEST_KEY, AuthParamCodec.selectKey(TEST_KEY));
assertThrows(IllegalArgumentException.class, () -> AuthParamCodec.selectKey("invalid length"));
}
@Test
public void generatedKeyRoundTripsSyntheticAuth() {
AuthParam auth = AuthParam.builder().authType("token").token("synthetic-only").build();
String key = AuthParamCodec.selectKey(null);
assertEquals("synthetic-only",
AuthParamCodec.decode(AuthParamCodec.encode(auth, key), key).getToken());
}
@Test
public void donatedAccountsRequireExplicitOptInAndDatabase() {
JsonObject server = new JsonObject().put("enableDatabase", true);
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server));
assertTrue(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDonatedAccounts", true)));
assertFalse(ParserAuthUtil.isDonatedAccountsEnabled(server.put("enableDatabase", false)));
assertTrue(ParserAuthUtil.supportsServerSideDonation("YE"));
assertFalse(ParserAuthUtil.supportsServerSideDonation("QK"));
assertFalse(ParserAuthUtil.supportsServerSideDonation("UC"));
}
@Test
public void testAuthParamModel() {
@@ -18,7 +18,7 @@ import java.util.Base64;
*/
public class AuthParamCodecTestMain {
private static final String TEST_KEY = "nfd_auth_key2026";
private static final String TEST_KEY = "dummy-test-key16";
private static int passCount = 0;
private static int failCount = 0;