1.0.0 • Published 8 months ago

@lock-sdk/csrf v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

🛡️ CSRF Protection

A robust and flexible Cross-Site Request Forgery (CSRF) protection module for the Lock Security Framework. Supports token generation, header/cookie/session validation, double-submit patterns, and pluggable storage backends.

🚀 Features

  • 🔐 Supports token validation via cookie, header, session, or combo
  • ✌️ Double-submit cookie + header validation
  • 🧠 Smart auto-ignore for GET, OPTIONS, and form uploads
  • 🍪 Custom cookie options with secure, SameSite, and domain control
  • 🔄 Optional token refresh on every request
  • 📦 Pluggable token stores: memory or Redis
  • ⚙️ Fine-grained config for ignored methods, paths, content-types

🛠 Usage

Basic Middleware (Cookie + Header)

import { secure, csrfProtection } from '@lock-sdk/main';

const middleware = secure()(
  csrfProtection({
    enabled: true,
    tokenLocation: 'cookie-header',
    doubleSubmit: true,
  })
);

⚙️ Configuration

OptionTypeDefaultDescription
enabledbooleantrueToggle protection
tokenNamestring'csrf-token'Token name (used in cookie/header/session)
tokenLengthnumber32Length of generated token
headerNamestring'x-csrf-token'Header to check when using header or cookie-header
cookieNamestring'csrf-token'Cookie name for token (if applicable)
cookieOptionsCookieOptionsSee belowCustomization for Set-Cookie
storage'memory' | 'redis''memory'Backend for token persistence
tokenLocation'cookie' | 'header' | 'cookie-header' | 'session''cookie-header'Where to expect/return token
ignoredMethodsstring[]['GET','HEAD','OPTIONS']Skip token check for these methods
ignoredPaths(string \| RegExp)[][]Skip token check for these routes
ignoredContentTypesstring[]['multipart/form-data']Skip check for uploads
failureStatusCodenumber403Response status on failure
failureMessagestring'CSRF token validation failed'Response message
refreshTokenbooleantrueRegenerate token on each request
tokenTtlnumber (seconds)86400 (24hr)Expiry duration for stored tokens
doubleSubmitbooleantrueEnforce cookie + header match
samesitebooleantrueApply SameSite cookie flags
redisOptionsRedisOptionsRedis connection settings
customStorageTokenStorageProviderProvide your own storage logic
includeFormTokenboolean(Coming soon) Inject token into forms
angularCompatibleboolean(Coming soon) Support Angular's $http token style

🍪 Cookie Options

cookieOptions: {
  httpOnly: false,
  secure: true,
  sameSite: 'lax',
  path: '/',
  domain: 'example.com',
  maxAge: 3600,
}

📡 Token Sources

LocationDescription
cookieToken is read from a cookie
headerToken is sent via header (x-csrf-token by default)
cookie-headerToken must be in both header and cookie (double-submit)
sessionToken is stored in req.sessiontokenName

📛 Event Types

Event CodeDescription
csrf.token.missingToken was not found in the request
csrf.token.invalidToken did not validate
csrf.double.submit.failureCookie and header token mismatch
csrf.validatedRequest passed CSRF validation
csrf.errorUnhandled exception in CSRF logic

🧩 Storage Backends

Memory (default)

storage: 'memory',
tokenTtl: 86400

Redis

storage: 'redis',
redisOptions: {
  url: 'redis://localhost:6379',
  password: 'secret',
  keyPrefix: 'csrf:',
}

🛡 Maintained By

Lock Team

1.0.0

8 months ago

0.1.0

8 months ago