mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 14:57:00 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5781100905 | ||
|
|
04ba9a0e2c | ||
|
|
3825527519 | ||
|
|
531f431faa | ||
|
|
25888661ad | ||
|
|
d692416a2e |
No files matched your search
@@ -470,7 +470,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.8/netdisk-fast-download-linux-amd64.zip
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.9/netdisk-fast-download-linux-amd64.zip
|
||||
unzip netdisk-fast-download.zip
|
||||
cd netdisk-fast-download
|
||||
bash service-install.sh
|
||||
|
||||
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
|
||||
|
||||
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
||||
|
||||
### 1. 使用ClassFilter限制类访问 🔒 必须
|
||||
### 1. 演练场与已注册解析器的类访问限制
|
||||
|
||||
```java
|
||||
import jdk.nashorn.api.scripting.ClassFilter;
|
||||
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
|
||||
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 黑名单:禁止访问危险类
|
||||
if (className.startsWith("java.lang.Runtime") ||
|
||||
className.startsWith("java.lang.ProcessBuilder") ||
|
||||
className.startsWith("java.io.File") ||
|
||||
className.startsWith("java.nio.file") ||
|
||||
className.startsWith("java.lang.System") ||
|
||||
className.startsWith("java.lang.Class") ||
|
||||
className.startsWith("java.lang.reflect") ||
|
||||
className.startsWith("java.net.Socket") ||
|
||||
className.startsWith("java.net.URL")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 白名单:只允许特定的类
|
||||
// return className.startsWith("允许的包名");
|
||||
|
||||
return false; // 默认拒绝所有
|
||||
}
|
||||
}
|
||||
|
||||
// 使用ClassFilter创建引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
|
||||
```
|
||||
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
|
||||
|
||||
### 2. 设置执行超时 ⏱️ 强烈推荐
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -134,15 +133,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -151,14 +142,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -111,15 +110,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -128,14 +119,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
final class ParserScriptEngine {
|
||||
private ParserScriptEngine() {}
|
||||
|
||||
static ScriptEngine create() throws ScriptException {
|
||||
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
|
||||
new String[]{"--no-java"}, null, new SecurityClassFilter());
|
||||
// Remove host loaders and scripting-context globals before binding the parser APIs.
|
||||
engine.eval("""
|
||||
(function (global) {
|
||||
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
|
||||
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
|
||||
"com", "edu"].forEach(function (name) {
|
||||
Object.defineProperty(global, name, {
|
||||
value: void 0, writable: false, configurable: false
|
||||
});
|
||||
});
|
||||
})(this);
|
||||
""");
|
||||
return engine;
|
||||
}
|
||||
}
|
||||
@@ -1,118 +1,11 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* JavaScript执行器安全类过滤器
|
||||
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
|
||||
*
|
||||
* @author <a href="https://qaiu.top">QAIU</a>
|
||||
*/
|
||||
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
|
||||
|
||||
// 危险类黑名单
|
||||
private static final String[] DANGEROUS_CLASSES = {
|
||||
// 系统命令执行
|
||||
"java.lang.Runtime",
|
||||
"java.lang.ProcessBuilder",
|
||||
"java.lang.Process",
|
||||
|
||||
// 文件系统访问
|
||||
"java.io.File",
|
||||
"java.io.FileInputStream",
|
||||
"java.io.FileOutputStream",
|
||||
"java.io.FileReader",
|
||||
"java.io.FileWriter",
|
||||
"java.io.RandomAccessFile",
|
||||
"java.nio.file.Files",
|
||||
"java.nio.file.Paths",
|
||||
"java.nio.file.Path",
|
||||
"java.nio.channels.FileChannel",
|
||||
|
||||
// 系统访问
|
||||
"java.lang.System",
|
||||
"java.lang.SecurityManager",
|
||||
|
||||
// 反射相关
|
||||
"java.lang.Class",
|
||||
"java.lang.reflect.Method",
|
||||
"java.lang.reflect.Field",
|
||||
"java.lang.reflect.Constructor",
|
||||
"java.lang.reflect.AccessibleObject",
|
||||
"java.lang.ClassLoader",
|
||||
|
||||
// 网络访问
|
||||
"java.net.Socket",
|
||||
"java.net.ServerSocket",
|
||||
"java.net.DatagramSocket",
|
||||
"java.net.URL",
|
||||
"java.net.URLConnection",
|
||||
"java.net.HttpURLConnection",
|
||||
"java.net.InetAddress",
|
||||
|
||||
// 线程和并发
|
||||
"java.lang.Thread",
|
||||
"java.lang.ThreadGroup",
|
||||
"java.util.concurrent.Executor",
|
||||
"java.util.concurrent.ExecutorService",
|
||||
|
||||
// 数据库访问
|
||||
"java.sql.Connection",
|
||||
"java.sql.Statement",
|
||||
"java.sql.PreparedStatement",
|
||||
"java.sql.DriverManager",
|
||||
|
||||
// 脚本引擎(防止嵌套执行)
|
||||
"javax.script.ScriptEngine",
|
||||
"javax.script.ScriptEngineManager",
|
||||
|
||||
// JVM控制
|
||||
"java.lang.invoke.MethodHandle",
|
||||
"sun.misc.Unsafe",
|
||||
|
||||
// Nashorn内部类
|
||||
"jdk.nashorn.internal",
|
||||
"jdk.internal",
|
||||
};
|
||||
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 检查是否在黑名单中
|
||||
for (String dangerous : DANGEROUS_CLASSES) {
|
||||
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 额外的包级别限制
|
||||
String[] dangerousPackages = {
|
||||
"java.lang.reflect.",
|
||||
"java.io.",
|
||||
"java.nio.",
|
||||
"java.net.",
|
||||
"java.sql.",
|
||||
"javax.script.",
|
||||
"sun.",
|
||||
"jdk.internal.",
|
||||
"jdk.nashorn.internal."
|
||||
};
|
||||
|
||||
for (String pkg : dangerousPackages) {
|
||||
if (className.startsWith(pkg)) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
|
||||
// 如果要更严格,可以改为 return false
|
||||
log.debug("允许访问类: {}", className);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
final class FjDownloadParams {
|
||||
private FjDownloadParams() {
|
||||
}
|
||||
|
||||
static JsonObject create(String fileId, String userId, String uuid, String shareId, long timestamp) {
|
||||
if (StringUtils.isBlank(fileId) || StringUtils.isBlank(shareId)) {
|
||||
throw new IllegalArgumentException("缺少 fileId 或 shareId");
|
||||
}
|
||||
return JsonObject.of("fileId", fileId,
|
||||
"fidEncode", AESUtils.encrypt2Hex(fileId + "|" + StringUtils.defaultString(userId)),
|
||||
"uuid", uuid, "shareId", shareId,
|
||||
"ts", AESUtils.encrypt2Hex(Long.toString(timestamp)),
|
||||
"auth", AESUtils.encrypt2Hex(fileId + "|" + timestamp));
|
||||
}
|
||||
|
||||
static String fileId(JsonObject params) throws Exception {
|
||||
String fileId = params.getString("fileId");
|
||||
if (StringUtils.isNotBlank(fileId)) {
|
||||
return fileId;
|
||||
}
|
||||
// 兼容已生成的目录链接,但不再复用其中的身份和过期签名。
|
||||
String decoded = AESUtils.decryptByHexAES(params.getString("fidEncode"), AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
if (separator <= 0) {
|
||||
throw new IllegalArgumentException("无效的 fidEncode");
|
||||
}
|
||||
return decoded.substring(0, separator);
|
||||
}
|
||||
|
||||
static String ownerId(JsonObject params) throws Exception {
|
||||
Object id = params.getValue("userId");
|
||||
if (id != null && StringUtils.isNotBlank(id.toString())) {
|
||||
return id.toString();
|
||||
}
|
||||
String encoded = params.getString("fidEncode");
|
||||
if (StringUtils.isBlank(encoded)) {
|
||||
return null;
|
||||
}
|
||||
String decoded = AESUtils.decryptByHexAES(encoded, AESUtils.CIPHER_AES0);
|
||||
int separator = decoded.indexOf('|');
|
||||
String owner = separator < 0 ? null : decoded.substring(separator + 1);
|
||||
return StringUtils.isBlank(owner) || "null".equals(owner) ? null : owner;
|
||||
}
|
||||
|
||||
static String missingLocation(int status, String body) {
|
||||
String message = "未获取到下载重定向地址, HTTP " + status;
|
||||
if (StringUtils.isBlank(body)) {
|
||||
return message + ", 响应体为空";
|
||||
}
|
||||
try {
|
||||
JsonObject json = new JsonObject(body);
|
||||
if (StringUtils.isNotBlank(json.getString("msg"))) {
|
||||
return message + ", 上游返回: " + preview(json.getString("msg"))
|
||||
+ " (code=" + json.getValue("code") + ")";
|
||||
}
|
||||
} catch (RuntimeException ignored) {
|
||||
// 非 JSON 错误页同样保留有限长度的诊断内容。
|
||||
}
|
||||
return message + ", 响应体: " + preview(body);
|
||||
}
|
||||
|
||||
private static String preview(String value) {
|
||||
return value.length() > 500 ? value.substring(0, 500) + "..." : value;
|
||||
}
|
||||
}
|
||||
@@ -129,8 +129,6 @@ public class FjTool extends PanBase {
|
||||
if (auths.contains("userId")) {
|
||||
FjTool.userId = auths.get("userId");
|
||||
log.info("已配置用户ID: {}", FjTool.userId);
|
||||
} else {
|
||||
log.warn("未配置用户ID, 可能会导致解析失败");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +197,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 检查是否有认证信息
|
||||
@@ -223,7 +221,7 @@ public class FjTool extends PanBase {
|
||||
log.warn("登录失败: {}", failRes.getMessage());
|
||||
fail(failRes.getMessage());
|
||||
}).onSuccess(r-> {
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
httpRequest.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
});
|
||||
@@ -245,7 +243,7 @@ public class FjTool extends PanBase {
|
||||
});
|
||||
} else {
|
||||
httpRequest
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId))
|
||||
.setTemplateParam("fidEncode", AESUtils.encrypt2Hex(fileId + "|" + userId))
|
||||
.putHeaders(header);
|
||||
httpRequest.send().onSuccess(this::down).onFailure(handleFail("请求2"));
|
||||
}
|
||||
@@ -444,8 +442,15 @@ public class FjTool extends PanBase {
|
||||
|
||||
private void down(HttpResponse<Buffer> res2) {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location") || headers.get("Location") == null) {
|
||||
fail("找不到下载链接可能服务器已被禁止或者配置的认证信息有误: " + res2.bodyAsString());
|
||||
if (StringUtils.isBlank(headers.get("Location"))) {
|
||||
String body;
|
||||
try {
|
||||
body = asText(res2);
|
||||
} catch (IllegalArgumentException | UnsupportedOperationException e) {
|
||||
fail(e, "读取下载错误响应失败, HTTP {}", res2.statusCode());
|
||||
return;
|
||||
}
|
||||
fail("{}", FjDownloadParams.missingLocation(res2.statusCode(), body));
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
@@ -523,7 +528,7 @@ public class FjTool extends PanBase {
|
||||
// 其他参数
|
||||
long nowTs2 = System.currentTimeMillis();
|
||||
String tsEncode2 = AESUtils.encrypt2Hex(Long.toString(nowTs2));
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + FjTool.userId);
|
||||
String fidEncode = AESUtils.encrypt2Hex(fileId + "|" + userId);
|
||||
String auth = AESUtils.encrypt2Hex(fileId + "|" + nowTs2);
|
||||
|
||||
// 回传用到的参数
|
||||
@@ -533,6 +538,8 @@ public class FjTool extends PanBase {
|
||||
//"auth", paramJson.getString("auth"))
|
||||
//"shareId", paramJson.getString("shareId"))
|
||||
JsonObject entries = JsonObject.of(
|
||||
"fileId", fileId,
|
||||
"userId", userId,
|
||||
"fidEncode", fidEncode,
|
||||
"uuid", uuid,
|
||||
"ts", tsEncode2,
|
||||
@@ -590,20 +597,24 @@ public class FjTool extends PanBase {
|
||||
promise.fail("缺少 paramJson 参数");
|
||||
return promise.future();
|
||||
}
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", paramJson.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", paramJson.getString("uuid"))
|
||||
.setTemplateParam("ts", paramJson.getString("ts"))
|
||||
.setTemplateParam("auth", paramJson.getString("auth"))
|
||||
.setTemplateParam("dataKey", paramJson.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(res2 -> {
|
||||
MultiMap headers = res2.headers();
|
||||
if (!headers.contains("Location")) {
|
||||
fail(SECOND_REQUEST_URL_VIP + " 未找到重定向URL: \n" + res2.headers());
|
||||
return;
|
||||
}
|
||||
promise.complete(headers.get("Location"));
|
||||
}).onFailure(handleFail(SECOND_REQUEST_URL_VIP));
|
||||
try {
|
||||
String ownerId = FjDownloadParams.ownerId(paramJson);
|
||||
if (StringUtils.isBlank(ownerId) || "null".equals(ownerId)) {
|
||||
fail("目录下载参数缺少分享者 userId,请刷新文件列表后重试");
|
||||
return promise.future();
|
||||
}
|
||||
JsonObject params = FjDownloadParams.create(FjDownloadParams.fileId(paramJson), ownerId,
|
||||
paramJson.getString("uuid"), paramJson.getString("shareId"), System.currentTimeMillis());
|
||||
clientNoRedirects.getAbs(UriTemplate.of(SECOND_REQUEST_URL_VIP))
|
||||
.setTemplateParam("fidEncode", params.getString("fidEncode"))
|
||||
.setTemplateParam("uuid", params.getString("uuid"))
|
||||
.setTemplateParam("ts", params.getString("ts"))
|
||||
.setTemplateParam("auth", params.getString("auth"))
|
||||
.setTemplateParam("dataKey", params.getString("shareId"))
|
||||
.putHeaders(header).send().onSuccess(this::down).onFailure(handleFail("下载请求"));
|
||||
} catch (Exception e) {
|
||||
fail(e, "下载参数无效");
|
||||
}
|
||||
return promise.future();
|
||||
}
|
||||
|
||||
|
||||
@@ -7,50 +7,7 @@
|
||||
// 全局类型定义,使用JSDoc注释
|
||||
// 这些类型定义将在VSCode中提供代码补全和类型检查
|
||||
|
||||
// ============================================================================
|
||||
// Nashorn Java 互操作全局对象
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Java 全局对象类型定义 (Nashorn引擎提供)
|
||||
* 用于访问Java类型和进行Java互操作
|
||||
* @typedef {Object} JavaGlobal
|
||||
* @property {function(string): any} type - 获取Java类,参数为完整类名(如"java.util.zip.CRC32")
|
||||
* @property {function(any): any} from - 将Java对象转换为JavaScript对象
|
||||
* @property {function(any): any} to - 将JavaScript对象转换为Java对象
|
||||
* @property {function(any): boolean} isType - 检查对象是否为指定Java类型
|
||||
* @property {function(any): boolean} isJavaObject - 检查对象是否为Java对象
|
||||
* @property {function(any): boolean} isJavaMethod - 检查对象是否为Java方法
|
||||
* @property {function(any): boolean} isJavaFunction - 检查对象是否为Java函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* Java 全局对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaGlobal}
|
||||
*/
|
||||
var Java;
|
||||
|
||||
/**
|
||||
* java 命名空间对象类型定义 (Nashorn引擎提供)
|
||||
* 用于直接访问Java包和类
|
||||
* @typedef {Object} JavaNamespace
|
||||
* @property {Object} lang - java.lang 包
|
||||
* @property {Object} util - java.util 包
|
||||
* @property {Object} io - java.io 包
|
||||
* @property {Object} net - java.net 包
|
||||
* @property {Object} math - java.math 包
|
||||
* @property {Object} security - java.security 包
|
||||
* @property {Object} text - java.text 包
|
||||
* @property {Object} time - java.time 包
|
||||
*/
|
||||
|
||||
/**
|
||||
* java 命名空间对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaNamespace}
|
||||
*/
|
||||
var java;
|
||||
// 解析脚本通过项目注入的接口访问分享信息、HTTP 和日志。
|
||||
|
||||
/**
|
||||
* @typedef {Object} ShareLinkInfo
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.custom.CustomParserConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ParserScriptEngineTest {
|
||||
@Test
|
||||
public void disablesClassLookupAndHostLoadersBeforeRunningScripts() throws Exception {
|
||||
SecurityClassFilter filter = new SecurityClassFilter();
|
||||
assertFalse(filter.exposeToScripts("java.lang.String"));
|
||||
assertFalse(filter.exposeToScripts("java.util.Formatter"));
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
for (String name : new String[]{"Java", "JavaImporter", "Packages", "java", "javax",
|
||||
"org", "com", "edu", "javafx", "load", "loadWithNewGlobal", "engine", "context", "exit", "quit"}) {
|
||||
assertEquals(name, "undefined", engine.eval("typeof " + name));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').writable"));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').configurable"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ordinaryScriptsCanStillCallAnInjectedParserApi() throws Exception {
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
engine.put("logger", new JsPlaygroundLogger());
|
||||
assertEquals("ok", engine.eval("logger.info('parser test'); JSON.parse('{\"result\":\"ok\"}').result"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothExecutorsPreserveParserApisAndDisableHostGlobals() throws Exception {
|
||||
String script = """
|
||||
function parse(info, http, logger) {
|
||||
logger.info("parser test");
|
||||
return [info.getShareKey(), typeof fetch, typeof java, typeof loadWithNewGlobal].join("|");
|
||||
}
|
||||
""";
|
||||
String expected = "sample|function|undefined|undefined";
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().shareKey("sample").build();
|
||||
CustomParserConfig config = CustomParserConfig.builder()
|
||||
.type("sandbox_test").displayName("Sandbox test").isJsParser(true).jsCode(script).build();
|
||||
Vertx vertx = Vertx.vertx();
|
||||
try {
|
||||
WebClientVertxInit.init(vertx);
|
||||
try (JsPlaygroundExecutor playground = new JsPlaygroundExecutor(info, script);
|
||||
JsParserExecutor registered = new JsParserExecutor(info, config)) {
|
||||
assertEquals(expected, playground.executeParseAsync().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
assertEquals(expected, registered.parse().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjDownloadParamsTest {
|
||||
@Test
|
||||
public void anonymousIdentityIsEmptyRatherThanNull() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", null, "uuid", "share", 1000L);
|
||||
assertEquals("123|", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("1000", decrypt(params.getString("ts")));
|
||||
assertEquals("123|1000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void authenticatedIdentityAndTimestampAreRegenerated() throws Exception {
|
||||
JsonObject params = FjDownloadParams.create("123", "456", "uuid", "share", 2000L);
|
||||
assertEquals("123|456", decrypt(params.getString("fidEncode")));
|
||||
assertEquals("123|2000", decrypt(params.getString("auth")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void legacyLinksRecoverOnlyFileId() throws Exception {
|
||||
JsonObject old = JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"), "ts", "expired");
|
||||
assertEquals("123", FjDownloadParams.fileId(old));
|
||||
assertEquals("789", FjDownloadParams.fileId(JsonObject.of("fileId", "789")));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException.class)
|
||||
public void invalidLegacyLinkFailsExplicitly() throws Exception {
|
||||
FjDownloadParams.fileId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("invalid")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamErrorPreservesBusinessCodeAndMessage() {
|
||||
String message = FjDownloadParams.missingLocation(200, "{\"code\":401,\"msg\":\"请登录后下载\"}");
|
||||
assertTrue(message.contains("HTTP 200"));
|
||||
assertTrue(message.contains("code=401"));
|
||||
assertTrue(message.contains("请登录后下载"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "").contains("响应体为空"));
|
||||
assertTrue(FjDownloadParams.missingLocation(502, "x".repeat(1000)).length() < 600);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ownerIdentityComesFromDirectoryDataOrLegacySignature() throws Exception {
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(JsonObject.of("userId", 11069975L)));
|
||||
assertEquals("11069975", FjDownloadParams.ownerId(
|
||||
JsonObject.of("fidEncode", AESUtils.encrypt2Hex("61731757356|11069975"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|null"))));
|
||||
assertNull(FjDownloadParams.ownerId(JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|"))));
|
||||
}
|
||||
|
||||
private String decrypt(String value) throws Exception {
|
||||
return AESUtils.decryptByHexAES(value, AESUtils.CIPHER_AES0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.util.AESUtils;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import io.vertx.ext.web.client.WebClient;
|
||||
import io.vertx.ext.web.client.WebClientOptions;
|
||||
import io.vertx.uritemplate.UriTemplate;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class FjToolDownloadTest {
|
||||
private Vertx vertx;
|
||||
private WebClient local;
|
||||
private HttpServer server;
|
||||
private final AtomicInteger logins = new AtomicInteger();
|
||||
private final AtomicInteger downloads = new AtomicInteger();
|
||||
private String identity;
|
||||
private String businessError;
|
||||
private String contentEncoding;
|
||||
|
||||
@Before
|
||||
public void setup() throws Exception {
|
||||
FjTool.resetToken();
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
local = WebClient.create(vertx, new WebClientOptions().setFollowRedirects(false));
|
||||
server = vertx.createHttpServer().requestHandler(req -> {
|
||||
if (req.path().equals("/ws/login")) {
|
||||
logins.incrementAndGet();
|
||||
req.response().setStatusCode(500).end("Share downloads must not require login");
|
||||
} else if (req.path().equals("/ws/file/redirect")) {
|
||||
downloads.incrementAndGet();
|
||||
try {
|
||||
identity = AESUtils.decryptByHexAES(req.getParam("downloadId"), AESUtils.CIPHER_AES0);
|
||||
long timestamp = Long.parseLong(AESUtils.decryptByHexAES(req.getParam("timestamp"), AESUtils.CIPHER_AES0));
|
||||
assertTrue(Math.abs(System.currentTimeMillis() - timestamp) < 10000);
|
||||
assertEquals(AESUtils.encrypt2Hex("123|" + timestamp), req.getParam("auth"));
|
||||
assertEquals("share", req.getParam("shareId"));
|
||||
if (businessError != null) {
|
||||
if (contentEncoding != null) {
|
||||
req.response().putHeader("Content-Encoding", contentEncoding);
|
||||
}
|
||||
req.response().end(businessError);
|
||||
} else {
|
||||
req.response().setStatusCode(302).putHeader("Location", "https://download.example/file").end();
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
req.response().setStatusCode(500).end(e.toString());
|
||||
}
|
||||
} else {
|
||||
req.response().setStatusCode(404).end();
|
||||
}
|
||||
}).listen(0, "127.0.0.1").toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@After
|
||||
public void cleanup() throws Exception {
|
||||
local.close();
|
||||
server.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
FjTool.resetToken();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void directoryLinkUsesOwnerEvenWithConfiguredCredentials() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("auths", MultiMap.caseInsensitiveMultiMap()
|
||||
.set("username", "test-user").set("password", "test-password"));
|
||||
assertEquals("https://download.example/file", tool(info).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals(0, logins.get());
|
||||
assertEquals(1, downloads.get());
|
||||
assertEquals("123|11069975", identity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shareRequestUsesOwnerNotGlobalUserIdentity() throws Exception {
|
||||
FjTool.userId = "other-user";
|
||||
assertEquals("https://download.example/file", tool(info()).parseById()
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS));
|
||||
assertEquals("123|11069975", identity);
|
||||
assertEquals(0, logins.get());
|
||||
FjTool.userId = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void upstreamBusinessErrorCompletesFutureWithReason() throws Exception {
|
||||
businessError = "{\"code\":403,\"msg\":\"需要会员\"}";
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected upstream error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("需要会员"));
|
||||
assertTrue(e.getCause().getMessage().contains("code=403"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsupportedErrorEncodingFailsWithoutLeavingFuturePending() throws Exception {
|
||||
contentEncoding = "zstd";
|
||||
businessError = "upstream error";
|
||||
assertErrorBodyFailure("zstd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void oversizedErrorBodyFailsWithoutLeavingFuturePending() throws Exception {
|
||||
businessError = "x".repeat(8 * 1024 * 1024 + 1);
|
||||
assertErrorBodyFailure("响应体过大");
|
||||
}
|
||||
|
||||
private void assertErrorBodyFailure(String expectedReason) throws Exception {
|
||||
try {
|
||||
tool(info()).parseById().toCompletionStage().toCompletableFuture().get(3, TimeUnit.SECONDS);
|
||||
fail("Expected response decoding error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains(expectedReason));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingOwnerFailsBeforeDownload() throws Exception {
|
||||
ShareLinkInfo info = info();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fileId", "123", "shareId", "share"));
|
||||
try {
|
||||
tool(info).parseById().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
fail("Expected missing owner error");
|
||||
} catch (ExecutionException e) {
|
||||
assertTrue(e.getCause().getMessage().contains("缺少分享者 userId"));
|
||||
}
|
||||
assertEquals(0, downloads.get());
|
||||
}
|
||||
|
||||
private ShareLinkInfo info() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().type("fj").shareKey("share")
|
||||
.shareUrl("https://share.feijipan.com/s/share").build();
|
||||
info.getOtherParam().put("paramJson", JsonObject.of("fidEncode", AESUtils.encrypt2Hex("123|11069975"),
|
||||
"uuid", "test-uuid", "ts", "expired", "auth", "expired", "shareId", "share"));
|
||||
return info;
|
||||
}
|
||||
|
||||
private FjTool tool(ShareLinkInfo info) {
|
||||
WebClient routed = (WebClient) Proxy.newProxyInstance(WebClient.class.getClassLoader(),
|
||||
new Class<?>[]{WebClient.class}, (proxy, method, args) -> {
|
||||
if (args != null && args.length > 0 && args[0] instanceof UriTemplate template) {
|
||||
args[0] = Proxy.newProxyInstance(UriTemplate.class.getClassLoader(),
|
||||
new Class<?>[]{UriTemplate.class}, (p, m, a) -> {
|
||||
Object expanded = m.invoke(template, a);
|
||||
return expanded instanceof String url
|
||||
? url.replace("https://api.feijipan.com", "http://127.0.0.1:" + server.actualPort())
|
||||
: expanded;
|
||||
});
|
||||
}
|
||||
return method.invoke(local, args);
|
||||
});
|
||||
return new FjTool(info) {{ client = routed; clientNoRedirects = routed; }};
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<revision>0.4.8</revision>
|
||||
<revision>0.4.9</revision>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nfd-web",
|
||||
"version": "0.4.8",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<el-icon :size="50"><WarningFilled /></el-icon>
|
||||
</div>
|
||||
<div class="auth-title">演练场功能已禁用</div>
|
||||
<div class="auth-subtitle">请联系管理员启用演练场功能</div>
|
||||
<div class="auth-subtitle">请联系管理员检查演练场开关与服务日志。私有模式需要先设置实例专属的访问密码。</div>
|
||||
<el-button type="primary" size="large" @click="goHome" class="auth-button">
|
||||
<span>返回首页</span>
|
||||
</el-button>
|
||||
|
||||
@@ -6,15 +6,16 @@ JS解析器演练场现在支持密码保护功能,可以通过配置文件控
|
||||
|
||||
## 配置说明
|
||||
|
||||
在 `web-service/src/main/resources/app-dev.yml` 文件中添加以下配置:
|
||||
编辑当前启用的配置文件。发行包默认使用 `resources/app-dev.yml`。
|
||||
|
||||
```yaml
|
||||
# JS演练场配置
|
||||
playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前须设置实例专属密码
|
||||
password: ''
|
||||
```
|
||||
|
||||
### 配置项说明
|
||||
@@ -24,8 +25,7 @@ playground:
|
||||
- `true`: 公开访问,无需密码
|
||||
|
||||
- `password`: 字符串,访问密码
|
||||
- 默认密码:`nfd_playground_2024`
|
||||
- **强烈建议在生产环境中修改为自定义密码!**
|
||||
- 无默认值。私有模式缺少密码、密码为空白或沿用旧版公开密码时,演练场保持关闭。
|
||||
|
||||
## 功能特点
|
||||
|
||||
@@ -64,24 +64,14 @@ playground:
|
||||
|
||||
⚠️ **重要安全提示:**
|
||||
|
||||
1. **修改默认密码**:在生产环境中,务必修改 `playground.password` 为自定义的强密码
|
||||
1. **设置专属密码**:启用私有模式前,请设置 `playground.password` 为自定义的强密码
|
||||
2. **使用密码保护**:建议保持 `public: false`,避免未授权访问
|
||||
3. **定期更换密码**:定期更换访问密码以提高安全性
|
||||
4. **配置文件保护**:确保配置文件的访问权限受到保护
|
||||
|
||||
## 系统启动提示
|
||||
|
||||
当系统启动时,会在日志中显示当前配置:
|
||||
|
||||
```
|
||||
INFO - Playground配置已加载: public=false, password=已设置
|
||||
```
|
||||
|
||||
如果使用默认密码,会显示警告:
|
||||
|
||||
```
|
||||
WARN - ⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!
|
||||
```
|
||||
配置文件及启用开关 `NFD_PLAYGROUND_ENABLED` 生效后,服务会检查私有模式密码。若检查失败,日志会提示配置 `playground.password` 并重启服务,其他功能继续启动。显式选择 `public: true` 会允许免密码访问管理接口。
|
||||
|
||||
## API 端点
|
||||
|
||||
@@ -145,9 +135,9 @@ A: 修改配置文件中的 `playground.password` 为新密码,然后重启服
|
||||
|
||||
A: 当前版本密码以明文形式存储在配置文件中,请确保配置文件的访问权限受到保护
|
||||
|
||||
### Q: Session 有效期多久?
|
||||
### 登录令牌有效期多久?
|
||||
|
||||
A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏览器后失效
|
||||
私有模式的令牌自签发起最多有效 24 小时。服务重启或重新加载演练场配置会使已签发的令牌失效。
|
||||
|
||||
## 后续版本计划
|
||||
|
||||
@@ -156,7 +146,6 @@ A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏
|
||||
- [ ] 支持环境变量配置密码
|
||||
- [ ] 支持加密存储密码
|
||||
- [ ] 支持多用户账户系统
|
||||
- [ ] 支持 Token 认证方式
|
||||
- [ ] 支持 Session 超时配置
|
||||
|
||||
## 相关文档
|
||||
|
||||
@@ -26,7 +26,7 @@ public class PlaygroundConfig {
|
||||
/**
|
||||
* 单例实例
|
||||
*/
|
||||
private static PlaygroundConfig instance;
|
||||
private static volatile PlaygroundConfig instance = new PlaygroundConfig();
|
||||
|
||||
/**
|
||||
* 已颁发的认证Token及其创建时间
|
||||
@@ -47,9 +47,8 @@ public class PlaygroundConfig {
|
||||
|
||||
/**
|
||||
* 访问密码
|
||||
* 默认密码:nfd_playground_2024
|
||||
*/
|
||||
private String password = "nfd_playground_2024";
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 私有构造函数
|
||||
@@ -117,13 +116,6 @@ public class PlaygroundConfig {
|
||||
* 获取单例实例
|
||||
*/
|
||||
public static PlaygroundConfig getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (PlaygroundConfig.class) {
|
||||
if (instance == null) {
|
||||
instance = new PlaygroundConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -131,23 +123,13 @@ public class PlaygroundConfig {
|
||||
* 从JsonObject加载配置
|
||||
*/
|
||||
public static void loadFromJson(JsonObject config) {
|
||||
PlaygroundConfig cfg = getInstance();
|
||||
if (config != null && config.containsKey("playground")) {
|
||||
JsonObject playgroundConfig = config.getJsonObject("playground");
|
||||
cfg.enabled = playgroundConfig.getBoolean("enabled", false);
|
||||
cfg.isPublic = playgroundConfig.getBoolean("public", false);
|
||||
cfg.password = playgroundConfig.getString("password", "nfd_playground_2024");
|
||||
|
||||
log.info("Playground配置已加载: enabled={}, public={}, password={}",
|
||||
cfg.enabled, cfg.isPublic, cfg.isPublic ? "N/A" : "已设置");
|
||||
|
||||
if (!cfg.enabled) {
|
||||
log.info("演练场功能已禁用");
|
||||
} else if (!cfg.isPublic && "nfd_playground_2024".equals(cfg.password)) {
|
||||
log.warn("⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!");
|
||||
PlaygroundConfig cfg = new PlaygroundConfig();
|
||||
if (config != null && config.getValue("playground") instanceof JsonObject playground) {
|
||||
cfg.enabled = playground.getBoolean("enabled", false);
|
||||
cfg.isPublic = playground.getBoolean("public", false);
|
||||
if (playground.getValue("password") instanceof String configuredPassword) {
|
||||
cfg.password = configuredPassword;
|
||||
}
|
||||
} else {
|
||||
log.info("未找到playground配置,使用默认值: enabled=false, public=false");
|
||||
}
|
||||
String enabledOverride = System.getProperty("NFD_PLAYGROUND_ENABLED");
|
||||
if (enabledOverride == null || enabledOverride.isBlank()) {
|
||||
@@ -155,7 +137,16 @@ public class PlaygroundConfig {
|
||||
}
|
||||
if (enabledOverride != null && !enabledOverride.isBlank()) {
|
||||
cfg.enabled = Boolean.parseBoolean(enabledOverride);
|
||||
log.info("Playground enabled 已被 NFD_PLAYGROUND_ENABLED 覆盖为 {}", cfg.enabled);
|
||||
}
|
||||
|
||||
// Validate after all overrides so enabling via the environment follows the same rules.
|
||||
if (cfg.enabled && !cfg.isPublic && (cfg.password == null || cfg.password.isBlank()
|
||||
|| "nfd_playground_2024".equals(cfg.password.strip()))) {
|
||||
cfg.enabled = false;
|
||||
log.warn("演练场已禁用:请在 app-dev.yml 中设置实例专属的 playground.password,替换空值或旧版默认密码,然后重启服务。");
|
||||
} else {
|
||||
log.info("演练场配置已加载:enabled={}, public={}", cfg.enabled, cfg.isPublic);
|
||||
}
|
||||
instance = cfg;
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,8 @@ playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前请填写实例专属密码;留空或沿用旧版默认密码将禁用演练场。
|
||||
password: ''
|
||||
|
||||
# vertx核心线程配置(一般无需改的), 为0表示eventLoopPoolSize将会采用默认配置(CPU核心*2) workerPoolSize将会采用默认20
|
||||
vertx:
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.qaiu.lz.web.config;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PlaygroundPasswordTest {
|
||||
@Test
|
||||
public void validatesPrivateModeAfterTheEnableOverride() {
|
||||
String key = "NFD_PLAYGROUND_ENABLED";
|
||||
String previous = System.getProperty(key);
|
||||
try {
|
||||
System.setProperty(key, "true");
|
||||
JsonObject playground = new JsonObject().put("enabled", false);
|
||||
JsonObject config = new JsonObject().put("playground", playground);
|
||||
for (String password : new String[]{null, "", " ", "nfd_playground_2024"}) {
|
||||
playground.put("password", password);
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
}
|
||||
playground.put("password", "instance-specific-test-value");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertEquals(playground.getString("password"), PlaygroundConfig.getInstance().getPassword());
|
||||
String token = PlaygroundConfig.getInstance().generateToken();
|
||||
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertFalse(PlaygroundConfig.getInstance().validateToken(token));
|
||||
|
||||
playground.put("public", true).remove("password");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
System.setProperty(key, "false");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
} finally {
|
||||
if (previous == null) System.clearProperty(key);
|
||||
else System.setProperty(key, previous);
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user