Language: TypeScript
Label: safe
CWE: CWE-352 \u2014 Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.

Code:
    secret: 'a'.repeat(32),
    cookie: { path: '/', secure: false }
  })
  await fastify.register(fastifyCsrf, {
    sessionPlugin: '@fastify/session',
    getUserInfo (req) {
      return req.session.username
    },
    csrfOpts: {
      hmacKey: 'foo'
    }
  })

  fastify.post('/login', async (req, reply) => {
    req.session.username = req.body.username
    const token = await reply.generateCsrf({ userInfo: req.body.username })
    return { token }
  })

  // must be preHandler as we are parsing the body
  fastify.post('/', { preHandler: fastify.csrfProtection }, async (req, reply) => {
    return req.body
  })

  const response1 = await fastify.inject({
    method: 'POST',
    path: '/login',
    body: {
      username: 'foo'
    }
  })

  t.equal(response1.statusCode, 200)

  const cookie1 = response1.cookies[0]
  const { token } = response1.json()

  const response2 = await fastify.inject({
    method: 'POST',
    path: '/',
    cookies: {
      sessionId: cookie1.value
    },
    body: {
      _csrf: token,
      username: 'foo'
    }
  })

  t.equal(response2.statusCode, 200)
})