セキュアヘッダーミドルウェア
セキュアヘッダーミドルウェアは、セキュリティヘッダーの設定を簡素化します。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 |
contentSecurityPolicy | Content-Security-Policy | 使用法: Content-Security-Policyの設定 | 設定なし |
contentSecurityPolicyReportOnly | Content-Security-Policy-Report-Only | 使用法: Content-Security-Policyの設定 | 設定なし |
crossOriginEmbedderPolicy | Cross-Origin-Embedder-Policy | require-corp | False |
crossOriginResourcePolicy | Cross-Origin-Resource-Policy | same-origin | True |
crossOriginOpenerPolicy | Cross-Origin-Opener-Policy | same-origin | True |
originAgentCluster | Origin-Agent-Cluster | ?1 | True |
referrerPolicy | Referrer-Policy | no-referrer | True |
reportingEndpoints | Reporting-Endpoints | 使用法: Content-Security-Policyの設定 | 設定なし |
reportTo | Report-To | 使用法: Content-Security-Policyの設定 | 設定なし |
strictTransportSecurity | Strict-Transport-Security | max-age=15552000; includeSubDomains | True |
xContentTypeOptions | X-Content-Type-Options | nosniff | True |
xDnsPrefetchControl | X-DNS-Prefetch-Control | off | True |
xDownloadOptions | X-Download-Options | noopen | True |
xFrameOptions | X-Frame-Options | SAMEORIGIN | True |
xPermittedCrossDomainPolicies | X-Permitted-Cross-Domain-Policies | none | True |
xXssProtection | X-XSS-Protection | 0 | True |
permissionPolicy | Permissions-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
をscriptSrc
または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")
},
})
)