Registry / web-framework / egg-security

egg-security

JSON →
library3.7.0jsnpmunverified

The `@eggjs/security` (formerly `egg-security`) package is a robust security plugin specifically designed for the Egg.js framework. It provides comprehensive protection against common web vulnerabilities, including Cross-Site Request Forgery (CSRF), Cross-Site Scripting (XSS), Server-Side Request Forgery (SSRF), SQL injection, and more. The current stable version is 4.0.1 (under the `@eggjs/security` namespace), with the 3.x branch (`egg-security`) also receiving maintenance updates, with `3.8.0` being the latest for that line. The project maintains an active release cadence, frequently publishing minor and patch versions to introduce new features, improve existing protections, and address bug fixes. A significant update to version 4.0.0 migrated the codebase to TypeScript and dropped support for Node.js versions older than 18.19.0. Its key differentiator lies in its deep integration with the Egg.js ecosystem, offering out-of-the-box security measures that are easily configurable within the framework's convention-over-configuration paradigm, simplifying the implementation of robust security practices for developers building Egg.js applications.

npm install egg-security
INSTALL
IMPORT
SIG · EGG-SECURITY
E
egg-security
web-frameworkjavascriptv3.7.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Enable Plugin
// config/plugin.ts export default { security: { enable: true, package: '@eggjs/security' } };
import { Security } from 'egg-security'; // Plugins are enabled via config, not direct import
For Egg.js plugins, you enable them in `config/plugin.ts` (or `.js`) by specifying the package name. Note the package name change to `@eggjs/security` since v4.0.0.
Configure Security
// config/config.default.ts import { EggAppConfig } from 'egg'; export default (appInfo: EggAppInfo) => { const config = {} as Partial<EggAppConfig>; config.security = { csrf: { enable: true, headerName: 'x-csrf-token', }, xframe: { enable: true, value: 'SAMEORIGIN', }, }; return config; };
const securityConfig = require('egg-security').config; // Incorrect module access and CJS for TS project
Security configurations are typically defined in `config/config.default.ts` (or `.js`) within the `config.security` object.
Access CSRF Token (Context)
// app/controller/home.ts import { Controller } from 'egg'; class HomeController extends Controller { public async showForm() { const { ctx } = this; ctx.body = ` <html> <body> <form method="POST" action="/submit"> <input type="hidden" name="_csrf" value="${ctx.csrf}" /> <input type="text" name="data" /> <button type="submit">Submit</button> </form> </body> </html> `; } }
import { csrf } from '@eggjs/security'; // CSRF token is context-bound, not a direct import.
The CSRF token is exposed via `ctx.csrf` on the `Context` object, which should be included in non-GET requests.

This quickstart demonstrates how to set up a basic Egg.js application, enable the `@eggjs/security` plugin, configure its CSRF protection, and show how to embed and validate a CSRF token in a simple HTML form using TypeScript.

