@authsignal/browser 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,4 +13,10 @@ export declare class Authsignal {
13
13
  launch(url: string, options?: {
14
14
  mode: "popup";
15
15
  } & LaunchOptions): Promise<TokenPayload>;
16
+ launch(url: string, options?: {
17
+ mode: "window";
18
+ } & LaunchOptions): Promise<TokenPayload>;
19
+ private launchWithRedirect;
20
+ private launchWithPopup;
21
+ private launchWithWindow;
16
22
  }
@@ -0,0 +1,2 @@
1
+ export { WindowHandler } from "./window-handler";
2
+ export { PopupHandler } from "./popup-handler";
@@ -6,7 +6,7 @@ declare type EventHandler = (node: Element, event?: Event) => void;
6
6
  declare type PopupHandlerOptions = {
7
7
  width?: string;
8
8
  };
9
- declare class PopupHandler {
9
+ export declare class PopupHandler {
10
10
  private popup;
11
11
  constructor({ width }: PopupHandlerOptions);
12
12
  create({ width }: PopupHandlerOptions): void;
@@ -15,4 +15,4 @@ declare class PopupHandler {
15
15
  close(): void;
16
16
  on(event: EventType, handler: EventHandler): void;
17
17
  }
18
- export { PopupHandler };
18
+ export {};
@@ -0,0 +1,11 @@
1
+ declare type WindowShowInput = {
2
+ url: string;
3
+ width?: number;
4
+ height?: number;
5
+ };
6
+ export declare class WindowHandler {
7
+ private windowRef;
8
+ show({ url, width, height }: WindowShowInput): Window;
9
+ close(): void;
10
+ }
11
+ export {};
package/dist/index.js CHANGED
@@ -90,6 +90,39 @@ var AuthsignalWindowMessage;
90
90
  AuthsignalWindowMessage["AUTHSIGNAL_CLOSE_POPUP"] = "AUTHSIGNAL_CLOSE_POPUP";
91
91
  })(AuthsignalWindowMessage || (AuthsignalWindowMessage = {}));
92
92
 
