|
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 } 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[] = [] |
14 | | - |
15 | 13 | /** |
16 | 14 | * Get current request token |
17 | 15 | * |
18 | 16 | * @return Current request token or null if not set |
19 | 17 | */ |
20 | 18 | 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 |
| 19 | + if (globalThis.document) { |
| 20 | + return document.head.dataset.requesttoken ?? null |
| 21 | + } |
| 22 | + // for service workers or other contexts without DOM, we keep the token in memory |
| 23 | + return globalThis._nc_auth_requesttoken ?? null |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Set a new CSRF token (e.g. because of session refresh). |
| 28 | + * This also emits an event bus event for the updated token. |
| 29 | + * |
| 30 | + * @param token - The new token |
| 31 | + * @fires Error - If the passed token is not a potential valid token |
| 32 | + */ |
| 33 | +export function setRequestToken(token: string): void { |
| 34 | + if (!token || typeof token !== 'string') { |
| 35 | + throw new Error('Invalid CSRF token given', { cause: { token } }) |
| 36 | + } |
| 37 | + |
| 38 | + if (globalThis.document) { |
| 39 | + document.head.dataset.requesttoken = token |
| 40 | + } else { |
| 41 | + globalThis._nc_auth_requesttoken = token |
24 | 42 | } |
| 43 | + emit('csrf-token-update', { token }) |
| 44 | +} |
| 45 | + |
| 46 | +/** |
| 47 | + * Fetch the request token from the API. |
| 48 | + * This does also set it on the current context, see `setRequestToken`. |
| 49 | + * |
| 50 | + * @fires Error - If the request failed |
| 51 | + */ |
| 52 | +export async function fetchRequestToken(): Promise<string> { |
| 53 | + const url = generateUrl('/csrftoken') |
| 54 | + |
| 55 | + const response = await fetch(url) |
| 56 | + if (!response.ok) { |
| 57 | + throw new Error('Could not fetch CSRF token from API', { cause: response }) |
| 58 | + } |
| 59 | + |
| 60 | + const { token } = await response.json() |
| 61 | + setRequestToken(token) |
25 | 62 | return token |
26 | 63 | } |
27 | 64 |
|
| 65 | +const _observers: CsrfTokenObserver[] = [] |
28 | 66 | /** |
29 | 67 | * Add an observer which is called when the CSRF token changes |
30 | 68 | * |
31 | 69 | * @param observer The observer |
32 | 70 | */ |
33 | 71 | export function onRequestTokenUpdate(observer: CsrfTokenObserver): void { |
34 | | - observers.push(observer) |
| 72 | + _subscribeToTokenUpdates() |
| 73 | + _observers.push(observer) |
35 | 74 | } |
36 | 75 |
|
37 | | -// Listen to server event and keep token in sync |
38 | | -subscribe('csrf-token-update', (e: unknown) => { |
39 | | - token = (e as { token: string }).token |
40 | | - |
41 | | - observers.forEach((observer) => { |
42 | | - try { |
43 | | - observer(token!) |
44 | | - } catch (error) { |
45 | | - // we cannot use the logger as the logger uses this library = circular dependency |
46 | | - // eslint-disable-next-line no-console |
47 | | - console.error('Error updating CSRF token observer', error) |
| 76 | +let _initialized = false |
| 77 | +/** |
| 78 | + * Subscribe to token update events from server. |
| 79 | + * |
| 80 | + * This is legacy and not needed once all supported server versions use `setRequestToken` of this library. |
| 81 | + */ |
| 82 | +function _subscribeToTokenUpdates(): void { |
| 83 | + if (_initialized) { |
| 84 | + return |
| 85 | + } |
| 86 | + |
| 87 | + _initialized = true |
| 88 | + // Listen to server event and keep token in sync |
| 89 | + subscribe('csrf-token-update', (event) => { |
| 90 | + setRequestToken(event.token) |
| 91 | + for (const observer of _observers) { |
| 92 | + try { |
| 93 | + observer(event.token) |
| 94 | + } catch (error) { |
| 95 | + // we cannot use the logger as the logger uses this library = circular dependency |
| 96 | + // eslint-disable-next-line no-console |
| 97 | + console.error('Error updating CSRF token observer', error) |
| 98 | + } |
48 | 99 | } |
49 | 100 | }) |
50 | | -}) |
| 101 | +} |
0 commit comments