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
Provenance
- Commit
039cac9- Tree
9719fe1- Author
Aris Kemper <aris.github@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
0800acc
2 files changed+88 added−56 removed
modified:deno_dist/middleware/secure-headers/index.ts+44 added-28 removed
1234590 unmodified lines9697989999100101102103104105100101102108109110111112113114115116117118103104105106122123124125107108109110129130111112113114115135136137138116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157import type { Context } from '../../context.ts'import type { MiddlewareHandler } from '../../types.ts'
interface ContentSecurityPolicyOptions { defaultSrc?: string[]90 unmodified lines}
export const secureHeaders = (customOptions?: Partial<SecureHeadersOptions>): MiddlewareHandler => { const options = { ...DEFAULT_OPTIONS, ...customOptions } const headersToSet = Object.entries(HEADERS_MAP) .filter(([key]) => options[key as keyof SecureHeadersOptions]) .map(([key, defaultValue]) => { const overrideValue = options[key as keyof SecureHeadersOptions] if (typeof overrideValue === 'string') return [defaultValue[0], overrideValue] return defaultValue }) const headersToSet = getFilteredHeaders(options)
if (options.contentSecurityPolicy) { const cspDirectives = Object.entries(options.contentSecurityPolicy) .map(([directive, value]) => { // convert camelCase to kebab-case directives (e.g. `defaultSrc` -> `default-src`) directive = directive.replace( /[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) => (offset ? '-' : '') + match.toLowerCase() ) return `${directive} ${Array.isArray(value) ? value.join(' ') : value}` }) .join('; ') headersToSet.push(['Content-Security-Policy', cspDirectives]) headersToSet.push(['Content-Security-Policy', getCSPDirectives(options.contentSecurityPolicy)]) }
if (options.reportingEndpoints) { const reportingEndpoints = options.reportingEndpoints .map((endpoint) => `${endpoint.name}="${endpoint.url}"`) .join(', ') headersToSet.push(['Reporting-Endpoints', reportingEndpoints]) headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)]) }
if (options.reportTo) { const reportToOptions = options.reportTo.map((option) => JSON.stringify(option)).join(', ') headersToSet.push(['Report-To', reportToOptions]) headersToSet.push(['Report-To', getReportToOptions(options.reportTo)]) }
return async function secureHeaders(ctx, next) { await next() headersToSet.forEach(([header, value]) => { ctx.res.headers.set(header, value) })
setHeaders(ctx, headersToSet) ctx.res.headers.delete('X-Powered-By') }}
function getFilteredHeaders(options: SecureHeadersOptions): [string, string][] { return Object.entries(HEADERS_MAP) .filter(([key]) => options[key as keyof SecureHeadersOptions]) .map(([key, defaultValue]) => { const overrideValue = options[key as keyof SecureHeadersOptions] return typeof overrideValue === 'string' ? [defaultValue[0], overrideValue] : defaultValue })}
function getCSPDirectives( contentSecurityPolicy: SecureHeadersOptions['contentSecurityPolicy']): string { return Object.entries(contentSecurityPolicy || []) .map(([directive, value]) => { const kebabCaseDirective = directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) => offset ? '-' + match.toLowerCase() : match.toLowerCase() ) return `${kebabCaseDirective} ${Array.isArray(value) ? value.join(' ') : value}` }) .join('; ')}
function getReportingEndpoints( reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []): string { return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')}
function getReportToOptions(reportTo: SecureHeadersOptions['reportTo'] = []): string { return reportTo.map((option) => JSON.stringify(option)).join(', ')}
function setHeaders(ctx: Context, headersToSet: [string, string][]) { headersToSet.forEach(([header, value]) => { ctx.res.headers.set(header, value) })}modified:src/middleware/secure-headers/index.ts+44 added-28 removed
1+import type { Context } from '../../context'2 import type { MiddlewareHandler } from '../../types'3 4 interface ContentSecurityPolicyOptions {5 defaultSrc?: string[]90 unmodified lines96 }97 98 export 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)101 102 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 }105 106 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 }109 110 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 }113 114 return async function secureHeaders(ctx, next) {115 await next()135- headersToSet.forEach(([header, value]) => {136- ctx.res.headers.set(header, value)137- })138-116+ setHeaders(ctx, headersToSet)117 ctx.res.headers.delete('X-Powered-By')118 }119 }120+121+function 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+}129+130+function 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+}142+143+function getReportingEndpoints(144+ reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []145+): string {146+ return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')147+}148+149+function getReportToOptions(reportTo: SecureHeadersOptions['reportTo'] = []): string {150+ return reportTo.map((option) => JSON.stringify(option)).join(', ')151+}152+153+function setHeaders(ctx: Context, headersToSet: [string, string][]) {154+ headersToSet.forEach(([header, value]) => {155+ ctx.res.headers.set(header, value)156+ })157+}