93
+ var DEFAULT_WIDTH$1 = 400;
94
+ var DEFAULT_HEIGHT = 500;
95
+ var WindowHandler = /** @class */ (function () {
96
+ function WindowHandler() {
97
+ this.windowRef = null;
98
+ }
99
+ WindowHandler.prototype.show = function (_a) {
100
+ var url = _a.url, _b = _a.width, width = _b === void 0 ? DEFAULT_WIDTH$1 : _b, _c = _a.height, height = _c === void 0 ? DEFAULT_HEIGHT : _c;
101
+ var windowRef = openWindow({ url: url, width: width, height: height, win: window });
102
+ if (!windowRef) {
103
+ throw new Error("Window is not initialized");
104
+ }
105
+ this.windowRef = windowRef;
106
+ return windowRef;
107
+ };
108
+ WindowHandler.prototype.close = function () {
109
+ if (!this.windowRef) {
110
+ throw new Error("Window is not initialized");
111
+ }
112
+ this.windowRef.close();
113
+ };
114
+ return WindowHandler;
115
+ }());
116
+ function openWindow(_a) {
117
+ var url = _a.url, width = _a.width, height = _a.height, win = _a.win;
118
+ if (!win.top) {
119
+ return null;
120
+ }
121
+ var y = win.top.outerHeight / 2 + win.top.screenY - height / 2;
122
+ var x = win.top.outerWidth / 2 + win.top.screenX - width / 2;
123
+ return window.open(url, "", "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(width, ", height=").concat(height, ", top=").concat(y, ", left=").concat(x));
124
+ }
125
+
93
126
  var focusableSelectors = [
94
127
  'a[href]:not([tabindex^="-"])',
95
128
  'area[href]:not([tabindex^="-"])',
@@ -1736,35 +1769,68 @@ var Authsignal = /** @class */ (function () {
1736
1769
  }
1737
1770
  }
1738
1771
  Authsignal.prototype.launch = function (url, options) {
1739
- var _this = this;
1740
- if (!(options === null || options === void 0 ? void 0 : options.mode) || options.mode === "redirect") {
1741
- window.location.href = url;
1772
+ switch (options === null || options === void 0 ? void 0 : options.mode) {
1773
+ case "window":
1774
+ return this.launchWithWindow(url, options);
1775
+ case "popup":
1776
+ return this.launchWithPopup(url, options);
1777
+ case "redirect":
1778
+ default:
1779
+ this.launchWithRedirect(url);
1742
1780
  }
1743
- else {
1744
- var popupOptions = options.popupOptions;
1745
- var Popup_1 = new PopupHandler({ width: popupOptions === null || popupOptions === void 0 ? void 0 : popupOptions.width });
1746
- var popupUrl = "".concat(url, "&mode=popup");
1747
- Popup_1.show({ url: popupUrl });
1748
- return new Promise(function (resolve) {
1749
- var onMessage = function (event) {
1750
- var data = null;
1751
- try {
1752
- data = JSON.parse(event.data);
1753
- }
1754
- catch (_a) {
1755
- // Ignore if the event data is not valid JSON
1756
- }
1757
- if ((data === null || data === void 0 ? void 0 : data.event) === AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP) {
1758
- _this._token = data.token;
1759
- Popup_1.close();
1760
- }
1761
- };
1762
- Popup_1.on("hide", function () {
1763
- resolve({ token: _this._token });
1764
- });
1765
- window.addEventListener("message", onMessage, false);
1781
+ };
1782
+ Authsignal.prototype.launchWithRedirect = function (url) {
1783
+ window.location.href = url;
1784
+ };
1785
+ Authsignal.prototype.launchWithPopup = function (url, options) {
1786
+ var _this = this;
1787
+ var popupOptions = options.popupOptions;
1788
+ var popupHandler = new PopupHandler({ width: popupOptions === null || popupOptions === void 0 ? void 0 : popupOptions.width });
1789
+ var popupUrl = "".concat(url, "&mode=popup");
1790
+ popupHandler.show({ url: popupUrl });
1791
+ return new Promise(function (resolve) {
1792
+ var onMessage = function (event) {
1793
+ var data = null;
1794
+ try {
1795
+ data = JSON.parse(event.data);
1796
+ }
1797
+ catch (_a) {
1798
+ // Ignore if the event data is not valid JSON
1799
+ }
1800
+ if ((data === null || data === void 0 ? void 0 : data.event) === AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP) {
1801
+ _this._token = data.token;
1802
+ popupHandler.close();
1803
+ }
1804
+ };
1805
+ popupHandler.on("hide", function () {
1806
+ resolve({ token: _this._token });
1766
1807
  });
1767
- }
1808
+ window.addEventListener("message", onMessage, false);
1809
+ });
1810
+ };
1811
+ Authsignal.prototype.launchWithWindow = function (url, options) {
1812
+ var _this = this;
1813
+ var windowOptions = options.windowOptions;
1814
+ var windowHandler = new WindowHandler();
1815
+ var windowUrl = "".concat(url, "&mode=popup");
1816
+ windowHandler.show({ url: windowUrl, width: windowOptions === null || windowOptions === void 0 ? void 0 : windowOptions.width, height: windowOptions === null || windowOptions === void 0 ? void 0 : windowOptions.height });
1817
+ return new Promise(function (resolve) {
1818
+ var onMessage = function (event) {
1819
+ var data = null;
1820
+ try {
1821
+ data = JSON.parse(event.data);
1822
+ }
1823
+ catch (_a) {
1824
+ // Ignore if the event data is not valid JSON
1825
+ }
1826
+ if ((data === null || data === void 0 ? void 0 : data.event) === AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP) {
1827
+ _this._token = data.token;
1828
+ windowHandler.close();
1829
+ resolve({ token: _this._token });
1830
+ }
1831
+ };
1832
+ window.addEventListener("message", onMessage, false);
1833
+ });
1768
1834
  };
1769
1835
  return Authsignal;
1770
1836
  }());
package/dist/index.min.js CHANGED
@@ -1,2 +1,2 @@
1
- var authsignal=function(t){"use strict";let e;const n=new Uint8Array(16);function o(){if(!e&&(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}const r=[];for(let t=0;t<256;++t)r.push((t+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(t,e,n){if(i.randomUUID&&!e&&!t)return i.randomUUID();const s=(t=t||{}).random||(t.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e){n=n||0;for(let t=0;t<16;++t)e[n+t]=s[t];return e}return function(t,e=0){return(r[t[e+0]]+r[t[e+1]]+r[t[e+2]]+r[t[e+3]]+"-"+r[t[e+4]]+r[t[e+5]]+"-"+r[t[e+6]]+r[t[e+7]]+"-"+r[t[e+8]]+r[t[e+9]]+"-"+r[t[e+10]]+r[t[e+11]]+r[t[e+12]]+r[t[e+13]]+r[t[e+14]]+r[t[e+15]]).toLowerCase()}(s)}t.AuthsignalWindowMessage=void 0,(t.AuthsignalWindowMessage||(t.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var a=['a[href]:not([tabindex^="-"])','area[href]:not([tabindex^="-"])','input:not([type="hidden"]):not([type="radio"]):not([disabled]):not([tabindex^="-"])','input[type="radio"]:not([disabled]):not([tabindex^="-"])','select:not([disabled]):not([tabindex^="-"])','textarea:not([disabled]):not([tabindex^="-"])','button:not([disabled]):not([tabindex^="-"])','iframe:not([tabindex^="-"])','audio[controls]:not([tabindex^="-"])','video[controls]:not([tabindex^="-"])','[contenteditable]:not([tabindex^="-"])','[tabindex]:not([tabindex^="-"])'];function u(t){this._show=this.show.bind(this),this._hide=this.hide.bind(this),this._maintainFocus=this._maintainFocus.bind(this),this._bindKeypress=this._bindKeypress.bind(this),this.$el=t,this.shown=!1,this._id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this._previouslyFocused=null,this._listeners={},this.create()}function c(t,e){return n=(e||document).querySelectorAll(t),Array.prototype.slice.call(n);var n}function l(t){(t.querySelector("[autofocus]")||t).focus()}function h(){c("[data-a11y-dialog]").forEach((function(t){new u(t)}))}u.prototype.create=function(){this.$el.setAttribute("aria-hidden",!0),this.$el.setAttribute("aria-modal",!0),this.$el.setAttribute("tabindex",-1),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),this._openers=c('[data-a11y-dialog-show="'+this._id+'"]'),this._openers.forEach(function(t){t.addEventListener("click",this._show)}.bind(this));const t=this.$el;return this._closers=c("[data-a11y-dialog-hide]",this.$el).filter((function(e){return e.closest('[aria-modal="true"], [data-a11y-dialog]')===t})).concat(c('[data-a11y-dialog-hide="'+this._id+'"]')),this._closers.forEach(function(t){t.addEventListener("click",this._hide)}.bind(this)),this._fire("create"),this},u.prototype.show=function(t){return this.shown||(this._previouslyFocused=document.activeElement,this.$el.removeAttribute("aria-hidden"),this.shown=!0,l(this.$el),document.body.addEventListener("focus",this._maintainFocus,!0),document.addEventListener("keydown",this._bindKeypress),this._fire("show",t)),this},u.prototype.hide=function(t){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this._previouslyFocused&&this._previouslyFocused.focus&&this._previouslyFocused.focus(),document.body.removeEventListener("focus",this._maintainFocus,!0),document.removeEventListener("keydown",this._bindKeypress),this._fire("hide",t),this):this},u.prototype.destroy=function(){return this.hide(),this._openers.forEach(function(t){t.removeEventListener("click",this._show)}.bind(this)),this._closers.forEach(function(t){t.removeEventListener("click",this._hide)}.bind(this)),this._fire("destroy"),this._listeners={},this},u.prototype.on=function(t,e){return void 0===this._listeners[t]&&(this._listeners[t]=[]),this._listeners[t].push(e),this},u.prototype.off=function(t,e){var n=(this._listeners[t]||[]).indexOf(e);return n>-1&&this._listeners[t].splice(n,1),this},u.prototype._fire=function(t,e){var n=this._listeners[t]||[],o=new CustomEvent(t,{detail:e});this.$el.dispatchEvent(o),n.forEach(function(t){t(this.$el,e)}.bind(this))},u.prototype._bindKeypress=function(t){const e=document.activeElement;e&&e.closest('[aria-modal="true"]')!==this.$el||(this.shown&&"Escape"===t.key&&"alertdialog"!==this.$el.getAttribute("role")&&(t.preventDefault(),this.hide(t)),this.shown&&"Tab"===t.key&&function(t,e){var n=function(t){return c(a.join(","),t).filter((function(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)}))}(t),o=n.indexOf(document.activeElement);e.shiftKey&&0===o?(n[n.length-1].focus(),e.preventDefault()):e.shiftKey||o!==n.length-1||(n[0].focus(),e.preventDefault())}(this.$el,t))},u.prototype._maintainFocus=function(t){!this.shown||t.target.closest('[aria-modal="true"]')||t.target.closest("[data-a11y-dialog-ignore-focus-trap]")||l(this.$el)},"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",h):window.requestAnimationFrame?window.requestAnimationFrame(h):window.setTimeout(h,16));var d="__authsignal-popup-container",p="__authsignal-popup-content",f="__authsignal-popup-overlay",b="__authsignal-popup-style",m="__authsignal-popup-iframe",y="385px",w=function(){function t(t){var e=t.width;if(this.popup=null,document.querySelector("#".concat(d)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:e})}return t.prototype.create=function(t){var e=this,n=t.width,o=void 0===n?y:n,r=o;CSS.supports("width",o)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),r=y);var i=document.createElement("div");i.setAttribute("id",d),i.setAttribute("aria-hidden","true");var s=document.createElement("div");s.setAttribute("id",f),s.setAttribute("data-a11y-dialog-hide","true");var a=document.createElement("div");a.setAttribute("id",p),document.body.appendChild(i);var c=document.createElement("style");c.setAttribute("id",b),c.textContent="\n #".concat(d,",\n #").concat(f," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(d," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(d,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(f," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(p," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(r,";\n }\n\n #").concat(p," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n }\n "),document.head.insertAdjacentElement("beforeend",c),i.appendChild(s),i.appendChild(a),this.popup=new u(i),this.popup.on("hide",(function(){e.destroy()}))},t.prototype.destroy=function(){var t=document.querySelector("#".concat(d)),e=document.querySelector("#".concat(b));t&&e&&(document.body.removeChild(t),document.head.removeChild(e)),window.removeEventListener("message",g)},t.prototype.show=function(t){var e,n=t.url;if(!this.popup)throw new Error("Popup is not initialized");var o=document.createElement("iframe");o.setAttribute("id",m),o.setAttribute("name","authsignal"),o.setAttribute("title","Authsignal multi-factor authentication"),o.setAttribute("src",n),o.setAttribute("frameborder","0"),o.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var r=document.querySelector("#".concat(p));r&&r.appendChild(o),window.addEventListener("message",g),null===(e=this.popup)||void 0===e||e.show()},t.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},t.prototype.on=function(t,e){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(t,e)},t}();function g(t){var e=document.querySelector("#".concat(m));e&&t.data.height&&(e.style.height=t.data.height+"px")}function _(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(t);r<o.length;r++)e.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(t,o[r])&&(n[o[r]]=t[o[r]])}return n}function v(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))}function E(t,e){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){s.label=i[1];break}if(6===i[0]&&s.label<r[1]){s.label=r[1],r=i;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(i);break}r[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function R(t){const e=new Uint8Array(t);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function A(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4,o=e.padEnd(e.length+n,"="),r=atob(o),i=new ArrayBuffer(r.length),s=new Uint8Array(i);for(let t=0;t<r.length;t++)s[t]=r.charCodeAt(t);return i}function T(){return void 0!==window?.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential}function O(t){const{id:e}=t;return{...t,id:A(e),transports:t.transports}}function I(t){return"localhost"===t||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class C extends Error{constructor({message:t,code:e,cause:n,name:o}){super(t,{cause:n}),this.name=o??n.name,this.code=e}}const S=new class{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const t=new AbortController;return this.controller=t,t.signal}},P=["cross-platform","platform"];function x(t){if(t&&!(P.indexOf(t)<0))return t}async function k(t){if(!T())throw new Error("WebAuthn is not supported in this browser");var e;const n={publicKey:{...t,challenge:A(t.challenge),user:{...t.user,id:(e=t.user.id,(new TextEncoder).encode(e))},excludeCredentials:t.excludeCredentials?.map(O)}};let o;n.signal=S.createNewAbortSignal();try{o=await navigator.credentials.create(n)}catch(t){throw function({error:t,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(e.signal instanceof AbortSignal)return new C({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("ConstraintError"===t.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new C({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if("required"===n.authenticatorSelection?.userVerification)return new C({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if("InvalidStateError"===t.name)return new C({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if("NotAllowedError"===t.name)return new C({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if("NotSupportedError"===t.name)return 0===n.pubKeyCredParams.filter((t=>"public-key"===t.type)).length?new C({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new C({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if("SecurityError"===t.name){const e=window.location.hostname;if(!I(e))return new C({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(n.rp.id!==e)return new C({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("TypeError"===t.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new C({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if("UnknownError"===t.name)return new C({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}({error:t,options:n})}if(!o)throw new Error("Registration was not completed");const{id:r,rawId:i,response:s,type:a}=o;let u,c,l,h;if("function"==typeof s.getTransports&&(u=s.getTransports()),"function"==typeof s.getPublicKeyAlgorithm)try{c=s.getPublicKeyAlgorithm()}catch(t){U("getPublicKeyAlgorithm()",t)}if("function"==typeof s.getPublicKey)try{const t=s.getPublicKey();null!==t&&(l=R(t))}catch(t){U("getPublicKey()",t)}if("function"==typeof s.getAuthenticatorData)try{h=R(s.getAuthenticatorData())}catch(t){U("getAuthenticatorData()",t)}return{id:r,rawId:R(i),response:{attestationObject:R(s.attestationObject),clientDataJSON:R(s.clientDataJSON),transports:u,publicKeyAlgorithm:c,publicKey:l,authenticatorData:h},type:a,clientExtensionResults:o.getClientExtensionResults(),authenticatorAttachment:x(o.authenticatorAttachment)}}function U(t,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${t}. You should report this error to them.\n`,e)}async function D(t,e=!1){if(!T())throw new Error("WebAuthn is not supported in this browser");let n;0!==t.allowCredentials?.length&&(n=t.allowCredentials?.map(O));const o={...t,challenge:A(t.challenge),allowCredentials:n},r={};if(e){if(!await function(){const t=window.PublicKeyCredential;return void 0===t.isConditionalMediationAvailable?new Promise((t=>t(!1))):t.isConditionalMediationAvailable()}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');r.mediation="conditional",o.allowCredentials=[]}let i;r.publicKey=o,r.signal=S.createNewAbortSignal();try{i=await navigator.credentials.get(r)}catch(t){throw function({error:t,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(e.signal instanceof AbortSignal)return new C({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if("NotAllowedError"===t.name)return new C({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if("SecurityError"===t.name){const e=window.location.hostname;if(!I(e))return new C({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(n.rpId!==e)return new C({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new C({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}({error:t,options:r})}if(!i)throw new Error("Authentication was not completed");const{id:s,rawId:a,response:u,type:c}=i;let l;var h;return u.userHandle&&(h=u.userHandle,l=new TextDecoder("utf-8").decode(h)),{id:s,rawId:R(a),response:{authenticatorData:R(u.authenticatorData),clientDataJSON:R(u.clientDataJSON),signature:R(u.signature),userHandle:l},type:c,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:x(i.authenticatorAttachment)}}class N extends Error{constructor(t,e,n){const o=`${t.status||0===t.status?t.status:""} ${t.statusText||""}`.trim();super(`Request failed with ${o?`status code ${o}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=n}}class q extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const L=t=>null!==t&&"object"==typeof t,j=(...t)=>{for(const e of t)if((!L(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return H({},...t)},$=(t={},e={})=>{const n=new globalThis.Headers(t),o=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[t,e]of r.entries())o&&"undefined"===e||void 0===e?n.delete(t):n.set(t,e);return n},H=(...t)=>{let e={},n={};for(const o of t)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(L(o)){for(let[t,n]of Object.entries(o))L(n)&&t in e&&(n=H(e[t],n)),e={...e,[t]:n};L(o.headers)&&(n=$(n,o.headers),e.headers=n)}return e},K=(()=>{let t=!1,e=!1;const n="function"==typeof globalThis.ReadableStream,o="function"==typeof globalThis.Request;return n&&o&&(e=new globalThis.Request("https://a.com",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),M="function"==typeof globalThis.AbortController,F="function"==typeof globalThis.ReadableStream,B="function"==typeof globalThis.FormData,G=["get","post","put","patch","head","delete"],V={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},W=2147483647,J=Symbol("stop"),Y=t=>G.includes(t)?t.toUpperCase():t,z=[413,429,503],Q={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:z,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY},X=(t={})=>{if("number"==typeof t)return{...Q,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Q,...t,afterStatusCodes:z}};const Z=Boolean(globalThis.DOMException);function tt(t){if(Z)return new DOMException(t?.reason??"The operation was aborted.","AbortError");const e=new Error(t?.reason??"The operation was aborted.");return e.name="AbortError",e}class et{static create(t,e){const n=new et(t,e),o=async()=>{if(n._options.timeout>W)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await n._fetch();for(const e of n._options.hooks.afterResponse){const o=await e(n.request,n._options,n._decorateResponse(t.clone()));o instanceof globalThis.Response&&(t=o)}if(n._decorateResponse(t),!t.ok&&n._options.throwHttpErrors){let e=new N(t,n.request,n._options);for(const t of n._options.hooks.beforeError)e=await t(e);throw e}if(n._options.onDownloadProgress){if("function"!=typeof n._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!F)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(t.clone(),n._options.onDownloadProgress)}return t},r=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(o):o();for(const[t,o]of Object.entries(V))r[t]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||o);const i=(await r).clone();if("json"===t){if(204===i.status)return"";if(0===(await i.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await i.text())}return i[t]()};return r}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:$(this._input.headers,e.headers),hooks:H({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:Y(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:X(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:void 0===e.timeout?1e4:e.timeout,fetch:e.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(M){if(this.abortController=new globalThis.AbortController,this._options.signal){const t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.reason)}))}this._options.signal=this.abortController.signal}if(K&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(B&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(e,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof q)){if(t instanceof N){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=.3;return Math.min(this._options.retry.backoffLimit,e*2**(this._retryCount-1)*1e3)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const n=Math.min(this._calculateRetryDelay(e),W);if(0!==n&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((n,o)=>{if(e){if(e.aborted)return void o(tt(e));e.addEventListener("abort",r,{once:!0})}function r(){o(tt(e)),clearTimeout(i)}const i=setTimeout((()=>{e?.removeEventListener("abort",r),n()}),t)}))}(n,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===J)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}return!1===this._options.timeout?this._options.fetch(this.request.clone()):async function(t,e,n){return new Promise(((o,r)=>{const i=setTimeout((()=>{e&&e.abort(),r(new q(t))}),n.timeout);n.fetch(t).then(o).catch(r).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),this.abortController,this._options)}_stream(t,e){const n=Number(t.headers.get("content-length"))||0;let o=0;return 204===t.status?(e&&e({percent:1,totalBytes:n,transferredBytes:o},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(r){const i=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array),await async function t(){const{done:s,value:a}=await i.read();if(s)r.close();else{if(e){o+=a.byteLength;e({percent:0===n?0:o/n,transferredBytes:o,totalBytes:n},a)}r.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}
2
- /*! MIT License © Sindre Sorhus */const nt=t=>{const e=(e,n)=>et.create(e,j(t,n));for(const n of G)e[n]=(e,o)=>et.create(e,j(t,o,{method:n}));return e.create=t=>nt(j(t)),e.extend=e=>nt(j(t,e)),e.stop=J,e};var ot=nt(),rt=function(){function t(t){var e=t.baseUrl,n=t.tenantId;this.tenantId=n,this.api=ot.create({prefixUrl:e})}return t.prototype.registrationOptions=function(t){var e=t.token,n=t.userName;return v(this,void 0,void 0,(function(){return E(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey/registration-options",{json:{username:n},headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.authenticationOptions=function(t){var e=t.token;return v(this,void 0,void 0,(function(){return E(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey/authentication-options",{json:{},headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.addAuthenticator=function(t){var e=t.token,n=_(t,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey",{json:n,headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.verify=function(t){var e=t.token,n=_(t,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/verify/passkey",{json:n,headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.buildHeaders=function(t){return{Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(this.tenantId)))}},t}(),it=function(){function t(t){var e=t.baseUrl,n=t.tenantId;this.api=new rt({baseUrl:e,tenantId:n})}return t.prototype.signUp=function(t){var e=t.userName,n=t.token;return v(this,void 0,void 0,(function(){var t,o,r;return E(this,(function(i){switch(i.label){case 0:return[4,this.api.registrationOptions({userName:e,token:n})];case 1:return[4,k((t=i.sent()).options)];case 2:return o=i.sent(),[4,this.api.addAuthenticator({challengeId:t.challengeId,registrationCredential:o,token:n})];case 3:return[2,null==(r=i.sent())?void 0:r.accessToken]}}))}))},t.prototype.signIn=function(t){return v(this,void 0,void 0,(function(){var e,n,o;return E(this,(function(r){switch(r.label){case 0:if((null==t?void 0:t.token)&&t.autofill)throw new Error("Autofill is not supported when providing a token");return[4,this.api.authenticationOptions({token:null==t?void 0:t.token})];case 1:return[4,D((e=r.sent()).options,null==t?void 0:t.autofill)];case 2:return n=r.sent(),[4,this.api.verify({challengeId:e.challengeId,authenticationCredential:n,token:null==t?void 0:t.token})];case 3:return[2,null==(o=r.sent())?void 0:o.accessToken]}}))}))},t}(),st=function(){function e(t){var e=t.cookieDomain,n=t.cookieName,o=void 0===n?"__as_aid":n,r=t.baseUrl,i=void 0===r?"https://api.authsignal.com/v1":r,a=t.tenantId;if(this.anonymousId="",this.cookieDomain="",this.anonymousIdCookieName="",this._token=void 0,this.cookieDomain=e||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,!a)throw new Error("tenantId is required");this.passkey=new it({tenantId:a,baseUrl:i});var u,c=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;c?this.anonymousId=c:(this.anonymousId=s(),function(t){var e=t.name,n=t.value,o=t.expire,r=t.domain,i=t.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(e)+"="+n+"; path=/;"+s+(r?"; domain="+r:"")+(i?"; secure":"")}({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol}))}return e.prototype.launch=function(e,n){var o=this;if((null==n?void 0:n.mode)&&"redirect"!==n.mode){var r=n.popupOptions,i=new w({width:null==r?void 0:r.width}),s="".concat(e,"&mode=popup");return i.show({url:s}),new Promise((function(e){i.on("hide",(function(){e({token:o._token})})),window.addEventListener("message",(function(e){var n=null;try{n=JSON.parse(e.data)}catch(t){}(null==n?void 0:n.event)===t.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o._token=n.token,i.close())}),!1)}))}window.location.href=e},e}();return t.Authsignal=st,Object.defineProperty(t,"__esModule",{value:!0}),t}({});
1
+ var authsignal=function(t){"use strict";let e;const n=new Uint8Array(16);function o(){if(!e&&(e="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!e))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return e(n)}const r=[];for(let t=0;t<256;++t)r.push((t+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(t,e,n){if(i.randomUUID&&!e&&!t)return i.randomUUID();const s=(t=t||{}).random||(t.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,e){n=n||0;for(let t=0;t<16;++t)e[n+t]=s[t];return e}return function(t,e=0){return(r[t[e+0]]+r[t[e+1]]+r[t[e+2]]+r[t[e+3]]+"-"+r[t[e+4]]+r[t[e+5]]+"-"+r[t[e+6]]+r[t[e+7]]+"-"+r[t[e+8]]+r[t[e+9]]+"-"+r[t[e+10]]+r[t[e+11]]+r[t[e+12]]+r[t[e+13]]+r[t[e+14]]+r[t[e+15]]).toLowerCase()}(s)}t.AuthsignalWindowMessage=void 0,(t.AuthsignalWindowMessage||(t.AuthsignalWindowMessage={})).AUTHSIGNAL_CLOSE_POPUP="AUTHSIGNAL_CLOSE_POPUP";var a=function(){function t(){this.windowRef=null}return t.prototype.show=function(t){var e=t.url,n=t.width,o=void 0===n?400:n,r=t.height,i=function(t){var e=t.url,n=t.width,o=t.height,r=t.win;if(!r.top)return null;var i=r.top.outerHeight/2+r.top.screenY-o/2,s=r.top.outerWidth/2+r.top.screenX-n/2;return window.open(e,"","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=".concat(n,", height=").concat(o,", top=").concat(i,", left=").concat(s))}({url:e,width:o,height:void 0===r?500:r,win:window});if(!i)throw new Error("Window is not initialized");return this.windowRef=i,i},t.prototype.close=function(){if(!this.windowRef)throw new Error("Window is not initialized");this.windowRef.close()},t}();var u=['a[href]:not([tabindex^="-"])','area[href]:not([tabindex^="-"])','input:not([type="hidden"]):not([type="radio"]):not([disabled]):not([tabindex^="-"])','input[type="radio"]:not([disabled]):not([tabindex^="-"])','select:not([disabled]):not([tabindex^="-"])','textarea:not([disabled]):not([tabindex^="-"])','button:not([disabled]):not([tabindex^="-"])','iframe:not([tabindex^="-"])','audio[controls]:not([tabindex^="-"])','video[controls]:not([tabindex^="-"])','[contenteditable]:not([tabindex^="-"])','[tabindex]:not([tabindex^="-"])'];function c(t){this._show=this.show.bind(this),this._hide=this.hide.bind(this),this._maintainFocus=this._maintainFocus.bind(this),this._bindKeypress=this._bindKeypress.bind(this),this.$el=t,this.shown=!1,this._id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this._previouslyFocused=null,this._listeners={},this.create()}function l(t,e){return n=(e||document).querySelectorAll(t),Array.prototype.slice.call(n);var n}function h(t){(t.querySelector("[autofocus]")||t).focus()}function d(){l("[data-a11y-dialog]").forEach((function(t){new c(t)}))}c.prototype.create=function(){this.$el.setAttribute("aria-hidden",!0),this.$el.setAttribute("aria-modal",!0),this.$el.setAttribute("tabindex",-1),this.$el.hasAttribute("role")||this.$el.setAttribute("role","dialog"),this._openers=l('[data-a11y-dialog-show="'+this._id+'"]'),this._openers.forEach(function(t){t.addEventListener("click",this._show)}.bind(this));const t=this.$el;return this._closers=l("[data-a11y-dialog-hide]",this.$el).filter((function(e){return e.closest('[aria-modal="true"], [data-a11y-dialog]')===t})).concat(l('[data-a11y-dialog-hide="'+this._id+'"]')),this._closers.forEach(function(t){t.addEventListener("click",this._hide)}.bind(this)),this._fire("create"),this},c.prototype.show=function(t){return this.shown||(this._previouslyFocused=document.activeElement,this.$el.removeAttribute("aria-hidden"),this.shown=!0,h(this.$el),document.body.addEventListener("focus",this._maintainFocus,!0),document.addEventListener("keydown",this._bindKeypress),this._fire("show",t)),this},c.prototype.hide=function(t){return this.shown?(this.shown=!1,this.$el.setAttribute("aria-hidden","true"),this._previouslyFocused&&this._previouslyFocused.focus&&this._previouslyFocused.focus(),document.body.removeEventListener("focus",this._maintainFocus,!0),document.removeEventListener("keydown",this._bindKeypress),this._fire("hide",t),this):this},c.prototype.destroy=function(){return this.hide(),this._openers.forEach(function(t){t.removeEventListener("click",this._show)}.bind(this)),this._closers.forEach(function(t){t.removeEventListener("click",this._hide)}.bind(this)),this._fire("destroy"),this._listeners={},this},c.prototype.on=function(t,e){return void 0===this._listeners[t]&&(this._listeners[t]=[]),this._listeners[t].push(e),this},c.prototype.off=function(t,e){var n=(this._listeners[t]||[]).indexOf(e);return n>-1&&this._listeners[t].splice(n,1),this},c.prototype._fire=function(t,e){var n=this._listeners[t]||[],o=new CustomEvent(t,{detail:e});this.$el.dispatchEvent(o),n.forEach(function(t){t(this.$el,e)}.bind(this))},c.prototype._bindKeypress=function(t){const e=document.activeElement;e&&e.closest('[aria-modal="true"]')!==this.$el||(this.shown&&"Escape"===t.key&&"alertdialog"!==this.$el.getAttribute("role")&&(t.preventDefault(),this.hide(t)),this.shown&&"Tab"===t.key&&function(t,e){var n=function(t){return l(u.join(","),t).filter((function(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)}))}(t),o=n.indexOf(document.activeElement);e.shiftKey&&0===o?(n[n.length-1].focus(),e.preventDefault()):e.shiftKey||o!==n.length-1||(n[0].focus(),e.preventDefault())}(this.$el,t))},c.prototype._maintainFocus=function(t){!this.shown||t.target.closest('[aria-modal="true"]')||t.target.closest("[data-a11y-dialog-ignore-focus-trap]")||h(this.$el)},"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",d):window.requestAnimationFrame?window.requestAnimationFrame(d):window.setTimeout(d,16));var p="__authsignal-popup-container",f="__authsignal-popup-content",w="__authsignal-popup-overlay",b="__authsignal-popup-style",y="__authsignal-popup-iframe",m="385px",g=function(){function t(t){var e=t.width;if(this.popup=null,document.querySelector("#".concat(p)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:e})}return t.prototype.create=function(t){var e=this,n=t.width,o=void 0===n?m:n,r=o;CSS.supports("width",o)||(console.warn("Invalid CSS value for `popupOptions.width`. Using default value instead."),r=m);var i=document.createElement("div");i.setAttribute("id",p),i.setAttribute("aria-hidden","true");var s=document.createElement("div");s.setAttribute("id",w),s.setAttribute("data-a11y-dialog-hide","true");var a=document.createElement("div");a.setAttribute("id",f),document.body.appendChild(i);var u=document.createElement("style");u.setAttribute("id",b),u.textContent="\n #".concat(p,",\n #").concat(w," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(p," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(p,"[aria-hidden='true'] {\n display: none;\n }\n\n #").concat(w," {\n background-color: rgba(0, 0, 0, 0.18);\n }\n\n #").concat(f," {\n margin: auto;\n z-index: 2147483647;\n position: relative;\n background-color: transparent;\n border-radius: 8px;\n width: ").concat(r,";\n }\n\n #").concat(f," iframe {\n width: 1px;\n min-width: 100%;\n border-radius: inherit;\n max-height: 95vh;\n }\n "),document.head.insertAdjacentElement("beforeend",u),i.appendChild(s),i.appendChild(a),this.popup=new c(i),this.popup.on("hide",(function(){e.destroy()}))},t.prototype.destroy=function(){var t=document.querySelector("#".concat(p)),e=document.querySelector("#".concat(b));t&&e&&(document.body.removeChild(t),document.head.removeChild(e)),window.removeEventListener("message",_)},t.prototype.show=function(t){var e,n=t.url;if(!this.popup)throw new Error("Popup is not initialized");var o=document.createElement("iframe");o.setAttribute("id",y),o.setAttribute("name","authsignal"),o.setAttribute("title","Authsignal multi-factor authentication"),o.setAttribute("src",n),o.setAttribute("frameborder","0"),o.setAttribute("allow","publickey-credentials-get *; publickey-credentials-create *; clipboard-write");var r=document.querySelector("#".concat(f));r&&r.appendChild(o),window.addEventListener("message",_),null===(e=this.popup)||void 0===e||e.show()},t.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},t.prototype.on=function(t,e){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(t,e)},t}();function _(t){var e=document.querySelector("#".concat(y));e&&t.data.height&&(e.style.height=t.data.height+"px")}function v(t,e){var n={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(n[o]=t[o]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(t);r<o.length;r++)e.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(t,o[r])&&(n[o[r]]=t[o[r]])}return n}function E(t,e,n,o){return new(n||(n=Promise))((function(r,i){function s(t){try{u(o.next(t))}catch(t){i(t)}}function a(t){try{u(o.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(s,a)}u((o=o.apply(t,e||[])).next())}))}function R(t,e){var n,o,r,i,s={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,o&&(r=2&i[0]?o.return:i[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,i[1])).done)return r;switch(o=0,r&&(i=[2&i[0],r.value]),i[0]){case 0:case 1:r=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,o=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(r=s.trys,(r=r.length>0&&r[r.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!r||i[1]>r[0]&&i[1]<r[3])){s.label=i[1];break}if(6===i[0]&&s.label<r[1]){s.label=r[1],r=i;break}if(r&&s.label<r[2]){s.label=r[2],s.ops.push(i);break}r[2]&&s.ops.pop(),s.trys.pop();continue}i=e.call(t,s)}catch(t){i=[6,t],o=0}finally{n=r=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function A(t){const e=new Uint8Array(t);let n="";for(const t of e)n+=String.fromCharCode(t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function T(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4,o=e.padEnd(e.length+n,"="),r=atob(o),i=new ArrayBuffer(r.length),s=new Uint8Array(i);for(let t=0;t<r.length;t++)s[t]=r.charCodeAt(t);return i}function O(){return void 0!==window?.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential}function I(t){const{id:e}=t;return{...t,id:T(e),transports:t.transports}}function C(t){return"localhost"===t||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(t)}class P extends Error{constructor({message:t,code:e,cause:n,name:o}){super(t,{cause:n}),this.name=o??n.name,this.code=e}}const S=new class{createNewAbortSignal(){if(this.controller){const t=new Error("Cancelling existing WebAuthn API call for new one");t.name="AbortError",this.controller.abort(t)}const t=new AbortController;return this.controller=t,t.signal}},x=["cross-platform","platform"];function k(t){if(t&&!(x.indexOf(t)<0))return t}async function U(t){if(!O())throw new Error("WebAuthn is not supported in this browser");var e;const n={publicKey:{...t,challenge:T(t.challenge),user:{...t.user,id:(e=t.user.id,(new TextEncoder).encode(e))},excludeCredentials:t.excludeCredentials?.map(I)}};let o;n.signal=S.createNewAbortSignal();try{o=await navigator.credentials.create(n)}catch(t){throw function({error:t,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(e.signal instanceof AbortSignal)return new P({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else if("ConstraintError"===t.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new P({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:t});if("required"===n.authenticatorSelection?.userVerification)return new P({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:t})}else{if("InvalidStateError"===t.name)return new P({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:t});if("NotAllowedError"===t.name)return new P({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if("NotSupportedError"===t.name)return 0===n.pubKeyCredParams.filter((t=>"public-key"===t.type)).length?new P({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:t}):new P({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:t});if("SecurityError"===t.name){const e=window.location.hostname;if(!C(e))return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(n.rp.id!==e)return new P({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("TypeError"===t.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new P({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:t})}else if("UnknownError"===t.name)return new P({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}({error:t,options:n})}if(!o)throw new Error("Registration was not completed");const{id:r,rawId:i,response:s,type:a}=o;let u,c,l,h;if("function"==typeof s.getTransports&&(u=s.getTransports()),"function"==typeof s.getPublicKeyAlgorithm)try{c=s.getPublicKeyAlgorithm()}catch(t){N("getPublicKeyAlgorithm()",t)}if("function"==typeof s.getPublicKey)try{const t=s.getPublicKey();null!==t&&(l=A(t))}catch(t){N("getPublicKey()",t)}if("function"==typeof s.getAuthenticatorData)try{h=A(s.getAuthenticatorData())}catch(t){N("getAuthenticatorData()",t)}return{id:r,rawId:A(i),response:{attestationObject:A(s.attestationObject),clientDataJSON:A(s.clientDataJSON),transports:u,publicKeyAlgorithm:c,publicKey:l,authenticatorData:h},type:a,clientExtensionResults:o.getClientExtensionResults(),authenticatorAttachment:k(o.authenticatorAttachment)}}function N(t,e){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${t}. You should report this error to them.\n`,e)}async function D(t,e=!1){if(!O())throw new Error("WebAuthn is not supported in this browser");let n;0!==t.allowCredentials?.length&&(n=t.allowCredentials?.map(I));const o={...t,challenge:T(t.challenge),allowCredentials:n},r={};if(e){if(!await function(){const t=window.PublicKeyCredential;return void 0===t.isConditionalMediationAvailable?new Promise((t=>t(!1))):t.isConditionalMediationAvailable()}())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete*='webauthn']").length<1)throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');r.mediation="conditional",o.allowCredentials=[]}let i;r.publicKey=o,r.signal=S.createNewAbortSignal();try{i=await navigator.credentials.get(r)}catch(t){throw function({error:t,options:e}){const{publicKey:n}=e;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===t.name){if(e.signal instanceof AbortSignal)return new P({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:t})}else{if("NotAllowedError"===t.name)return new P({message:t.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:t});if("SecurityError"===t.name){const e=window.location.hostname;if(!C(e))return new P({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:t});if(n.rpId!==e)return new P({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:t})}else if("UnknownError"===t.name)return new P({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:t})}return t}({error:t,options:r})}if(!i)throw new Error("Authentication was not completed");const{id:s,rawId:a,response:u,type:c}=i;let l;var h;return u.userHandle&&(h=u.userHandle,l=new TextDecoder("utf-8").decode(h)),{id:s,rawId:A(a),response:{authenticatorData:A(u.authenticatorData),clientDataJSON:A(u.clientDataJSON),signature:A(u.signature),userHandle:l},type:c,clientExtensionResults:i.getClientExtensionResults(),authenticatorAttachment:k(i.authenticatorAttachment)}}class q extends Error{constructor(t,e,n){const o=`${t.status||0===t.status?t.status:""} ${t.statusText||""}`.trim();super(`Request failed with ${o?`status code ${o}`:"an unknown error"}`),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="HTTPError",this.response=t,this.request=e,this.options=n}}class L extends Error{constructor(t){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=t}}const j=t=>null!==t&&"object"==typeof t,$=(...t)=>{for(const e of t)if((!j(e)||Array.isArray(e))&&void 0!==e)throw new TypeError("The `options` argument must be an object");return K({},...t)},H=(t={},e={})=>{const n=new globalThis.Headers(t),o=e instanceof globalThis.Headers,r=new globalThis.Headers(e);for(const[t,e]of r.entries())o&&"undefined"===e||void 0===e?n.delete(t):n.set(t,e);return n},K=(...t)=>{let e={},n={};for(const o of t)if(Array.isArray(o))Array.isArray(e)||(e=[]),e=[...e,...o];else if(j(o)){for(let[t,n]of Object.entries(o))j(n)&&t in e&&(n=K(e[t],n)),e={...e,[t]:n};j(o.headers)&&(n=H(n,o.headers),e.headers=n)}return e},M=(()=>{let t=!1,e=!1;const n="function"==typeof globalThis.ReadableStream,o="function"==typeof globalThis.Request;return n&&o&&(e=new globalThis.Request("https://a.com",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type")),t&&!e})(),W="function"==typeof globalThis.AbortController,F="function"==typeof globalThis.ReadableStream,B="function"==typeof globalThis.FormData,G=["get","post","put","patch","head","delete"],V={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},z=2147483647,J=Symbol("stop"),Y=t=>G.includes(t)?t.toUpperCase():t,X=[413,429,503],Q={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:X,maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY},Z=(t={})=>{if("number"==typeof t)return{...Q,limit:t};if(t.methods&&!Array.isArray(t.methods))throw new Error("retry.methods must be an array");if(t.statusCodes&&!Array.isArray(t.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Q,...t,afterStatusCodes:X}};const tt=Boolean(globalThis.DOMException);function et(t){if(tt)return new DOMException(t?.reason??"The operation was aborted.","AbortError");const e=new Error(t?.reason??"The operation was aborted.");return e.name="AbortError",e}class nt{static create(t,e){const n=new nt(t,e),o=async()=>{if(n._options.timeout>z)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let t=await n._fetch();for(const e of n._options.hooks.afterResponse){const o=await e(n.request,n._options,n._decorateResponse(t.clone()));o instanceof globalThis.Response&&(t=o)}if(n._decorateResponse(t),!t.ok&&n._options.throwHttpErrors){let e=new q(t,n.request,n._options);for(const t of n._options.hooks.beforeError)e=await t(e);throw e}if(n._options.onDownloadProgress){if("function"!=typeof n._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!F)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(t.clone(),n._options.onDownloadProgress)}return t},r=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(o):o();for(const[t,o]of Object.entries(V))r[t]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||o);const i=(await r).clone();if("json"===t){if(204===i.status)return"";if(0===(await i.clone().arrayBuffer()).byteLength)return"";if(e.parseJson)return e.parseJson(await i.text())}return i[t]()};return r}constructor(t,e={}){if(Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"abortController",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_retryCount",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"_input",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._input=t,this._options={credentials:this._input.credentials||"same-origin",...e,headers:H(this._input.headers,e.headers),hooks:K({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:Y(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:Z(e.retry),throwHttpErrors:!1!==e.throwHttpErrors,timeout:void 0===e.timeout?1e4:e.timeout,fetch:e.fetch??globalThis.fetch.bind(globalThis)},"string"!=typeof this._input&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&"string"==typeof this._input){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(W){if(this.abortController=new globalThis.AbortController,this._options.signal){const t=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(t.reason)}))}this._options.signal=this.abortController.signal}if(M&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const t="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),e=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);!(B&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)||this._options.headers&&this._options.headers["content-type"]||this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(e,{...this.request}),this._options)}void 0!==this._options.json&&(this._options.body=JSON.stringify(this._options.json),this.request.headers.set("content-type",this._options.headers.get("content-type")??"application/json"),this.request=new globalThis.Request(this.request,{body:this._options.body}))}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(t instanceof L)){if(t instanceof q){if(!this._options.retry.statusCodes.includes(t.response.status))return 0;const e=t.response.headers.get("Retry-After");if(e&&this._options.retry.afterStatusCodes.includes(t.response.status)){let t=Number(e);return Number.isNaN(t)?t=Date.parse(e)-Date.now():t*=1e3,void 0!==this._options.retry.maxRetryAfter&&t>this._options.retry.maxRetryAfter?0:t}if(413===t.response.status)return 0}const e=.3;return Math.min(this._options.retry.backoffLimit,e*2**(this._retryCount-1)*1e3)}return 0}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const n=Math.min(this._calculateRetryDelay(e),z);if(0!==n&&this._retryCount>0){await async function(t,{signal:e}){return new Promise(((n,o)=>{if(e){if(e.aborted)return void o(et(e));e.addEventListener("abort",r,{once:!0})}function r(){o(et(e)),clearTimeout(i)}const i=setTimeout((()=>{e?.removeEventListener("abort",r),n()}),t)}))}(n,{signal:this._options.signal});for(const t of this._options.hooks.beforeRetry){if(await t({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===J)return}return this._retry(t)}throw e}}async _fetch(){for(const t of this._options.hooks.beforeRequest){const e=await t(this.request,this._options);if(e instanceof Request){this.request=e;break}if(e instanceof Response)return e}return!1===this._options.timeout?this._options.fetch(this.request.clone()):async function(t,e,n){return new Promise(((o,r)=>{const i=setTimeout((()=>{e&&e.abort(),r(new L(t))}),n.timeout);n.fetch(t).then(o).catch(r).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),this.abortController,this._options)}_stream(t,e){const n=Number(t.headers.get("content-length"))||0;let o=0;return 204===t.status?(e&&e({percent:1,totalBytes:n,transferredBytes:o},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(r){const i=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array),await async function t(){const{done:s,value:a}=await i.read();if(s)r.close();else{if(e){o+=a.byteLength;e({percent:0===n?0:o/n,transferredBytes:o,totalBytes:n},a)}r.enqueue(a),await t()}}()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}
2
+ /*! MIT License © Sindre Sorhus */const ot=t=>{const e=(e,n)=>nt.create(e,$(t,n));for(const n of G)e[n]=(e,o)=>nt.create(e,$(t,o,{method:n}));return e.create=t=>ot($(t)),e.extend=e=>ot($(t,e)),e.stop=J,e};var rt=ot(),it=function(){function t(t){var e=t.baseUrl,n=t.tenantId;this.tenantId=n,this.api=rt.create({prefixUrl:e})}return t.prototype.registrationOptions=function(t){var e=t.token,n=t.userName;return E(this,void 0,void 0,(function(){return R(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey/registration-options",{json:{username:n},headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.authenticationOptions=function(t){var e=t.token;return E(this,void 0,void 0,(function(){return R(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey/authentication-options",{json:{},headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.addAuthenticator=function(t){var e=t.token,n=v(t,["token"]);return E(this,void 0,void 0,(function(){return R(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/user-authenticators/passkey",{json:n,headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.verify=function(t){var e=t.token,n=v(t,["token"]);return E(this,void 0,void 0,(function(){return R(this,(function(t){switch(t.label){case 0:return[4,this.api.post("client/verify/passkey",{json:n,headers:this.buildHeaders(e)})];case 1:return[2,t.sent().json()]}}))}))},t.prototype.buildHeaders=function(t){return{Authorization:t?"Bearer ".concat(t):"Basic ".concat(window.btoa(encodeURIComponent(this.tenantId)))}},t}(),st=function(){function t(t){var e=t.baseUrl,n=t.tenantId;this.api=new it({baseUrl:e,tenantId:n})}return t.prototype.signUp=function(t){var e=t.userName,n=t.token;return E(this,void 0,void 0,(function(){var t,o,r;return R(this,(function(i){switch(i.label){case 0:return[4,this.api.registrationOptions({userName:e,token:n})];case 1:return[4,U((t=i.sent()).options)];case 2:return o=i.sent(),[4,this.api.addAuthenticator({challengeId:t.challengeId,registrationCredential:o,token:n})];case 3:return[2,null==(r=i.sent())?void 0:r.accessToken]}}))}))},t.prototype.signIn=function(t){return E(this,void 0,void 0,(function(){var e,n,o;return R(this,(function(r){switch(r.label){case 0:if((null==t?void 0:t.token)&&t.autofill)throw new Error("Autofill is not supported when providing a token");return[4,this.api.authenticationOptions({token:null==t?void 0:t.token})];case 1:return[4,D((e=r.sent()).options,null==t?void 0:t.autofill)];case 2:return n=r.sent(),[4,this.api.verify({challengeId:e.challengeId,authenticationCredential:n,token:null==t?void 0:t.token})];case 3:return[2,null==(o=r.sent())?void 0:o.accessToken]}}))}))},t}(),at=function(){function e(t){var e=t.cookieDomain,n=t.cookieName,o=void 0===n?"__as_aid":n,r=t.baseUrl,i=void 0===r?"https://api.authsignal.com/v1":r,a=t.tenantId;if(this.anonymousId="",this.cookieDomain="",this.anonymousIdCookieName="",this._token=void 0,this.cookieDomain=e||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,!a)throw new Error("tenantId is required");this.passkey=new st({tenantId:a,baseUrl:i});var u,c=(u=this.anonymousIdCookieName)&&decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*"+encodeURIComponent(u).replace(/[\-\.\+\*]/g,"\\$&")+"\\s*\\=\\s*([^;]*).*$)|^.*$"),"$1"))||null;c?this.anonymousId=c:(this.anonymousId=s(),function(t){var e=t.name,n=t.value,o=t.expire,r=t.domain,i=t.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(e)+"="+n+"; path=/;"+s+(r?"; domain="+r:"")+(i?"; secure":"")}({name:this.anonymousIdCookieName,value:this.anonymousId,expire:1/0,domain:this.cookieDomain,secure:"http:"!==document.location.protocol}))}return e.prototype.launch=function(t,e){switch(null==e?void 0:e.mode){case"window":return this.launchWithWindow(t,e);case"popup":return this.launchWithPopup(t,e);default:this.launchWithRedirect(t)}},e.prototype.launchWithRedirect=function(t){window.location.href=t},e.prototype.launchWithPopup=function(e,n){var o=this,r=n.popupOptions,i=new g({width:null==r?void 0:r.width}),s="".concat(e,"&mode=popup");return i.show({url:s}),new Promise((function(e){i.on("hide",(function(){e({token:o._token})})),window.addEventListener("message",(function(e){var n=null;try{n=JSON.parse(e.data)}catch(t){}(null==n?void 0:n.event)===t.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o._token=n.token,i.close())}),!1)}))},e.prototype.launchWithWindow=function(e,n){var o=this,r=n.windowOptions,i=new a,s="".concat(e,"&mode=popup");return i.show({url:s,width:null==r?void 0:r.width,height:null==r?void 0:r.height}),new Promise((function(e){window.addEventListener("message",(function(n){var r=null;try{r=JSON.parse(n.data)}catch(t){}(null==r?void 0:r.event)===t.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o._token=r.token,i.close(),e({token:o._token}))}),!1)}))},e}();return t.Authsignal=at,Object.defineProperty(t,"__esModule",{value:!0}),t}({});
package/dist/types.d.ts CHANGED
@@ -5,12 +5,12 @@ declare type BaseLaunchOptions = {
5
5
  * will trigger a full page redirect.
6
6
  * If no value is supplied, mode defaults to `redirect`.
7
7
  */
8
- mode?: "popup" | "redirect";
8
+ mode?: "popup" | "redirect" | "window";
9
9
  };
10
- declare type RedirectLaunchOptions = BaseLaunchOptions & {
10
+ export declare type RedirectLaunchOptions = BaseLaunchOptions & {
11
11
  mode: "redirect";
12
12
  };
13
- declare type PopupLaunchOptions = BaseLaunchOptions & {
13
+ export declare type PopupLaunchOptions = BaseLaunchOptions & {
14
14
  mode: "popup";
15
15
  popupOptions?: {
16
16
  /** Any valid CSS value for the `width` property. */
@@ -21,7 +21,14 @@ declare type PopupLaunchOptions = BaseLaunchOptions & {
21
21
  height?: string;
22
22
  };
23
23
  };
24
- export declare type LaunchOptions = RedirectLaunchOptions | PopupLaunchOptions;
24
+ export declare type WindowLaunchOptions = BaseLaunchOptions & {
25
+ mode: "window";
26
+ windowOptions?: {
27
+ width?: number;
28
+ height?: number;
29
+ };
30
+ };
31
+ export declare type LaunchOptions = RedirectLaunchOptions | PopupLaunchOptions | WindowLaunchOptions;
25
32
  export declare type AuthsignalOptions = {
26
33
  /**
27
34
  * Cookie domain that will be used to identify
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authsignal/browser",
3
- "version": "0.3.2",
3
+ "version": "0.3.3",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",