|
| 1 | +/* |
| 2 | + * Copyright (c) 2025 Ping Identity Corporation. All rights reserved. |
| 3 | + * |
| 4 | + * This software may be modified and distributed under the terms |
| 5 | + * of the MIT license. See the LICENSE file for details. |
| 6 | + */ |
| 7 | + |
| 8 | +/* eslint-disable @typescript-eslint/no-empty-function */ |
| 9 | +import { AuthorizeUrl } from '@forgerock/sdk-types'; |
| 10 | + |
| 11 | +// Define specific options for the iframe request |
| 12 | +export interface IframeRequestOptions { |
| 13 | + url: string; |
| 14 | + timeout: number; |
| 15 | + // Specify query parameters expected on success/error if needed, |
| 16 | + // otherwise, parse all parameters found. |
| 17 | + // Example: expectedParams?: string[]; |
| 18 | +} |
| 19 | + |
| 20 | +type ResolvedParams<T> = Record<string, T>; |
| 21 | + |
| 22 | +type Noop = () => void; |
| 23 | + |
| 24 | +/** |
| 25 | + * Initializes the Iframe Manager effect. |
| 26 | + * This follows the functional effect pattern, returning an API |
| 27 | + * within a closure. Configuration could be passed here if needed |
| 28 | + * for default behaviors (e.g., default timeout), but currently, |
| 29 | + * all config is per-request. |
| 30 | + * |
| 31 | + * @returns An object containing the API for managing iframe requests. |
| 32 | + */ |
| 33 | +export default function iframeManagerInit(/*config: OAuthConfig*/) { |
| 34 | + /** |
| 35 | + * Creates an iframe to make a background request to the specified URL, |
| 36 | + * waits for a redirect, and resolves with the query parameters from the |
| 37 | + * redirect URL. |
| 38 | + * |
| 39 | + * @param options - The options for the iframe request (URL, timeout). |
| 40 | + * @returns A Promise that resolves with the query parameters from the redirect URL or rejects on timeout or error. |
| 41 | + */ |
| 42 | + const getAuthCodeByIFrame = (options: { |
| 43 | + url: AuthorizeUrl; |
| 44 | + requestTimeout: number; |
| 45 | + }): Promise<ResolvedParams<string>> => { |
| 46 | + const { url, requestTimeout } = options; |
| 47 | + |
| 48 | + return new Promise((resolve, reject) => { |
| 49 | + let iframe: HTMLIFrameElement | null = document.createElement('iframe'); |
| 50 | + let timerId: number | ReturnType<typeof setTimeout> | null = null; |
| 51 | + |
| 52 | + // Define these within the promise closure to avoid retaining |
| 53 | + // references after completion. |
| 54 | + let onLoadHandler: () => void = () => {}; |
| 55 | + let cleanup: Noop = () => {}; |
| 56 | + |
| 57 | + cleanup = (): void => { |
| 58 | + if (timerId) { |
| 59 | + clearTimeout(timerId); |
| 60 | + timerId = null; |
| 61 | + } |
| 62 | + if (iframe) { |
| 63 | + iframe.removeEventListener('load', onLoadHandler); |
| 64 | + // Check if iframe is still mounted before removing |
| 65 | + if (iframe.parentNode) { |
| 66 | + iframe.remove(); |
| 67 | + } |
| 68 | + iframe = null; // Dereference iframe for garbage collection |
| 69 | + } |
| 70 | + onLoadHandler = () => {}; |
| 71 | + cleanup = () => {}; |
| 72 | + }; |
| 73 | + |
| 74 | + onLoadHandler = (): void => { |
| 75 | + try { |
| 76 | + // Accessing contentWindow or contentDocument can throw cross-origin errors |
| 77 | + // if the iframe navigated to a different origin unexpectedly before redirecting back. |
| 78 | + // We expect the final navigation to be back to the original redirect_uri origin. |
| 79 | + if (iframe && iframe.contentWindow) { |
| 80 | + const newHref = iframe.contentWindow.location.href; |
| 81 | + |
| 82 | + // Avoid processing 'about:blank' or initial load if it's not the target URL |
| 83 | + if ( |
| 84 | + newHref === 'about:blank' || |
| 85 | + !newHref.startsWith(options.url.substring(0, options.url.indexOf('?'))) |
| 86 | + ) { |
| 87 | + // Check if the newHref origin matches expected redirect_uri origin if possible |
| 88 | + // Or simply check if it contains expected parameters. |
| 89 | + // For now, we proceed assuming any load could be the redirect. |
| 90 | + } |
| 91 | + |
| 92 | + const redirectUrl = new URL(newHref); |
| 93 | + const params: ResolvedParams<string> = {}; |
| 94 | + redirectUrl.searchParams.forEach((value, key) => { |
| 95 | + params[key] = value; |
| 96 | + }); |
| 97 | + |
| 98 | + // Check for standard OAuth error parameters |
| 99 | + if (params.error) { |
| 100 | + cleanup(); |
| 101 | + // Reject with error details from the URL |
| 102 | + reject( |
| 103 | + new Error( |
| 104 | + `Authorization error: ${params.error}. Description: ${params.error_description || 'N/A'}`, |
| 105 | + ), |
| 106 | + ); |
| 107 | + } else if (Object.keys(params).length > 0) { |
| 108 | + // Assume success if parameters are present and no error param exists |
| 109 | + // More specific checks (e.g., for 'code' or 'state') could be added here |
| 110 | + // based on `options.expectedParams` if provided. |
| 111 | + cleanup(); |
| 112 | + resolve(params); |
| 113 | + } |
| 114 | + // If no params and no error, it might be an intermediate step, |
| 115 | + // The timeout will eventually handle non-resolving states. |
| 116 | + } |
| 117 | + } catch (error) { |
| 118 | + // Catch potential cross-origin errors or other issues accessing iframe content |
| 119 | + cleanup(); |
| 120 | + reject( |
| 121 | + new Error( |
| 122 | + `Failed to process iframe response: ${error instanceof Error ? error.message : String(error)}`, |
| 123 | + ), |
| 124 | + ); |
| 125 | + } |
| 126 | + }; |
| 127 | + |
| 128 | + timerId = setTimeout(() => { |
| 129 | + cleanup(); |
| 130 | + reject(new Error(`Iframe request timed out after ${requestTimeout}ms`)); |
| 131 | + }, requestTimeout); |
| 132 | + |
| 133 | + if (iframe) { |
| 134 | + iframe.style.display = 'none'; |
| 135 | + iframe.addEventListener('load', onLoadHandler); |
| 136 | + document.body.appendChild(iframe); |
| 137 | + iframe.src = url; // Start the loading process |
| 138 | + } else { |
| 139 | + // Should not happen, but handle defensively |
| 140 | + reject(new Error('Failed to create iframe element')); |
| 141 | + } |
| 142 | + }); |
| 143 | + }; |
| 144 | + |
| 145 | + // Return the public API |
| 146 | + return { |
| 147 | + getAuthCodeByIFrame, |
| 148 | + }; |
| 149 | +} |
0 commit comments