@azure/msal-browser
Version:
Microsoft Authentication Library for js
593 lines (582 loc) • 25.2 kB
JavaScript
/*! @azure/msal-browser v5.30.0 2026-11-18 */
;
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.msalPopupRelay = {}));
})(this, (function (exports) { 'use strict';
/*! @azure/msal-common v16.17.0 2026-11-18 */
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function getDefaultErrorMessage$1(code) {
return `See https://aka.ms/msal.js.errors#${code} for details`;
}
/**
* General error class thrown by the MSAL.js library.
*/
class AuthError extends Error {
constructor(errorCode, correlationId, errorMessage, suberror) {
const message = errorMessage ||
(errorCode ? getDefaultErrorMessage$1(errorCode) : "");
const errorString = message ? `${errorCode}: ${message}` : errorCode;
super(errorString);
Object.setPrototypeOf(this, AuthError.prototype);
this.errorCode = errorCode || "";
this.errorMessage = message || "";
this.subError = suberror || "";
this.correlationId = correlationId;
this.name = "AuthError";
}
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const popupWindowError = "popup_window_error";
const userCancelled = "user_cancelled";
const popupRelayUnsupportedFlow = "popup_relay_unsupported_flow";
const timedOut = "timed_out";
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
function getDefaultErrorMessage(code) {
return `See https://aka.ms/msal.js.errors#${code} for details`;
}
/**
* Browser library error class thrown by the MSAL.js library for SPAs
*/
class BrowserAuthError extends AuthError {
constructor(errorCode, correlationId, subError) {
super(errorCode, correlationId, getDefaultErrorMessage(errorCode), subError);
Object.setPrototypeOf(this, BrowserAuthError.prototype);
this.name = "BrowserAuthError";
}
}
function createBrowserAuthError(errorCode, correlationId, subError) {
return new BrowserAuthError(errorCode, correlationId, subError);
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* postMessage envelope type used to relay an auth response from a popup-relay
* page (see `runPopupRelay`) back to the embedded frame that opened it. See
* {@link BrowserAuthOptions.popupRelayUri}.
*
* Shared by the relay-page entry and client helpers without importing either
* implementation into the other bundle.
*
* @internal
*/
const POPUP_RELAY_RESPONSE_TYPE = "msal:popup-relay-response:v1";
/** @internal Response bound to an authenticated v2 relay document. */
const POPUP_RELAY_V2_RESPONSE_TYPE = "msal:popup-relay-response:v2";
/** @internal Ready signal for the authenticated popup-relay request handoff. */
const POPUP_RELAY_READY_TYPE = "msal:popup-relay-ready:v2";
/** @internal Request delivered only to the same-origin relay window. */
const POPUP_RELAY_REQUEST_TYPE = "msal:popup-relay-request:v2";
/** @internal Resolve the compatibility default without downgrading invalid versions. */
function getPopupRelayProtocolVersion(version, correlationId = "") {
if (version === undefined) {
return 1;
}
if (version !== 1 && version !== 2) {
throw createBrowserAuthError(popupRelayUnsupportedFlow, correlationId, "popup_relay_invalid_protocol");
}
return version;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/*
* Interaction type of the API - used for state and telemetry
*/
var InteractionType;
(function (InteractionType) {
InteractionType["Redirect"] = "redirect";
InteractionType["Popup"] = "popup";
InteractionType["Silent"] = "silent";
InteractionType["None"] = "none";
})(InteractionType || (InteractionType = {}));
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// UUID hex digits
const UUID_CHARS = "0123456789abcdef";
// Array to store UINT32 random value
const UINT32_ARR = new Uint32Array(1);
/**
* Returns random Uint32 value.
* @returns {number}
*/
function getRandomUint32() {
window.crypto.getRandomValues(UINT32_ARR);
return UINT32_ARR[0];
}
/**
* Creates a UUID v7 from the current timestamp.
* Implementation relies on the system clock to guarantee increasing order of generated identifiers.
* @returns {number}
*/
function createNewGuid() {
const currentTimestamp = Date.now();
const baseRand = getRandomUint32() * 0x400 + (getRandomUint32() & 0x3ff);
// Result byte array
const bytes = new Uint8Array(16);
// A 12-bit `rand_a` field value
const randA = Math.trunc(baseRand / 2 ** 30);
// The higher 30 bits of 62-bit `rand_b` field value
const randBHi = baseRand & (2 ** 30 - 1);
// The lower 32 bits of 62-bit `rand_b` field value
const randBLo = getRandomUint32();
bytes[0] = currentTimestamp / 2 ** 40;
bytes[1] = currentTimestamp / 2 ** 32;
bytes[2] = currentTimestamp / 2 ** 24;
bytes[3] = currentTimestamp / 2 ** 16;
bytes[4] = currentTimestamp / 2 ** 8;
bytes[5] = currentTimestamp;
bytes[6] = 0x70 | (randA >>> 8);
bytes[7] = randA;
bytes[8] = 0x80 | (randBHi >>> 24);
bytes[9] = randBHi >>> 16;
bytes[10] = randBHi >>> 8;
bytes[11] = randBHi;
bytes[12] = randBLo >>> 24;
bytes[13] = randBLo >>> 16;
bytes[14] = randBLo >>> 8;
bytes[15] = randBLo;
let text = "";
for (let i = 0; i < bytes.length; i++) {
text += UUID_CHARS.charAt(bytes[i] >>> 4);
text += UUID_CHARS.charAt(bytes[i] & 0xf);
if (i === 3 || i === 5 || i === 7 || i === 9) {
text += "-";
}
}
return text;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Creates a POST `<form>` in the provided document with the given auth
* parameters as hidden inputs, targeting `action`. Shared by the popup auth
* flows (`getEARForm` / `getCodeForm`) and the popup-relay page
* (`runPopupRelay`) so the form is built one way only.
*
* @param frame - document to create the form in
* @param action - form action (the /authorize URL)
* @param fields - POST-body fields
* @internal
*/
function createForm(frame, action, fields) {
const form = frame.createElement("form");
form.method = "post";
form.action = action;
Object.keys(fields).forEach((name) => {
const input = frame.createElement("input");
input.hidden = true;
input.name = name;
input.value = fields[name];
form.appendChild(input);
});
frame.body.appendChild(form);
return form;
}
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const DEFAULT_POPUP_RELAY_TIMEOUT_MS = 300000;
const DEFAULT_POPUP_RELAY_WIDTH = 520;
const DEFAULT_POPUP_RELAY_HEIGHT = 640;
const BAD_REQUEST_SUBERROR = "popup_relay_bad_request";
const UNSAFE_URL_SUBERROR = "popup_relay_unsafe_url";
const UNTRUSTED_AUTHORITY_SUBERROR = "popup_relay_untrusted_authority";
const INVALID_ALLOWED_ORIGIN_SUBERROR = "popup_relay_invalid_allowed_origin";
function throwRelayError(subError) {
throw createBrowserAuthError(popupRelayUnsupportedFlow, "", subError);
}
function tryParseUrl(raw) {
try {
return new URL(raw);
}
catch (e) {
return null;
}
}
/**
* Reduces each configured allow-list entry to its origin so the comparison is
* robust to the shapes a developer naturally reaches for. Passing the
* configured authority (`https://login.microsoftonline.com/common`), a trailing
* slash, mixed case, or an explicit default port all normalize to the same
* origin the navigation target is compared against.
*
* A malformed entry is a configuration bug in the relay page, and silently
* dropping it would quietly change the size of the allow list, so it fails
* loudly instead.
*/
function normalizeAllowedOrigins(allowedAuthorityOrigins) {
return allowedAuthorityOrigins.map((entry) => {
const parsed = typeof entry === "string" ? tryParseUrl(entry) : null;
if (!parsed ||
parsed.protocol !== "https:" ||
parsed.username ||
parsed.password) {
throwRelayError(INVALID_ALLOWED_ORIGIN_SUBERROR);
}
return parsed.origin;
});
}
/**
* Validates a navigation target before it can
* reach `window.open` or a form `action`.
*
* Only absolute `https:` URLs without embedded credentials are
* accepted, which rules out active/local schemes (`javascript:`, `data:`,
* `blob:`, `vbscript:`, `file:`) that would otherwise execute in — or read
* from — the relay page's own first-party security origin. `https:`-only also
* matches the scheme MSAL already requires of an authority, so it cannot reject
* a navigation MSAL would have been willing to build.
*
* When `allowedAuthorityOrigins` is omitted the origin check is skipped and any
* https target is accepted — the behavior every relay page had before this
* validation existed. An explicitly empty array means "allow nothing" and is
* honored as such rather than being treated as "unset".
*/
function validateNavigationTarget(raw, allowedAuthorityOrigins) {
if (typeof raw !== "string" || !raw) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
const parsed = tryParseUrl(raw);
if (!parsed ||
parsed.protocol !== "https:" ||
parsed.username ||
parsed.password) {
throwRelayError(UNSAFE_URL_SUBERROR);
}
if (allowedAuthorityOrigins !== undefined &&
!Array.isArray(allowedAuthorityOrigins)) {
throwRelayError(INVALID_ALLOWED_ORIGIN_SUBERROR);
}
const normalizedAllowedOrigins = allowedAuthorityOrigins === undefined
? undefined
: normalizeAllowedOrigins(allowedAuthorityOrigins);
if (normalizedAllowedOrigins &&
normalizedAllowedOrigins.indexOf(parsed.origin) < 0) {
throwRelayError(UNTRUSTED_AUTHORITY_SUBERROR);
}
/*
* Return the original string rather than `parsed.href`: `window.open` and
* `form.action` resolve it with the same URL parser used here, so the
* navigation is byte-identical to what MSAL built and no normalization can
* alter an authority's query encoding.
*/
return raw;
}
/**
* Fully validates a v1 descriptor or an authenticated v2 request. The shape
* is checked exactly (no implicit GET fallback for an unknown `method`) and both
* navigation targets — the GET `url` and the POST `action` — are run through
* {@link validateNavigationTarget}.
*/
function parseRelayRequest(rawReq, allowedAuthorityOrigins) {
if (typeof rawReq !== "object" || rawReq === null) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
const request = rawReq;
const id = request.id;
if (typeof id !== "string" || !id) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
if (request.method === "GET") {
return {
id,
method: "GET",
url: validateNavigationTarget(request.url, allowedAuthorityOrigins),
};
}
if (request.method === "POST") {
const action = validateNavigationTarget(request.action, allowedAuthorityOrigins);
const rawFields = request.fields;
if (typeof rawFields !== "object" ||
rawFields === null ||
Array.isArray(rawFields)) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
const fields = {};
Object.keys(rawFields).forEach((name) => {
const value = rawFields[name];
if (typeof value !== "string") {
throwRelayError(BAD_REQUEST_SUBERROR);
}
fields[name] = value;
});
return { id, method: "POST", action, fields };
}
return throwRelayError(BAD_REQUEST_SUBERROR);
}
/**
* Builds the `window.open` features string for the IdP child popup from a
* {@link PopupWindowAttributes}, mirroring the shape used by
* `PopupRequest.popupWindowAttributes`.
*/
function buildChildPopupFeatures(attributes) {
const width = attributes?.popupSize?.width || DEFAULT_POPUP_RELAY_WIDTH;
const height = attributes?.popupSize?.height || DEFAULT_POPUP_RELAY_HEIGHT;
const features = [`width=${width}`, `height=${height}`];
if (attributes?.popupPosition?.top !== undefined) {
features.push(`top=${attributes.popupPosition.top}`);
}
if (attributes?.popupPosition?.left !== undefined) {
features.push(`left=${attributes.popupPosition.left}`);
}
features.push("scrollbars=yes");
return features.join(",");
}
/**
* Entry point for the top-level "popup-relay" page referenced by
* `auth.popupRelayUri`. Call this from the relay page (which MSAL opens as a
* top-level popup from inside an embedded, cross-origin iframe).
*
* V1 (the compatibility default) is deprecated due to security concerns. It
* executes validated but unauthenticated fragment descriptors and returns the
* legacy response envelope. It retains the legacy risk when origins are not
* pinned; retire that endpoint after migrating callers.
*
* V2 must be explicitly selected on both the app and its separate relay
* endpoint. It:
*
* 1. Reads the request id from the hash, then scrubs the hash. Navigation
* descriptors in the hash are never executed.
* 2. Reserves a blank child popup during the user gesture, then requests the
* navigation from the opener through an origin- and source-checked
* postMessage handoff bound to this relay document's nonce.
* 3. Validates and performs the authenticated navigation (the relay page
* stays put, so its `window.opener` link back to the embedded frame
* survives COOP).
* 4. Waits for the child's redirect URI page (which must run the redirect
* bridge, `broadcastResponseToMainFrame`) to broadcast the raw auth
* response over a same-origin `BroadcastChannel`.
* 5. Relays that raw response back to the embedded frame via
* `opener.postMessage`, posting only to its own (same) origin, then closes.
*
* The embedded frame keeps the PKCE verifier (and EAR private key) and exchanges
* the relayed response itself — no token, verifier, or private key ever crosses
* a window boundary.
*
* Note: the child popup is opened when this function runs, so call it from a
* user gesture (e.g. a "Continue" button click) to avoid popup blockers.
*
* @param options - {@link PopupRelayOptions}
*/
function runPopupRelay(options) {
const protocolVersion = getPopupRelayProtocolVersion(options?.protocolVersion);
const opener = window.opener;
const targetOrigin = window.location.origin;
const hashParams = new URLSearchParams(window.location.hash.replace(/^#/, ""));
const incomingVersion = hashParams.has("id") ? 2 : 1;
let legacyDescriptor;
if (incomingVersion === 1) {
try {
legacyDescriptor = JSON.parse(hashParams.get("req") || "");
}
catch {
legacyDescriptor = null;
}
}
let id = hashParams.get("id") || "";
if (incomingVersion === 1 &&
legacyDescriptor &&
typeof legacyDescriptor === "object" &&
"id" in legacyDescriptor) {
id = legacyDescriptor.id;
}
// Scrub the relayed request out of the relay page's own URL immediately.
if (typeof window.history.replaceState === "function") {
window.history.replaceState(null, "", window.location.origin + window.location.pathname);
}
if (!opener) {
throw createBrowserAuthError(popupRelayUnsupportedFlow, "", "popup_relay_no_opener");
}
if (typeof id !== "string" || !id) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
if (incomingVersion !== protocolVersion) {
const error = createBrowserAuthError(popupRelayUnsupportedFlow, "", "popup_relay_protocol_mismatch");
opener.postMessage({
type: incomingVersion === 1
? POPUP_RELAY_RESPONSE_TYPE
: POPUP_RELAY_V2_RESPONSE_TYPE,
id,
error: error.errorCode,
subError: error.subError,
}, targetOrigin);
throw error;
}
const legacyRequest = protocolVersion === 1
? parseRelayRequest(legacyDescriptor, options?.allowedAuthorityOrigins)
: undefined;
const nonce = protocolVersion === 2 ? createNewGuid() : undefined;
const channel = new BroadcastChannel(id);
let settled = false;
let requestReceived = protocolVersion === 1;
/*
* Timer handles are kept on a const holder so relay() (declared before the
* timers are created) can clear them — `let` handles trip prefer-const, and
* `const` handles can't be referenced before assignment (TDZ).
*/
const timers = {};
const relay = (message) => {
if (settled) {
return;
}
settled = true;
try {
channel.close();
}
catch (e) {
/* ignore */
}
clearInterval(timers.closedPoll);
clearTimeout(timers.timeoutId);
window.removeEventListener("message", onRequest);
window.removeEventListener("pagehide", onPageHide);
opener.postMessage({
type: protocolVersion === 1
? POPUP_RELAY_RESPONSE_TYPE
: POPUP_RELAY_V2_RESPONSE_TYPE,
id,
...(protocolVersion === 2 ? { nonce } : {}),
...message,
}, targetOrigin);
setTimeout(() => {
try {
window.close();
}
catch (e) {
/* ignore */
}
}, 0);
};
// The redirect bridge broadcasts the raw auth response payload here.
channel.onmessage = (event) => {
const payload = event.data && event.data.payload;
if (requestReceived && payload) {
relay({ payload });
}
};
const onRequest = (event) => {
const data = event.data;
if (settled ||
requestReceived ||
protocolVersion !== 2 ||
!childPopup ||
event.origin !== targetOrigin ||
event.source !== opener ||
!data ||
data.type !== POPUP_RELAY_REQUEST_TYPE ||
data.id !== id ||
data.nonce !== nonce) {
return;
}
window.removeEventListener("message", onRequest);
try {
const request = parseRelayRequest(data.request, options?.allowedAuthorityOrigins);
if (request.id !== id) {
throwRelayError(BAD_REQUEST_SUBERROR);
}
requestReceived = true;
if (request.method === "GET") {
childPopup.location.replace(request.url);
}
else {
createForm(childPopup.document, request.action, request.fields).submit();
}
}
catch (e) {
relay({
error: e instanceof BrowserAuthError
? e.errorCode
: popupWindowError,
subError: e instanceof BrowserAuthError
? e.subError
: "popup_relay_navigation_failed",
});
childPopup.close();
}
};
const features = buildChildPopupFeatures(options?.popupWindowAttributes);
// Reserve a fresh window before the asynchronous handoff consumes activation.
const childPopup = legacyRequest?.method === "GET"
? window.open(legacyRequest.url, "msalPopupRelayChild", features)
: window.open("about:blank", protocolVersion === 1 ? "msalPopupRelayChild" : "_blank", features);
if (!childPopup) {
relay({ error: popupWindowError });
return;
}
function onPageHide() {
settled = true;
window.removeEventListener("message", onRequest);
window.removeEventListener("pagehide", onPageHide);
clearInterval(timers.closedPoll);
clearTimeout(timers.timeoutId);
channel.close();
childPopup?.close();
}
if (protocolVersion === 2) {
window.addEventListener("message", onRequest);
}
else if (legacyRequest?.method === "POST") {
createForm(childPopup.document, legacyRequest.action, legacyRequest.fields).submit();
}
window.addEventListener("pagehide", onPageHide);
timers.closedPoll = window.setInterval(() => {
if (childPopup.closed && !settled) {
/*
* The popup is gone, so the overall timeout no longer applies —
* drop it and report cancellation. A successful sign-in settles
* first: the redirect bridge broadcasts the response before it
* closes the popup, so onmessage runs on the
* next event-loop turn, well before this 500ms poll observes the
* close — the `!settled` guard then skips cancellation.
*/
clearTimeout(timers.timeoutId);
relay({ error: userCancelled });
}
}, 500);
timers.timeoutId = window.setTimeout(() => {
if (!settled) {
/*
* Stop the close poll before we close the popup ourselves, so it
* can't observe the close and report user_cancelled instead.
*/
clearInterval(timers.closedPoll);
try {
childPopup.close();
}
catch (e) {
/* ignore */
}
relay({
error: timedOut,
subError: requestReceived
? undefined
: "popup_relay_handshake_timeout",
});
}
}, options?.timeoutMs || DEFAULT_POPUP_RELAY_TIMEOUT_MS);
if (protocolVersion === 2) {
opener.postMessage({ type: POPUP_RELAY_READY_TYPE, id, nonce }, targetOrigin);
}
}
exports.runPopupRelay = runPopupRelay;
}));
//# sourceMappingURL=msal-popup-relay.js.map