Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enabling CSP protection with koa + @koa/helmet causes 404 error #303

Open
leandroruel opened this issue Apr 15, 2024 · 0 comments
Open

Enabling CSP protection with koa + @koa/helmet causes 404 error #303

leandroruel opened this issue Apr 15, 2024 · 0 comments

Comments

@leandroruel
Copy link

i was following one of examples from koa repository to CSP but in koa instead of express. but it causes a 404 error Not Found and don't give me any more information.

my code:

import Koa from 'koa'
import logger from 'koa-logger'
import helmet from 'koa-helmet'
import cors from '@koa/cors'
import bodyParser from 'koa-bodyparser'
import {
  getGraphQLParameters,
  processRequest,
  renderGraphiQL,
  shouldRenderGraphiQL,
  sendResult
} from 'graphql-helix'
import Mongoose from 'mongoose'
import { schema } from './graphql/schema'
import router from './routes'
import { MONGODB_USERNAME, MONGODB_PASSWORD, MONGODB_URL } from './config'
import { randomBytes } from 'crypto'
import { formatGraphQLResult } from '@/helpers/errors'

const app = new Koa()

// Middlewares
app.use(logger())

app.use(
  cors({
    origin: '*',
    allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],
    exposeHeaders: ['X-Request-Id']
  })
)

// Routes
app.use(router.routes())
app.use(router.allowedMethods())

// Body parser
app.use(bodyParser())

// Database
const mongooseOptions = {
  user: MONGODB_USERNAME,
  pass: MONGODB_PASSWORD
}

Mongoose.connect(MONGODB_URL, mongooseOptions)

app.use(async (ctx, next) => {
  ctx.state.contentSecurityPolicyNonce = randomBytes(16).toString('hex')
  await next()
})

app.use(async (ctx, next) => {
  helmet({
    contentSecurityPolicy: {
      directives: {
        'default-src': ["'self'"],
        'script-src': [
          "'self'",
          'data:',
          `'nonce-${ctx.state.contentSecurityPolicyNonce}'`
        ]
      }
    }
  })
})

// GraphQL
app.use(async (ctx) => {
  const request: any = {
    body: ctx.request.body,
    headers: ctx.req.headers,
    method: ctx.request.method,
    query: ctx.request.query
  }

  if (shouldRenderGraphiQL(request)) {
    ctx.body = renderGraphiQL({ nonce: ctx.state.contentSecurityPolicyNonce })
  } else {
    const { operationName, query, variables } = getGraphQLParameters(request)

    const result = await processRequest({
      operationName,
      query,
      variables,
      request,
      schema
    })

    ctx.respond = false
    sendResult(result, ctx.res, formatGraphQLResult)
  }
})

export default app
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant