GithubHelp home page GithubHelp logo

csrf-protection's Introduction

CI Package Manager CI Web SIte js-standard-style CII Best Practices

NPM version NPM downloads Security Responsible Disclosure Discord Contribute with Gitpod Open Collective backers and sponsors


An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the resources of your server, knowing that you are serving the highest number of requests as possible, without sacrificing security validations and handy development?

Enter Fastify. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.

The main branch refers to the Fastify v4 release. Check out the v3.x branch for v3.

Table of Contents

Quick start

Create a folder and make it your current working directory:

mkdir my-app
cd my-app

Generate a fastify project with npm init:

npm init fastify

Install dependencies:

npm i

To start the app in dev mode:

npm run dev

For production mode:

npm start

Under the hood npm init downloads and runs Fastify Create, which in turn uses the generate functionality of Fastify CLI.

Install

To install Fastify in an existing project as a dependency:

Install with npm:

npm i fastify

Install with yarn:

yarn add fastify

Example

// Require the framework and instantiate it

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

// Declare a route
fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

with async-await:

// ESM
import Fastify from 'fastify'
const fastify = Fastify({
  logger: true
})
// CommonJs
const fastify = require('fastify')({
  logger: true
})

fastify.get('/', async (request, reply) => {
  reply.type('application/json').code(200)
  return { hello: 'world' }
})

fastify.listen({ port: 3000 }, (err, address) => {
  if (err) throw err
  // Server is now listening on ${address}
})

Do you want to know more? Head to the Getting Started.

Note

.listen binds to the local host, localhost, interface by default (127.0.0.1 or ::1, depending on the operating system configuration). If you are running Fastify in a container (Docker, GCP, etc.), you may need to bind to 0.0.0.0. Be careful when deciding to listen on all interfaces; it comes with inherent security risks. See the documentation for more information.

Core features

  • Highly performant: as far as we know, Fastify is one of the fastest web frameworks in town, depending on the code complexity we can serve up to 76+ thousand requests per second.
  • Extensible: Fastify is fully extensible via its hooks, plugins and decorators.
  • Schema based: even if it is not mandatory we recommend to use JSON Schema to validate your routes and serialize your outputs, internally Fastify compiles the schema in a highly performant function.
  • Logging: logs are extremely important but are costly; we chose the best logger to almost remove this cost, Pino!
  • Developer friendly: the framework is built to be very expressive and help the developer in their daily use, without sacrificing performance and security.

Benchmarks

Machine: EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD.

Method:: autocannon -c 100 -d 40 -p 10 localhost:3000 * 2, taking the second average

Framework Version Router? Requests/sec
Express 4.17.3 14,200
hapi 20.2.1 42,284
Restify 8.6.1 50,363
Koa 2.13.0 54,272
Fastify 4.0.0 77,193
-
http.Server 16.14.2 74,513

Benchmarks taken using https://github.com/fastify/benchmarks. This is a synthetic, "hello world" benchmark that aims to evaluate the framework overhead. The overhead that each framework has on your application depends on your application, you should always benchmark if performance matters to you.

Documentation

中文文档地址

Ecosystem

  • Core - Core plugins maintained by the Fastify team.
  • Community - Community supported plugins.
  • Live Examples - Multirepo with a broad set of real working examples.
  • Discord - Join our discord server and chat with the maintainers.

Support

Please visit Fastify help to view prior support issues and to ask new support questions.

Contributing

Whether reporting bugs, discussing improvements and new ideas or writing code, we welcome contributions from anyone and everyone. Please read the CONTRIBUTING guidelines before submitting pull requests.

Team

Fastify is the result of the work of a great community. Team members are listed in alphabetical order.

Lead Maintainers:

Fastify Core team

Fastify Plugins team

Great Contributors

Great contributors on a specific area in the Fastify ecosystem will be invited to join this group by Lead Maintainers.

Past Collaborators

Hosted by

We are a At-Large Project in the OpenJS Foundation.