import { Application, Controller } from 'egg'; // 1. Create a minimal Egg.js application (e.g., in a directory named 'my-egg-app') // Install dependencies: npm init egg --type=ts && npm i @eggjs/security // 2. config/plugin.ts (enable the security plugin) // Note the package name change to @eggjs/security for v4+ export default { static: { enable: true }, // Built-in plugin security: { enable: true, package: '@eggjs/security', }, }; // 3. config/config.default.ts (configure security options) import { EggAppConfig, EggAppInfo } from 'egg'; export default (appInfo: EggAppInfo) => { const config = {} as Partial<EggAppConfig>; // For security reasons, you should change your own keys. config.keys = appInfo.name + '_123456'; config.security = { csrf: { enable: true, headerName: 'x-csrf-token', // Common header for AJAX requests // rotateWhenInvalid: true, // Example of another CSRF option }, xframe: { enable: true, value: 'SAMEORIGIN', }, // More security configurations (e.g., xss, ssrf, csp) can be added here }; return config; }; // 4. app/controller/home.ts (example controller using CSRF) export default class HomeController extends Controller { public async showForm() { const { ctx } = this; ctx.body = ` <html> <head><title>CSRF Test</title></head> <body> <h1>Submit Data with CSRF</h1> <form method="POST" action="/submit"> <input type="hidden" name="_csrf" value="${ctx.csrf}" /> <label for="data">Data:</label> <input type="text" id="data" name="data" required /> <button type="submit">Submit</button> </form> <p>Your CSRF Token: <code>${ctx.csrf}</code></p> </body> </html> `; } public async submitData() { const { ctx } = this; // If CSRF check fails, Egg.js will automatically throw a 403 error ctx.body = `Data received: ${ctx.request.body.data || 'No data'}. Token Validated!`; } } // 5. app/router.ts export default (app: Application) => { const { router, controller } = app; router.get('/', controller.home.showForm); router.post('/submit', controller.home.submitData); }; // To run this: // 1. mkdir my-egg-app && cd my-egg-app // 2. npm init egg --type=ts // 3. npm i @eggjs/security // 4. Copy the code above into the respective files (plugin.ts, config.default.ts, app/controller/home.ts, app/router.ts) // 5. npm run dev // 6. Open http://localhost:7001 in your browser.
Debug
Known issues
breakingThe package name for `egg-security` was officially changed to `@eggjs/security` starting from version 4.0.0. Upgrading from v3.x to v4.x requires updating your `package.json` dependencies and `config/plugin.ts` (or `.js`) to use the new scoped package name.
fix
In `package.json`, change `"egg-security": "^3.x.x"` to `"@eggjs/security": "^4.x.x"`. In `config/plugin.ts` (or `.js`), update `package: 'egg-security'` to `package: '@eggjs/security'`.
affects: >=4.0.0
breakingVersion 4.0.0 of `@eggjs/security` drops support for Node.js versions older than 18.19.0. Running the plugin on unsupported Node.js versions will lead to errors.
fix
Upgrade your Node.js environment to version 18.19.0 or newer to ensure compatibility.
affects: >=4.0.0
breakingThe codebase for `@eggjs/security` was migrated to TypeScript in version 4.0.0. While compiled JavaScript is provided, projects written in plain JavaScript might encounter subtle changes in behavior or require adjustments if relying on specific internal structures that changed during the migration, especially regarding configuration types.
fix
For TypeScript projects, ensure `tsconfig.json` is correctly configured. For JavaScript projects, be aware of potential changes and review the documentation for any new configuration patterns or type-related impacts.
affects: >=4.0.0
gotchaCSRF protection is enabled by default and requires including the CSRF token in all non-GET requests (POST, PUT, DELETE). Failing to do so will result in a 403 Forbidden error.
fix
For form submissions, include `<input type="hidden" name="_csrf" value="${ctx.csrf}" />`. For AJAX requests, send the token in a header (e.g., `X-CSRF-Token`) or as a body parameter (e.g., `_csrf`). The token can be accessed via `ctx.csrf`.
affects: *
gotchaServer-Side Request Forgery (SSRF) protection is provided via `ctx.safeCurl`, `app.safeCurl`, and `agent.safeCurl`. Direct use of `ctx.curl` without proper URL validation can expose your application to SSRF vulnerabilities, even with the plugin enabled.
fix
Always use `ctx.safeCurl` (or `app.safeCurl`/`agent.safeCurl`) for making HTTP requests to external or user-provided URLs. Configure `security.ssrf.hostnameExceptionList` for explicitly whitelisting internal hosts if necessary.
affects: *
Errors
Common errors & fixes
Error: Cannot find module 'egg-security'
Attempting to use the `egg-security` package name after upgrading to Egg.js v4, where the plugin was renamed to `@eggjs/security`.
fix
Update your `package.json` to depend on `@eggjs/security` and adjust `config/plugin.ts` (or `.js`) to use `package: '@eggjs/security'`. Then run `npm install`.
Error: CSRF token mismatch
A non-GET request (e.g., POST, PUT) was made without a valid CSRF token, or the token provided did not match the server-generated one.
fix
Ensure that the CSRF token (obtained from `ctx.csrf`) is included in your form submissions (as a hidden field `_csrf`) or AJAX requests (e.g., in the `X-CSRF-Token` header).
TypeError: Cannot read properties of undefined (reading 'csrf')
Attempting to access `ctx.csrf` when the security plugin is not enabled or not properly configured in `config/plugin.ts`.
fix
Verify that `config/plugin.ts` (or `.js`) explicitly enables the security plugin: `security: { enable: true, package: '@eggjs/security' }`. Also ensure Egg.js is initialized correctly.
Error: Node.js v16.x is not supported by @eggjs/security@4.x
Running `@eggjs/security` version 4.0.0 or higher on an unsupported Node.js version (below 18.19.0).
fix
Upgrade your Node.js runtime to version 18.19.0 or higher. You can use a Node Version Manager (NVM) to manage multiple Node.js versions.
SecurityWarning: SSRF detected, URL 'http://127.0.0.1:8080/internal' is forbidden
An HTTP request was made to an internal or blacklisted IP address/domain using `ctx.safeCurl` (or `app.safeCurl`/`agent.safeCurl`) without explicitly whitelisting it.
fix
If the URL is legitimate, configure `config.security.ssrf.hostnameExceptionList` or `checkAddress` to explicitly allow access to that hostname or IP. Avoid using `ctx.curl` for external or user-provided URLs.
Upgrade
Version history
3.7.0latest on npm
Audit
Dependencies
eggrequiredPeer dependency as an Egg.js framework plugin.
@eggjs/iprequiredInternal IP utility for security checks, replaced `ip` package in v3.3.1.
Agent activity
18 hits · last 30 days
node
16
Amazon
1
OpenAI (training)
1
Resources
egg-security — npm install egg-security · libregistry