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

presets for CSP directives #43

Open
nibtime opened this issue Jul 10, 2022 · 0 comments
Open

presets for CSP directives #43

nibtime opened this issue Jul 10, 2022 · 0 comments
Labels
enhancement New feature or request

Comments

@nibtime
Copy link
Owner

nibtime commented Jul 10, 2022

Moitivation

In work projects I always use setups for the follwing services:

  • DatoCMS for Content Management
  • Vercel for Deployment
  • Sentry for Monitoring
  • Stripe for Payment
  • Algolia for Search

So basically I copy&paste the CSP directives required for those to work from project to project. To avoid that I thought it could be good idea if the lib shipped reusable and stackable presets for common services

Rough design

// presets.ts
import type { NextRequest } from 'next/server'
import type { CspDirectives} from './types'
import { isPreviewModeRequest } from './matchers'

// different preset directives based on request data and dev mode
type PresetCfg = {
  req: NextRequest
  isDev: boolean
}

type Preset = (cfg: PresetCfg) => CspDirectives

const default: Preset = () => {
   return {
    "default-src": ['self'],
    "object-src" : ['none'],
    "base-uri": ['none'],
   }
}

const nextjs: Preset = ({ isDev }) => {
   return {
    "script-src": isDev ? ['self', 'unsafe-inline', 'unsafe-eval'] : []
    "style-src": isDev ? ['self', 'unsafe-inline'] : []
   }
}

const datocms: Preset = ({ req, isDev }) => {
   return {
    "connect-src": isDev || isPreviewModeRequest(req) ? ['https://api.datocms.com'] : []
    "img-src": ['https://datocms-assets.com']
   }
}

const presets = {
  default,
  nextjs,
  datocms,  
}

type CspPresets = keyof typeof presets
// middleware.js
import { chainMatch, isPageRequest, csp, strictDynamic } from '@next-safe/middleware';

const securityMiddleware = [
  csp({
    // stackable presets
    presets: ['default', 'nextjs', 'datocms'],
    // custom directives on top of presets
    directives: {
      'img-src': ['self', 'data:', 'https://images.unsplash.com'],
      'font-src': ['self', 'https://fonts.gstatic.com'],
    },
  }),
  strictDynamic(),
];

export default chainMatch(isPageRequest)(...securityMiddleware);
})
@nibtime nibtime added the enhancement New feature or request label Jul 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant