This section introduces some security policies commonly used in THE JS technology stack. Because this is 101 articles, so the content is not difficult; These are all cliche strategies, so you can quiz yourself on them.
Depend on the audit
Dependency audit is to use the audit command provided by NPM or YARN to check the dependencies that have security risks in node_module. I am used to yarn audit, so I have posted a yarn audit result from my blog. It shows that a package called Trim is too old and poses a high security risk.
Risky dependencies should be resolved as soon as possible. Some developers are naive enough to ignore security audits because their client environment is updated once a year, so they can’t rush. This goes against common development wisdom — dependency problems are hard to fix once they build up.
Back to the topic, manual audit is not often used in production environments. It is usually done as follows: Add YARN audit to CI; If a vulnerability is identified, alert immediately — send a message to the workgroup and update the dependencies.
If developed using Github, a Dependabot bot automatically detects dependencies and reports risks. After certain Settings, it can also automatically submit PR to fix related vulnerabilities.
Launch minor releases and patch updates
Relying on CI to remind us to update dependencies is relatively passive. Many third-party libraries frequently repair security risks by upgrading minor versions or installing patches. Yarn Audit is difficult to track such security reports in a timely manner. It is best to proactively follow up on such fixes during the development phase and avoid unnecessary risks early on. In practice, it is often yarn upgrade.
Here’s a little bit of knowledge, depending on the version rules:
state | The development phase | The rules | The sample |
---|---|---|---|
First release | The new product | Starting from 1.0.0 | 1.0.0 |
Backward compatible bug fixes | Patch release | Add a third digit | 1.0.1 |
New backward compatible functionality | minor | Increment the middle number and place the last position zero | 1.1.0 |
Changes that do not require backward compatibility | Major version | Increment the first digit and zero the next two positions | 2.0.0 |
As shown in the preceding table, backward compatibility is affected by the update of the major version. Therefore, the common upgrade policy is to enable only the minor version or patch update to avoid compatibility problems during YARN Upgrade. So how do you specify the update type of the dependency? You can simply prefix the version of the package.json dependency with a ^ or ~ sign. For example, we specify the version 1.0.4 upgradable range:
- Upgrade only patch versions:
1.0
或X 1.0.
或~ 1.0.4
- Minor and patch versions:
1
或1.x
或^ 1.0.4
- The main version can be upgraded:
*
或x
Example:
"dependencies": {
"my_dep": "^" 1.0.4."another_dep": "~ 2.2.0." "
},
Copy the code
Integrity & Nonce detection
Integrity, as I mentioned in Understanding Script Tags, is the ability to use a hash value to verify that a loaded JS file is complete. In the following tags, integrity tells the browser that when loading the react.production.min.js file, the sha256 algorithm is used to calculate the summary signature of the file. The signature is then compared to the preset integrity value, and if it is inconsistent, the resource is not executed. Its main function is to prevent the resources hosted on the CDN from being tampered with.
<script
src="https://unpkg.com/react@17/umd/react.production.min.js"
integrity="sha384-7Er69WnAl0+tY5MWEvnQzWHeDFjgHSnlQfDDeWUvv8qlRXtzaF/pNo18Q2aoZNiO"
crossorigin="anonymous"
></script>
Copy the code
Similarly, nonce is a default value that checks against the CSP in the HTTP header to prevent script tags that have been string modified from executing the script.
<script nonce="nonce-EfNBf03nceIOAn39fn389h3sdfa" src="./hello.js"></script>
Copy the code
Trusted Types
Nonce and CSP are mentioned above; CSP is a must-know for every front-end developer, and I’ve written Content Security Policy 101 before, if you’re interested. A new feature, Trusted Types, is now supported by all major browsers. It is actually a CSP rule:
Content-Security-Policy: require-trusted-types-for 'script'
Copy the code
The main function is to restrict the use of risky means to manipulate the Web API. For example, when Trusted Types is enabled, directly modifying the HTML will throw an exception:
el.innerHTML = "<img src=x onerror=alert(1)>"; // This throws an exception.
Copy the code
The trusted approach is to only allow apis from the browser vendor’s trustedTypes to operate on Web pages. In the following case, using trustedTypes, the developer consciously replaced the tag tags — < and > — in the inner HTML with special symbols (< and >) to prevent XSS injection.
const policy = trustedTypes.createPolicy("escapePolicy", {
createHTML: (str) = > {
return str.replace(/\</g."<").replace(/>/g.">"); }});// accepted operation
const escaped = policy.createHTML("<img src=x onerror=alert(1)>");
el.innerHTML = escaped; // '< img src=x onerror=alert(1)> '
Copy the code
Enable strict mode
Let’s look at the security policy of JS itself. Modern JS development basically enforces strict mode — use strict. For one thing, some syntax of JS is too rough and not suitable for production. In strict mode, some unsafe operation methods will throw exceptions at runtime, such as:
- Modifying the Global object
this
Point to the global- use
eval
This is a dangerous method of injection - Use escape characters
- Duplicate variable names or delete variables
Compression and obfuscation
In addition, the front-end page will inevitably expose JS files, and some hackers will try to attack by understanding your code (even though we can’t read much of the junk code ourselves). So making your code hard to read effectively reduces this risk. A common practice is to use a component tool like WebPack to compress and obfuscate the source code; Compressed code has the added benefit of faster loading. Of course, some particularly sensitive source code is better off using back-end rendering techniques to avoid direct exposure to the client.
Lint code
Common Lint tools provide static analysis; In addition to the basic functionality of providing uniform formatting and improved code quality, it also alerts developers to pitfalls. In a sense, it also reduces some of the security risks (personally, junk code is the biggest risk). Eslint is most commonly used during development; During the CI phase, you also use a tool like SonarCloud, which produces a report showing code “stinks” and possible security vulnerabilities.
summary
This article lists some of the most common network security measures used in front-end development. These methods are relatively basic, but the most basic is often the most effective; After all, these measures have been proven over the years to prevent the vast majority of security breaches. As a 101 article, actually enough. Of course, the deeper level of “cyber security” becomes a very specialized domain; Knowledge points are very different from our usual “web development”; This article is not specific, interested friends can have an in-depth understanding of their own, this is also a very popular job.
This article was posted on Github by an-Onion. Code word is not easy, welcome to like.