|
3 | 3 | * SPDX-License-Identifier: GPL-3.0-or-later |
4 | 4 | */ |
5 | 5 |
|
6 | | -import { subscribe } from '@nextcloud/event-bus' |
| 6 | +import { emit, subscribe, unsubscribe } from '@nextcloud/event-bus' |
| 7 | +import { generateUrl } from '@nextcloud/router' |
7 | 8 |
|
8 | 9 | export interface CsrfTokenObserver { |
9 | 10 | (token: string): void |
10 | 11 | } |
11 | 12 |
|
12 | | -let token: string | null | undefined |
13 | | -const observers: CsrfTokenObserver[] = [] |
| 13 | +_subscribeToTokenUpdates() // TODO: remove once we drop support for Nextcloud 33 and before |
14 | 14 |
|
15 | 15 | /** |
16 | 16 | * Get current request token |
17 | 17 | * |
18 | 18 | * @return Current request token or null if not set |
19 | 19 | */ |
20 | 20 | export function getRequestToken(): string | null { |
21 | | - if (token === undefined) { |
22 | | - // Only on first load, try to get token from document |
23 | | - token = document.head.dataset.requesttoken ?? null |
| 21 | + if (globalThis._nc_auth_requestToken) { |
| 22 | + return globalThis._nc_auth_requestToken |
24 | 23 | } |
25 | | - return token |
| 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 |
26 | 30 | } |
27 | 31 |
|
28 | 32 | /** |
29 | | - * Add an observer which is called when the CSRF token changes |
| 33 | + * Set a new CSRF token (e.g. because of session refresh). |
| 34 | + * This also emits an event bus event for the updated token. |
30 | 35 | * |
31 | | - * @param observer The observer |
| 36 | + * @param token - The new token |
| 37 | + * @throws {Error} - If the passed token is not a potential valid token |
32 | 38 | */ |
33 | | -export function onRequestTokenUpdate(observer: CsrfTokenObserver): void { |
34 | | - observers.push(observer) |
| 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 }) |
35 | 56 | } |
36 | 57 |
|
37 | | -// Listen to server event and keep token in sync |
38 | | -subscribe('csrf-token-update', (e: unknown) => { |
39 | | - token = (e as { token: string }).token |
| 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 | +} |
40 | 80 |
|
41 | | - observers.forEach((observer) => { |
| 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 }) => { |
42 | 89 | try { |
43 | | - observer(token!) |
| 90 | + observer(token) |
44 | 91 | } catch (error) { |
45 | 92 | // we cannot use the logger as the logger uses this library = circular dependency |
46 | 93 | // eslint-disable-next-line no-console |
47 | 94 | console.error('Error updating CSRF token observer', error) |
48 | 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 | + } |
49 | 114 | }) |
50 | | -}) |
| 115 | +} |
0 commit comments