コンテンツへスキップ

セキュアヘッダーミドルウェア

セキュアヘッダーミドルウェアは、セキュリティヘッダーの設定を簡素化します。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からインポートした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")
    },
  })
)

MITライセンスの下でリリースされています。