Skip to content
Myr

refactor: secure headers middleware (#2039)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Aris Kemper · committed by GitHub · parent 0800acc · Browse files · 2 files+88 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+88 added−56 removed

  • other:+88 added−56 removed

2 files+88 added−56 removed

modified:deno_dist/middleware/secure-headers/index.ts+44 added-28 removed
modified:src/middleware/secure-headers/index.ts+44 added-28 removed
1import type { Context } from '../../context'2import type { MiddlewareHandler } from '../../types'34interface ContentSecurityPolicyOptions {5 defaultSrc?: string[]
90 unmodified lines
96}9798export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => {99 const options = { ...DEFAULT_OPTIONS, ...customOptions }99 const headersToSet = Object.entries(HEADERS_MAP)100 .filter(([key]) => options[key as keyof SecureHeadersOptions])101 .map(([key, defaultValue]) => {102 const overrideValue = options[key as keyof SecureHeadersOptions]103 if (typeof overrideValue === 'string') return [defaultValue[0], overrideValue]104 return defaultValue105 })100 const headersToSet = getFilteredHeaders(options)101102 if (options.contentSecurityPolicy) {108 const cspDirectives = Object.entries(options.contentSecurityPolicy)109 .map(([directive, value]) => {110 // convert camelCase to kebab-case directives (e.g. `defaultSrc` -> `default-src`)111 directive = directive.replace(112 /[A-Z]+(?![a-z])|[A-Z]/g,113 (match, offset) => (offset ? '-' : '') + match.toLowerCase()114 )115 return `${directive} ${Array.isArray(value) ? value.join(' ') : value}`116 })117 .join('; ')118 headersToSet.push(['Content-Security-Policy', cspDirectives])103 headersToSet.push(['Content-Security-Policy', getCSPDirectives(options.contentSecurityPolicy)])104 }105106 if (options.reportingEndpoints) {122 const reportingEndpoints = options.reportingEndpoints123 .map((endpoint) => `${endpoint.name}="${endpoint.url}"`)124 .join(', ')125 headersToSet.push(['Reporting-Endpoints', reportingEndpoints])107 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])108 }109110 if (options.reportTo) {129 const reportToOptions = options.reportTo.map((option) => JSON.stringify(option)).join(', ')130 headersToSet.push(['Report-To', reportToOptions])111 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])112 }113114 return async function secureHeaders(ctx, next) {115 await next()135 headersToSet.forEach(([header, value]) => {136 ctx.res.headers.set(header, value)137 })138116 setHeaders(ctx, headersToSet)117 ctx.res.headers.delete('X-Powered-By')118 }119}120121function getFilteredHeaders(options: SecureHeadersOptions): [string, string][] {122 return Object.entries(HEADERS_MAP)123 .filter(([key]) => options[key as keyof SecureHeadersOptions])124 .map(([key, defaultValue]) => {125 const overrideValue = options[key as keyof SecureHeadersOptions]126 return typeof overrideValue === 'string' ? [defaultValue[0], overrideValue] : defaultValue127 })128}129130function getCSPDirectives(131 contentSecurityPolicy: SecureHeadersOptions['contentSecurityPolicy']132): string {133 return Object.entries(contentSecurityPolicy || [])134 .map(([directive, value]) => {135 const kebabCaseDirective = directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>136 offset ? '-' + match.toLowerCase() : match.toLowerCase()137 )138 return `${kebabCaseDirective} ${Array.isArray(value) ? value.join(' ') : value}`139 })140 .join('; ')141}142143function getReportingEndpoints(144 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []145): string {146 return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')147}148149function getReportToOptions(reportTo: SecureHeadersOptions['reportTo'] = []): string {150 return reportTo.map((option) => JSON.stringify(option)).join(', ')151}152153function setHeaders(ctx: Context, headersToSet: [string, string][]) {154 headersToSet.forEach(([header, value]) => {155 ctx.res.headers.set(header, value)156 })157}