Sponsors

Support this project by becoming a SPONSOR! Fastify has an Open Collective page where we accept and manage financial contributions.

Acknowledgements

This project is kindly sponsored by:

Past Sponsors:

This list includes all companies that support one or more of the team members in the maintenance of this project.

License

Licensed under MIT.

For your convenience, here is a list of all the licenses of our production dependencies:

  • MIT
  • ISC
  • BSD-3-Clause
  • BSD-2-Clause

csrf-protection's People

Contributors

58bits avatar arnesfield avatar climba03003 avatar davidcralph avatar delvedor avatar dependabot[bot] avatar droet avatar eomm avatar fdawgs avatar genediazjr avatar github-actions[bot] avatar hobi9 avatar jurca avatar leftiefriele avatar marco-ippolito avatar mcollina avatar mksony avatar salmanm avatar simoneb avatar tarang11 avatar tnovau avatar uzlopak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

csrf-protection's Issues

Bug in type definition

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.23.2

Plugin version

6.4.0

Node.js version

20.9.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

14.1

Description

Hi, when using typescript and trying to register the csrf-protection plugin, i get a compiler error because csrfOpts.hmacKey is not defined even though on the docs and on the javascript code that property is required only if the sessionPlugin is fastify/cookie and csrfOpts.userInfo is truthy.

  if (sessionPlugin === '@fastify/cookie' && csrfOpts.userInfo) {
    assert(csrfOpts.hmacKey, 'csrfOpts.hmacKey is required')
  }

Steps to Reproduce

  await fastify.register(Csrf, {
    sessionPlugin: '@fastify/cookie',
    cookieOpts: {
      signed: true,
    },
  });

Expected Behavior

I would expect to be able to register the plugin without any compiler errors.

Bug with sessionPlugin in NestJS with Fastify

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.17.0

Plugin version

6.3.0

Node.js version

20.0.0

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

The documentation says:

// if you want to sign cookies:
fastify.register(require('@fastify/cookie'), { secret }) // See following section to ensure security
fastify.register(require('@fastify/csrf-protection'), { cookieOpts: { signed: true } })

And when in NestJS 9.4.0 it declares csrf-protection in accordance with the documentation, code below in section "Steps to Reproduce".

Error:

error TS2322: Type '"@fastify/cookie"' is not assignable to type '"@fastify/secure-session"'.
sessionPlugin: '@fastify/cookie', 
error TS2345: Argument of type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyCsrfProtectionOptions>'.
  Type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' is not assignable to type 'RegisterOptions & FastifyCsrfProtectionOptionsBase & 
FastifyCsrfProtectionOptionsFastifySecureSession'.
    Property 'sessionPlugin' is missing in type '{ cookieKey: string; cookieOpts: { httpOnly: true; sameSite: "strict"; path: string; secure: true; signed: false; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'.
await app.register(fastifyCsrf, {
cookieKey: 'csrf-token',
},
});
  node_modules/@fastify/csrf-protection/types/index.d.ts:49:5
sessionPlugin: '@fastify/secure-session';
    'sessionPlugin' is declared here.

Even adding session Plugin and setting the value to '@fastify/cookie' gives an error and giving the value undefined shows that 1 of 3 types must be selected, e.g. @fastify/cookie or @fastify/session. So if it wasn't for the help on Stack, I would still think that I'm doing something wrong and here it turns out that it's a bug in your version, so I was forced to use version 6.2.0 and I would prefer the latest one.

If you need the code of my application, I will add it to the repo so that you can check for yourself that this bug exists :)

Steps to Reproduce

  // XCSRF - Protection
  app.register(fastifyCookie, { secret: 'ddddd' });
  app.register(fastifyCsrf, {
    sessionPlugin: '@fastify/cookie',
    cookieKey: 'csrf-token',
    cookieOpts: {
      httpOnly: true,
      sameSite: 'strict',
      path: '/',
      secure: true,
      signed: false,
    },
  });

