Compare commits

..
Author SHA1 Message Date
qaiu 4c48e992da fix: match browser UTF-8 AES key bytes for auth params (#321) 2026-12-04 03:35:55 +08:00
qaiu 76aaa7d214 fix: isolate server-side donation credentials and rotate auth defaults (#320) 2026-12-04 03:09:45 +08:00
qaiu 3047ba97a2 Merge pull request #318 from qaiu/docs/readme-nfd-client-fallback
在 README 开头添加 NFD Client 入口
2026-12-03 13:51:36 +08:00
qaiu c894e38ffa docs: link to NFD Client for local share parsing 2026-12-03 13:23:10 +08:00
qaiu 72893efd83 docs: add Proxy-Seller discount link and code 2026-12-03 09:25:47 +08:00
qaiu 5cec707d76 docs: simplify proxy support acknowledgment 2026-11-30 10:44:16 +08:00
qaiu 793733853b docs: acknowledge Proxy-Seller proxy testing 2026-11-30 10:41:32 +08:00
qaiu b0471904fa Merge pull request #317 from qaiu/release/v0.4.14
release: v0.4.14
2026-11-29 14:34:07 +08:00
qaiu 53e921aa80 release: v0.4.14
Bump the app version to 0.4.14 and parserVersion to 10.2.7 for the
Lanzou cross-site ajax password-page fix (#316) and the 123 pan
v2 App-Version 149 change (#313). Skip parser 10.2.6, which is already
on Maven Central from before these fixes. Release notes record the
2026-11-29 14:19 Asia/Shanghai check on 249 with 792d721: the share
resolved to 2311.exe / 64.9 M, direct link only, file body not fully
downloaded.
2026-11-29 14:28:32 +08:00
qaiu f08dd36635 Merge pull request #316 from qaiu/fix/lz-ajax-empty
fix(parser): 蓝奏跨站 ajax 对齐浏览器头,避免空响应误报
2026-11-29 14:21:53 +08:00
qaiu 792d7210a7 fix(parser): 蓝奏跨站 ajax 对齐浏览器头,避免空 body 被报成空响应
密码页官方 ajax 在 apifile2.woozooo.com,属跨站 XHR。原先固定
Sec-Fetch-Site: same-origin 且不带 Origin,与 Referer 矛盾。
空响应时 bodyAsString 为 null 会 NPE,最终只看到「空响应」。
2026-11-29 13:44:12 +08:00
31 changed files with 367 additions and 571 deletions

No files matched your search

+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version
attributes:
label: 版本号
description: 页面上的版本,或发布包名里的版本,例如 0.4.13。
placeholder: "0.4.13"
description: 页面上的版本,或发布包名里的版本,例如 0.4.15。
placeholder: "0.4.15"
validations:
required: true
- type: dropdown
+2 -2
View File
@@ -25,8 +25,8 @@ body:
id: version
attributes:
label: 版本号
description: 例如 0.4.13。不确定就写获取方式。
placeholder: "0.4.13"
description: 例如 0.4.15。不确定就写获取方式。
placeholder: "0.4.15"
validations:
required: true
- type: dropdown
+7 -19
View File
@@ -1,22 +1,10 @@
## 更新内容
## v0.4.15
- 蓝奏文件页识别 `ajaxfiles.php`(#310):
- 单文件页 iframe 里的下载 ajax 写成了 `/ajaxfiles.php`。解析器原来只认 `ajaxm.php` 和 `ajaxfile.php`,匹配不上就报「获取失败0, 可能分享已失效」。表单字段没有改。
- `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`。
- 界面验收跑在本机开发服务和本机夹具,不是线上分享页。
- 浏览器与服务端以相同的 UTF-8 密钥字节处理临时认证,兼容 16、24 和 32 字节的密钥。
- 临时认证不再使用发行包里的公共密钥。未手动配置的服务实例每次启动生成随机密钥,只记录来源和指纹。保留旧发行包配置的实例也会自动迁移。
- 捐赠池默认关闭。显式启用后,受支持的网盘使用服务端选号,不再向前端提供捐赠账号。已保存的捐赠记录不会删除。
- 清理网页和文档中的公共密钥。需要网页个人认证、外部客户端或多实例共享密钥的自建站,须显式配置和安全分发 `server.authEncryptKey`。
## 限制
### 升级提醒
- 没有把这次界面验收当成线上分享页或全站界面已验。
- 三个对照链接只验证了 1 MiB Range,不能据此说这些文件已经完整下载并核对。
- 带密码的单文件分享未测。
- 本机访问部分蓝奏下载域时连接时好时坏。winx123 曾连续超时,重试后完整下载成功。
旧公共密钥生成的 `auth` 参数不再兼容。升级后请核对部署配置,并视部署情况清理过往解析缓存和轮换捐赠凭据。
+26 -6
View File
@@ -1,4 +1,8 @@
# 一款网盘分享链接云解析快速下载服务
> [!TIP]
> 如果在线解析失败,可以试试 [NFD Client](https://github.com/qaiu/nfd-client-parser),在本机解析网盘分享链接。[下载安装包](https://github.com/qaiu/nfd-client-parser/releases/latest)
QQ交流群:1017480890
<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>
@@ -159,14 +163,13 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
- `your_host` 替换为您的域名或 IP
### 认证参数(v0.2.1+)
[可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
部分网盘需要登录后的 Cookie 或 Authorization 才能下载。可通过 `auth` 参数传递认证信息:
**参数格式**:`auth` 参数值为 AES 加密后的 JSON 字符串,经过 Base64 编码和 URL 编码
**加密方式**:
- 算法:AES/ECB/PKCS5Padding
- 密钥:`nfd_auth_key2026`(16字节)
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
- 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**:
@@ -195,14 +198,20 @@ GET /json/getFileList?url={分享链接}&pwd={密码}
GET /parser?url={分享链接}&pwd={密码}&auth={加密后的认证参数}
```
> 💡 提示:Web 界面已内置认证配置功能,可自动处理加密过程,无需手动构造参数。
> [可以使用在线认证参数加密](https://qaiu.top/nfd-auth.html)
> 💡 提示:自建站的可信客户端可在网页中填写其显式配置的服务认证密钥;网页不会获取或保存服务端密钥。
> 不要在不受信任的站点输入服务密钥或网盘凭据。
#### 升级与捐赠开关
- 没有手动配置密钥(包括升级后仍保留旧发布包默认配置)的实例,在每次启动时自动生成进程随机密钥。启动日志只记录来源和指纹,不输出原文。重启后,之前用进程密钥生成的认证参数会失效。
- 要让可信浏览器、外部工具或多实例使用同一密钥,显式配置 `server.authEncryptKey`,通过安全渠道分发;不要使用旧发布包默认值。
- 捐赠默认关闭。仅设置 `server.enableDonatedAccounts: true` 且启用数据库后,才允许提交和服务端选用捐赠账号。关闭不删除已有记录。旧的浏览器取号接口已移除。仅 123 云盘、小飞机和蓝奏优享可使用服务端捐赠池;需要在下载响应携带账号请求头的网盘暂不开放。
#### 密钥作用说明
- `server.authEncryptKey`
- 作用:用于 `auth` 参数的 AES 加解密
- 要求:16位(AES-128)
- 要求:16、24 或 32 个 UTF-8 字节
- `server.donatedAccountFailureTokenSignKey`
- 作用:用于“捐赠账号失败计数 token”的 HMAC 签名/验签
@@ -470,7 +479,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
```shell
cd ~
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.13/netdisk-fast-download-linux-amd64.zip
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.15/netdisk-fast-download-linux-amd64.zip
unzip netdisk-fast-download.zip
cd netdisk-fast-download
bash service-install.sh
@@ -599,3 +608,14 @@ Core模块集成Vert.x实现类似spring的注解式路由API
<a href="https://www.dkdun.cn/aff/WDBRYKGH" target="_blank">
<img src="https://www.dkdun.cn/themes/web/www/upload/local68c2dbb2ab148.png" width="200">
</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
- 构建:Maven
- 模块版本:10.2.5
- 模块版本:10.2.7
## 依赖(Maven Central)
```xml
<dependency>
<groupId>cn.qaiu</groupId>
<artifactId>parser</artifactId>
<version>10.2.5</version>
<version>10.2.7</version>
</dependency>
```
- Gradle Groovy DSL:
```groovy
dependencies {
implementation 'cn.qaiu:parser:10.2.5'
implementation 'cn.qaiu:parser:10.2.7'
}
```
- Gradle Kotlin DSL:
```kotlin
dependencies {
implementation("cn.qaiu:parser:10.2.5")
implementation("cn.qaiu:parser:10.2.7")
}
```
+1 -1
View File
@@ -28,7 +28,7 @@
**加密方式**:
- 算法:AES/ECB/PKCS5Padding
- 密钥:`nfd_auth_key2026`(16字节)
- 密钥:由自建服务显式配置并通过安全渠道交给可信客户端(无公共默认值)
- 流程:JSON → AES加密 → Base64 → URL编码
**JSON 结构**:
+8 -7
View File
@@ -33,8 +33,8 @@ URL解码 → Base64解码 → AES解密 → JSON对象
### 加密配置
- **加密算法**: AES/ECB/PKCS5Padding
- **密钥长度**: 16位(128位)
- **默认密钥**: `nfd_auth_key2026`(可在 `app-dev.yml` 中通过 `server.authEncryptKey` 配置)
- **密钥长度**: 16、24 或 32 个 UTF-8 字节
- **密钥**: 没有公共默认值。需要对接的可信客户端应使用自建服务显式配置的 `server.authEncryptKey`。
### 密钥作用说明(重要)
@@ -43,7 +43,7 @@ URL解码 → Base64解码 → AES解密 → JSON对象
1. `server.authEncryptKey`
- 用途:加解密 `auth` 参数(前端/调用方传入的认证信息)
- 影响范围:`/parser`、`/json/parser`、`/v2/linkInfo` 等接口中的 `auth` 参数
- 注意:这是 **AES 对称加密密钥**,要求 16 位
- 注意:这是 **AES 对称加密密钥**,要求 16、24 或 32 字节
2. `server.donatedAccountFailureTokenSignKey`
- 用途:签名和验签“捐赠账号失败计数 token”(用于防伪造、失败计数)
@@ -194,7 +194,7 @@ AuthParam decoded = AuthParamCodec.decode(encrypted);
// 使用 CryptoJS 库
const CryptoJS = require('crypto-js');
const AUTH_KEY = 'nfd_auth_key2026';
const AUTH_KEY = process.env.NFD_AUTH_ENCRYPT_KEY;
// 加密
function encodeAuthParam(authObj) {
@@ -234,7 +234,8 @@ from urllib.parse import quote, unquote
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
AUTH_KEY = b'nfd_auth_key2026'
import os
AUTH_KEY = os.environ['NFD_AUTH_ENCRYPT_KEY'].encode('utf-8')
def encode_auth_param(auth_obj):
"""加密认证参数"""
@@ -323,8 +324,8 @@ if (auths != null) {
```yaml
server:
# auth参数加密密钥(16位AES密钥)
authEncryptKey: 'your_custom_key16'
# auth参数加密密钥(16、24 或 32 字节)
# authEncryptKey: "" # 仅在可信客户端或多实例需共享密钥时显式配置
# 捐赠账号失败计数token签名密钥(HMAC)
# 建议使用较长随机字符串,并与 authEncryptKey 不同
@@ -72,7 +72,7 @@
## 使用说明
1. **编码流程**: JSON对象 → AES加密 → Base64编码 → URL编码
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: `nfd_auth_key2026` (16位)
2. **加密配置**: AES/ECB/PKCS5Padding, 密钥: 自建服务配置值(无公共默认值)
3. **接口调用**: `GET /parser?url={分享链接}&pwd={提取码}&auth={加密认证参数}`
@@ -394,33 +394,6 @@ 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
* @param res HttpResponse
@@ -25,7 +25,7 @@ public enum PanDomainTemplate {
// https://www.ilanzou.com/s/
IZ("蓝奏云优享",
compile("https://www\\.ilanzou\\.com/s/(?<KEY>[^/?#]+)(?:[?#].*)?"),
compile("https://www\\.ilanzou\\.com/s/(?<KEY>.+)"),
"https://www.ilanzou.com/s/{shareKey}",
IzTool.class),
// 网盘定义
@@ -111,7 +111,7 @@ public enum PanDomainTemplate {
// https://www.feijix.com/s/
// https://share.feijipan.com/s/
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}",
FjTool.class),
@@ -5,7 +5,6 @@ import cn.qaiu.parser.custom.CustomParserConfig;
import cn.qaiu.parser.custom.CustomParserRegistry;
import cn.qaiu.parser.customjs.JsParserExecutor;
import cn.qaiu.util.ShareUrlParams;
import org.apache.commons.lang3.StringUtils;
import java.net.URLEncoder;
@@ -97,8 +96,6 @@ public class ParserCreate {
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
applyShareUrlParams(shareLinkInfo, shareUrl);
// 设置标准URL
if (customParserConfig.getStandardUrlTemplate() != null) {
String standardUrl = customParserConfig.getStandardUrlTemplate()
@@ -129,10 +126,6 @@ public class ParserCreate {
Matcher matcher = this.panDomainTemplate.getPattern().matcher(shareUrl);
if (matcher.find()) {
String k0 = matcher.group(KEY);
String cleanedKey = ShareUrlParams.cleanShareKey(k0);
if (StringUtils.isNotEmpty(cleanedKey)) {
k0 = cleanedKey;
}
String shareKey = URLEncoder.encode(k0, StandardCharsets.UTF_8);
// 返回规范化的标准链接
@@ -149,15 +142,6 @@ public class ParserCreate {
shareLinkInfo.setShareUrl(shareUrl);
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)) {
shareLinkInfo.setStandardUrl(standardUrl);
}
@@ -306,8 +290,6 @@ public class ParserCreate {
}
} catch (IllegalStateException | IllegalArgumentException ignored) {}
applyShareUrlParams(shareLinkInfo, shareUrl);
// 设置标准URL(如果有模板)
if (customConfig.getStandardUrlTemplate() != null) {
String standardUrl = customConfig.getStandardUrlTemplate()
@@ -428,23 +410,6 @@ public class ParserCreate {
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) {
return GENERIC_BUILT_IN_PARSERS.contains(panDomainTemplate);
}
@@ -81,14 +81,18 @@ public class CeTool extends PanBase {
// 禁止跟随重定向:assertPublicHost 只校验初始 host,自动 30x 会绕过 SSRF 防护
clientNoRedirects.getAbs(pingUrlV4).send().onSuccess(res -> {
if (res.statusCode() == 200) {
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
JsonObject json = tryParseJson(res);
if (json != null && !json.isEmpty()) {
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
delegateToCe4Tool();
return;
try {
JsonObject json = asJson(res);
// v4 ping 成功且返回有效JSON,使用 Ce4Tool
if (json != null && !json.isEmpty()) {
log.debug("检测到Cloudreve 4.x (通过v4 ping)");
delegateToCe4Tool();
return;
}
} catch (Exception e) {
// JSON解析失败,继续尝试 v3
log.debug("v4 ping返回非JSON响应,尝试v3");
}
log.debug("v4 ping返回非JSON响应,尝试v3");
}
// v4 ping失败或返回非JSON,尝试 v3
tryV3Ping(baseUrl, key, pwd);
@@ -107,14 +111,18 @@ public class CeTool extends PanBase {
clientNoRedirects.getAbs(pingUrlV3).send().onSuccess(res -> {
if (res.statusCode() == 200) {
// 使用 tryParseJson 而非 asJson,避免非JSON响应(如HTML)提前终止整个解析流程
JsonObject json = tryParseJson(res);
if (json != null && !json.isEmpty()) {
// 尝试调用 v3 share API 来确认
verifyV3AndParse(baseUrl, key, pwd);
return;
try {
JsonObject json = asJson(res);
// v3 ping 成功且返回有效JSON,进一步验证是否为 v3
if (json != null && !json.isEmpty()) {
// 尝试调用 v3 share API 来确认
verifyV3AndParse(baseUrl, key, pwd);
return;
}
} catch (Exception e) {
// JSON解析失败,不是Cloudreve盘
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
}
log.debug("v3 ping返回非JSON响应,不是Cloudreve盘");
}
// v3 ping失败,不是Cloudreve盘
log.debug("v3 ping失败,尝试下一个解析器");
@@ -140,9 +148,9 @@ public class CeTool extends PanBase {
httpRequest.send().onSuccess(res -> {
try {
if (res.statusCode() == 200) {
JsonObject jsonObject = tryParseJson(res);
JsonObject jsonObject = asJson(res);
// 检查响应格式是否符合 v3 API
if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
// v3 share API 成功,确认是 v3 版本
// 设置文件信息
setFileInfo(jsonObject);
@@ -176,9 +184,9 @@ public class CeTool extends PanBase {
httpRequest.send().onSuccess(res -> {
try {
if (res.statusCode() == 200) {
JsonObject jsonObject = tryParseJson(res);
JsonObject jsonObject = asJson(res);
// 检查响应格式是否符合 v4 API
if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
if (jsonObject.containsKey("code") && jsonObject.getInteger("code") == 0) {
// v4 share API 成功,使用 Ce4Tool
log.debug("确认是Cloudreve 4.x (通过v4 share API)");
delegateToCe4Tool();
@@ -423,6 +423,38 @@ public class LzTool extends PanBase {
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) {
if (origin != null && origin.contains("://") && !origins.contains(origin)) {
origins.add(origin);
@@ -814,13 +846,12 @@ public class LzTool extends PanBase {
}
private void getDownURL(String referer, AjaxCall call) {
MultiMap headers = HeaderUtils.parseHeaders(DOWN_AJAX_HEADERS);
// 文件 ajax 优先用页面里的绝对地址(常见 apifile.lanzouw.com)。
// 文件 ajax 优先用页面里的绝对地址(常见 apifile / apifile2)。
// 页面源站空响应再换 FILE_AJAX_FALLBACK_ORIGINS,wwww 仍在最后。
// iframe / 分享页的 Referer 保持原主机,不把页面 GET 改写到 wwww。
String page = referer != null && !referer.isBlank() ? referer : resolveShareUrl();
headers.set("referer", page);
String target = call.absoluteUrl() != null ? call.absoluteUrl() : call.path();
MultiMap headers = fileAjaxHeaders(page, target);
postAjaxAt(fileAjaxOrigins(page, target), 0, call, headers, this::handleAjaxDownResponse, null);
}
@@ -92,7 +92,17 @@ public class HttpResponseHelper {
// -------------------- Buffer 转换 --------------------
private static Buffer toBuffer(HttpResponse<?> res) {
return res.body() instanceof Buffer ? (Buffer) res.body() : Buffer.buffer(res.bodyAsString());
Object raw = res.body();
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) {
@@ -1,102 +0,0 @@
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;
}
}
}
@@ -1,131 +0,0 @@
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格式异常"));
}
}
@@ -1,71 +0,0 @@
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,4 +237,51 @@ public class LzToolShareUrlTest {
assertEquals("https://wwww.lanzoux.com", origins.get(origins.size() - 1));
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"));
}
}
@@ -1,40 +0,0 @@
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>
<properties>
<revision>0.4.13</revision>
<revision>0.4.15</revision>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
@@ -32,7 +32,7 @@
<slf4j.version>2.0.16</slf4j.version>
<commons-lang3.version>3.18.0</commons-lang3.version>
<commons-beanutils2.version>2.0.0</commons-beanutils2.version>
<parserVersion>10.2.5</parserVersion>
<parserVersion>10.2.7</parserVersion>
<jackson.version>2.18.9</jackson.version>
<!-- Logback 最新稳定版 -->
<logback.version>1.5.34</logback.version>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "nfd-web",
"version": "0.4.13",
"version": "0.4.15",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
+24 -28
View File
@@ -51,7 +51,7 @@
<el-icon><Key /></el-icon>
</el-button>
</el-tooltip>
<el-tooltip content="捐赠网盘账号" placement="bottom">
<el-tooltip v-if="donatedAccountsEnabled" content="捐赠网盘账号" placement="bottom">
<el-button circle size="small" type="warning" @click="showDonateDialog = true">
<el-icon><Present /></el-icon>
</el-button>
@@ -319,6 +319,10 @@
width="550px"
:close-on-click-modal="false">
<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-select v-model="authConfig.panType" placeholder="请选择网盘类型" style="width: 100%" @change="onPanTypeChange">
<el-option-group label="必须认证">
@@ -573,10 +577,6 @@
<el-form :model="donateConfig" label-width="100px" size="default">
<el-form-item label="网盘类型" required>
<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 label="小飞机网盘 (FJ)" value="FJ" />
<el-option label="蓝奏优享 (IZ)" value="IZ" />
@@ -712,8 +712,10 @@ export default {
},
// 所有网盘的认证配置 { panType: config }
allAuthConfigs: {},
serverAuthKey: '',
// 捐赠账号相关
donatedAccountsEnabled: false,
showDonateDialog: false,
donateSubmitting: false,
donateConfig: {
@@ -979,6 +981,10 @@ export default {
// 保存认证配置
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) {
this.$message.warning('请先选择网盘类型')
return
@@ -1021,6 +1027,7 @@ export default {
ext5: ''
}
this.allAuthConfigs = {}
this.serverAuthKey = ''
localStorage.removeItem('nfd_auth_configs')
this.$message.success('所有认证配置已清除')
this.showAuthConfigDialog = false
@@ -1040,31 +1047,15 @@ export default {
}
},
// 生成加密的 auth 参数(优先使用个人配置,否则从后端随机获取捐赠账号)
// 个人认证由可信客户端使用自建服务显式配置的密钥编码;捐赠凭据只在服务端使用。
async generateAuthParam() {
const panType = this.getCurrentPanType()
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 = {}
if (config.authType) authObj.authType = config.authType
if (config.username) authObj.username = config.username
@@ -1079,7 +1070,7 @@ export default {
if (config.ext5) authObj.ext5 = config.ext5
try {
const encrypted = this.aesEncrypt(JSON.stringify(authObj), 'nfd_auth_key2026')
const encrypted = this.aesEncrypt(JSON.stringify(authObj), key)
return encodeURIComponent(encrypted)
} catch (e) {
console.error('生成认证参数失败:', e)
@@ -1719,7 +1710,11 @@ export default {
token: isPasswordAuth ? '' : (this.donateConfig.token || ''),
remark: this.donateConfig.remark || ''
}
await axios.post(`${this.baseAPI}/v2/donateAccount`, payload)
const response = 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)} 账号,感谢您的贡献!`)
// 重置表单
@@ -1749,6 +1744,7 @@ export default {
}
if (data && typeof data === 'object') {
this.donatedAccountsEnabled = data.enabled === true
// 兼容新结构: { active: {...}, inactive: {...} }
if (data.active && data.inactive) {
if (data.active.total === undefined) {
@@ -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,18 @@ 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 javax.crypto.spec.SecretKeySpec;
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 +29,56 @@ 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);
}
}
private static SecretKeySpec asAesKey(String key) {
// Match CryptoJS: AES key lengths and values are defined by the full UTF-8 bytes.
return new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
}
public static String getEncryptKey() {
return encryptKey;
}
/**
@@ -69,7 +96,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,15 +112,13 @@ public class AuthParamCodec {
}
// 兼容 query 参数中 '+' 被还原为空格的情况
normalized = normalized.replace(' ', '+');
log.debug("认证参数规范化结果: {}", normalized);
// Step 2: Base64解码
byte[] base64Decoded = Base64Decoder.decode(normalized);
log.debug("Base64解码成功,长度: {}", base64Decoded.length);
// Step 3: AES解密
String jsonStr = AESUtils.decryptByAES(base64Decoded, key);
log.debug("AES解密结果: {}", jsonStr);
String jsonStr = AESUtils.decryptByAES(base64Decoded, asAesKey(key));
// Step 4: JSON解析
JsonObject json = new JsonObject(jsonStr);
@@ -102,9 +127,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 +149,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 +160,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);
String base64Encoded = AESUtils.encryptBase64ByAES(jsonStr, asAesKey(key));
// 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
@@ -5,6 +5,8 @@ import cn.qaiu.util.AESUtils;
import io.vertx.core.json.JsonObject;
import org.junit.Test;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -21,7 +23,64 @@ 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 interoperatesWithBrowserCryptoJsUsingFullUtf8Key() throws Exception {
// CryptoJS 4.2.0: AES-ECB/PKCS7, Utf8.parse(key),
// plaintext {"authType":"token","token":"synthetic-认证"}.
String[][] browserVectors = {
{"0123456789abcdef", "VxQ8JVsWso0Fhf76r82AjtWhuqKaDUtBWPUJcD+Oc1lGwDq001J2N8LJH3RSFBcA"},
{"0123456789abcdefghijklmn", "kCYuDyekW7KZf8rlLqIR0Rcwp7QWcFYn5X6tsGd6XUqlGf9RoJyFzogOgU26JJNS"},
{"0123456789abcdefghijklmnopqrstuv", "FB94nNibPhLIh+oMcnJW0Iuu3O3xSPK0WVHXCiwnvbblwSfe++oPk3RZmw6/7OqX"},
{"密钥测试甲乙丙丁", "cg0YzgNOQxws0chQxDOnepm1Ht+Pkgo7Am9McLXjkUcC35QcRiyHELm0/g4WQm2e"}
};
for (String[] vector : browserVectors) {
String key = vector[0];
AuthParam decoded = AuthParamCodec.decode(URLEncoder.encode(vector[1], StandardCharsets.UTF_8), key);
assertNotNull("browser ciphertext should decode with " + key.getBytes(StandardCharsets.UTF_8).length + "-byte key", decoded);
assertEquals("token", decoded.getAuthType());
assertEquals("synthetic-认证", decoded.getToken());
String encoded = AuthParamCodec.encode(decoded, key);
assertNotNull(encoded);
Cipher peer = Cipher.getInstance("AES/ECB/PKCS5Padding");
peer.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"));
String base64 = URLDecoder.decode(encoded, StandardCharsets.UTF_8);
JsonObject plaintext = new JsonObject(new String(peer.doFinal(Base64.getDecoder().decode(base64)), StandardCharsets.UTF_8));
assertEquals("synthetic-认证", plaintext.getString("token"));
}
}
@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;
+7 -9
View File
@@ -214,7 +214,7 @@
<div class="info-box">
<p><strong>加密算法:</strong> AES/ECB/PKCS5Padding</p>
<p><strong>默认密钥:</strong> nfd_auth_key2026 (16位)</p>
<p><strong>密钥:</strong> 自建服务配置的认证密钥(仅在可信本地环境使用)</p>
<p><strong>编码流程:</strong> JSON对象 → AES加密 → Base64编码 → URL编码</p>
</div>
@@ -268,8 +268,8 @@
</div>
<div class="form-group">
<label for="encryptKey">加密密钥 (可选,默认: nfd_auth_key2026)</label>
<input type="text" id="encryptKey" placeholder="留空使用默认密钥" value="nfd_auth_key2026">
<label for="encryptKey">加密密钥(必填)</label>
<input type="password" id="encryptKey" autocomplete="off" placeholder="本地服务配置的密钥">
</div>
<div class="button-group">
@@ -368,7 +368,10 @@
// AES 加密
try {
const encryptKey = document.getElementById('encryptKey').value.trim() || 'nfd_auth_key2026';
const encryptKey = document.getElementById('encryptKey').value;
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);
document.getElementById('encryptedResult').textContent = encrypted;
@@ -389,11 +392,6 @@
// AES 加密函数
function encryptAuthParam(jsonString, key) {
// 确保密钥是16位
if (key.length !== 16) {
throw new Error('密钥必须是16位字符');
}
// AES 加密 (ECB 模式, PKCS5Padding)
const encrypted = CryptoJS.AES.encrypt(
jsonString,