helmetjs / helmet

Help secure Express apps with various HTTP headers

Home Page:https://helmetjs.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cannot extract type for ContentSecurityPolicyOptions

judithhartmann opened this issue · comments

With the changes in the type export from version 6.2 onwards, i do not find a way to correctly type our ContentSecurityPolicyOptions

I have tried the following workarounds:

// #1
type ContentSecurityPolicyOptions = Parameters<typeof helmet.contentSecurityPolicy>[0];

// #2
type ContentSecurityPolicyOptions = Extract<HelmetOptions['contentSecurityPolicy'], object>

// #3
type ContentSecurityPolicyOptions = HelmetOptions["contentSecurityPolicy"];

All of them result in a TS4023 Error:
Exported variable 'defaultPolicies' has or is using name 'ContentSecurityPolicyOptions' from external module "[PROJECT_PATH]/node_modules/helmet/index" but cannot be named.

import { HelmetOptions } from "helmet";
export type ContentSecurityPolicyOptions =
  HelmetOptions['contentSecurityPolicy'];

const defaultPolicies = {
  directives: {
    'default-src': ["'self'"],
    'script-src': [
      "'self'",
    ],
    'connect-src': [
      "'self'",
    ],
    'manifest-src': ["'self'"],
    'img-src': ["'self'"],
    'style-src': ["'self'"],
    'object-src': ["'none'"],
    'font-src': ["'self'"],
  },
} as ContentSecurityPolicyOptions;

export default defaultPolicies;

Typescript version: 4.9.5

As soon as an export is added to ContentSecurityPolicyOptions within the index.ts of helmet , this solution starts to work

ok.. now i found a workaround, when not using the as syntax it works

export type ContentSecurityPolicyOptions =
  HelmetOptions['contentSecurityPolicy'];
  
const defaultPolicies: ContentSecurityPolicyOptions = {
}

export default defaultPolicies

i would still prefer importing the type directly from helmet, as now we need to either

  1. put the workaround everywhere we use it
  2. put the workaround at a central place in our repo and import it from there

which it both more effort than just using it from helmet directly.