Compare commits

..
Author SHA1 Message Date
qaiu e4db064a71 fix(parser): 分享链接提取码不再污染 shareKey,Cloudreve 探测避免提前失败
完整分享 URL 中的 ?pwd= / ?password= / ?code= 以及 # 片段不再被吞进
shareKey;小飞机、123、蓝奏等粘贴带提取码的链接时可正确带上密码。
同时收紧小飞机与蓝奏优享的路径正则。

CeTool 版本探测改用 tryParseJson:上游返回 HTML 时不再经由 asJson()
调用 fail(),以免阻断 nextParser 责任链(表现为「json格式异常」)。
2026-11-27 15:44:28 +08:00
31 changed files with 560 additions and 320 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version id: version
attributes: attributes:
label: 版本号 label: 版本号
description: 页面上的版本,或发布包名里的版本,例如 0.4.15。 description: 页面上的版本,或发布包名里的版本,例如 0.4.13。
placeholder: "0.4.15" placeholder: "0.4.13"
validations: validations:
required: true required: true
- type: dropdown - type: dropdown
+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version id: version
attributes: attributes:
label: 版本号 label: 版本号
description: 例如 0.4.15。不确定就写获取方式。 description: 例如 0.4.13。不确定就写获取方式。
placeholder: "0.4.15" placeholder: "0.4.13"
validations: validations:
required: true required: true
- type: dropdown - type: dropdown
+19 -6
View File
@@ -1,9 +1,22 @@
## v0.4.15 ## 更新内容
- 临时认证不再使用发行包里的公共密钥。未手动配置的服务实例每次启动生成随机密钥,只记录来源和指纹。保留旧发行包配置的实例也会自动迁移。 - 蓝奏文件页识别 `ajaxfiles.php`(#310):
- 捐赠池默认关闭。显式启用后,受支持的网盘使用服务端选号,不再向前端提供捐赠账号。已保存的捐赠记录不会删除。 - 单文件页 iframe 里的下载 ajax 写成了 `/ajaxfiles.php`。解析器原来只认 `ajaxm.php` 和 `ajaxfile.php`,匹配不上就报「获取失败0, 可能分享已失效」。表单字段没有改。
- 清理网页和文档中的公共密钥。需要网页个人认证、外部客户端或多实例共享密钥的自建站,须显式配置和安全分发 `server.authEncryptKey`。 - `https://njkn.lanzouw.com/winx123`(无密码)没有失效。修复后本机完整下载 1,197,569 字节,`unzip -t` 无错误。
- 另外三个同样改成 `ajaxfiles.php` 的对照只各下载了 1 MiB Range,返回 206,文件头分别是 7z、zip、zip,没有做完整下载:
- `wwn.lanzouy.com/ihLkw1gezutg`
- b66477 目录下的 `pan.lanzoui.com/io4y41i3zq5e`
- 密码目录 `b00yaejvte` 里的子文件 `w1.lanzn.com/i4VjZ332qzwh`
- 带密码的单文件分享没有找到公开样例,没有实测。
- 目录按已加载文件名筛选(#311):
- 分享目录浏览器和首页解析后的目录共用目录树。两套视图以及独立的 `list.html` 按文件名做大小写不敏感的子串匹配,只筛已经加载的行,不把后续页自动拉完。
- 目录树底部「全选 / 取消全选」只作用于当前关键字命中的、已经加载的可选文件。不勾选被筛掉的项,不拉取未加载分页,也不清掉范围外原来的选择。
- 分页仍走现有的 `nextCursor` / `pageCursor`。
- 界面验收跑在本机开发服务和本机夹具,不是线上分享页。
### 升级提醒 ## 限制
旧公共密钥生成的 `auth` 参数不再兼容。升级后请核对部署配置,并视部署情况清理过往解析缓存和轮换捐赠凭据。 - 没有把这次界面验收当成线上分享页或全站界面已验。
- 三个对照链接只验证了 1 MiB Range,不能据此说这些文件已经完整下载并核对。
- 带密码的单文件分享未测。
- 本机访问部分蓝奏下载域时连接时好时坏。winx123 曾连续超时,重试后完整下载成功。
+6 -26
View File
@@ -1,8 +1,4 @@
# 一款网盘分享链接云解析快速下载服务 # 一款网盘分享链接云解析快速下载服务
> [!TIP]
> 如果在线解析失败,可以试试 [NFD Client](https://github.com/qaiu/nfd-client-parser),在本机解析网盘分享链接。[下载安装包](https://github.com/qaiu/nfd-client-parser/releases/latest)
QQ交流群:1017480890 QQ交流群:1017480890
<p align="center"> <p align="center">
<a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a> <a href="https://github.com/qaiu/netdisk-fast-download/actions/workflows/maven.yml"><img src="https://img.shields.io/github/actions/workflow/status/qaiu/netdisk-fast-download/build.yml?branch=main&style=flat"></a>
@@ -163,13 +159,14 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
- `your_host` 替换为您的域名或 IP - `your_host` 替换为您的域名或 IP
### 认证参数(v0.2.1+) ### 认证参数(v0.2.1+)
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息: 部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码 **参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
**加密方式**: **加密方式**:
- 算法:AES/ECB/PKCS5Padding - 算法:AES/ECB/PKCS5Padding
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值) - 密钥:`nfd_auth_key2026`(16字节)
- 流程:JSON → AES加密 → Base64 → URL编码 - 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**: **JSON 结构**:
@@ -198,20 +195,14 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数} GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
``` ```
> 💡 提示:自建站的可信客户端可在网页中填写其显式配置的服务认证密钥;网页不会获取或保存服务端密钥。 > 💡 提示:Web 界面已内置认证配置功能,可自动处理加密过程,无需手动构造参数。
> 不要在不受信任的站点输入服务密钥或网盘凭据。 > [可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
#### 升级与捐赠开关
- 没有手动配置密钥(包括升级后仍保留旧发布包默认配置)的实例,在每次启动时自动生成进程随机密钥。启动日志只记录来源和指纹,不输出原文。重启后,之前用进程密钥生成的认证参数会失效。
- 要让可信浏览器、外部工具或多实例使用同一密钥,显式配置 `server.authEncryptKey`,通过安全渠道分发;不要使用旧发布包默认值。
- 捐赠默认关闭。仅设置 `server.enableDonatedAccounts: true` 且启用数据库后,才允许提交和服务端选用捐赠账号。关闭不删除已有记录。旧的浏览器取号接口已移除。仅 123 云盘、小飞机和蓝奏优享可使用服务端捐赠池;需要在下载响应携带账号请求头的网盘暂不开放。
#### 密钥作用说明 #### 密钥作用说明
- `server.authEncryptKey` - `server.authEncryptKey`
- 作用:用于 `auth` 参数的 AES 加解密 - 作用:用于 `auth` 参数的 AES 加解密
- 要求:16、24 或 32 个 UTF-8 字节 - 要求:16位(AES-128)
- `server.donatedAccountFailureTokenSignKey` - `server.donatedAccountFailureTokenSignKey`
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签 - 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
@@ -479,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径 > 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
```shell ```shell
cd ~ cd ~
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.15/netdisk-fast-download-linux-amd64.zip wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.13/netdisk-fast-download-linux-amd64.zip
unzip netdisk-fast-download.zip unzip netdisk-fast-download.zip
cd netdisk-fast-download cd netdisk-fast-download
bash service-install.sh bash service-install.sh
@@ -608,14 +599,3 @@ Core模块集成Vert.x实现类似spring的注解式路由API
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank"> <a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200"> <img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
</a> </a>
### 代理资源支持
<a href="https://proxy-seller.com/?partner=5799A39425654D33">
<img src="https://raw.githubusercontent.com/wujunwei928/parse-video-py/main/resources/proxy-seller-logo.png" alt="Proxy-Seller" width="120">
</a>
感谢 [Proxy-Seller](https://proxy-seller.com/?partner=5799A39425654D33) 提供代理 IP 支持,其香港 IP 可用于本项目。
[Proxy-Seller 优惠链接](https://proxy-seller.com/?partner=5799A39425654D33) · 专属折扣码:`BJSBDD_664959`
+4 -4
View File
@@ -4,26 +4,26 @@ NFD 解析器模块:聚合各类网盘/分享页解析,统一输出文件列
- 语言:Java 17 - 语言:Java 17
- 构建:Maven - 构建:Maven
- 模块版本:10.2.7 - 模块版本:10.2.5
## 依赖(Maven Central) ## 依赖(Maven Central)
```xml ```xml
<dependency> <dependency>
<groupId>cn.qaiu</groupId> <groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId> <artifactId>parser</artifactId>
<version>10.2.7</version> <version>10.2.5</version>
</dependency> </dependency>
``` ```
- Gradle Groovy DSL: - Gradle Groovy DSL:
```groovy ```groovy
dependencies { dependencies {
implementation 'cn.qaiu:parser:10.2.7' implementation 'cn.qaiu:parser:10.2.5'
} }
``` ```
- Gradle Kotlin DSL: - Gradle Kotlin DSL:
```kotlin ```kotlin
dependencies { dependencies {
implementation("cn.qaiu:parser:10.2.7") implementation("cn.qaiu:parser:10.2.5")
} }
``` ```
+1 -1
View File
@@ -28,7 +28,7 @@
**加密方式**: **加密方式**:
- 算法:AES/ECB/PKCS5Padding - 算法:AES/ECB/PKCS5Padding
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值) - 密钥:`nfd_auth_key2026`(16字节)
- 流程:JSON → AES加密 → Base64 → URL编码 - 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**: **JSON 结构**:
+7 -8
View File
@@ -33,8 +33,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
### 加密配置 ### 加密配置
- **加密算法**: AES/ECB/PKCS5Padding - **加密算法**: AES/ECB/PKCS5Padding
- **密钥长度**: 16、24 或 32 个 UTF-8 字节 - **密钥长度**: 16位(128位)
- **密钥**: 没有公共默认值。需要对接的可信客户端应使用自建服务显式配置的 `server.authEncryptKey`。 - **默认密钥**: `nfd_auth_key2026`(可在 `app-dev.yml` 中通过 `server.authEncryptKey` 配置)
### 密钥作用说明(重要) ### 密钥作用说明(重要)
@@ -43,7 +43,7 @@ URL解码 → Base64解码 → AES解密 → JSON对象
1. `server.authEncryptKey` 1. `server.authEncryptKey`
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息) - 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数 - 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
- 注意:这是 **AES 对称加密密钥**,要求 16、24 或 32 字节 - 注意:这是 **AES 对称加密密钥**,要求 16 位
2. `server.donatedAccountFailureTokenSignKey` 2. `server.donatedAccountFailureTokenSignKey`
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数) - 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
@@ -194,7 +194,7 @@ AuthParam decoded = AuthParamCodec.decode(encrypted);
// 使用 CryptoJS 库 // 使用 CryptoJS 库
const CryptoJS = require('crypto-js'); const CryptoJS = require('crypto-js');
const AUTH_KEY = process.env.NFD_AUTH_ENCRYPT_KEY; const AUTH_KEY = 'nfd_auth_key2026';
// 加密 // 加密
function encodeAuthParam(authObj) { function encodeAuthParam(authObj) {
@@ -234,8 +234,7 @@ from urllib.parse import quote, unquote
from Crypto.Cipher import AES from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad from Crypto.Util.Padding import pad, unpad
import os AUTH_KEY = b'nfd_auth_key2026'
AUTH_KEY = os.environ['NFD_AUTH_ENCRYPT_KEY'].encode('utf-8')
def encode_auth_param(auth_obj): def encode_auth_param(auth_obj):
"""加密认证参数""" """加密认证参数"""
@@ -324,8 +323,8 @@ if (auths != null) {
```yaml ```yaml
server: server:
# auth参数加密密钥(16、24 或 32 字节) # auth参数加密密钥(16位AES密钥)
# authEncryptKey: "" # 仅在可信客户端或多实例需共享密钥时显式配置 authEncryptKey: 'your_custom_key16'
# 捐赠账号失败计数token签名密钥(HMAC) # 捐赠账号失败计数token签名密钥(HMAC)
# 建议使用较长随机字符串,并与 authEncryptKey 不同 # 建议使用较长随机字符串,并与 authEncryptKey 不同
@@ -72,7 +72,7 @@
## 使用说明 ## 使用说明
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码 1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: 自建服务配置值(无公共默认值) 2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: `nfd_auth_key2026` (16位)
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}` 3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
@@ -394,6 +394,33 @@ public abstract class PanBase implements IPanTool, Closeable {
} }
} }
/**
* 尝试将响应体解析为 JsonObject,失败时返回 null,且不调用 fail()。
* 用于版本探测等允许非 JSON(例如 HTML)的场景,避免提前终止解析并阻断 nextParser()。
*
* @param res HttpResponse
* @return JsonObject,若响应体不是合法 JSON 则返回 null
*/
protected JsonObject tryParseJson(HttpResponse<?> res) {
String contentEncoding = res.getHeader("Content-Encoding");
try {
if ("gzip".equalsIgnoreCase(contentEncoding) && res.body() instanceof Buffer gzipBody
&& gzipBody.length() >= 2
&& (gzipBody.getByte(0) & 0xff) == 0x1f
&& (gzipBody.getByte(1) & 0xff) == 0x8b) {
String decompressed = decompressGzip(gzipBody);
return new JsonObject(decompressed);
} else {
return res.bodyAsJsonObject();
}
} catch (Exception e) {
log.debug("响应体不是合法JSON,跳过: {}", e.getMessage());
return null;
}
}
/**
* body To text的封装, 会自动处理异常, 会自动解压gzip
/** /**
* body To text的封装, 会自动处理异常, 会自动解压gzip * body To text的封装, 会自动处理异常, 会自动解压gzip
* @param res HttpResponse * @param res HttpResponse
@@ -25,7 +25,7 @@ public enum PanDomainTemplate {
// https://www.ilanzou.com/s/ // https://www.ilanzou.com/s/
IZ("蓝奏云优享", IZ("蓝奏云优享",
compile("https://www\\.ilanzou\\.com/s/(?<KEY>.+)"), compile("https://www\\.ilanzou\\.com/s/(?<KEY>[^/?#]+)(?:[?#].*)?"),
"https://www.ilanzou.com/s/{shareKey}", "https://www.ilanzou.com/s/{shareKey}",
IzTool.class), IzTool.class),
// 网盘定义 // 网盘定义
@@ -111,7 +111,7 @@ public enum PanDomainTemplate {
// https://www.feijix.com/s/ // https://www.feijix.com/s/
// https://share.feijipan.com/s/ // https://share.feijipan.com/s/
FJ("小飞机网盘", FJ("小飞机网盘",
compile("https://(share\\.feijipan\\.com|www\\.feijix\\.com)/s/(?<KEY>.+)"), compile("https://(share\\.feijipan\\.com|www\\.feijix\\.com)/s/(?<KEY>[^/?#]+)(?:[?#].*)?"),
"https://www.feijix.com/s/{shareKey}", "https://www.feijix.com/s/{shareKey}",
FjTool.class), FjTool.class),
@@ -5,6 +5,7 @@ import cn.qaiu.parser.custom.CustomParserConfig;
import cn.qaiu.parser.custom.CustomParserRegistry; import cn.qaiu.parser.custom.CustomParserRegistry;
import cn.qaiu.parser.customjs.JsParserExecutor; import cn.qaiu.parser.customjs.JsParserExecutor;
import cn.qaiu.util.ShareUrlParams;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder; import java.net.URLEncoder;
@@ -96,6 +97,8 @@ public class ParserCreate {
} }
} catch (IllegalStateException | IllegalArgumentException ignored) {} } catch (IllegalStateException | IllegalArgumentException ignored) {}
applyShareUrlParams(shareLinkInfo, shareUrl);
// 设置标准URL // 设置标准URL
if (customParserConfig.getStandardUrlTemplate() != null) { if (customParserConfig.getStandardUrlTemplate() != null) {
String standardUrl = customParserConfig.getStandardUrlTemplate() String standardUrl = customParserConfig.getStandardUrlTemplate()
@@ -126,6 +129,10 @@ public class ParserCreate {
Matcher matcher = this.panDomainTemplate.getPattern().matcher(shareUrl); Matcher matcher = this.panDomainTemplate.getPattern().matcher(shareUrl);
if (matcher.find()) { if (matcher.find()) {
String k0 = matcher.group(KEY); String k0 = matcher.group(KEY);
String cleanedKey = ShareUrlParams.cleanShareKey(k0);
if (StringUtils.isNotEmpty(cleanedKey)) {
k0 = cleanedKey;
}
String shareKey = URLEncoder.encode(k0, StandardCharsets.UTF_8); String shareKey = URLEncoder.encode(k0, StandardCharsets.UTF_8);
// 返回规范化的标准链接 // 返回规范化的标准链接
@@ -142,6 +149,15 @@ public class ParserCreate {
shareLinkInfo.setShareUrl(shareUrl); shareLinkInfo.setShareUrl(shareUrl);
shareLinkInfo.setShareKey(shareKey); shareLinkInfo.setShareKey(shareKey);
if (StringUtils.isBlank(shareLinkInfo.getSharePassword())) {
String pwdFromUrl = ShareUrlParams.extractSharePassword(shareUrl);
if (StringUtils.isNotEmpty(pwdFromUrl)) {
shareLinkInfo.setSharePassword(pwdFromUrl);
if (standardUrl != null && standardUrl.contains("{pwd}")) {
standardUrl = standardUrl.replace("{pwd}", pwdFromUrl);
}
}
}
if (!isGenericBuiltInParser(panDomainTemplate)) { if (!isGenericBuiltInParser(panDomainTemplate)) {
shareLinkInfo.setStandardUrl(standardUrl); shareLinkInfo.setStandardUrl(standardUrl);
} }
@@ -290,6 +306,8 @@ public class ParserCreate {
} }
} catch (IllegalStateException | IllegalArgumentException ignored) {} } catch (IllegalStateException | IllegalArgumentException ignored) {}
applyShareUrlParams(shareLinkInfo, shareUrl);
// 设置标准URL(如果有模板) // 设置标准URL(如果有模板)
if (customConfig.getStandardUrlTemplate() != null) { if (customConfig.getStandardUrlTemplate() != null) {
String standardUrl = customConfig.getStandardUrlTemplate() String standardUrl = customConfig.getStandardUrlTemplate()
@@ -410,6 +428,23 @@ public class ParserCreate {
return customParserConfig; return customParserConfig;
} }
private static void applyShareUrlParams(ShareLinkInfo shareLinkInfo, String shareUrl) {
String key = shareLinkInfo.getShareKey();
if (StringUtils.isNotEmpty(key)) {
String cleaned = ShareUrlParams.cleanShareKey(key);
if (StringUtils.isNotEmpty(cleaned)) {
shareLinkInfo.setShareKey(cleaned);
}
}
if (StringUtils.isBlank(shareLinkInfo.getSharePassword())) {
String pwdFromUrl = ShareUrlParams.extractSharePassword(shareUrl);
if (StringUtils.isNotEmpty(pwdFromUrl)) {
shareLinkInfo.setSharePassword(pwdFromUrl);
}
}
}
private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) { private static boolean isGenericBuiltInParser(PanDomainTemplate panDomainTemplate) {
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate); return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
} }
@@ -81,19 +81,15 @@ public class CeTool extends PanBase {
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护 // 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> { clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
if (res.statusCode() == 200) { if (res.statusCode() == 200) {
try { // 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
JsonObject json = asJson(res); JsonObject json = tryParseJson(res);
// v4 ping 成功且返回有效JSON,使用 Ce4Tool
if (json != null && !json.isEmpty()) { if (json != null && !json.isEmpty()) {
log.debug("检测到Cloudreve 4.x (通过v4 ping)"); log.debug("检测到Cloudreve 4.x (通过v4 ping)");
delegateToCe4Tool(); delegateToCe4Tool();
return; return;
} }
} catch (Exception e) {
// JSON解析失败,继续尝试 v3
log.debug("v4 ping返回非JSON响应,尝试v3"); log.debug("v4 ping返回非JSON响应,尝试v3");
} }
}
// v4 ping失败或返回非JSON,尝试 v3 // v4 ping失败或返回非JSON,尝试 v3
tryV3Ping(baseUrl, key, pwd); tryV3Ping(baseUrl, key, pwd);
}).onFailure(t -> { }).onFailure(t -> {
@@ -111,19 +107,15 @@ public class CeTool extends PanBase {
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> { clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
if (res.statusCode() == 200) { if (res.statusCode() == 200) {
try { // 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
JsonObject json = asJson(res); JsonObject json = tryParseJson(res);
// v3 ping 成功且返回有效JSON,进一步验证是否为 v3
if (json != null && !json.isEmpty()) { if (json != null && !json.isEmpty()) {
// 尝试调用 v3 share API 来确认 // 尝试调用 v3 share API 来确认
verifyV3AndParse(baseUrl, key, pwd); verifyV3AndParse(baseUrl, key, pwd);
return; return;
} }
} catch (Exception e) {
// JSON解析失败,不是Cloudreve盘
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘"); log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
} }
}
// v3 ping失败,不是Cloudreve盘 // v3 ping失败,不是Cloudreve盘
log.debug("v3 ping失败,尝试下一个解析器"); log.debug("v3 ping失败,尝试下一个解析器");
nextParser(); nextParser();
@@ -148,9 +140,9 @@ public class CeTool extends PanBase {
httpRequest.send().onSuccess(res -> { httpRequest.send().onSuccess(res -> {
try { try {
if (res.statusCode() == 200) { if (res.statusCode() == 200) {
JsonObject jsonObject = asJson(res); JsonObject jsonObject = tryParseJson(res);
// 检查响应格式是否符合 v3 API // 检查响应格式是否符合 v3 API
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) { if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
// v3 share API 成功,确认是 v3 版本 // v3 share API 成功,确认是 v3 版本
// 设置文件信息 // 设置文件信息
setFileInfo(jsonObject); setFileInfo(jsonObject);
@@ -184,9 +176,9 @@ public class CeTool extends PanBase {
httpRequest.send().onSuccess(res -> { httpRequest.send().onSuccess(res -> {
try { try {
if (res.statusCode() == 200) { if (res.statusCode() == 200) {
JsonObject jsonObject = asJson(res); JsonObject jsonObject = tryParseJson(res);
// 检查响应格式是否符合 v4 API // 检查响应格式是否符合 v4 API
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) { if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
// v4 share API 成功,使用 Ce4Tool // v4 share API 成功,使用 Ce4Tool
log.debug("确认是Cloudreve 4.x (通过v4 share API)"); log.debug("确认是Cloudreve 4.x (通过v4 share API)");
delegateToCe4Tool(); delegateToCe4Tool();
@@ -423,38 +423,6 @@ public class LzTool extends PanBase {
return "/" + ajax.group(1); return "/" + ajax.group(1);
} }
/** 分享页 / iframe 里的文件 ajax 表单;提取不到时返回 null。 */
static Map<String, String> fileAjaxForm(String html, String pwd) {
AjaxCall call = extractAjaxFromHtml(html, pwd);
return call == null ? null : call.form();
}
/**
* 文件 ajax 头。官方页把下载 POST 打到 apifile / apifile2 等跨站主机,
* 浏览器会带 Origin 且 Sec-Fetch-Site=cross-site;写 same-origin 与 Referer 矛盾,部分出口会被 ESA 拦。
*/
static MultiMap fileAjaxHeaders(String pageUrl, String ajaxTarget) {
MultiMap headers = HeaderUtils.parseHeaders(DOWN_AJAX_HEADERS);
String page = pageUrl == null ? "" : pageUrl.trim();
if (!page.isEmpty()) {
headers.set("referer", page);
}
String pageOrigin = normalizeOrigin(originOf(page, ""));
String ajaxOrigin = originFromAjaxTarget(ajaxTarget);
if (ajaxOrigin.isEmpty()) {
ajaxOrigin = pageOrigin;
}
if (!pageOrigin.isEmpty()) {
headers.set("origin", pageOrigin);
}
if (!ajaxOrigin.isEmpty() && !ajaxOrigin.equalsIgnoreCase(pageOrigin)) {
headers.set("Sec-Fetch-Site", "cross-site");
} else {
headers.set("Sec-Fetch-Site", "same-origin");
}
return headers;
}
private static void addAjaxOrigin(List<String> origins, String origin) { private static void addAjaxOrigin(List<String> origins, String origin) {
if (origin != null && origin.contains("://") && !origins.contains(origin)) { if (origin != null && origin.contains("://") && !origins.contains(origin)) {
origins.add(origin); origins.add(origin);
@@ -846,12 +814,13 @@ public class LzTool extends PanBase {
} }
private void getDownURL(String referer, AjaxCall call) { private void getDownURL(String referer, AjaxCall call) {
// 文件 ajax 优先用页面里的绝对地址(常见 apifile / apifile2)。 MultiMap headers = HeaderUtils.parseHeaders(DOWN_AJAX_HEADERS);
// 文件 ajax 优先用页面里的绝对地址(常见 apifile.lanzouw.com)。
// 页面源站空响应再换 FILE_AJAX_FALLBACK_ORIGINS,wwww 仍在最后。 // 页面源站空响应再换 FILE_AJAX_FALLBACK_ORIGINS,wwww 仍在最后。
// iframe / 分享页的 Referer 保持原主机,不把页面 GET 改写到 wwww。 // iframe / 分享页的 Referer 保持原主机,不把页面 GET 改写到 wwww。
String page = referer != null && !referer.isBlank() ? referer : resolveShareUrl(); String page = referer != null && !referer.isBlank() ? referer : resolveShareUrl();
headers.set("referer", page);
String target = call.absoluteUrl() != null ? call.absoluteUrl() : call.path(); String target = call.absoluteUrl() != null ? call.absoluteUrl() : call.path();
MultiMap headers = fileAjaxHeaders(page, target);
postAjaxAt(fileAjaxOrigins(page, target), 0, call, headers, this::handleAjaxDownResponse, null); postAjaxAt(fileAjaxOrigins(page, target), 0, call, headers, this::handleAjaxDownResponse, null);
} }
@@ -92,17 +92,7 @@ public class HttpResponseHelper {
// -------------------- Buffer 转换 -------------------- // -------------------- Buffer 转换 --------------------
private static Buffer toBuffer(HttpResponse<?> res) { private static Buffer toBuffer(HttpResponse<?> res) {
Object raw = res.body(); return res.body() instanceof Buffer ? (Buffer) res.body() : Buffer.buffer(res.bodyAsString());
if (raw instanceof Buffer buf) {
return buf;
}
// 407/空 body 时 body() 与 bodyAsString() 都可能是 null,Buffer.buffer(null) 会 NPE,
// 最终被当成「ajax 返回非JSON: 空响应」。
if (raw == null) {
return Buffer.buffer();
}
String text = res.bodyAsString();
return text == null ? Buffer.buffer() : Buffer.buffer(text);
} }
private static void ensureBodyLimit(Buffer body) { private static void ensureBodyLimit(Buffer body) {
@@ -0,0 +1,102 @@
package cn.qaiu.util;
import org.apache.commons.lang3.StringUtils;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 从分享链接中整理 shareKey、提取常见提取码查询参数。
* 许多网盘模板用贪婪的 KEY 分组匹配路径,会把 ?pwd= / ?code= 或 # 片段吞进 shareKey。
*/
public final class ShareUrlParams {
private static final String[] PASSWORD_QUERY_KEYS = {"pwd", "password", "code"};
private ShareUrlParams() {
}
/**
* 去掉误捕获的查询串和 hash 片段,保留路径中的 shareKey。
* 若清理后为空则返回原始值,避免把合法 key 清掉。
*/
public static String cleanShareKey(String key) {
if (StringUtils.isEmpty(key)) {
return key;
}
String cleaned = key;
int hashIndex = cleaned.indexOf('#');
if (hashIndex >= 0) {
cleaned = cleaned.substring(0, hashIndex);
}
int queryIndex = cleaned.indexOf('?');
if (queryIndex >= 0) {
cleaned = cleaned.substring(0, queryIndex);
}
return StringUtils.isEmpty(cleaned) ? key : cleaned;
}
/**
* 从完整分享 URL(或误带在 key 里的查询串)提取提取码。
* 优先 {@code pwd},其次 {@code password}、{@code code}(小飞机等)。
*/
public static String extractSharePassword(String shareUrl) {
if (StringUtils.isBlank(shareUrl)) {
return null;
}
String query = queryString(shareUrl);
if (StringUtils.isEmpty(query)) {
return null;
}
Map<String, String> params = parseQuery(query);
for (String name : PASSWORD_QUERY_KEYS) {
String value = params.get(name);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return null;
}
static String queryString(String url) {
String noHash = url;
int hashIndex = url.indexOf('#');
if (hashIndex >= 0) {
noHash = url.substring(0, hashIndex);
}
int queryIndex = noHash.indexOf('?');
if (queryIndex < 0 || queryIndex == noHash.length() - 1) {
return null;
}
return noHash.substring(queryIndex + 1);
}
static Map<String, String> parseQuery(String query) {
Map<String, String> params = new LinkedHashMap<>();
String[] pairs = query.split("&");
for (String pair : pairs) {
if (pair.isEmpty()) {
continue;
}
int eq = pair.indexOf('=');
String rawName = eq >= 0 ? pair.substring(0, eq) : pair;
String rawValue = eq >= 0 ? pair.substring(eq + 1) : "";
String name = decode(rawName).toLowerCase();
if (name.isEmpty() || params.containsKey(name)) {
continue;
}
params.put(name, decode(rawValue));
}
return params;
}
private static String decode(String value) {
try {
return URLDecoder.decode(value, StandardCharsets.UTF_8);
} catch (IllegalArgumentException e) {
return value;
}
}
}
@@ -0,0 +1,131 @@
package cn.qaiu.parser;
import cn.qaiu.WebClientVertxInit;
import cn.qaiu.entity.ShareLinkInfo;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpResponse;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
/**
* 探测场景必须用 tryParseJson:asJson 会 fail(),从而阻断 nextParser。
*/
public class PanBaseTryParseJsonTest {
private static Vertx vertx;
@BeforeClass
public static void setUpClass() {
// 不在用例结束后关闭 Vertx:共享 WebClient 绑定该实例,关闭会导致同 JVM 后续测试出现 Client is closed
vertx = Vertx.vertx();
WebClientVertxInit.init(vertx);
}
private static final class ProbeTool extends PanBase {
ProbeTool() {
super();
this.shareLinkInfo = ShareLinkInfo.newBuilder()
.type("ce")
.panName("Cloudreve")
.shareKey("k")
.shareUrl("https://example.com/s/k")
.build();
}
@Override
public io.vertx.core.Future<String> parse() {
return promise.future();
}
JsonObject probe(HttpResponse<?> res) {
return tryParseJson(res);
}
JsonObject parseOrFail(HttpResponse<?> res) {
return asJson(res);
}
boolean promiseCompleted() {
return promise.future().isComplete();
}
boolean promiseFailed() {
return promise.future().failed();
}
String failureMessage() {
return promise.future().cause() == null ? null : promise.future().cause().getMessage();
}
}
@SuppressWarnings("unchecked")
private static HttpResponse<Buffer> stub(String contentEncoding, String body) {
Buffer buffer = body == null ? null : Buffer.buffer(body);
return (HttpResponse<Buffer>) Proxy.newProxyInstance(
HttpResponse.class.getClassLoader(),
new Class<?>[]{HttpResponse.class},
(proxy, method, args) -> {
switch (method.getName()) {
case "getHeader":
String name = args != null && args.length > 0 ? String.valueOf(args[0]) : "";
return "Content-Encoding".equalsIgnoreCase(name) ? contentEncoding : null;
case "body":
return buffer;
case "bodyAsString":
return body;
case "bodyAsJsonObject":
if (body == null) {
return null;
}
return new JsonObject(body);
default:
if (method.isDefault()) {
return InvocationHandler.invokeDefault(proxy, method, args);
}
Class<?> type = method.getReturnType();
if (type == boolean.class) {
return false;
}
if (type == int.class || type == long.class) {
return 0;
}
return null;
}
});
}
@Test
public void tryParseJsonReturnsNullForHtmlWithoutFailingPromise() {
ProbeTool tool = new ProbeTool();
JsonObject json = tool.probe(stub(null, "<html><body>not json</body></html>"));
assertNull(json);
assertFalse(tool.promiseCompleted());
}
@Test
public void tryParseJsonParsesObject() {
ProbeTool tool = new ProbeTool();
JsonObject json = tool.probe(stub(null, "{\"code\":0,\"data\":\"ok\"}"));
assertEquals(0, json.getInteger("code").intValue());
assertFalse(tool.promiseCompleted());
}
@Test
public void asJsonFailsPromiseOnHtml() {
ProbeTool tool = new ProbeTool();
JsonObject json = tool.parseOrFail(stub(null, "<!DOCTYPE html>"));
assertTrue(json == null || json.isEmpty());
assertTrue(tool.promiseFailed());
assertTrue(tool.failureMessage(), tool.failureMessage().contains("json格式异常"));
}
}
@@ -0,0 +1,71 @@
package cn.qaiu.parser;
import cn.qaiu.entity.ShareLinkInfo;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* 完整分享链接里的提取码不应被吞进 shareKey。
*/
public class ShareUrlQueryTest {
@Test
public void feijipanCodeQueryBecomesPassword() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://share.feijipan.com/s/SjfEaY2z?code=064d")
.getShareLinkInfo();
assertEquals("fj", info.getType());
assertEquals("SjfEaY2z", info.getShareKey());
assertEquals("064d", info.getSharePassword());
assertTrue(info.getStandardUrl().contains("SjfEaY2z"));
assertTrue("standard url should not keep the query in the key",
!info.getStandardUrl().contains("code=064d") || !info.getStandardUrl().contains("SjfEaY2z?"));
}
@Test
public void yePwdQueryIsExtractedWithoutChangingKey() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://www.123278.com/s/lN7UVv-pbYJ.html?pwd=abcd")
.getShareLinkInfo();
assertEquals("ye", info.getType());
assertEquals("lN7UVv-pbYJ", info.getShareKey());
assertEquals("abcd", info.getSharePassword());
}
@Test
public void lanzouQueryPasswordAndWebpageDoNotPolluteKey() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret")
.getShareLinkInfo();
assertEquals("lz", info.getType());
assertEquals("iabc", info.getShareKey());
assertEquals("secret", info.getSharePassword());
assertTrue(info.getShareUrl().contains("webpage=wp1"));
}
@Test
public void ilanzouHashAndCodeQuery() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://www.ilanzou.com/s/RkR09zIL?code=abc#/list")
.getShareLinkInfo();
assertEquals("iz", info.getType());
assertEquals("RkR09zIL", info.getShareKey());
assertEquals("abc", info.getSharePassword());
}
@Test
public void ucPublicQueryIsNotTreatedAsPassword() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://drive.uc.cn/s/e623b6da278e4?public=1#/list/share")
.getShareLinkInfo();
assertEquals("uc", info.getType());
assertEquals("e623b6da278e4", info.getShareKey());
assertTrue(info.getSharePassword() == null || info.getSharePassword().isEmpty());
}
@Test
public void plainLanzouUrlUnchanged() {
ShareLinkInfo info = ParserCreate.fromShareUrl("https://wwn.lanzouy.com/ihLkw1gezutg")
.getShareLinkInfo();
assertEquals("lz", info.getType());
assertEquals("ihLkw1gezutg", info.getShareKey());
assertTrue(info.getSharePassword() == null || info.getSharePassword().isEmpty());
}
}
@@ -237,51 +237,4 @@ public class LzToolShareUrlTest {
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1)); assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
assertFalse(origins.get(0).contains("wwww")); assertFalse(origins.get(0).contains("wwww"));
} }
@Test
public void passwordPageUsesApifile2AndIsngisSign() {
String html = """
<div class="passwddiv-btn" onclick="down_p();"></div>
<input id="pwd" />
<script type="text/javascript">
function down_p(){
var kdns =1;
var isngis = '';
var isngis = 'SIGNVALUEFROMISNGIS';
var pwd =document.getElementById('pwd').value;
$.ajax({
type : 'post',
url : 'https://apifile2.woozooo.com/ajaxfile.php?file=333149117',
data : { 'action':'downprocess','sign':isngis,'kd':kdns,'p':pwd, },
dataType : 'json'
});
}
</script>
""";
String target = LzTool.fileAjaxTarget(html);
assertEquals("https://apifile2.woozooo.com/ajaxfile.php?file=333149117", target);
Map<String, String> form = LzTool.fileAjaxForm(html, "1t54");
assertEquals("downprocess", form.get("action"));
assertEquals("SIGNVALUEFROMISNGIS", form.get("sign"));
assertEquals("1", form.get("kd"));
assertEquals("1t54", form.get("p"));
List<String> origins = LzTool.fileAjaxOrigins("https://wwaov.lanzouw.com/iNUOu4hbih4h", target);
assertEquals("https://apifile2.woozooo.com", origins.get(0));
io.vertx.core.MultiMap headers = LzTool.fileAjaxHeaders(
"https://wwaov.lanzouw.com/iNUOu4hbih4h", target);
assertEquals("https://wwaov.lanzouw.com/iNUOu4hbih4h", headers.get("referer"));
assertEquals("https://wwaov.lanzouw.com", headers.get("origin"));
assertEquals("cross-site", headers.get("Sec-Fetch-Site"));
}
@Test
public void sameOriginFileAjaxKeepsSameSiteFetchMetadata() {
io.vertx.core.MultiMap headers = LzTool.fileAjaxHeaders(
"https://apifile.lanzouw.com/fn?x", "/ajaxfile.php?file=1");
assertEquals("same-origin", headers.get("Sec-Fetch-Site"));
assertEquals("https://apifile.lanzouw.com", headers.get("origin"));
assertEquals("https://apifile.lanzouw.com/fn?x", headers.get("referer"));
}
} }
@@ -0,0 +1,40 @@
package cn.qaiu.util;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ShareUrlParamsTest {
@Test
public void cleanShareKeyStripsQueryAndHash() {
assertEquals("SjfEaY2z", ShareUrlParams.cleanShareKey("SjfEaY2z?code=064d"));
assertEquals("lN7UVv-pbYJ", ShareUrlParams.cleanShareKey("lN7UVv-pbYJ?pwd=abcd#/list"));
assertEquals("iabc", ShareUrlParams.cleanShareKey("iabc?webpage=wp1&pwd=secret"));
assertEquals("s/someShareKey", ShareUrlParams.cleanShareKey("s/someShareKey"));
assertEquals("key", ShareUrlParams.cleanShareKey("key"));
assertNull(ShareUrlParams.cleanShareKey(null));
assertEquals("", ShareUrlParams.cleanShareKey(""));
}
@Test
public void extractPasswordFromCommonQueryNames() {
assertEquals("064d", ShareUrlParams.extractSharePassword("https://share.feijipan.com/s/SjfEaY2z?code=064d"));
assertEquals("Pbdl", ShareUrlParams.extractSharePassword("https://www.123684.com/s/6gXfvd-7H9kh?pwd=Pbdl#/list"));
assertEquals("secret", ShareUrlParams.extractSharePassword(
"https://a.lanzouw.com/iabc?webpage=wp1&pwd=secret"));
assertEquals("I4KG7H", ShareUrlParams.extractSharePassword(
"https://www.vyuyun.com/s/QMa6ie?password=I4KG7H"));
assertEquals("测码", ShareUrlParams.extractSharePassword("https://example.com/s/k?pwd=%E6%B5%8B%E7%A0%81"));
assertNull(ShareUrlParams.extractSharePassword("https://drive.uc.cn/s/abc?public=1#/list/share"));
assertNull(ShareUrlParams.extractSharePassword("https://www.123pan.com/s/abc"));
assertNull(ShareUrlParams.extractSharePassword("https://www.123pan.com/s/abc?pwd="));
}
@Test
public void prefersPwdOverCode() {
assertEquals("fromPwd", ShareUrlParams.extractSharePassword(
"https://example.com/s/k?code=fromCode&pwd=fromPwd"));
}
}
+2 -2
View File
@@ -17,7 +17,7 @@
</modules> </modules>
<properties> <properties>
<revision>0.4.15</revision> <revision>0.4.13</revision>
<java.version>17</java.version> <java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source> <maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target> <maven.compiler.target>17</maven.compiler.target>
@@ -32,7 +32,7 @@
<slf4j.version>2.0.16</slf4j.version> <slf4j.version>2.0.16</slf4j.version>
<commons-lang3.version>3.18.0</commons-lang3.version> <commons-lang3.version>3.18.0</commons-lang3.version>
<commons-beanutils2.version>2.0.0</commons-beanutils2.version> <commons-beanutils2.version>2.0.0</commons-beanutils2.version>
<parserVersion>10.2.7</parserVersion> <parserVersion>10.2.5</parserVersion>
<jackson.version>2.18.9</jackson.version> <jackson.version>2.18.9</jackson.version>
<!-- Logback 最新稳定版 --> <!-- Logback 最新稳定版 -->
<logback.version>1.5.34</logback.version> <logback.version>1.5.34</logback.version>
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "nfd-web", "name": "nfd-web",
"version": "0.4.15", "version": "0.4.13",
"private": true, "private": true,
"scripts": { "scripts": {
"serve": "vue-cli-service serve", "serve": "vue-cli-service serve",
+28 -24
View File
@@ -51,7 +51,7 @@
<el-icon><Key /></el-icon> <el-icon><Key /></el-icon>
</el-button> </el-button>
</el-tooltip> </el-tooltip>
<el-tooltip v-if="donatedAccountsEnabled" content="捐赠网盘账号" placement="bottom"> <el-tooltip content="捐赠网盘账号" placement="bottom">
<el-button circle size="small" type="warning" @click="showDonateDialog = true"> <el-button circle size="small" type="warning" @click="showDonateDialog = true">
<el-icon><Present /></el-icon> <el-icon><Present /></el-icon>
</el-button> </el-button>
@@ -319,10 +319,6 @@
width="550px" width="550px"
:close-on-click-modal="false"> :close-on-click-modal="false">
<el-form :model="authConfig" label-width="100px" size="default"> <el-form :model="authConfig" label-width="100px" size="default">
<el-form-item label="服务认证密钥">
<el-input v-model="serverAuthKey" type="password" show-password
autocomplete="off" placeholder="自建站已配置的 authEncryptKey(仅本页内存)" />
</el-form-item>
<el-form-item label="网盘类型" required> <el-form-item label="网盘类型" required>
<el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange"> <el-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange">
<el-option-group label="必须认证"> <el-option-group label="必须认证">
@@ -577,6 +573,10 @@
<el-form :model="donateConfig" label-width="100px" size="default"> <el-form :model="donateConfig" label-width="100px" size="default">
<el-form-item label="网盘类型" required> <el-form-item label="网盘类型" required>
<el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange"> <el-select v-model="donateConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onDonatePanTypeChange">
<el-option-group label="必须认证">
<el-option label="夸克网盘 (QK)" value="QK" />
<el-option label="UC网盘 (UC)" value="UC" />
</el-option-group>
<el-option-group label="大文件需认证"> <el-option-group label="大文件需认证">
<el-option label="小飞机网盘 (FJ)" value="FJ" /> <el-option label="小飞机网盘 (FJ)" value="FJ" />
<el-option label="蓝奏优享 (IZ)" value="IZ" /> <el-option label="蓝奏优享 (IZ)" value="IZ" />
@@ -712,10 +712,8 @@ export default {
}, },
// 所有网盘的认证配置 { panType: config } // 所有网盘的认证配置 { panType: config }
allAuthConfigs: {}, allAuthConfigs: {},
serverAuthKey: '',
// 捐赠账号相关 // 捐赠账号相关
donatedAccountsEnabled: false,
showDonateDialog: false, showDonateDialog: false,
donateSubmitting: false, donateSubmitting: false,
donateConfig: { donateConfig: {
@@ -981,10 +979,6 @@ export default {
// 保存认证配置 // 保存认证配置
saveAuthConfig() { saveAuthConfig() {
if (![16, 24, 32].includes(new TextEncoder().encode(this.serverAuthKey).length)) {
this.$message.warning('个人认证需要自建站配置的服务认证密钥(16、24 或 32 个 UTF-8 字节)')
return
}
if (!this.authConfig.panType) { if (!this.authConfig.panType) {
this.$message.warning('请先选择网盘类型') this.$message.warning('请先选择网盘类型')
return return
@@ -1027,7 +1021,6 @@ export default {
ext5: '' ext5: ''
} }
this.allAuthConfigs = {} this.allAuthConfigs = {}
this.serverAuthKey = ''
localStorage.removeItem('nfd_auth_configs') localStorage.removeItem('nfd_auth_configs')
this.$message.success('所有认证配置已清除') this.$message.success('所有认证配置已清除')
this.showAuthConfigDialog = false this.showAuthConfigDialog = false
@@ -1047,15 +1040,31 @@ export default {
} }
}, },
// 个人认证由可信客户端使用自建服务显式配置的密钥编码;捐赠凭据只在服务端使用。 // 生成加密的 auth 参数(优先使用个人配置,否则从后端随机获取捐赠账号)
async generateAuthParam() { async generateAuthParam() {
const panType = this.getCurrentPanType() const panType = this.getCurrentPanType()
if (!panType) return '' if (!panType) return ''
const config = this.allAuthConfigs[panType]
if (!config) return ''
const key = this.serverAuthKey
if (![16, 24, 32].includes(new TextEncoder().encode(key).length)) return ''
let config = null
// 优先使用个人配置
if (this.allAuthConfigs[panType]) {
config = this.allAuthConfigs[panType]
} else {
// 从后端随机获取捐赠账号(后端已加密,直接使用 encryptedAuth)
try {
const response = await axios.get(`${this.baseAPI}/v2/randomAuth`, { params: { panType } })
const encryptedAuth = response.data?.data?.encryptedAuth
if (encryptedAuth) {
return encryptedAuth
}
} catch (e) {
// no available donated account
}
return ''
}
// 个人配置:本地 AES 加密
const authObj = {} const authObj = {}
if (config.authType) authObj.authType = config.authType if (config.authType) authObj.authType = config.authType
if (config.username) authObj.username = config.username if (config.username) authObj.username = config.username
@@ -1070,7 +1079,7 @@ export default {
if (config.ext5) authObj.ext5 = config.ext5 if (config.ext5) authObj.ext5 = config.ext5
try { try {
const encrypted = this.aesEncrypt(JSON.stringify(authObj), key) const encrypted = this.aesEncrypt(JSON.stringify(authObj), 'nfd_auth_key2026')
return encodeURIComponent(encrypted) return encodeURIComponent(encrypted)
} catch (e) { } catch (e) {
console.error('生成认证参数失败:', e) console.error('生成认证参数失败:', e)
@@ -1710,11 +1719,7 @@ export default {
token: isPasswordAuth ? '' : (this.donateConfig.token || ''), token: isPasswordAuth ? '' : (this.donateConfig.token || ''),
remark: this.donateConfig.remark || '' remark: this.donateConfig.remark || ''
} }
const response = await axios.post(`${this.baseAPI}/v2/donateAccount`, payload) await axios.post(`${this.baseAPI}/v2/donateAccount`, payload)
if (response.data?.code !== 200) {
this.$message.error(response.data?.msg || '捐赠失败')
return
}
this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`) this.$message.success(`已捐赠 ${this.getPanDisplayName(this.donateConfig.panType)} 账号,感谢您的贡献!`)
// 重置表单 // 重置表单
@@ -1744,7 +1749,6 @@ export default {
} }
if (data && typeof data === 'object') { if (data && typeof data === 'object') {
this.donatedAccountsEnabled = data.enabled === true
// 兼容新结构: { active: {...}, inactive: {...} } // 兼容新结构: { active: {...}, inactive: {...} }
if (data.active && data.inactive) { if (data.active && data.inactive) {
if (data.active.total === undefined) { if (data.active.total === undefined) {
@@ -5,7 +5,6 @@ import cn.qaiu.db.pool.JDBCPoolInit;
import cn.qaiu.lz.common.cache.CacheConfigLoader; import cn.qaiu.lz.common.cache.CacheConfigLoader;
import cn.qaiu.lz.common.cache.CacheManager; import cn.qaiu.lz.common.cache.CacheManager;
import cn.qaiu.lz.common.interceptorImpl.RateLimiter; 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.config.PlaygroundConfig;
import cn.qaiu.lz.web.service.DbService; import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.lz.web.service.impl.ShoutServiceImpl; import cn.qaiu.lz.web.service.impl.ShoutServiceImpl;
@@ -91,7 +90,6 @@ public class AppMain {
* @param jsonObject 配置 * @param jsonObject 配置
*/ */
private static void exec(JsonObject jsonObject) { private static void exec(JsonObject jsonObject) {
AuthParamCodec.configure(jsonObject.getJsonObject(ConfigConstant.SERVER));
WebClientVertxInit.init(VertxHolder.getVertxInstance()); WebClientVertxInit.init(VertxHolder.getVertxInstance());
DatabindCodec.mapper().registerModule(new JavaTimeModule()); DatabindCodec.mapper().registerModule(new JavaTimeModule());
// 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。 // 演练场配置要先加载,后续启动流程才能按开关决定是否注册动态解析器。
@@ -3,17 +3,13 @@ package cn.qaiu.lz.common.util;
import cn.qaiu.lz.web.model.AuthParam; import cn.qaiu.lz.web.model.AuthParam;
import cn.qaiu.util.AESUtils; import cn.qaiu.util.AESUtils;
import cn.qaiu.util.Base64Decoder; import cn.qaiu.util.Base64Decoder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.nio.charset.StandardCharsets; 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;
/** /**
* 认证参数编解码工具类 * 认证参数编解码工具类
@@ -28,51 +24,34 @@ import java.util.HexFormat;
@Slf4j @Slf4j
public class AuthParamCodec { 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 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() { private AuthParamCodec() {
// 工具类禁止实例化
} }
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;
}
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() { public static String getEncryptKey() {
return encryptKey; try {
String configKey = SharedDataUtil.getJsonStringForServerConfig(CONFIG_KEY_PATH);
if (StringUtils.isNotBlank(configKey)) {
return configKey;
}
} catch (Exception e) {
log.debug("从配置读取加密密钥失败,使用默认密钥: {}", e.getMessage());
}
return DEFAULT_ENCRYPT_KEY;
} }
/** /**
@@ -90,7 +69,7 @@ public class AuthParamCodec {
* 解码认证参数(指定密钥) * 解码认证参数(指定密钥)
* *
* @param encryptedAuth 加密后的认证参数字符串 * @param encryptedAuth 加密后的认证参数字符串
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节) * @param key AES密钥(16位)
* @return AuthParam 对象,解码失败返回 null * @return AuthParam 对象,解码失败返回 null
*/ */
public static AuthParam decode(String encryptedAuth, String key) { public static AuthParam decode(String encryptedAuth, String key) {
@@ -106,6 +85,7 @@ public class AuthParamCodec {
} }
// 兼容 query 参数中 '+' 被还原为空格的情况 // 兼容 query 参数中 '+' 被还原为空格的情况
normalized = normalized.replace(' ', '+'); normalized = normalized.replace(' ', '+');
log.debug("认证参数规范化结果: {}", normalized);
// Step 2: Base64解码 // Step 2: Base64解码
byte[] base64Decoded = Base64Decoder.decode(normalized); byte[] base64Decoded = Base64Decoder.decode(normalized);
@@ -113,6 +93,7 @@ public class AuthParamCodec {
// Step 3: AES解密 // Step 3: AES解密
String jsonStr = AESUtils.decryptByAES(base64Decoded, key); String jsonStr = AESUtils.decryptByAES(base64Decoded, key);
log.debug("AES解密结果: {}", jsonStr);
// Step 4: JSON解析 // Step 4: JSON解析
JsonObject json = new JsonObject(jsonStr); JsonObject json = new JsonObject(jsonStr);
@@ -121,9 +102,9 @@ public class AuthParamCodec {
return authParam; return authParam;
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
log.warn("认证参数格式无效"); log.warn("认证参数Base64解码失败: {}", e.getMessage());
} catch (Exception e) { } catch (Exception e) {
log.warn("认证参数解码失败"); log.warn("认证参数解码失败: {}", e.getMessage());
} }
return null; return null;
} }
@@ -143,7 +124,7 @@ public class AuthParamCodec {
* 编码认证参数(指定密钥) * 编码认证参数(指定密钥)
* *
* @param authParam 认证参数对象 * @param authParam 认证参数对象
* @param key AES 密钥(16、24 或 32 个 UTF-8 字节) * @param key AES密钥(16位)
* @return 加密后的字符串,编码失败返回 null * @return 加密后的字符串,编码失败返回 null
*/ */
public static String encode(AuthParam authParam, String key) { public static String encode(AuthParam authParam, String key) {
@@ -154,12 +135,15 @@ public class AuthParamCodec {
try { try {
// Step 1: 转换为JSON // Step 1: 转换为JSON
String jsonStr = authParam.toJsonObject().encode(); String jsonStr = authParam.toJsonObject().encode();
log.debug("JSON字符串: {}", jsonStr);
// Step 2: AES加密 + Base64编码 // Step 2: AES加密 + Base64编码
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, key); String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, key);
log.debug("AES+Base64编码结果: {}", base64Encoded);
// Step 3: URL编码 // Step 3: URL编码
String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8); String urlEncoded = java.net.URLEncoder.encode(base64Encoded, StandardCharsets.UTF_8);
log.debug("URL编码结果: {}", urlEncoded);
return urlEncoded; return urlEncoded;
@@ -6,7 +6,6 @@ import cn.qaiu.lz.web.service.DbService;
import cn.qaiu.parser.ParserCreate; import cn.qaiu.parser.ParserCreate;
import cn.qaiu.vx.core.util.ConfigConstant; import cn.qaiu.vx.core.util.ConfigConstant;
import cn.qaiu.vx.core.util.VertxHolder; import cn.qaiu.vx.core.util.VertxHolder;
import cn.qaiu.vx.core.util.SharedDataUtil;
import io.vertx.core.Future; import io.vertx.core.Future;
import io.vertx.core.MultiMap; import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerRequest;
@@ -89,7 +88,7 @@ public class ParserAuthUtil {
public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam, public static void recordDonatedAccountFailureIfNeeded(DbService dbService, JsonObject otherParam,
Throwable cause) { Throwable cause) {
if (otherParam == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) { if (!isLikelyAuthFailure(cause) || otherParam == null) {
return; return;
} }
String donatedAccountToken = otherParam.getString("donatedAccountToken"); String donatedAccountToken = otherParam.getString("donatedAccountToken");
@@ -102,7 +101,7 @@ public class ParserAuthUtil {
public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo, public static void recordAutoDonatedFailureIfNeeded(DbService dbService, ShareLinkInfo shareLinkInfo,
Throwable cause) { Throwable cause) {
if (shareLinkInfo == null || !isLikelyAuthFailure(cause) || !isDonatedAccountsEnabled()) { if (shareLinkInfo == null || !isLikelyAuthFailure(cause)) {
return; return;
} }
Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN); Object tokenObj = shareLinkInfo.getOtherParam().get(DONATED_ACCOUNT_TOKEN);
@@ -113,31 +112,14 @@ public class ParserAuthUtil {
.onFailure(e -> log.warn("记录自动捐赠账号失败次数失败", e)); .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) { private static Future<Void> applyDonatedAccountFallback(ParserCreate parserCreate, DbService dbService) {
if (!isDonatedAccountsEnabled()) {
return Future.succeededFuture();
}
ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo(); ShareLinkInfo shareLinkInfo = parserCreate.getShareLinkInfo();
Map<String, Object> otherParam = shareLinkInfo.getOtherParam(); Map<String, Object> otherParam = shareLinkInfo.getOtherParam();
if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) { if (Boolean.TRUE.equals(otherParam.get(TEMP_AUTH_ADDED))) {
return Future.succeededFuture(); return Future.succeededFuture();
} }
String type = shareLinkInfo.getType(); String type = shareLinkInfo.getType();
if (!supportsServerSideDonation(type) || hasUsableStaticAuthConfig(type)) { if (StringUtils.isBlank(type) || hasUsableStaticAuthConfig(type)) {
return Future.succeededFuture(); return Future.succeededFuture();
} }
return dbService.getRandomDonatedAccount(type.toUpperCase()) return dbService.getRandomDonatedAccount(type.toUpperCase())
@@ -770,18 +770,11 @@ public class ParserApi {
*/ */
@RouteMapping(value = "/donateAccount", method = RouteMethod.POST) @RouteMapping(value = "/donateAccount", method = RouteMethod.POST)
public Future<JsonObject> donateAccount(RoutingContext ctx) { public Future<JsonObject> donateAccount(RoutingContext ctx) {
if (!ParserAuthUtil.isDonatedAccountsEnabled()) {
return Future.succeededFuture(JsonResult.error("捐赠账号功能未启用").toJsonObject());
}
JsonObject body = ctx.body().asJsonObject(); JsonObject body = ctx.body().asJsonObject();
if (body == null || StringUtils.isBlank(body.getString("panType")) if (body == null || StringUtils.isBlank(body.getString("panType"))
|| StringUtils.isBlank(body.getString("authType"))) { || StringUtils.isBlank(body.getString("authType"))) {
return Future.succeededFuture(JsonResult.error("panType and authType are required").toJsonObject()); 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(); String ip = ctx.request().remoteAddress().host();
body.put("ip", ip); body.put("ip", ip);
return dbService.saveDonatedAccount(body); return dbService.saveDonatedAccount(body);
@@ -792,16 +785,23 @@ public class ParserApi {
*/ */
@RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET) @RouteMapping(value = "/donateAccountCounts", method = RouteMethod.GET)
public Future<JsonObject> getDonateAccountCounts() { public Future<JsonObject> getDonateAccountCounts() {
if (!ParserAuthUtil.isDonatedAccountsEnabled()) { return dbService.getDonatedAccountCounts();
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 result;
});
} }
/**
* 随机获取指定网盘类型的捐赠账号(内部使用,返回加密后的 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);
}
return res;
});
}
} }
@@ -39,7 +39,7 @@ public class DbServiceImpl implements DbService {
private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L; private static final long FAILURE_TOKEN_TTL_MILLIS = 10 * 60 * 1000L;
private static final String HMAC_ALGORITHM = "HmacSHA256"; 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_CONFIG = "donatedAccountFailureTokenSignKey";
private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = java.util.UUID.randomUUID().toString() + java.util.UUID.randomUUID(); private static final String DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK = "nfd_donate_fail_token_sign_2026";
@Override @Override
public Future<JsonObject> sayOk(String data) { public Future<JsonObject> sayOk(String data) {
log.info("say ok1 -> wait..."); log.info("say ok1 -> wait...");
@@ -574,7 +574,7 @@ public class DbServiceImpl implements DbService {
return configKey; return configKey;
} }
} catch (Exception e) { } catch (Exception e) {
log.debug("读取捐赠账号失败计数签名密钥失败,使用进程随机值: {}", e.getMessage()); log.debug("读取捐赠账号失败计数签名密钥失败,使用默认值: {}", e.getMessage());
} }
return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK; return DONATED_ACCOUNT_TOKEN_SIGN_KEY_FALLBACK;
} }
+2 -4
View File
@@ -8,10 +8,8 @@ server:
# domainName: http://127.0.0.1:6401 # domainName: http://127.0.0.1:6401
# 预览服务URL # 预览服务URL
previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src= previewURL: https://nfd-parser.github.io/nfd-preview/preview.html?src=
# 未配置时每次启动自动生成随机密钥;多实例或外部客户端可配置共享密钥。 # auth参数加密密钥(16位AES密钥)
# authEncryptKey: "" authEncryptKey: 'nfd_auth_key2026'
# 捐赠默认关闭;开启后凭据仅供服务端选用。
enableDonatedAccounts: false
# 反向代理服务器配置路径(不用加后缀) # 反向代理服务器配置路径(不用加后缀)
proxyConf: server-proxy proxyConf: server-proxy
@@ -21,37 +21,7 @@ import static org.junit.Assert.*;
public class AuthParamCodecTest { public class AuthParamCodecTest {
// 测试用的固定密钥 // 测试用的固定密钥
private static final String TEST_KEY = "dummy-test-key16"; private static final String TEST_KEY = "nfd_auth_key2026";
@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 @Test
public void testAuthParamModel() { public void testAuthParamModel() {
@@ -18,7 +18,7 @@ import java.util.Base64;
*/ */
public class AuthParamCodecTestMain { public class AuthParamCodecTestMain {
private static final String TEST_KEY = "dummy-test-key16"; private static final String TEST_KEY = "nfd_auth_key2026";
private static int passCount = 0; private static int passCount = 0;
private static int failCount = 0; private static int failCount = 0;
+9 -7
View File
@@ -214,7 +214,7 @@
<div class="info-box"> <div class="info-box">
<p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p> <p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p>
<p><strong>密钥:</strong> 自建服务配置的认证密钥(仅在可信本地环境使用)</p> <p><strong>默认密钥:</strong> nfd_auth_key2026 (16位)</p>
<p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p> <p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p>
</div> </div>
@@ -268,8 +268,8 @@
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="encryptKey">加密密钥(必填)</label> <label for="encryptKey">加密密钥 (可选,默认: nfd_auth_key2026)</label>
<input type="password" id="encryptKey" autocomplete="off" placeholder="本地服务配置的密钥"> <input type="text" id="encryptKey" placeholder="留空使用默认密钥" value="nfd_auth_key2026">
</div> </div>
<div class="button-group"> <div class="button-group">
@@ -368,10 +368,7 @@
// AES 加密 // AES 加密
try { try {
const encryptKey = document.getElementById('encryptKey').value; const encryptKey = document.getElementById('encryptKey').value.trim() || 'nfd_auth_key2026';
if (![16, 24, 32].includes(new TextEncoder().encode(encryptKey).length)) {
throw new Error('密钥必须为 16、24 或 32 个 UTF-8 字节');
}
const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey); const encrypted = encryptAuthParam(JSON.stringify(authParam), encryptKey);
document.getElementById('encryptedResult').textContent = encrypted; document.getElementById('encryptedResult').textContent = encrypted;
@@ -392,6 +389,11 @@
// AES 加密函数 // AES 加密函数
function encryptAuthParam(jsonString, key) { function encryptAuthParam(jsonString, key) {
// 确保密钥是16位
if (key.length !== 16) {
throw new Error('密钥必须是16位字符');
}
// AES 加密 (ECB 模式, PKCS5Padding) // AES 加密 (ECB 模式, PKCS5Padding)
const encrypted = CryptoJS.AES.encrypt( const encrypted = CryptoJS.AES.encrypt(
jsonString, jsonString,