|
| 1 | +/* eslint-disable @typescript-eslint/unbound-method */ |
| 2 | + |
| 3 | +import { AuthLogger } from '@badisi/auth-js'; |
| 4 | + |
| 5 | +import type { InjectToken } from './models/inject-token.model'; |
| 6 | +import type { OIDCAuthManager } from './oidc-auth-manager'; |
| 7 | + |
| 8 | +declare global { |
| 9 | + interface XMLHttpRequest { |
| 10 | + url?: string | URL; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +const logger = new AuthLogger('OIDCAuthInterceptor'); |
| 15 | + |
| 16 | +export class OIDCAuthInterceptor { |
| 17 | + #manager: OIDCAuthManager; |
| 18 | + |
| 19 | + #originalFetch = window.fetch; |
| 20 | + #originalXmlHttpRequestOpen = XMLHttpRequest.prototype.open; |
| 21 | + #originalXmlHttpRequestSend = XMLHttpRequest.prototype.send; |
| 22 | + |
| 23 | + constructor(manager: OIDCAuthManager) { |
| 24 | + logger.debug('init'); |
| 25 | + this.#manager = manager; |
| 26 | + this.#monkeyPathFetch(); |
| 27 | + this.#monkeyPatchXmlHttpRequest(); |
| 28 | + } |
| 29 | + |
| 30 | + // ---- HELPER(s) ---- |
| 31 | + |
| 32 | + #getCompleteUrl(url: string): string { |
| 33 | + try { |
| 34 | + return new URL(url).href; |
| 35 | + } catch { |
| 36 | + return new URL(`${location.origin}${url.startsWith('/') ? '' : '/'}${url}`).href; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + #isMatching(url: string, pattern: string | RegExp | ((url: string) => boolean)): boolean { |
| 41 | + const completeUrl = this.#getCompleteUrl(url); |
| 42 | + if (typeof pattern === 'function') { |
| 43 | + return pattern(completeUrl); |
| 44 | + } else if (typeof pattern === 'string') { |
| 45 | + // Make the pattern regexp friendly |
| 46 | + const match = pattern |
| 47 | + .replace(/\//g, '\\/') // escape / with \/ |
| 48 | + .replace(/\./g, '\\.') // escape . with \. |
| 49 | + .replace(/\*\*/g, '*') // replace ** with * |
| 50 | + .replace(/\*/g, '.*'); // replace * with .* |
| 51 | + |
| 52 | + return (new RegExp(match).exec(completeUrl) !== null); |
| 53 | + } else { |
| 54 | + return (pattern.exec(completeUrl) !== null); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + #isAllowedRequest(url: string, injectToken: InjectToken): boolean { |
| 59 | + let isAllowed = false; |
| 60 | + if (typeof injectToken === 'boolean') { |
| 61 | + isAllowed = injectToken; |
| 62 | + } else { |
| 63 | + const { include, exclude } = injectToken; |
| 64 | + |
| 65 | + if (Array.isArray(include)) { |
| 66 | + isAllowed = include.some((pattern: string | RegExp) => this.#isMatching(url, pattern)); |
| 67 | + } else if (include) { |
| 68 | + isAllowed = this.#isMatching(url, include); |
| 69 | + } |
| 70 | + |
| 71 | + if (Array.isArray(exclude)) { |
| 72 | + if (exclude.some((item: string | RegExp) => this.#isMatching(url, item))) { |
| 73 | + isAllowed = false; |
| 74 | + } |
| 75 | + } else if (exclude && this.#isMatching(url, exclude)) { |
| 76 | + isAllowed = false; |
| 77 | + } |
| 78 | + } |
| 79 | + return isAllowed; |
| 80 | + } |
| 81 | + |
| 82 | + #shouldInjectAuthToken(url: string): boolean { |
| 83 | + const injectToken = this.#manager.getSettings().automaticInjectToken ?? false; |
| 84 | + return (injectToken !== false) && this.#isAllowedRequest(url, injectToken); |
| 85 | + } |
| 86 | + |
| 87 | + #monkeyPathFetch(enable = true): void { |
| 88 | + const _logger = logger.createChild('monkeyPathFetch'); |
| 89 | + _logger.debug(enable ? 'enabling..' : 'disabling..'); |
| 90 | + |
| 91 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 92 | + if (window.fetch) { |
| 93 | + if (enable) { |
| 94 | + window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => { |
| 95 | + const url = (input instanceof Request) ? input.url : input.toString(); |
| 96 | + logger.debug('received fetch url:', url); |
| 97 | + |
| 98 | + // Add token to request headers |
| 99 | + if (this.#shouldInjectAuthToken(url)) { |
| 100 | + const accessToken = await this.#manager.getAccessToken(); |
| 101 | + if (init && accessToken) { |
| 102 | + logger.debug('adding bearer to url:', url); |
| 103 | + init.headers = { |
| 104 | + // eslint-disable-next-line @typescript-eslint/naming-convention |
| 105 | + 'Authorization': `Bearer ${accessToken}`, |
| 106 | + ...init.headers |
| 107 | + }; |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + // Proceed with request |
| 112 | + const response = await this.#originalFetch.apply(window, [input, init]); |
| 113 | + |
| 114 | + // Do a login on 401 |
| 115 | + if (response.status === 401) { |
| 116 | + const shouldLoginOn401 = this.#manager.getSettings().automaticLoginOn401 ?? false; |
| 117 | + if (shouldLoginOn401) { |
| 118 | + await this.#manager.login(); |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + return response; |
| 123 | + }; |
| 124 | + } else { |
| 125 | + window.fetch = this.#originalFetch; |
| 126 | + } |
| 127 | + |
| 128 | + _logger.debug('done'); |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + #monkeyPatchXmlHttpRequest(enable = true): void { |
| 133 | + const _logger = logger.createChild('monkeyPatchXmlHttpRequest'); |
| 134 | + _logger.debug(enable ? 'enabling..' : 'disabling..'); |
| 135 | + |
| 136 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 137 | + if (XMLHttpRequest.prototype.open && XMLHttpRequest.prototype.send) { |
| 138 | + if (enable) { |
| 139 | + // eslint-disable-next-line @typescript-eslint/no-this-alias |
| 140 | + const interceptor = this; |
| 141 | + |
| 142 | + XMLHttpRequest.prototype.open = function (method: string, url: string | URL, ...rest: unknown[]): void { |
| 143 | + this.url = url; |
| 144 | + // @ts-expect-error Rest should not be of type unknown |
| 145 | + interceptor.#originalXmlHttpRequestOpen.apply(this, [method, url, ...rest]); |
| 146 | + }; |
| 147 | + |
| 148 | + XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null): void { |
| 149 | + const url = (typeof this.url === 'string') ? this.url : this.url?.href; |
| 150 | + logger.debug('received xhr url:', url); |
| 151 | + |
| 152 | + // Do a login on 401 |
| 153 | + const onReadyStateChange = (): void => { |
| 154 | + if (this.readyState === XMLHttpRequest.DONE) { |
| 155 | + removeListeners(); |
| 156 | + |
| 157 | + if (this.status === 401) { |
| 158 | + const shouldLoginOn401 = interceptor.#manager.getSettings().automaticLoginOn401 ?? false; |
| 159 | + if (shouldLoginOn401) { |
| 160 | + void interceptor.#manager.login(); |
| 161 | + } |
| 162 | + } |
| 163 | + } |
| 164 | + } |
| 165 | + const removeListeners = (): void => { |
| 166 | + this.removeEventListener('readystatechange', onReadyStateChange); |
| 167 | + this.removeEventListener('timeout', removeListeners); |
| 168 | + this.removeEventListener('error', removeListeners); |
| 169 | + this.removeEventListener('abort', removeListeners); |
| 170 | + |
| 171 | + }; |
| 172 | + this.addEventListener('readystatechange', onReadyStateChange); |
| 173 | + this.addEventListener('timeout', removeListeners); |
| 174 | + this.addEventListener('error', removeListeners); |
| 175 | + this.addEventListener('abort', removeListeners); |
| 176 | + |
| 177 | + // Add token to request headers |
| 178 | + const shouldInjectToken = url ? interceptor.#shouldInjectAuthToken(url) : false; |
| 179 | + if (this.readyState === XMLHttpRequest.OPENED && shouldInjectToken) { |
| 180 | + interceptor.#manager.getAccessToken() |
| 181 | + .then(accessToken => { |
| 182 | + if (accessToken) { |
| 183 | + logger.debug('adding bearer to url:', url); |
| 184 | + this.setRequestHeader('Authorization', `Bearer ${accessToken}`); |
| 185 | + } |
| 186 | + }) |
| 187 | + .catch((error: unknown) => { |
| 188 | + logger.error(error) |
| 189 | + }) |
| 190 | + .finally(() => { |
| 191 | + interceptor.#originalXmlHttpRequestSend.apply(this, [body]); |
| 192 | + }) |
| 193 | + } else { |
| 194 | + interceptor.#originalXmlHttpRequestSend.apply(this, [body]); |
| 195 | + } |
| 196 | + }; |
| 197 | + } else { |
| 198 | + XMLHttpRequest.prototype.open = this.#originalXmlHttpRequestOpen; |
| 199 | + XMLHttpRequest.prototype.send = this.#originalXmlHttpRequestSend; |
| 200 | + } |
| 201 | + |
| 202 | + _logger.debug('done'); |
| 203 | + } |
| 204 | + } |
| 205 | +} |
0 commit comments