@csrf-armor/express
Version:
Express.js adapter for CSRF Armor - Advanced CSRF protection for Express.js applications
1 lines • 4.37 kB
Source Map (JSON)
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import {\n type CsrfConfig,\n CsrfError,\n createCsrfProtection,\n} from '@csrf-armor/core';\nimport type express from 'express';\nimport { ExpressAdapter } from './adapter.js';\n\nexport type { ExpressAdapter };\n\n/**\n * Creates Express middleware that enforces CSRF protection on incoming requests.\n *\n * This middleware automatically validates CSRF tokens on state-changing requests\n * (POST, PUT, DELETE, etc.) while allowing safe methods (GET, HEAD, OPTIONS) to pass through.\n * It integrates seamlessly with Express applications and provides comprehensive CSRF protection.\n *\n * **Behavior:**\n * - For safe methods (GET, HEAD, OPTIONS): Generates and sets CSRF tokens, calls `next()`\n * - For state-changing methods: Validates CSRF tokens, calls `next()` on success or throws on failure\n * - Attaches `req.csrfToken` property containing the current CSRF token for use in views/responses\n * - Respects `excludePaths` configuration to skip protection for specified routes\n * - Handles multiple token sources: headers, cookies, query parameters, and request body\n *\n * **Token Sources (in order of precedence):**\n * 1. HTTP headers (e.g., `X-CSRF-Token`)\n * 2. Cookies (for double-submit strategies)\n * 3. URL query parameters\n * 4. Request body (form data or JSON)\n *\n * @public\n * @param config - Optional CSRF protection configuration (uses secure defaults if not provided)\n * @returns Express middleware function that validates CSRF tokens and manages token lifecycle\n *\n * @throws {CsrfError} If CSRF token validation fails, with code `'CSRF_VERIFICATION_ERROR'`\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { csrfMiddleware } from '@csrf-armor/express';\n *\n * const app = express();\n *\n * // Basic usage with default configuration\n * app.use(csrfMiddleware());\n *\n * // Custom configuration\n * app.use(csrfMiddleware({\n * strategy: 'signed-double-submit',\n * secret: process.env.CSRF_SECRET,\n * excludePaths: ['/api/public', '/webhook'],\n * allowedOrigins: ['https://yourdomain.com'],\n * cookie: {\n * name: 'csrf-token',\n * secure: process.env.NODE_ENV === 'production',\n * httpOnly: false, // Allow client-side access for SPA\n * sameSite: 'strict'\n * }\n * }));\n *\n * // Access token in route handlers\n * app.get('/form', (req, res) => {\n * res.render('form', {\n * csrfToken: req.csrfToken // Available after middleware runs\n * });\n * });\n *\n * // Error handling\n * app.use((err, req, res, next) => {\n * if (err.code === 'CSRF_VERIFICATION_ERROR') {\n * res.status(403).json({ error: 'CSRF token validation failed' });\n * } else {\n * next(err);\n * }\n * });\n * ```\n *\n * @example\n * ```typescript\n * // Integration with different strategies\n *\n * // Double-submit strategy (good for SPAs)\n * app.use(csrfMiddleware({\n * strategy: 'double-submit',\n * cookie: { httpOnly: false } // Allow client JS access\n * }));\n *\n * // Origin-check strategy (simple, less robust)\n * app.use(csrfMiddleware({\n * strategy: 'origin-check',\n * allowedOrigins: ['https://app.example.com', 'https://admin.example.com']\n * }));\n *\n * // Hybrid strategy (maximum security)\n * app.use(csrfMiddleware({\n * strategy: 'hybrid',\n * secret: 'your-secret-key'\n * }));\n * ```\n */\nexport function csrfMiddleware(config?: CsrfConfig) {\n const adapter = new ExpressAdapter();\n const protection = createCsrfProtection(adapter, config);\n\n return async (\n req: express.Request,\n res: express.Response,\n next: express.NextFunction\n ) => {\n const result = await protection.protect(req, res);\n\n if (result.success) {\n req.csrfToken = result.token ?? undefined;\n next();\n } else {\n throw new CsrfError(\n result.reason ?? 'CSRF: Token validation failed.',\n 'CSRF_VERIFICATION_ERROR'\n );\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,SAAgB,eAAe,QAAqB;CAElD,MAAM,aAAa,qBADH,IAAI,gBAAgB,EACa,OAAO;AAExD,QAAO,OACL,KACA,KACA,SACG;EACH,MAAM,SAAS,MAAM,WAAW,QAAQ,KAAK,IAAI;AAEjD,MAAI,OAAO,SAAS;AAClB,OAAI,YAAY,OAAO,SAAS;AAChC,SAAM;QAEN,OAAM,IAAI,UACR,OAAO,UAAU,kCACjB,0BACD"}