Skip to content

Secure Headers ミドルウェア

Secure Headers Middleware は、セキュリティヘッダーの設定を簡単にします。 Helmet の機能に一部インスピレーションを受けており、特定のセキュリティヘッダーの有効化と無効化を制御できます。

Import

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',
  })
)

サポートされているオプション

各オプションは、次のヘッダーのキーと値のペアに対応しています。

OptionHeaderValueDefault
-X-Powered-By(Delete Header)True
contentSecurityPolicyContent-Security-PolicyUsage: Setting Content-Security-PolicyNo Setting
contentSecurityPolicyReportOnlyContent-Security-Policy-Report-OnlyUsage: Setting Content-Security-PolicyNo Setting
trustedTypesTrusted TypesUsage: Setting Content-Security-PolicyNo Setting
requireTrustedTypesForRequire Trusted Types ForUsage: Setting Content-Security-PolicyNo Setting
crossOriginEmbedderPolicyCross-Origin-Embedder-Policyrequire-corpFalse
crossOriginResourcePolicyCross-Origin-Resource-Policysame-originTrue
crossOriginOpenerPolicyCross-Origin-Opener-Policysame-originTrue
originAgentClusterOrigin-Agent-Cluster?1True
referrerPolicyReferrer-Policyno-referrerTrue
reportingEndpointsReporting-EndpointsUsage: Setting Content-Security-PolicyNo Setting
reportToReport-ToUsage: Setting Content-Security-PolicyNo Setting
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-PolicyUsage: Setting Permission-PolicyNo Setting

Middleware Conflict

同じヘッダーを操作するミドルウェアを扱う場合は、指定の順序に注意してください。

この場合、 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',
      reportUri: '/csp-report',
      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 からインポートした NONCEscriptSrc または styleSrc に追加することで、 script または style 要素に nonce 属性 を追加できます:

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")
    },
  })
)

このドキュメントは非公式の日本語翻訳版です。
Released under the MIT License.