Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block vscode typescript file importing from a folder it should not?

We use typescript & webpack. All of the code is in one repo. The product is a game thus the states and objects need to be shared so it has 3 different main folders.

The shared code is used both on the backend and the frontend. The server code should never be imported by shared or client otherwise it creates a security risk.

We had server code accidentally imported previously which resulted in a security issue where we needed to change all the keys. We don't have any system set up in place to prevent this from happening again.

One method is to break up the server & client into 2 different projects, but that would take a lot of time and increase the complexity too much.

Another method is to run a script that detects if server code has been imported into Shared or Client. I can do it with python and make it run when we push a code. But with all the functions of VSCode I'm sure they probably have such a thing. Or maybe npm has such a library.

Any help is appreciated.

enter image description here

like image 381
demiculus Avatar asked Oct 03 '20 07:10

demiculus


Video Answer


1 Answers

If you use ESLint, which has a plugin for VS Code as well, you can use cascading configurations along with restricted imports. Autocomplete will still suggest the imports, but at least they will instantly be marked as red and squigly.

The directory setup remains the same as it is, with the addition of configuration files:

code
├ client
│ └ .eslintrc
├ server
│ └ .eslintrc
└ .eslintrc

The key note here is that the root .eslintrc contains your primary rules, where as .eslintrc files in subdirectories can extend it as show in this answer. You can find more information on how to configure that in the docs.

This will allow you to set up restricted imports which support both path-based and pattern-based restrictions:

"no-restricted-imports": ["error", {
    "paths": ["import1", "import2"],
    "patterns": ["import1/private/*", "import2/*", "!import2/good"]
}]

You can then disallow server code imports in the client and shared subdirectories.

like image 79
Etheryte Avatar answered Oct 19 '22 17:10

Etheryte