secure-headers.ts
This file
Path
src/middleware/secure-headers/secure-headers.ts
341 lines · 12.4 KiB · TypeScript
Last changed by
fix(secure-headers): output standard empty parentheses () instead of none for disabled Permissions-Policy directives (#5197)Nanasibefore adoption13a9481
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–184why, one step back1/**2 * @module3 * Secure Headers Middleware for Hono.4 */56import type { Context } from '../../context'7import type { MiddlewareHandler } from '../../types'8import { encodeBase64 } from '../../utils/encode'9import type { PermissionsPolicyDirective } from './permissions-policy'1011export type SecureHeadersVariables = {12 secureHeadersNonce?: string13}1415export type ContentSecurityPolicyOptionHandler = (ctx: Context, directive: string) => string16type ContentSecurityPolicyOptionValue = (string | ContentSecurityPolicyOptionHandler)[]1718interface ContentSecurityPolicyOptions {19 defaultSrc?: ContentSecurityPolicyOptionValue20 baseUri?: ContentSecurityPolicyOptionValue21 childSrc?: ContentSecurityPolicyOptionValue22 connectSrc?: ContentSecurityPolicyOptionValue23 fontSrc?: ContentSecurityPolicyOptionValue24 formAction?: ContentSecurityPolicyOptionValue25 frameAncestors?: ContentSecurityPolicyOptionValue26 frameSrc?: ContentSecurityPolicyOptionValue27 imgSrc?: ContentSecurityPolicyOptionValue28 manifestSrc?: ContentSecurityPolicyOptionValue29 mediaSrc?: ContentSecurityPolicyOptionValue30 objectSrc?: ContentSecurityPolicyOptionValue31 reportTo?: string32 reportUri?: string | string[]33 sandbox?: ContentSecurityPolicyOptionValue34 scriptSrc?: ContentSecurityPolicyOptionValue35 scriptSrcAttr?: ContentSecurityPolicyOptionValue36 scriptSrcElem?: ContentSecurityPolicyOptionValue37 styleSrc?: ContentSecurityPolicyOptionValue38 styleSrcAttr?: ContentSecurityPolicyOptionValue39 styleSrcElem?: ContentSecurityPolicyOptionValue40 upgradeInsecureRequests?: ContentSecurityPolicyOptionValue41 workerSrc?: ContentSecurityPolicyOptionValue42 requireTrustedTypesFor?: ContentSecurityPolicyOptionValue43 trustedTypes?: ContentSecurityPolicyOptionValue44}4546interface ReportToOptions {47 group: string48 max_age: number49 endpoints: ReportToEndpoint[]50}5152interface ReportToEndpoint {53 url: string54}5556interface ReportingEndpointOptions {57 name: string58 url: string59}6061type PermissionsPolicyValue = '*' | 'self' | 'src' | 'none' | string6263type PermissionsPolicyOptions = Partial<64 Record<PermissionsPolicyDirective, PermissionsPolicyValue[] | boolean>65>6667type overridableHeader = boolean | string6869interface SecureHeadersOptions {70 contentSecurityPolicy?: ContentSecurityPolicyOptions71 contentSecurityPolicyReportOnly?: ContentSecurityPolicyOptions72 crossOriginEmbedderPolicy?: overridableHeader73 crossOriginResourcePolicy?: overridableHeader74 crossOriginOpenerPolicy?: overridableHeader75 originAgentCluster?: overridableHeader76 referrerPolicy?: overridableHeader77 reportingEndpoints?: ReportingEndpointOptions[]78 reportTo?: ReportToOptions[]79 strictTransportSecurity?: overridableHeader80 xContentTypeOptions?: overridableHeader81 xDnsPrefetchControl?: overridableHeader82 xDownloadOptions?: overridableHeader83 xFrameOptions?: overridableHeader84 xPermittedCrossDomainPolicies?: overridableHeader85 xXssProtection?: overridableHeader86 removePoweredBy?: boolean87 permissionsPolicy?: PermissionsPolicyOptions88}8990type HeadersMap = {91 [key in keyof SecureHeadersOptions]: [string, string]92}9394const HEADERS_MAP: HeadersMap = {95 crossOriginEmbedderPolicy: ['Cross-Origin-Embedder-Policy', 'require-corp'],96 crossOriginResourcePolicy: ['Cross-Origin-Resource-Policy', 'same-origin'],97 crossOriginOpenerPolicy: ['Cross-Origin-Opener-Policy', 'same-origin'],98 originAgentCluster: ['Origin-Agent-Cluster', '?1'],99 referrerPolicy: ['Referrer-Policy', 'no-referrer'],100 strictTransportSecurity: ['Strict-Transport-Security', 'max-age=15552000; includeSubDomains'],101 xContentTypeOptions: ['X-Content-Type-Options', 'nosniff'],102 xDnsPrefetchControl: ['X-DNS-Prefetch-Control', 'off'],103 xDownloadOptions: ['X-Download-Options', 'noopen'],104 xFrameOptions: ['X-Frame-Options', 'SAMEORIGIN'],105 xPermittedCrossDomainPolicies: ['X-Permitted-Cross-Domain-Policies', 'none'],106 xXssProtection: ['X-XSS-Protection', '0'],107}108109const DEFAULT_OPTIONS: SecureHeadersOptions = {110 crossOriginEmbedderPolicy: false,111 crossOriginResourcePolicy: true,112 crossOriginOpenerPolicy: true,113 originAgentCluster: true,114 referrerPolicy: true,115 strictTransportSecurity: true,116 xContentTypeOptions: true,117 xDnsPrefetchControl: true,118 xDownloadOptions: true,119 xFrameOptions: true,120 xPermittedCrossDomainPolicies: true,121 xXssProtection: true,122 removePoweredBy: true,123 permissionsPolicy: {},124}125126type SecureHeadersCallback = (127 ctx: Context,128 headersToSet: [string, string | string[]][]129) => [string, string][]130131const generateNonce = () => {132 const arrayBuffer = new Uint8Array(16)133 crypto.getRandomValues(arrayBuffer)134 return encodeBase64(arrayBuffer.buffer)135}136137export const NONCE: ContentSecurityPolicyOptionHandler = (ctx) => {138 const key = 'secureHeadersNonce'139 const init = ctx.get(key)140 const nonce = init || generateNonce()141 if (init == null) {142 ctx.set(key, nonce)143 }144 return `'nonce-${nonce}'`145}146147/**148 * Secure Headers Middleware for Hono.149 *150 * @see {@link https://hono.dev/docs/middleware/builtin/secure-headers}151 *152 * @param {Partial<SecureHeadersOptions>} [customOptions] - The options for the secure headers middleware.153 * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicy] - Settings for the Content-Security-Policy header.154 * @param {ContentSecurityPolicyOptions} [customOptions.contentSecurityPolicyReportOnly] - Settings for the Content-Security-Policy-Report-Only header.155 * @param {overridableHeader} [customOptions.crossOriginEmbedderPolicy=false] - Settings for the Cross-Origin-Embedder-Policy header.156 * @param {overridableHeader} [customOptions.crossOriginResourcePolicy=true] - Settings for the Cross-Origin-Resource-Policy header.157 * @param {overridableHeader} [customOptions.crossOriginOpenerPolicy=true] - Settings for the Cross-Origin-Opener-Policy header.158 * @param {overridableHeader} [customOptions.originAgentCluster=true] - Settings for the Origin-Agent-Cluster header.159 * @param {overridableHeader} [customOptions.referrerPolicy=true] - Settings for the Referrer-Policy header.160 * @param {ReportingEndpointOptions[]} [customOptions.reportingEndpoints] - Settings for the Reporting-Endpoints header.161 * @param {ReportToOptions[]} [customOptions.reportTo] - Settings for the Report-To header.162 * @param {overridableHeader} [customOptions.strictTransportSecurity=true] - Settings for the Strict-Transport-Security header.163 * @param {overridableHeader} [customOptions.xContentTypeOptions=true] - Settings for the X-Content-Type-Options header.164 * @param {overridableHeader} [customOptions.xDnsPrefetchControl=true] - Settings for the X-DNS-Prefetch-Control header.165 * @param {overridableHeader} [customOptions.xDownloadOptions=true] - Settings for the X-Download-Options header.166 * @param {overridableHeader} [customOptions.xFrameOptions=true] - Settings for the X-Frame-Options header.167 * @param {overridableHeader} [customOptions.xPermittedCrossDomainPolicies=true] - Settings for the X-Permitted-Cross-Domain-Policies header.168 * @param {overridableHeader} [customOptions.xXssProtection=true] - Settings for the X-XSS-Protection header.169 * @param {boolean} [customOptions.removePoweredBy=true] - Settings for remove X-Powered-By header.170 * @param {PermissionsPolicyOptions} [customOptions.permissionsPolicy] - Settings for the Permissions-Policy header.171 * @returns {MiddlewareHandler} The middleware handler function.172 *173 * @example174 * ```ts175 * const app = new Hono()176 * app.use(secureHeaders())177 * ```178 */179export const secureHeaders = (customOptions?: SecureHeadersOptions): MiddlewareHandler => {180 const options = { ...DEFAULT_OPTIONS, ...customOptions }181 const headersToSet = getFilteredHeaders(options)182 const callbacks: SecureHeadersCallback[] = []183184 if (options.contentSecurityPolicy) {fix(secure-headers): keep CSP callbacks scoped to their header (#5147)Lattebefore adoption402eb3a
lines 185–188why, one step back185 const [callback, value] = getCSPDirectives(186 options.contentSecurityPolicy,187 'Content-Security-Policy'188 )Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 189–195why, one step back189 if (callback) {190 callbacks.push(callback)191 }192 headersToSet.push(['Content-Security-Policy', value as string])193 }194195 if (options.contentSecurityPolicyReportOnly) {fix(secure-headers): keep CSP callbacks scoped to their header (#5147)Lattebefore adoption402eb3a
lines 196–199why, one step back196 const [callback, value] = getCSPDirectives(197 options.contentSecurityPolicyReportOnly,198 'Content-Security-Policy-Report-Only'199 )Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 200–246why, one step back200 if (callback) {201 callbacks.push(callback)202 }203 headersToSet.push(['Content-Security-Policy-Report-Only', value as string])204 }205206 if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) {207 headersToSet.push([208 'Permissions-Policy',209 getPermissionsPolicyDirectives(options.permissionsPolicy),210 ])211 }212213 if (options.reportingEndpoints) {214 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])215 }216217 if (options.reportTo) {218 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])219 }220221 return async function secureHeaders(ctx, next) {222 // should evaluate callbacks before next()223 // some callback calls ctx.set() for embedding nonce to the page224 const headersToSetForReq =225 callbacks.length === 0226 ? headersToSet227 : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet)228 await next()229 setHeaders(ctx, headersToSetForReq)230231 if (options?.removePoweredBy) {232 ctx.res.headers.delete('X-Powered-By')233 }234 }235}236237function getFilteredHeaders(options: SecureHeadersOptions): [string, string][] {238 return Object.entries(HEADERS_MAP)239 .filter(([key]) => options[key as keyof SecureHeadersOptions])240 .map(([key, defaultValue]) => {241 const overrideValue = options[key as keyof SecureHeadersOptions]242 return typeof overrideValue === 'string' ? [defaultValue[0], overrideValue] : defaultValue243 })244}245246function getCSPDirectives(fix(secure-headers): keep CSP callbacks scoped to their header (#5147)Lattebefore adoption402eb3a
lines 247–248why, one step back247 contentSecurityPolicy: ContentSecurityPolicyOptions,248 headerName: 'Content-Security-Policy' | 'Content-Security-Policy-Report-Only'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 249–279why, one step back249): [SecureHeadersCallback | undefined, string | string[]] {250 const callbacks: ((ctx: Context, values: string[]) => void)[] = []251 const resultValues: string[] = []252253 for (const [directive, value] of Object.entries(contentSecurityPolicy)) {254 const valueArray = Array.isArray(value) ? value : [value]255256 valueArray.forEach((value, i) => {257 if (typeof value === 'function') {258 const index = i * 2 + 2 + resultValues.length259 callbacks.push((ctx, values) => {260 values[index] = value(ctx, directive)261 })262 }263 })264265 resultValues.push(266 directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>267 offset ? '-' + match.toLowerCase() : match.toLowerCase()268 ),269 ...valueArray.flatMap((value) => [' ', value]),270 '; '271 )272 }273 resultValues.pop()274275 return callbacks.length === 0276 ? [undefined, resultValues.join('')]277 : [278 (ctx, headersToSet) =>279 headersToSet.map((values) => {fix(secure-headers): keep CSP callbacks scoped to their header (#5147)Lattebefore adoption402eb3a
line 280why, one step back280 if (values[0] === headerName) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 281–299why, one step back281 const clone = values[1].slice() as unknown as string[]282 callbacks.forEach((cb) => {283 cb(ctx, clone)284 })285 return [values[0], clone.join('')]286 } else {287 return values as [string, string]288 }289 }),290 resultValues,291 ]292}293294function getPermissionsPolicyDirectives(policy: PermissionsPolicyOptions): string {295 return Object.entries(policy)296 .map(([directive, value]) => {297 const kebabDirective = camelToKebab(directive)298299 if (typeof value === 'boolean') {fix(secure-headers): output standard empty parentheses () instead of none for disabled Permissions-Policy directives (#5197)Nanasibefore adoption13a9481
line 300why, one step back300 return `${kebabDirective}=${value ? '*' : '()'}`Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 301–306why, one step back301 }302303 if (Array.isArray(value)) {304 if (value.length === 0) {305 return `${kebabDirective}=()`306 }fix(secure-headers): output standard empty parentheses () instead of none for disabled Permissions-Policy directives (#5197)Nanasibefore adoption13a9481
lines 307–311why, one step back307 if (value.length === 1 && value[0] === '*') {308 return `${kebabDirective}=*`309 }310 if (value.length === 1 && value[0] === 'none') {311 return `${kebabDirective}=()`Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 312–341why, one step back312 }313 const allowlist = value.map((item) => (['self', 'src'].includes(item) ? item : `"${item}"`))314 return `${kebabDirective}=(${allowlist.join(' ')})`315 }316317 return ''318 })319 .filter(Boolean)320 .join(', ')321}322323function camelToKebab(str: string): string {324 return str.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase()325}326327function getReportingEndpoints(328 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []329): string {330 return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')331}332333function getReportToOptions(reportTo: SecureHeadersOptions['reportTo'] = []): string {334 return reportTo.map((option) => JSON.stringify(option)).join(', ')335}336337function setHeaders(ctx: Context, headersToSet: [string, string][]) {338 headersToSet.forEach(([header, value]) => {339 ctx.res.headers.set(header, value)340 })341}