|
| 1 | +/** |
| 2 | + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors |
| 3 | + * SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | + */ |
| 5 | +import { randomBytes } from 'crypto' |
| 6 | +import { beforeEach, describe, expect, test, vi } from 'vitest' |
| 7 | + |
| 8 | +/** |
| 9 | + * Mock `<meta>` element with nonce |
| 10 | + */ |
| 11 | +function mockNonce() { |
| 12 | + const nonce = randomBytes(16).toString('base64') |
| 13 | + const el = document.createElement('meta') |
| 14 | + el.name = 'csp-nonce' |
| 15 | + el.nonce = nonce |
| 16 | + document.head.appendChild(el) |
| 17 | + return nonce |
| 18 | +} |
| 19 | + |
| 20 | +describe('CSP nonce', () => { |
| 21 | + beforeEach(() => { |
| 22 | + vi.resetModules() |
| 23 | + // reset document |
| 24 | + document.head.innerHTML = '' |
| 25 | + delete document.head.dataset.requesttoken |
| 26 | + }) |
| 27 | + |
| 28 | + test('read nonce from meta element', async () => { |
| 29 | + const { getCSPNonce } = await import('../lib') |
| 30 | + const nonce = mockNonce() |
| 31 | + expect(getCSPNonce()).toBe(nonce) |
| 32 | + }) |
| 33 | + |
| 34 | + test('prefer nonce over csrf token', async () => { |
| 35 | + const { getCSPNonce } = await import('../lib') |
| 36 | + |
| 37 | + const nonce = mockNonce() |
| 38 | + document.head.dataset.requesttoken = 'csrf-token' |
| 39 | + expect(getCSPNonce()).toBe(nonce) |
| 40 | + }) |
| 41 | + |
| 42 | + test('fall back to csrf token for legacy Nextcloud versions', async () => { |
| 43 | + const { getCSPNonce } = await import('../lib') |
| 44 | + |
| 45 | + document.head.dataset.requesttoken = 'csrf-token' |
| 46 | + expect(getCSPNonce()).toBe(btoa('csrf-token')) |
| 47 | + }) |
| 48 | + |
| 49 | + test('return undefined if neither csp nonce nor csrf token is set', async () => { |
| 50 | + const { getCSPNonce } = await import('../lib') |
| 51 | + |
| 52 | + expect(getCSPNonce()).toBe(undefined) |
| 53 | + }) |
| 54 | +}) |
0 commit comments