secure-headers.ts
This file
Path
src/middleware/secure-headers/secure-headers.ts
334 lines · 12.3 KiB · TypeScript
Last changed by
Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
History of this fileTake it
The walk stopped after 200 commits: lines older than 82bdc4d point at it.
4.9.0Yusuke Wadabefore adoption82bdc4d
lines 1–31why, 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?: stringMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 32why, one step back32 reportUri?: string | string[]4.9.0Yusuke Wadabefore adoption82bdc4d
lines 33–41why, one step back33 sandbox?: ContentSecurityPolicyOptionValue34 scriptSrc?: ContentSecurityPolicyOptionValue35 scriptSrcAttr?: ContentSecurityPolicyOptionValue36 scriptSrcElem?: ContentSecurityPolicyOptionValue37 styleSrc?: ContentSecurityPolicyOptionValue38 styleSrcAttr?: ContentSecurityPolicyOptionValue39 styleSrcElem?: ContentSecurityPolicyOptionValue40 upgradeInsecureRequests?: ContentSecurityPolicyOptionValue41 workerSrc?: ContentSecurityPolicyOptionValuefeat(secure-headers): support CSP TrustedTypePolicy (#4500)RosAprbefore adoption279184b
lines 42–43why, one step back42 requireTrustedTypesFor?: ContentSecurityPolicyOptionValue43 trustedTypes?: ContentSecurityPolicyOptionValue4.9.0Yusuke Wadabefore adoption82bdc4d
lines 44–334why, one step back44}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) {185 const [callback, value] = getCSPDirectives(options.contentSecurityPolicy)186 if (callback) {187 callbacks.push(callback)188 }189 headersToSet.push(['Content-Security-Policy', value as string])190 }191192 if (options.contentSecurityPolicyReportOnly) {193 const [callback, value] = getCSPDirectives(options.contentSecurityPolicyReportOnly)194 if (callback) {195 callbacks.push(callback)196 }197 headersToSet.push(['Content-Security-Policy-Report-Only', value as string])198 }199200 if (options.permissionsPolicy && Object.keys(options.permissionsPolicy).length > 0) {201 headersToSet.push([202 'Permissions-Policy',203 getPermissionsPolicyDirectives(options.permissionsPolicy),204 ])205 }206207 if (options.reportingEndpoints) {208 headersToSet.push(['Reporting-Endpoints', getReportingEndpoints(options.reportingEndpoints)])209 }210211 if (options.reportTo) {212 headersToSet.push(['Report-To', getReportToOptions(options.reportTo)])213 }214215 return async function secureHeaders(ctx, next) {216 // should evaluate callbacks before next()217 // some callback calls ctx.set() for embedding nonce to the page218 const headersToSetForReq =219 callbacks.length === 0220 ? headersToSet221 : callbacks.reduce((acc, cb) => cb(ctx, acc), headersToSet)222 await next()223 setHeaders(ctx, headersToSetForReq)224225 if (options?.removePoweredBy) {226 ctx.res.headers.delete('X-Powered-By')227 }228 }229}230231function getFilteredHeaders(options: SecureHeadersOptions): [string, string][] {232 return Object.entries(HEADERS_MAP)233 .filter(([key]) => options[key as keyof SecureHeadersOptions])234 .map(([key, defaultValue]) => {235 const overrideValue = options[key as keyof SecureHeadersOptions]236 return typeof overrideValue === 'string' ? [defaultValue[0], overrideValue] : defaultValue237 })238}239240function getCSPDirectives(241 contentSecurityPolicy: ContentSecurityPolicyOptions242): [SecureHeadersCallback | undefined, string | string[]] {243 const callbacks: ((ctx: Context, values: string[]) => void)[] = []244 const resultValues: string[] = []245246 for (const [directive, value] of Object.entries(contentSecurityPolicy)) {247 const valueArray = Array.isArray(value) ? value : [value]248249 valueArray.forEach((value, i) => {250 if (typeof value === 'function') {251 const index = i * 2 + 2 + resultValues.length252 callbacks.push((ctx, values) => {253 values[index] = value(ctx, directive)254 })255 }256 })257258 resultValues.push(259 directive.replace(/[A-Z]+(?![a-z])|[A-Z]/g, (match, offset) =>260 offset ? '-' + match.toLowerCase() : match.toLowerCase()261 ),262 ...valueArray.flatMap((value) => [' ', value]),263 '; '264 )265 }266 resultValues.pop()267268 return callbacks.length === 0269 ? [undefined, resultValues.join('')]270 : [271 (ctx, headersToSet) =>272 headersToSet.map((values) => {273 if (274 values[0] === 'Content-Security-Policy' ||275 values[0] === 'Content-Security-Policy-Report-Only'276 ) {277 const clone = values[1].slice() as unknown as string[]278 callbacks.forEach((cb) => {279 cb(ctx, clone)280 })281 return [values[0], clone.join('')]282 } else {283 return values as [string, string]284 }285 }),286 resultValues,287 ]288}289290function getPermissionsPolicyDirectives(policy: PermissionsPolicyOptions): string {291 return Object.entries(policy)292 .map(([directive, value]) => {293 const kebabDirective = camelToKebab(directive)294295 if (typeof value === 'boolean') {296 return `${kebabDirective}=${value ? '*' : 'none'}`297 }298299 if (Array.isArray(value)) {300 if (value.length === 0) {301 return `${kebabDirective}=()`302 }303 if (value.length === 1 && (value[0] === '*' || value[0] === 'none')) {304 return `${kebabDirective}=${value[0]}`305 }306 const allowlist = value.map((item) => (['self', 'src'].includes(item) ? item : `"${item}"`))307 return `${kebabDirective}=(${allowlist.join(' ')})`308 }309310 return ''311 })312 .filter(Boolean)313 .join(', ')314}315316function camelToKebab(str: string): string {317 return str.replace(/([a-z\d])([A-Z])/g, '$1-$2').toLowerCase()318}319320function getReportingEndpoints(321 reportingEndpoints: SecureHeadersOptions['reportingEndpoints'] = []322): string {323 return reportingEndpoints.map((endpoint) => `${endpoint.name}="${endpoint.url}"`).join(', ')324}325326function getReportToOptions(reportTo: SecureHeadersOptions['reportTo'] = []): string {327 return reportTo.map((option) => JSON.stringify(option)).join(', ')328}329330function setHeaders(ctx: Context, headersToSet: [string, string][]) {331 headersToSet.forEach(([header, value]) => {332 ctx.res.headers.set(header, value)333 })334}