安全头信息中间件
安全头信息中间件简化了安全头信息的设置。它部分借鉴了 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
中,将 nonce
属性 添加到 script
或 style
元素中。
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")
},
})
)