saltsthlm / kamel-graduation-project

Kamel's Graduation Project
MIT License
0 stars 0 forks source link

Regarding strict mode in backend code #43

Open worstpractice opened 4 years ago

worstpractice commented 4 years ago

Friends, beware: NodeJS modules are not in strict mode by default.

The eshint docs inform that only in ECMAScript modules are the directives unnecessary. This is in contrast to the CommonJS modules which we use on the backend.

For Node-running CommonJS modules (such as our backend code), a "use strict" literal at the beginning of a script or function body enables strict mode semantics. Without it, sloppy mode is on.

Sadly, it's not enough to include "use strict" in a single location. The ESHint docs warn that in the CommonJS module system, a hidden function wraps each module and limits the scope of a “global” strict mode directive.

As such, the need to manually include this directive on backend code is real.

Reading the built-in nodeJS standard library is likewise illuminating -- most-if-not-all CommonJS files manually declare the use of strict mode, because strict mode is not enabled by default in NodeJS.

This is code optimized for years by the best minds of the JavaScript community. They haven't manually littered their codebase with these directives for no reason.

Likewise, the Node REPL requires the passing of a specific flag to opt-into strict mode.

The readme for the NodeJS ECMAScript module team also informs (first result):

Files loaded as ES modules are loaded in strict mode, which in CommonJS requires adding 'use strict'; to the top of every file.

I really must recommend that we enable strict mode on the backend. Not doing so is to opt-into sloppy mode. I see no reason for doing so.

Aside from aiding VM performance, hardening against known bugs, and ensuring feature parity with modern JavaScript, enabling strict mode by manually including a simple "use strict" directive in each backend CommonJS file is a recommended security best practice.

It goes without saying that I would be glad to manually insert these, and -- of course -- this annoying directive must only be included where it is actually required. Which means (AFAICT): test files and backend code only, and CommonJS modules only.

As always, if I have missed something in the technical understanding of this, I'm all the happier to hear about it! The only pleasure I get from putting them in (exclusively where necessary) is that they actually enable strict mode for our beloved code.

All of this in my humble opinion, and as far as I can tell. Pointers and insights accepted with open arms.