|
| 1 | +/** |
| 2 | + * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors |
| 3 | + * SPDX-License-Identifier: GPL-3.0-or-later |
| 4 | + */ |
| 5 | + |
| 6 | +import { emit, subscribe, unsubscribe } from '@nextcloud/event-bus' |
| 7 | +import { generateUrl } from '@nextcloud/router' |
| 8 | + |
| 9 | +export interface CsrfTokenObserver { |
| 10 | + (token: string): void |
| 11 | +} |
| 12 | + |
| 13 | +_subscribeToTokenUpdates() // TODO: remove once we drop support for Nextcloud 33 and before |
| 14 | + |
| 15 | +/** |
| 16 | + * Get current request token |
| 17 | + * |
| 18 | + * @return Current request token or null if not set |
| 19 | + */ |
| 20 | +export function getRequestToken(): string | null { |
| 21 | + if (globalThis._nc_auth_requestToken) { |
| 22 | + return globalThis._nc_auth_requestToken |
| 23 | + } |
| 24 | + |
| 25 | + if (globalThis.document) { |
| 26 | + // for service workers or other contexts without DOM we need to safeguard this |
| 27 | + return document.head.dataset.requesttoken ?? null |
| 28 | + } |
| 29 | + return null |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Set a new CSRF token (e.g. because of session refresh). |
| 34 | + * This also emits an event bus event for the updated token. |
| 35 | + * |
| 36 | + * @param token - The new token |
| 37 | + * @throws {Error} - If the passed token is not a potential valid token |
| 38 | + */ |
| 39 | +export function setRequestToken(token: string): void { |
| 40 | + if (!token || typeof token !== 'string') { |
| 41 | + throw new Error('Invalid CSRF token given', { cause: { token } }) |
| 42 | + } |
| 43 | + |
| 44 | + if (globalThis._nc_auth_requestToken === token) { |
| 45 | + // token is the same as before, no need to update and especially no need to notify the observers |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + globalThis._nc_auth_requestToken = token |
| 50 | + if (globalThis.document) { |
| 51 | + // For DOM environments we also set the token to the DOM, so it is available for legacy code |
| 52 | + document.head.dataset.requesttoken = token |
| 53 | + } |
| 54 | + |
| 55 | + emit('csrf-token-update', { token, _internal: true }) |
| 56 | +} |
| 57 | + |
| 58 | +/** |
| 59 | + * Fetch the request token from the API. |
| 60 | + * This does also set it on the current context, see `setRequestToken`. |
| 61 | + * |
| 62 | + * @throws {Error} - If the request failed |
| 63 | + */ |
| 64 | +export async function fetchRequestToken(): Promise<string> { |
| 65 | + const url = generateUrl('/csrftoken') |
| 66 | + |
| 67 | + const response = await fetch(url) |
| 68 | + if (!response.ok) { |
| 69 | + throw new Error('Could not fetch CSRF token from API', { cause: response }) |
| 70 | + } |
| 71 | + |
| 72 | + try { |
| 73 | + const { token } = await response.json() |
| 74 | + setRequestToken(token) |
| 75 | + return token |
| 76 | + } catch (error) { |
| 77 | + throw new Error('Could not parse CSRF token from API response', { cause: error }) |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Add an observer which is called when the CSRF token changes |
| 83 | + * |
| 84 | + * @param observer The observer |
| 85 | + * @return A function to unsubscribe the observer |
| 86 | + */ |
| 87 | +export function onRequestTokenUpdate(observer: CsrfTokenObserver): () => void { |
| 88 | + const wrapper = async ({ token }: { token: string }) => { |
| 89 | + try { |
| 90 | + observer(token) |
| 91 | + } catch (error) { |
| 92 | + // we cannot use the logger as the logger uses this library = circular dependency |
| 93 | + // eslint-disable-next-line no-console |
| 94 | + console.error('Error updating CSRF token observer', error) |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + subscribe('csrf-token-update', wrapper) |
| 99 | + return () => unsubscribe('csrf-token-update', wrapper) |
| 100 | +} |
| 101 | + |
| 102 | +/** |
| 103 | + * Subscribe to token update events from server. |
| 104 | + * |
| 105 | + * @todo - This is legacy and not needed once all supported server versions use `setRequestToken` of this library. |
| 106 | + */ |
| 107 | +function _subscribeToTokenUpdates(): void { |
| 108 | + // Listen to server event and keep token in sync |
| 109 | + subscribe('csrf-token-update', ({ token, _internal }) => { |
| 110 | + if (!_internal) { |
| 111 | + // Only update the token if the event is not emitted from this library, otherwise we would end in a loop |
| 112 | + setRequestToken(token) |
| 113 | + } |
| 114 | + }) |
| 115 | +} |
0 commit comments