wendigo
wendigo

Reputation: 81

Evaluating code directly from JSON, bad idea or is there a better way?

Essentially I'm making a game using JavaScript, CSS, HTML, etc inside of Electron so that I can easily access local files. The game would be entirely local and offline. Never makes any kind of connections to servers.

But my idea is essentially small self contained stories that get loaded into a pool that the player can choose from, just drop them into a folder and they're included in the game. I was using JSON files for this but I also wanted the ability to make variables specific to the story module whenever one starts.

For example, I want a random name for characters in the story module, so at the start:

"do_at_start" : "story_variables.character_name = randomChoiceFunction('name1', 'name2', 'name3')" etc.

The reason I want to do this is the idea that anyone who wanted to could make a custom JSON file and have them in the game that way instead of writing functions and such to make a new module.

The easiest way I supposed was to just eval() code in the string in the JSON value when needed. This being a local application, is this still a bad idea? Or is there some other way that might work for this as well? Ideally I'd like to get suggestions that I can make from scratch as kind of an exercise to see if I can write something like this from scratch, but I will still take suggestions on other approaches if they are far easier to implement.

Upvotes: 0

Views: 74

Answers (1)

Sean Sutherland
Sean Sutherland

Reputation: 461

What you're describing seems to be a perfectly reasonable way to allow what is essentially a modding API for your app. Chromium (what electron is based on) has a fairly robust security model, so I wouldn't worry too much about the risks of malicious code.

If you're really concerned about hardening attack surfaces, make sure you follow the electron security best practices, and consider outright disabling network access, and/or limiting the app to a single folder. (SO links provided as examples, but you may want to look for other implementations).

The other option is building an entire custom parser with every function you might want to use. You'd be scanning and replacing predefined macros in your input files. If you want to go down the road, I'd suggest looking at the way Sugarcube does it.

Upvotes: 2

Related Questions