跳至内容

安全头信息中间件

安全头信息中间件简化了安全头信息的设置。它部分借鉴了 Helmet 的功能,允许你控制特定安全头信息的启用和禁用。

导入

ts
import { Hono } from 'hono'
import { secureHeaders } from 'hono/secure-headers'

用法

你可以使用默认的最佳设置。

ts
const app = new Hono()
app.use(secureHeaders())

你可以通过将其设置为 false 来抑制不必要的头信息。

ts
const app = new Hono()
app.use(
  '*',
  secureHeaders({
    xFrameOptions: false,
    xXssProtection: false,
  })
)

你可以使用字符串覆盖默认的头信息值。

ts
const app = new Hono()
app.use(
  '*',
  secureHeaders({
    strictTransportSecurity:
      'max-age=63072000; includeSubDomains; preload',
    xFrameOptions: 'DENY',
    xXssProtection: '1',
  })
)

支持的选项

每个选项都对应以下头信息键值对。

选项头信息默认值
-X-Powered-By(删除头信息)True
contentSecurityPolicyContent-Security-Policy用法:设置 Content-Security-Policy无设置
contentSecurityPolicyReportOnlyContent-Security-Policy-Report-Only用法:设置 Content-Security-Policy无设置
crossOriginEmbedderPolicyCross-Origin-Embedder-Policyrequire-corpFalse
crossOriginResourcePolicyCross-Origin-Resource-Policysame-originTrue
crossOriginOpenerPolicyCross-Origin-Opener-Policysame-originTrue
originAgentClusterOrigin-Agent-Cluster?1True
referrerPolicyReferrer-Policyno-referrerTrue
reportingEndpointsReporting-Endpoints用法:设置 Content-Security-Policy无设置
reportToReport-To用法:设置 Content-Security-Policy无设置
strictTransportSecurityStrict-Transport-Securitymax-age=15552000; includeSubDomainsTrue
xContentTypeOptionsX-Content-Type-OptionsnosniffTrue
xDnsPrefetchControlX-DNS-Prefetch-ControloffTrue
xDownloadOptionsX-Download-OptionsnoopenTrue
xFrameOptionsX-Frame-OptionsSAMEORIGINTrue
xPermittedCrossDomainPoliciesX-Permitted-Cross-Domain-PoliciesnoneTrue
xXssProtectionX-XSS-Protection0True
permissionPolicyPermissions-Policy用法:设置 Permission-Policy无设置

中间件冲突

在处理操作相同头信息的中间件时,请注意规范的顺序。

在本例中,Secure-headers 操作并删除了 x-powered-by

ts
const app = new Hono()
app.use(secureHeaders())
app.use(poweredBy())

在本例中,Powered-By 操作并添加了 x-powered-by

ts
const app = new Hono()
app.use(poweredBy())
app.use(secureHeaders())

设置 Content-Security-Policy

ts
const app = new Hono()
app.use(
  '/test',
  secureHeaders({
    reportingEndpoints: [
      {
        name: 'endpoint-1',
        url: 'https://example.com/reports',
      },
    ],
    // -- or alternatively
    // reportTo: [
    //   {
    //     group: 'endpoint-1',
    //     max_age: 10886400,
    //     endpoints: [{ url: 'https://example.com/reports' }],
    //   },
    // ],
    contentSecurityPolicy: {
      defaultSrc: ["'self'"],
      baseUri: ["'self'"],
      childSrc: ["'self'"],
      connectSrc: ["'self'"],
      fontSrc: ["'self'", 'https:', 'data:'],
      formAction: ["'self'"],
      frameAncestors: ["'self'"],
      frameSrc: ["'self'"],
      imgSrc: ["'self'", 'data:'],
      manifestSrc: ["'self'"],
      mediaSrc: ["'self'"],
      objectSrc: ["'none'"],
      reportTo: 'endpoint-1',
      sandbox: ['allow-same-origin', 'allow-scripts'],
      scriptSrc: ["'self'"],
      scriptSrcAttr: ["'none'"],
      scriptSrcElem: ["'self'"],
      styleSrc: ["'self'", 'https:', "'unsafe-inline'"],
      styleSrcAttr: ['none'],
      styleSrcElem: ["'self'", 'https:', "'unsafe-inline'"],
      upgradeInsecureRequests: [],
      workerSrc: ["'self'"],
    },
  })
)

nonce 属性

你可以通过将从 hono/secure-headers 导入的 NONCE 添加到 scriptSrcstyleSrc 中,将 nonce 属性 添加到 scriptstyle 元素中。

tsx
import { secureHeaders, NONCE } from 'hono/secure-headers'
import type { SecureHeadersVariables } from 'hono/secure-headers'

// Specify the variable types to infer the `c.get('secureHeadersNonce')`:
type Variables = SecureHeadersVariables

const app = new Hono<{ Variables: Variables }>()

// Set the pre-defined nonce value to `scriptSrc`:
app.get(
  '*',
  secureHeaders({
    contentSecurityPolicy: {
      scriptSrc: [NONCE, 'https://allowed1.example.com'],
    },
  })
)

// Get the value from `c.get('secureHeadersNonce')`:
app.get('/', (c) => {
  return c.html(
    <html>
      <body>
        {/** contents */}
        <script
          src='/js/client.js'
          nonce={c.get('secureHeadersNonce')}
        />
      </body>
    </html>
  )
})

如果你想自己生成 nonce 值,你也可以指定一个函数,如下所示。

tsx
const app = new Hono<{
  Variables: { myNonce: string }
}>()

const myNonceGenerator: ContentSecurityPolicyOptionHandler = (c) => {
  // This function is called on every request.
  const nonce = Math.random().toString(36).slice(2)
  c.set('myNonce', nonce)
  return `'nonce-${nonce}'`
}

app.get(
  '*',
  secureHeaders({
    contentSecurityPolicy: {
      scriptSrc: [myNonceGenerator, 'https://allowed1.example.com'],
    },
  })
)

app.get('/', (c) => {
  return c.html(
    <html>
      <body>
        {/** contents */}
        <script src='/js/client.js' nonce={c.get('myNonce')} />
      </body>
    </html>
  )
})

设置 Permission-Policy

Permission-Policy 头信息允许你控制哪些功能和 API 可在浏览器中使用。以下是如何设置它的示例。

ts
const app = new Hono()
app.use(
  '*',
  secureHeaders({
    permissionsPolicy: {
      fullscreen: ['self'], // fullscreen=(self)
      bluetooth: ['none'], // bluetooth=(none)
      payment: ['self', 'https://example.com'], // payment=(self "https://example.com")
      syncXhr: [], // sync-xhr=()
      camera: false, // camera=none
      microphone: true, // microphone=*
      geolocation: ['*'], // geolocation=*
      usb: ['self', 'https://a.example.com', 'https://b.example.com'], // usb=(self "https://a.example.com" "https://b.example.com")
      accelerometer: ['https://*.example.com'], // accelerometer=("https://*.example.com")
      gyroscope: ['src'], // gyroscope=(src)
      magnetometer: [
        'https://a.example.com',
        'https://b.example.com',
      ], // magnetometer=("https://a.example.com" "https://b.example.com")
    },
  })
)

在 MIT 许可证下发布。