Expected Behavior

I expected it to work according to the documentation and as it should after initialization

Signed cookies are not supported

Hello again,

setting the cookie.signed flag true in the options results in fastify-cookie signing the cookies being set by this middleware, however, fastify-csrf does not properly handle reading signed cookies, since they need to be "unsigned" to get to the raw value.

I recommmend adding an if (cookie.signed) { ... } check to the getSecret() function to make this work.

I am willing to submit a PR, if you'd prefer me to do so.

Thank you in advance.

TypeError: Cannot read property 'constructor' of undefined

🐛 Bug Report

"TypeError: Cannot read property 'constructor' of undefined
at Object.addHook (E:\myserver\node_modules\fastify\fastify.js:494:14)

To Reproduce

Steps to reproduce the behavior:

fastify.register(require('fastify-cookie'))
fastify.register(require('fastify-csrf'))
fastify.addHook('onRequest', fastify.csrfProtection)

Your Environment

  • node version: 12
  • fastify version: >=3.14.0
  • os: Windows

how does a cookie protect against CSRF?

If the CSRF token is in a cookie, that means all the data needed to make a request is known to the attacker (just the API call), and the browser adds the session and csrf secrets.

So isn't putting the CSRF token in a cookie pointless?

Invalid csrf token from cookie value

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.9.2

Plugin version

6.0.0

Node.js version

16.13.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

10

Description

I get the error "Invalid csrf token" when submitting a request with an XSRF-TOKEN header containing the value of the signed _csrf cookie.

Steps to Reproduce

Using nest as a framework. I send the CSRF token from login, and add a XSRF-TOKEN header to requests:

In main.ts:

  const adapter = new FastifyAdapter({ logger: true });
  const fastifyInstance = adapter.getInstance();
  const options: NestApplicationOptions = {};
  const app = await NestFactory.create<NestFastifyApplication>(AppModule, adapter, options);

  ...

  await app.register(fastifyCookie, {
    secret: configService.get('COOKIE_SECRET')
  });
  await app.register(fastifyCsrf, {
    cookieOpts: { signed: true },
    getToken: (req: FastifyRequest) => {
      return <string>req.headers['xsrf-token']; // for some reasons I have a type error error
    }
  });

  // Add hook
  fastifyInstance.addHook('onRequest', (request: FastifyRequest, reply: FastifyReply, done: (err?: Error) => void) => {
    if (request.url !== '/api/auth/login' && request.url !== '/api/auth/register') {
      fastifyInstance.csrfProtection(request, reply, done);
    } else {
      done();
    }
  });

In my auth controller (login endpoint):

  @Post('login')
  public async login(...): Promise<...> {
    ...

    const token = response.generateCsrf();
    response.status(HttpStatus.OK).send(ouput);
  }

On any endpoint, after login, I send a request with headers:

...
Cookie: Authorization=YYY; _csrf=XXX // results from login request
XSRF-TOKEN: XXX // taken from cookie _csrf value

And I'm returned with:

{
    "statusCode": 403,
    "code": "FST_CSRF_INVALID_TOKEN",
    "error": "Forbidden",
    "message": "Invalid csrf token"
}

Expected Behavior

There should be no error, the request should succeed (unless there is something I didn't understand?)

httpOnly

Why is not httpOnly set on the coockie? In order to protect against csrf the coockie should not be readable by javascript. How does this lib protect against csrf without this?

I got the error "Invalid token" when submitting a POST request to route registered from a file.

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I got the error "Invalid token" when submitting a POST request to route registered from a file.

fastify.register(indexPost);

This is an example:

https://codesandbox.io/s/fastify-csrf-protection-typescript-ngzpec?file=/index.ts:0-1634
You will see the error when you click submit.

The screenshot:

image

CSRF route protection example given in README not working

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.15.0

Plugin version

6.2.0

Node.js version

18.14.0

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 22.04.2 LTS

Description

I followed the sample code which is in the README. Using cookie version. I called the protected route without generate CSRF token, but as a result I can still access it. That's not what we want.

Steps to Reproduce

  • npm init -y
  • yarn add fastify @fastify/cookie @fastify/csrf-protection
  • Create index.js and add code below
const fastify = require('fastify')({ logger: true });

fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));

