Rhino:如何保护对象字段不被修改?

时间:2018-04-02 13:15:11

标签: javascript java rhino

我在Java中使用Rhino,在我的javascript中我更改了一些Java对象的字段没有问题,虽然我使用initSafeStandardObjects()初始化范围(并且在我向范围添加一些内容之后,我称之为范围。 sealObject())。我的问题是:如何确保我的javascript访问的Java对象不会被javascript代码修改?

示例代码(简化):

Context cx = Context.enter();
cx.setOptimizationLevel(-1);
sharedScope = cx.initSafeStandardObjects(new ImporterTopLevel(cx, true), true);
cx.evaluateString(sharedScope, "function log(text) { if (DEBUG) com.betalord.sgx.core.Misc.log(\"[JSBOT] \" + text); }", "init", 1, null);

String additionalImports = 
"importClass(Packages.com.betalord.sgx.core.Misc);" +
"importClass(Packages.com.betalord.sgx.core.Definitions);" +
"importClass(Packages.com.betalord.sgx.bots.BotUtils);" +
"importClass(Packages.com.betalord.sgx.core.GameState);";
cx.evaluateString(sharedScope , additionalImports, "additional imports", 1, null);

String loadMe = "RegExp; getClass; java; Packages; JavaAdapter;";
cx.evaluateString(sharedScope , loadMe, "lazyLoad", 1, null);
sharedScope.sealObject();
cx.seal(null);
Context.exit();

稍后,当我创建一个Bot类时,我创建了一个实例范围:

Scriptable scope = cx.newObject(sharedScope);
scope.setPrototype(sharedScope);
scope.setParentScope(null);

然后我从javascript获取函数并将其称为fnTick.call(cx, scope, scope, new String[]{});

javascript代码就是这个(执行不应该允许的调用的部分):

var myBest = BotUtils.getPlanetWithMostShips(mine);

myBest.ships++; // This works, but it shouldn't. It should raise an exception when trying to modify Planet's field "ships".

// Also the code bellow works, although it shouldn't (it's reflection):
var field = myBest.getClass().getDeclaredField("prod");
field.setAccessible(true);
field.set(myBest, new java.lang.Integer(30));

那么,我如何防止javascript代码修改我的Java对象?如何防止它使用反射(例如,getClass()方法?)

0 个答案:

没有答案