/prismy-csrf

:shield: CSRF Protection for Prismy (WIP)

Primary LanguageTypeScript

prismy-csrf

🛡️ CSRF Protection for prismy

Build Status codecov NPM download Language grade: JavaScript

npm i prismy-csrf

Example

import {
  prismy,
  Context,
  createInjectDecorators,
  createTextBodySelector,
  UrlEncodedBody
} from 'prismy'
import createCSRFProtection from 'prismy-csrf'
import JWTCSRFStrategy from 'prismy-csrf-strategy-jwt'
import querystring from 'querystring'

const { CSRFToken, CSRFMiddleware } = createCSRFProtection(
  new JWTCSRFStrategy({
    secret: 'RANDOM_HASH',
    tokenSelector: (context: Context) => {
      const body = createUrlEncodedBodySelector()(context)
      return body._csrf
    }
  })
)

class MyHandler extends BaseHandler {
  async handle(@CSRFToken() csrfToken: string) {
    return [
      '<!DOCTYPE html>',
      '<body>',
      '<form action="/" method="post">',
      '<input name="message">',
      `<input type="hidden" name="_csrf" value=${csrfToken}>`,
      '<button type="submit">Send</button>',
      '</form>',
      '</body>'
    ].join('')
  }
}

export default prismy([CSRFMiddleware, MyHandler])