Skip to content

Commit

Permalink
fix(secure-headers): optimize getPermissionsPolicyDirectives function (
Browse files Browse the repository at this point in the history
  • Loading branch information
kbkn3 committed Sep 9, 2024
1 parent c2b0de4 commit 3c4d4c2
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
11 changes: 9 additions & 2 deletions src/middleware/secure-headers/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ describe('Secure Headers Middleware', () => {
expect(res.headers.get('X-XSS-Protection')).toEqual('1')
})

it('should set Permission-Policy header', async () => {
it('should set Permission-Policy header correctly', async () => {
const app = new Hono()
app.use(
'/test',
Expand All @@ -173,13 +173,20 @@ describe('Secure Headers Middleware', () => {
camera: false,
microphone: true,
geolocation: ['*'],
usb: ['self', 'https://a.example.com', 'https://b.example.com'],
accelerometer: ['https://*.example.com'],
gyroscope: ['src'],
magnetometer: ['https://a.example.com', 'https://b.example.com'],
},
})
)

const res = await app.request('/test')
expect(res.headers.get('Permissions-Policy')).toEqual(
'fullscreen=(self), bluetooth=(none), payment=(self example.com), sync-xhr=(), camera=none, microphone=(), geolocation=(*)'
'fullscreen=(self), bluetooth=none, payment=(self "example.com"), sync-xhr=(), camera=none, microphone=*, ' +
'geolocation=*, usb=(self "https://a.example.com" "https://b.example.com"), ' +
'accelerometer=("https://*.example.com"), gyroscope=(src), ' +
'magnetometer=("https://a.example.com" "https://b.example.com")'
)
})
it('CSP Setting', async () => {
Expand Down
12 changes: 9 additions & 3 deletions src/middleware/secure-headers/secure-headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,12 +278,18 @@ function getPermissionsPolicyDirectives(policy: PermissionsPolicyOptions): strin
const kebabDirective = camelToKebab(directive)

if (typeof value === 'boolean') {
return `${kebabDirective}=${value ? '()' : 'none'}`
return `${kebabDirective}=${value ? '*' : 'none'}`
}

if (Array.isArray(value)) {
const allowlist = value.length === 0 ? '()' : `(${value.join(' ')})`
return `${kebabDirective}=${allowlist}`
if (value.length === 0) {
return `${kebabDirective}=()`
}
if (value.length === 1 && (value[0] === '*' || value[0] === 'none')) {
return `${kebabDirective}=${value[0]}`
}
const allowlist = value.map((item) => (['self', 'src'].includes(item) ? item : `"${item}"`))
return `${kebabDirective}=(${allowlist.join(' ')})`
}

return ''

Check warning on line 295 in src/middleware/secure-headers/secure-headers.ts

View check run for this annotation

Codecov / codecov/patch

src/middleware/secure-headers/secure-headers.ts#L295

Added line #L295 was not covered by tests
Expand Down

0 comments on commit 3c4d4c2

Please sign in to comment.