// generate a token
fastify.route({
  method: 'GET',
  path: '/',
  handler: async (req, reply) => {
    const token = await reply.generateCsrf();
    return { token };
  },
});

// protect a route
fastify.route({
  method: 'POST',
  path: '/',
  onRequest: fastify.csrfProtection,
  handler: async (req, reply) => {
    return req.body;
  },
});

fastify.listen({ port: 3000 }, function (err, address) {
  if (err) {
    fastify.log.error(err);
    process.exit(1);
  }
});
  • node index.js
  • Call the protected API http://localhost:3000/ using Postman or curl like curl --request POST --url http://localhost:3000/ --header 'content-type: application/json' --data '{ "hello": "world" }'

I'm want to use CommonJS style, not ESM.

Expected Behavior

It should show some kind error like "Missing CSRF token".

Module did not self-register

Error when try to register module

package.json

"@nestjs/platform-fastify": "^7.6.7",
"fastify-cookie": "^5.1.0",
"fastify-csrf": "^3.0.1",

main.ts

import { fastifyCookie } from 'fastify-cookie';
import fastifyCsrf from 'fastify-csrf';

const server = fastify();
await server.register(fastifyCookie);
await server.register(fastifyCsrf, { cookieOpts: { signed: true } });

error

Error: Module did not self-register: '\\?\...\node_modules\libxmljs\build\Release\xmljs.node'.
    at Object.Module._extensions..node (internal/modules/cjs/loader.js:1065:18)       
    at Module.load (internal/modules/cjs/loader.js:879:32)
    at Function.Module._load (internal/modules/cjs/loader.js:724:14)
    at Module.require (internal/modules/cjs/loader.js:903:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at bindings (...\node_modules\bindings\bindings.js:84:48)
    at Object.<anonymous> (...\node_modules\libxmljs\lib\bindings.js:1:37)
    at Module._compile (internal/modules/cjs/loader.js:1015:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
    at Module.load (internal/modules/cjs/loader.js:879:32)

Errors are not handled in the preHandler hook, if you don't throw it

Looking at the code you do return new Error('invalid csrf token'); in the async handleCsrf preHandler hook but looks like this error is never handled by Fastify.

My test:

const fastify = require('fastify')();
fastify.register(require('fastify-cookie'));
fastify.register(require('fastify-formbody'));
fastify.register(require('fastify-csrf'), { cookie: true });

fastify.get('/', async (req, reply) => {
  reply.type('text/html');
  return `<form method="POST" action="/send">
    <input type="hidden" name="_csrf" value="invalid"><input type="submit" /></form>`;
});

/* Fastify should not be able to reach this route, since the CSRF is invalid 
(aka not matching the token set in the cookie).
Unfortunally, it does not throw any errors even if the _csrf cookie is correctly set. */
fastify.post('/send', async (req, reply) => {
  return { hello: 'world' };
});

fastify.listen(3000, err => {
  if (err) throw err;
});

Replacing return new Error('invalid csrf token'); with throw new Error('invalid csrf token') in the lib works, then I can normally handle it with setErrorHandler().

Using fastify 1.13.4, fastify-csrf 1.0.1, fastify-formbody 2.1.0, fastify-cookie 2.1.6

Remarks regarding v6.0.0 release notes

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

I think that after merging #115 we are set to go and can publish next major version.

In the release notes we should note that we updated the used version of @fastify/csrf and that the csrf tokens will be by default sha256 hashed. And if they want to still use sha1 algorithm they will have to add algorithm: 'sha1' to csrfOpts.

I assume that some devs of massively used implementations maybe want to avoid csrf errors in production or have some concerns regarding user experience. So we should inform then to avoid surprises.

@Eomm
@mcollina

Cookie example given in the docs not working

I tried using the same code from the docs but was getting this error

{"statusCode":500,"error":"Internal Server Error","message":"invalid csrf token"}

Logs

{"level":30,"time":1567671488738,"pid":15370,"hostname":"tss-H110M-H","msg":"Server listening at http://127.0.0.1:3000","v":1}
{"level":30,"time":1567671496941,"pid":15370,"hostname":"tss-H110M-H","reqId":1,"req":{"method":"GET","url":"/","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45810},"msg":"incoming request","v":1}
{"level":30,"time":1567671496947,"pid":15370,"hostname":"tss-H110M-H","reqId":1,"res":{"statusCode":200},"responseTime":5.293844999745488,"msg":"request completed","v":1}
{"level":30,"time":1567671504128,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"req":{"method":"POST","url":"/data","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45868},"msg":"incoming request","v":1}
{"level":50,"time":1567671504132,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"req":{"method":"POST","url":"/data","hostname":"localhost:3000","remoteAddress":"127.0.0.1","remotePort":45868},"res":{"statusCode":500},"err":{"type":"Error","message":"invalid csrf token","stack":"Error: invalid csrf token\n    at Object.handleCsrf (/home/tss/csrf-test/node_modules/fastify-csrf/lib/fastifyCsrf.js:28:10)\n    at hookIterator (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:124:10)\n    at next (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:70:20)\n    at hookRunner (/home/tss/csrf-test/node_modules/fastify/lib/hooks.js:84:3)\n    at preValidationCallback (/home/tss/csrf-test/node_modules/fastify/lib/handleRequest.js:93:5)\n    at handler (/home/tss/csrf-test/node_modules/fastify/lib/handleRequest.js:70:5)\n    at done (/home/tss/csrf-test/node_modules/fastify/lib/contentTypeParser.js:115:7)\n    at Parser.contentParser [as fn] (/home/tss/csrf-test/node_modules/fastify-formbody/formbody.js:10:5)\n    at IncomingMessage.onEnd (/home/tss/csrf-test/node_modules/fastify/lib/contentTypeParser.js:185:25)\n    at IncomingMessage.emit (events.js:203:15)"},"msg":"invalid csrf token","v":1}
{"level":30,"time":1567671504133,"pid":15370,"hostname":"tss-H110M-H","reqId":2,"res":{"statusCode":500},"responseTime":4.723324000835419,"msg":"request completed","v":1}

Code

const fastify = require("fastify")({ logger: true });
const fastifyCookie = require("fastify-cookie");
const fastifyFormBody = require("fastify-formbody");
const fastifyCSRF = require("fastify-csrf");

fastify.register(fastifyCookie);
fastify.register(fastifyFormBody);
fastify.register(fastifyCSRF, { cookie: true });

fastify.get("/", (request, reply) => {
  var form = `
      <form method = "post" action="/data">
         <input type="text" name"field_name"/>
         <input type="hidden" value="${request.csrfToken()}" 
     name="_csrf /* this token can be sent in request header as well */"/>
         <button type="submit">Submit</button>
      </form>
    `;
  reply.type("text/html").send(form);
});

fastify.post("/data", (request, reply) => {
  reply.send("Post successful");
});

fastify.listen(3000, err => {
  if (err) {
    process.exit(0);
  }
});

Use tokens.secretSync instead of .secret

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the feature has not already been requested

🚀 Feature Proposal

Use .secretSync() instead of .secret() to generate the secret.

Motivation

secretSync is 4-5 times faster than .secret(). secret and secretSync are basically wrappers for crypto.randomBytes(secretLength).toString('base64url'). And when we compare to calls of randomBytes throughout the fastify ecosystem, then we can see that we use the "sync" call of randomBytes

see:
https://github.com/fastify/fastify-helmet/blob/b341c6879897c25f6fe3dbd0c7ae239760ed70d0/index.js#L83

So I assume we should call secretSync for better performance.

Example

No response

Typescript definitions not working

Hi there,
I tried to use this module with the provided typescript definitions and got

Argument of type '<HttpServer = any, HttpRequest = any, HttpResponse = any>(opts?: Options<HttpRequest> | undefined) => Plugin<HttpServer, HttpRequest, HttpResponse>' is not assignable to parameter of type '(instance: FastifyInstance<Server, IncomingMessage, ServerResponse>, options: { cookie: boolean; }, callback: (err?: FastifyError | undefined) => void) => void'.
  Types of parameters 'opts' and 'instance' are incompatible.

when using it via

server.register(fastifyCsrf, {cookie: true});

what actually worked for me are the following typings:

import {IncomingMessage, Server, ServerResponse} from "http";
import * as fastify from "fastify";
import {Options as TokenOptions} from "csrf";

declare module "fastify" {
    interface FastifyRequest {
        csrfToken(): string;
    }
}

interface Options<HttpRequest> extends TokenOptions {
    value?: (req: HttpRequest) => string;
    cookie?: fastify.CookieSerializeOptions | boolean;
    ignoreMethods?: Array<string>;
    sessionKey?: string;
}

declare const fastifyCsrf: fastify.Plugin<
    Server,
    IncomingMessage,
    ServerResponse,
    Options<ServerResponse>
>;

export = fastifyCsrf;

Would you accept a PR for this change? Or is there another way to make it work?

firefox mobile invalid csrf

Hi, I am getting "invalid csrf token" only in Firefox mobile (android device) with session storage configured. Verified _crsf value field is set in the form body.

2020-06-29T02:49:09.916098+00:00 app[web.1]: _csrf: 'T3j4XGw1-iP7JwuRT1lXlFcRyjdHF_kvVMRo'

(Works fine on Firefox Desktop and Chrome mobile/desktop)

Here is the server error:

{
2020-06-29T02:49:09.917542+00:00 app[web.1]: ServerError: Error: invalid csrf token
2020-06-29T02:49:09.917544+00:00 app[web.1]: at Object.handleCsrf (/app/node_modules/fastify-csrf/lib/fastifyCsrf.js:36:10)
2020-06-29T02:49:09.917544+00:00 app[web.1]: }

Do not mix callback and async/await

As an example this https://github.com/Tarang11/fastify-csrf/blob/master/lib/fastifyCsrf.js#L20-L31:

	async function handleCsrf(request, reply, done) {
		var secret = getSecret(request, cookie);
		// cookie for csrf token not set.
		if(!secret) {
			secret = await tokens.secret();
			setSecret(request, reply, secret, cookie);
		}
		if(ignoreMethods.indexOf(request.req.method) < 0 && !tokens.verify(secret, tokenIdentifier(request))) {
			return done(new Error('invalid csrf token'));
		}
		done();
	}

Could be rewritten as:

	async function handleCsrf(request, reply) {
		var secret = getSecret(request, cookie);
		// cookie for csrf token not set.
		if(!secret) {
			secret = await tokens.secret();
			setSecret(request, reply, secret, cookie);
		}
		if(ignoreMethods.indexOf(request.req.method) < 0 && !tokens.verify(secret, tokenIdentifier(request))) {
			throw new Error('invalid csrf token');
		}
	}

Property 'sessionPlugin' is missing in type '{ cookieOpts: { signed: true; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

8.2.1

Plugin version

6.3.0

Node.js version

16.13.2

Operating system

Windows

Operating system version (i.e. 20.04, 11.3, 10)

11

Description

app.register(fastifyCsrfProtection, { cookieOpts: { signed: true } }) 

Typescript is throwing the following error:

Argument of type '{ cookieOpts: { signed: true; }; }' is not assignable to parameter of type 'FastifyRegisterOptions<FastifyCsrfProtectionOptions>'.
  Type '{ cookieOpts: { signed: true; }; }' is not assignable to type 'RegisterOptions & FastifyCsrfProtectionOptionsBase & FastifyCsrfProtectionOptionsFastifySecureSession'.
    Property 'sessionPlugin' is missing in type '{ cookieOpts: { signed: true; }; }' but required in type 'FastifyCsrfProtectionOptionsFastifySecureSession'.

Steps to Reproduce

prepare a project with NestJs and Fastify. then use the @fastify/cookie with @fastify/csrf-protection.

in the mean file include:

     app.register(fastifyCookie, {
        secret: configService.get<string>('COOKIE_SECRET')
    })

    app.register(fastifyHelmet)

    app.register(fastifyCsrfProtection, { cookieOpts: { signed: true } })

Expected Behavior

not to see such an error. according to you the documentation adding { cookieOpts: { signed: true } } as second parameter should be sufficient.

FastifyCsrfProtectionOptionsFastifySecureSession is defined in fastifyCsrfProtection . as the following:

interface FastifyCsrfProtectionOptionsFastifySecureSession {
    sessionPlugin: '@fastify/secure-session';
    csrfOpts?: CSRFOptions;
  }

as sessionPlugin has already a default value of '@fastify/secure-session'. shouldn't it be optional in the definition ??

Method `generateCsrf` return type should be a `string` instead of `FastifyReply`

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.13.0

Plugin version

6.1.0

Node.js version

18.14.2

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

Ubuntu 22.04.2 LTS

Description

The return type of the decorated generateCsrf method is FastifyReply:

generateCsrf(
options?: fastifyCsrfProtection.CookieSerializeOptions
): FastifyReply;

Looking at the code, the generateCsrf methods return tokens.create() which is a string.

Not a big issue as the token is almost always returned or used in reply.send(), but it would be nice to have the type fixed.

Steps to Reproduce

Example:

const fastify = require('fastify')();

fastify.register(require('@fastify/cookie'));
fastify.register(require('@fastify/csrf-protection'));

fastify.get('/', (_, reply) => {
  const token = reply.generateCsrf();
  const type = typeof token;
  console.log('token type:', type); // type is 'string'
  return { token, type };
});

fastify.listen().then(address => {
  console.log('listening on', address);
});

The value of typeof token is string but the token type (hovering in VSCode) is FastifyReply.

Expected Behavior

Return type of generateCsrf method should be a string instead of FastifyReply.

Disable CSRF Token Reuse

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the issue has not already been raised

Issue

Thanks for this great plug in.

I have one concern. Save CSRF token I can use multiple time for the verification. Is there any option where I can make sure that token is used only once.

`req.body` is undefined

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Fastify version

4.13.0

Plugin version

6.1.0

Node.js version

18.13.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

13

Description

Hello,

I am trying to put the csrf token to be part of the input form (Similar to this), but it seems that the getToken() function fail in getting the token out from the body.

From the docs, it seems to be possible to do so.

I tried to print the body and it seems to have an undefined value.

      fastify.register(fastifyCsrfProtection, {
        sessionPlugin: "@fastify/secure-session",
        getToken: (req) => {
          console.log("the body", req.body);
          return "TEMP_TOKEN";
        },
      });

I am wondering if the middleware mentioned here is relevant to the undefined value.

Steps to Reproduce

  1. Setup a Fastify Server with the fastifyCsrfProtection enabled with the default config of getToken()
  2. From the FE, submit a that includes _csrf token as a hidden input.
  3. Submit the form and invalid csrf token error was thrown (InternalServerError), same token works if it is put in the header.

Expected Behavior

No Invalid csrf-token error thrown.

Move to the Fastify org

Hello! Tomas here, one of the maintainers of Fastify :)
Thank you for building this plugin!
We think this is very valuable, and we would love to have it inside our GitHub org, so we can offer official support for csrf.
Would you like to transfer this repository to https://github.com/fastify?
You will keep admin rights, and we'll help you out maintaining the plugin. We would also need publish access on npm.
Let me know what you think, thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.