@authsignal/browser 0.3.0 → 0.3.1
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.
- package/dist/index.js +52 -13
- package/dist/index.min.js +2 -2
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -659,7 +659,7 @@ function __generator(thisArg, body) {
|
|
|
659
659
|
}
|
|
660
660
|
}
|
|
661
661
|
|
|
662
|
-
/* [@simplewebauthn/browser@
|
|
662
|
+
/* [@simplewebauthn/browser@8.2.1] */
|
|
663
663
|
function utf8StringToBuffer(value) {
|
|
664
664
|
return new TextEncoder().encode(value);
|
|
665
665
|
}
|
|
@@ -688,7 +688,8 @@ function base64URLStringToBuffer(base64URLString) {
|
|
|
688
688
|
}
|
|
689
689
|
|
|
690
690
|
function browserSupportsWebAuthn() {
|
|
691
|
-
return (window?.PublicKeyCredential !== undefined &&
|
|
691
|
+
return (window?.PublicKeyCredential !== undefined &&
|
|
692
|
+
typeof window.PublicKeyCredential === 'function');
|
|
692
693
|
}
|
|
693
694
|
|
|
694
695
|
function toPublicKeyCredentialDescriptor(descriptor) {
|
|
@@ -701,11 +702,11 @@ function toPublicKeyCredentialDescriptor(descriptor) {
|
|
|
701
702
|
}
|
|
702
703
|
|
|
703
704
|
function isValidDomain(hostname) {
|
|
704
|
-
return (hostname === 'localhost' ||
|
|
705
|
+
return (hostname === 'localhost' ||
|
|
706
|
+
/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
|
|
705
707
|
}
|
|
706
708
|
|
|
707
709
|
class WebAuthnError extends Error {
|
|
708
|
-
code;
|
|
709
710
|
constructor({ message, code, cause, name, }) {
|
|
710
711
|
super(message, { cause });
|
|
711
712
|
this.name = name ?? cause.name;
|
|
@@ -747,7 +748,7 @@ function identifyRegistrationError({ error, options, }) {
|
|
|
747
748
|
return new WebAuthnError({
|
|
748
749
|
message: 'The authenticator was previously registered',
|
|
749
750
|
code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
|
|
750
|
-
cause: error
|
|
751
|
+
cause: error,
|
|
751
752
|
});
|
|
752
753
|
}
|
|
753
754
|
else if (error.name === 'NotAllowedError') {
|
|
@@ -758,7 +759,7 @@ function identifyRegistrationError({ error, options, }) {
|
|
|
758
759
|
});
|
|
759
760
|
}
|
|
760
761
|
else if (error.name === 'NotSupportedError') {
|
|
761
|
-
const validPubKeyCredParams = publicKey.pubKeyCredParams.filter(param => param.type === 'public-key');
|
|
762
|
+
const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');
|
|
762
763
|
if (validPubKeyCredParams.length === 0) {
|
|
763
764
|
return new WebAuthnError({
|
|
764
765
|
message: 'No entry in pubKeyCredParams was of type "public-key"',
|
|
@@ -778,7 +779,7 @@ function identifyRegistrationError({ error, options, }) {
|
|
|
778
779
|
return new WebAuthnError({
|
|
779
780
|
message: `${window.location.hostname} is an invalid domain`,
|
|
780
781
|
code: 'ERROR_INVALID_DOMAIN',
|
|
781
|
-
cause: error
|
|
782
|
+
cause: error,
|
|
782
783
|
});
|
|
783
784
|
}
|
|
784
785
|
else if (publicKey.rp.id !== effectiveDomain) {
|
|
@@ -809,7 +810,6 @@ function identifyRegistrationError({ error, options, }) {
|
|
|
809
810
|
}
|
|
810
811
|
|
|
811
812
|
class WebAuthnAbortService {
|
|
812
|
-
controller;
|
|
813
813
|
createNewAbortSignal() {
|
|
814
814
|
if (this.controller) {
|
|
815
815
|
const abortError = new Error('Cancelling existing WebAuthn API call for new one');
|
|
@@ -864,6 +864,36 @@ async function startRegistration(creationOptionsJSON) {
|
|
|
864
864
|
if (typeof response.getTransports === 'function') {
|
|
865
865
|
transports = response.getTransports();
|
|
866
866
|
}
|
|
867
|
+
let responsePublicKeyAlgorithm = undefined;
|
|
868
|
+
if (typeof response.getPublicKeyAlgorithm === 'function') {
|
|
869
|
+
try {
|
|
870
|
+
responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();
|
|
871
|
+
}
|
|
872
|
+
catch (error) {
|
|
873
|
+
warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
let responsePublicKey = undefined;
|
|
877
|
+
if (typeof response.getPublicKey === 'function') {
|
|
878
|
+
try {
|
|
879
|
+
const _publicKey = response.getPublicKey();
|
|
880
|
+
if (_publicKey !== null) {
|
|
881
|
+
responsePublicKey = bufferToBase64URLString(_publicKey);
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
catch (error) {
|
|
885
|
+
warnOnBrokenImplementation('getPublicKey()', error);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
let responseAuthenticatorData;
|
|
889
|
+
if (typeof response.getAuthenticatorData === 'function') {
|
|
890
|
+
try {
|
|
891
|
+
responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());
|
|
892
|
+
}
|
|
893
|
+
catch (error) {
|
|
894
|
+
warnOnBrokenImplementation('getAuthenticatorData()', error);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
867
897
|
return {
|
|
868
898
|
id,
|
|
869
899
|
rawId: bufferToBase64URLString(rawId),
|
|
@@ -871,21 +901,30 @@ async function startRegistration(creationOptionsJSON) {
|
|
|
871
901
|
attestationObject: bufferToBase64URLString(response.attestationObject),
|
|
872
902
|
clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
|
|
873
903
|
transports,
|
|
904
|
+
publicKeyAlgorithm: responsePublicKeyAlgorithm,
|
|
905
|
+
publicKey: responsePublicKey,
|
|
906
|
+
authenticatorData: responseAuthenticatorData,
|
|
874
907
|
},
|
|
875
908
|
type,
|
|
876
909
|
clientExtensionResults: credential.getClientExtensionResults(),
|
|
877
910
|
authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
|
|
878
911
|
};
|
|
879
912
|
}
|
|
913
|
+
function warnOnBrokenImplementation(methodName, cause) {
|
|
914
|
+
console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\n`, cause);
|
|
915
|
+
}
|
|
880
916
|
|
|
881
917
|
function bufferToUTF8String(value) {
|
|
882
918
|
return new TextDecoder('utf-8').decode(value);
|
|
883
919
|
}
|
|
884
920
|
|
|
885
|
-
|
|
886
|
-
const globalPublicKeyCredential = window
|
|
887
|
-
|
|
888
|
-
|
|
921
|
+
function browserSupportsWebAuthnAutofill() {
|
|
922
|
+
const globalPublicKeyCredential = window
|
|
923
|
+
.PublicKeyCredential;
|
|
924
|
+
if (globalPublicKeyCredential.isConditionalMediationAvailable === undefined) {
|
|
925
|
+
return new Promise((resolve) => resolve(false));
|
|
926
|
+
}
|
|
927
|
+
return globalPublicKeyCredential.isConditionalMediationAvailable();
|
|
889
928
|
}
|
|
890
929
|
|
|
891
930
|
function identifyAuthenticationError({ error, options, }) {
|
|
@@ -954,7 +993,7 @@ async function startAuthentication(requestOptionsJSON, useBrowserAutofill = fals
|
|
|
954
993
|
if (!(await browserSupportsWebAuthnAutofill())) {
|
|
955
994
|
throw Error('Browser does not support WebAuthn autofill');
|
|
956
995
|
}
|
|
957
|
-
const eligibleInputs = document.querySelectorAll(
|
|
996
|
+
const eligibleInputs = document.querySelectorAll('input[autocomplete*=\'webauthn\']');
|
|
958
997
|
if (eligibleInputs.length < 1) {
|
|
959
998
|
throw Error('No <input> with `"webauthn"` in its `autocomplete` attribute was detected');
|
|
960
999
|
}
|
package/dist/index.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var authsignal=function(e){"use strict";let t;const n=new Uint8Array(16);function o(){if(!t&&(t="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!t))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return t(n)}const r=[];for(let e=0;e<256;++e)r.push((e+256).toString(16).slice(1));var i={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function s(e,t,n){if(i.randomUUID&&!t&&!e)return i.randomUUID();const s=(e=e||{}).random||(e.rng||o)();if(s[6]=15&s[6]|64,s[8]=63&s[8]|128,t){n=n||0;for(let e=0;e<16;++e)t[n+e]=s[e];return t}return function(e,t=0){return(r[e[t+0]]+r[e[t+1]]+r[e[t+2]]+r[e[t+3]]+"-"+r[e[t+4]]+r[e[t+5]]+"-"+r[e[t+6]]+r[e[t+7]]+"-"+r[e[t+8]]+r[e[t+9]]+"-"+r[e[t+10]]+r[e[t+11]]+r[e[t+12]]+r[e[t+13]]+r[e[t+14]]+r[e[t+15]]).toLowerCase()}(s)}e.AuthsignalWindowMessage=void 0,(e.AuthsignalWindowMessage||(e.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(e){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=e,this.shown=!1,this._id=this.$el.getAttribute("data-a11y-dialog")||this.$el.id,this._previouslyFocused=null,this._listeners={},this.create()}function c(e,t){return n=(t||document).querySelectorAll(e),Array.prototype.slice.call(n);var n}function l(e){(e.querySelector("[autofocus]")||e).focus()}function d(){c("[data-a11y-dialog]").forEach((function(e){new u(e)}))}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(e){e.addEventListener("click",this._show)}.bind(this));const e=this.$el;return this._closers=c("[data-a11y-dialog-hide]",this.$el).filter((function(t){return t.closest('[aria-modal="true"], [data-a11y-dialog]')===e})).concat(c('[data-a11y-dialog-hide="'+this._id+'"]')),this._closers.forEach(function(e){e.addEventListener("click",this._hide)}.bind(this)),this._fire("create"),this},u.prototype.show=function(e){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",e)),this},u.prototype.hide=function(e){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",e),this):this},u.prototype.destroy=function(){return this.hide(),this._openers.forEach(function(e){e.removeEventListener("click",this._show)}.bind(this)),this._closers.forEach(function(e){e.removeEventListener("click",this._hide)}.bind(this)),this._fire("destroy"),this._listeners={},this},u.prototype.on=function(e,t){return void 0===this._listeners[e]&&(this._listeners[e]=[]),this._listeners[e].push(t),this},u.prototype.off=function(e,t){var n=(this._listeners[e]||[]).indexOf(t);return n>-1&&this._listeners[e].splice(n,1),this},u.prototype._fire=function(e,t){var n=this._listeners[e]||[],o=new CustomEvent(e,{detail:t});this.$el.dispatchEvent(o),n.forEach(function(e){e(this.$el,t)}.bind(this))},u.prototype._bindKeypress=function(e){const t=document.activeElement;t&&t.closest('[aria-modal="true"]')!==this.$el||(this.shown&&"Escape"===e.key&&"alertdialog"!==this.$el.getAttribute("role")&&(e.preventDefault(),this.hide(e)),this.shown&&"Tab"===e.key&&function(e,t){var n=function(e){return c(a.join(","),e).filter((function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)}))}(e),o=n.indexOf(document.activeElement);t.shiftKey&&0===o?(n[n.length-1].focus(),t.preventDefault()):t.shiftKey||o!==n.length-1||(n[0].focus(),t.preventDefault())}(this.$el,e))},u.prototype._maintainFocus=function(e){!this.shown||e.target.closest('[aria-modal="true"]')||e.target.closest("[data-a11y-dialog-ignore-focus-trap]")||l(this.$el)},"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",d):window.requestAnimationFrame?window.requestAnimationFrame(d):window.setTimeout(d,16));var h="__authsignal-popup-container",p="__authsignal-popup-content",f="__authsignal-popup-overlay",b="__authsignal-popup-style",m="__authsignal-popup-iframe",y="385px",w=function(){function e(e){var t=e.width;if(this.popup=null,document.querySelector("#".concat(h)))throw new Error("Multiple instances of Authsignal popup is not supported.");this.create({width:t})}return e.prototype.create=function(e){var t=this,n=e.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",h),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(h,",\n #").concat(f," {\n position: fixed;\n top: 0;\n right: 0;\n bottom: 0;\n left: 0;\n }\n\n #").concat(h," {\n z-index: 2147483647;\n display: flex;\n }\n\n #").concat(h,"[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(){t.destroy()}))},e.prototype.destroy=function(){var e=document.querySelector("#".concat(h)),t=document.querySelector("#".concat(b));e&&t&&(document.body.removeChild(e),document.head.removeChild(t)),window.removeEventListener("message",g)},e.prototype.show=function(e){var t,n=e.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 *; clipboard-write");var r=document.querySelector("#".concat(p));r&&r.appendChild(o),window.addEventListener("message",g),null===(t=this.popup)||void 0===t||t.show()},e.prototype.close=function(){if(!this.popup)throw new Error("Popup is not initialized");this.popup.hide()},e.prototype.on=function(e,t){if(!this.popup)throw new Error("Popup is not initialized");this.popup.on(e,t)},e}();function g(e){var t=document.querySelector("#".concat(m));t&&e.data.height&&(t.style.height=e.data.height+"px")}function _(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n}function v(e,t,n,o){return new(n||(n=Promise))((function(r,i){function s(e){try{u(o.next(e))}catch(e){i(e)}}function a(e){try{u(o.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}u((o=o.apply(e,t||[])).next())}))}function E(e,t){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=t.call(e,s)}catch(e){i=[6,e],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(e){const t=new Uint8Array(e);let n="";for(const e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function A(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=(4-t.length%4)%4,o=t.padEnd(t.length+n,"="),r=atob(o),i=new ArrayBuffer(r.length),s=new Uint8Array(i);for(let e=0;e<r.length;e++)s[e]=r.charCodeAt(e);return i}function T(){return void 0!==window?.PublicKeyCredential&&"function"==typeof window.PublicKeyCredential}function O(e){const{id:t}=e;return{...e,id:A(t),transports:e.transports}}function C(e){return"localhost"===e||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}class I extends Error{code;constructor({message:e,code:t,cause:n,name:o}){super(e,{cause:n}),this.name=o??n.name,this.code=t}}const S=new class{controller;createNewAbortSignal(){if(this.controller){const e=new Error("Cancelling existing WebAuthn API call for new one");e.name="AbortError",this.controller.abort(e)}const e=new AbortController;return this.controller=e,e.signal}},x=["cross-platform","platform"];function P(e){if(e&&!(x.indexOf(e)<0))return e}async function k(e){if(!T())throw new Error("WebAuthn is not supported in this browser");var t;const n={publicKey:{...e,challenge:A(e.challenge),user:{...e.user,id:(t=e.user.id,(new TextEncoder).encode(t))},excludeCredentials:e.excludeCredentials?.map(O)}};let o;n.signal=S.createNewAbortSignal();try{o=await navigator.credentials.create(n)}catch(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new I({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if("ConstraintError"===e.name){if(!0===n.authenticatorSelection?.requireResidentKey)return new I({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if("required"===n.authenticatorSelection?.userVerification)return new I({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if("InvalidStateError"===e.name)return new I({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if("NotAllowedError"===e.name)return new I({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("NotSupportedError"===e.name)return 0===n.pubKeyCredParams.filter((e=>"public-key"===e.type)).length?new I({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new I({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!C(t))return new I({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rp.id!==t)return new I({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("TypeError"===e.name){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new I({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if("UnknownError"===e.name)return new I({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:n})}if(!o)throw new Error("Registration was not completed");const{id:r,rawId:i,response:s,type:a}=o;let u;return"function"==typeof s.getTransports&&(u=s.getTransports()),{id:r,rawId:R(i),response:{attestationObject:R(s.attestationObject),clientDataJSON:R(s.clientDataJSON),transports:u},type:a,clientExtensionResults:o.getClientExtensionResults(),authenticatorAttachment:P(o.authenticatorAttachment)}}async function U(e,t=!1){if(!T())throw new Error("WebAuthn is not supported in this browser");let n;0!==e.allowCredentials?.length&&(n=e.allowCredentials?.map(O));const o={...e,challenge:A(e.challenge),allowCredentials:n},r={};if(t){if(!await async function(){const e=window.PublicKeyCredential;return void 0!==e.isConditionalMediationAvailable&&e.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(e){throw function({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if("AbortError"===e.name){if(t.signal instanceof AbortSignal)return new I({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if("NotAllowedError"===e.name)return new I({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if("SecurityError"===e.name){const t=window.location.hostname;if(!C(t))return new I({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e});if(n.rpId!==t)return new I({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else if("UnknownError"===e.name)return new I({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}({error:e,options:r})}if(!i)throw new Error("Authentication was not completed");const{id:s,rawId:a,response:u,type:c}=i;let l;var d;return u.userHandle&&(d=u.userHandle,l=new TextDecoder("utf-8").decode(d)),{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:P(i.authenticatorAttachment)}}class N extends Error{constructor(e,t,n){const o=`${e.status||0===e.status?e.status:""} ${e.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=e,this.request=t,this.options=n}}class D extends Error{constructor(e){super("Request timed out"),Object.defineProperty(this,"request",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="TimeoutError",this.request=e}}const q=e=>null!==e&&"object"==typeof e,L=(...e)=>{for(const t of e)if((!q(t)||Array.isArray(t))&&void 0!==t)throw new TypeError("The `options` argument must be an object");return $({},...e)},j=(e={},t={})=>{const n=new globalThis.Headers(e),o=t instanceof globalThis.Headers,r=new globalThis.Headers(t);for(const[e,t]of r.entries())o&&"undefined"===t||void 0===t?n.delete(e):n.set(e,t);return n},$=(...e)=>{let t={},n={};for(const o of e)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(q(o)){for(let[e,n]of Object.entries(o))q(n)&&e in t&&(n=$(t[e],n)),t={...t,[e]:n};q(o.headers)&&(n=j(n,o.headers),t.headers=n)}return t},H=(()=>{let e=!1,t=!1;const n="function"==typeof globalThis.ReadableStream,o="function"==typeof globalThis.Request;return n&&o&&(t=new globalThis.Request("https://a.com",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type")),e&&!t})(),M="function"==typeof globalThis.AbortController,K="function"==typeof globalThis.ReadableStream,F="function"==typeof globalThis.FormData,B=["get","post","put","patch","head","delete"],G={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},V=2147483647,W=Symbol("stop"),J=e=>B.includes(e)?e.toUpperCase():e,z=[413,429,503],Y={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},Q=(e={})=>{if("number"==typeof e)return{...Y,limit:e};if(e.methods&&!Array.isArray(e.methods))throw new Error("retry.methods must be an array");if(e.statusCodes&&!Array.isArray(e.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Y,...e,afterStatusCodes:z}};const X=Boolean(globalThis.DOMException);function Z(e){if(X)return new DOMException(e?.reason??"The operation was aborted.","AbortError");const t=new Error(e?.reason??"The operation was aborted.");return t.name="AbortError",t}class ee{static create(e,t){const n=new ee(e,t),o=async()=>{if(n._options.timeout>V)throw new RangeError("The `timeout` option cannot be greater than 2147483647");await Promise.resolve();let e=await n._fetch();for(const t of n._options.hooks.afterResponse){const o=await t(n.request,n._options,n._decorateResponse(e.clone()));o instanceof globalThis.Response&&(e=o)}if(n._decorateResponse(e),!e.ok&&n._options.throwHttpErrors){let t=new N(e,n.request,n._options);for(const e of n._options.hooks.beforeError)t=await e(t);throw t}if(n._options.onDownloadProgress){if("function"!=typeof n._options.onDownloadProgress)throw new TypeError("The `onDownloadProgress` option must be a function");if(!K)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return n._stream(e.clone(),n._options.onDownloadProgress)}return e},r=n._options.retry.methods.includes(n.request.method.toLowerCase())?n._retry(o):o();for(const[e,o]of Object.entries(G))r[e]=async()=>{n.request.headers.set("accept",n.request.headers.get("accept")||o);const i=(await r).clone();if("json"===e){if(204===i.status)return"";if(0===(await i.clone().arrayBuffer()).byteLength)return"";if(t.parseJson)return t.parseJson(await i.text())}return i[e]()};return r}constructor(e,t={}){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=e,this._options={credentials:this._input.credentials||"same-origin",...t,headers:j(this._input.headers,t.headers),hooks:$({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},t.hooks),method:J(t.method??this._input.method),prefixUrl:String(t.prefixUrl||""),retry:Q(t.retry),throwHttpErrors:!1!==t.throwHttpErrors,timeout:void 0===t.timeout?1e4:t.timeout,fetch:t.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 e=this._options.signal;this._options.signal.addEventListener("abort",(()=>{this.abortController.abort(e.reason)}))}this._options.signal=this.abortController.signal}if(H&&(this._options.duplex="half"),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const e="?"+("string"==typeof this._options.searchParams?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),t=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,e);!(F&&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(t,{...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(e){if(this._retryCount++,this._retryCount<this._options.retry.limit&&!(e instanceof D)){if(e instanceof N){if(!this._options.retry.statusCodes.includes(e.response.status))return 0;const t=e.response.headers.get("Retry-After");if(t&&this._options.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t);return Number.isNaN(e)?e=Date.parse(t)-Date.now():e*=1e3,void 0!==this._options.retry.maxRetryAfter&&e>this._options.retry.maxRetryAfter?0:e}if(413===e.response.status)return 0}const t=.3;return Math.min(this._options.retry.backoffLimit,t*2**(this._retryCount-1)*1e3)}return 0}_decorateResponse(e){return this._options.parseJson&&(e.json=async()=>this._options.parseJson(await e.text())),e}async _retry(e){try{return await e()}catch(t){const n=Math.min(this._calculateRetryDelay(t),V);if(0!==n&&this._retryCount>0){await async function(e,{signal:t}){return new Promise(((n,o)=>{if(t){if(t.aborted)return void o(Z(t));t.addEventListener("abort",r,{once:!0})}function r(){o(Z(t)),clearTimeout(i)}const i=setTimeout((()=>{t?.removeEventListener("abort",r),n()}),e)}))}(n,{signal:this._options.signal});for(const e of this._options.hooks.beforeRetry){if(await e({request:this.request,options:this._options,error:t,retryCount:this._retryCount})===W)return}return this._retry(e)}throw t}}async _fetch(){for(const e of this._options.hooks.beforeRequest){const t=await e(this.request,this._options);if(t instanceof Request){this.request=t;break}if(t instanceof Response)return t}return!1===this._options.timeout?this._options.fetch(this.request.clone()):async function(e,t,n){return new Promise(((o,r)=>{const i=setTimeout((()=>{t&&t.abort(),r(new D(e))}),n.timeout);n.fetch(e).then(o).catch(r).then((()=>{clearTimeout(i)}))}))}(this.request.clone(),this.abortController,this._options)}_stream(e,t){const n=Number(e.headers.get("content-length"))||0;let o=0;return 204===e.status?(t&&t({percent:1,totalBytes:n,transferredBytes:o},new Uint8Array),new globalThis.Response(null,{status:e.status,statusText:e.statusText,headers:e.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(r){const i=e.body.getReader();t&&t({percent:0,transferredBytes:0,totalBytes:n},new Uint8Array),await async function e(){const{done:s,value:a}=await i.read();if(s)r.close();else{if(t){o+=a.byteLength;t({percent:0===n?0:o/n,transferredBytes:o,totalBytes:n},a)}r.enqueue(a),await e()}}()}}),{status:e.status,statusText:e.statusText,headers:e.headers})}}
|
|
2
|
-
/*! MIT License © Sindre Sorhus */const
|
|
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 *; 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}({});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@authsignal/browser",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.js",
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
30
|
"@fingerprintjs/fingerprintjs": "^3.3.6",
|
|
31
|
-
"@simplewebauthn/browser": "^
|
|
31
|
+
"@simplewebauthn/browser": "^8.2.1",
|
|
32
32
|
"a11y-dialog": "^7.5.2",
|
|
33
33
|
"ky": "^0.33.3",
|
|
34
34
|
"uuid": "^9.0.0"
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"@rollup/plugin-node-resolve": "^14.1.0",
|
|
38
38
|
"@rollup/plugin-terser": "^0.4.3",
|
|
39
39
|
"@rollup/plugin-typescript": "^8.5.0",
|
|
40
|
-
"@simplewebauthn/typescript-types": "^
|
|
40
|
+
"@simplewebauthn/typescript-types": "^8.0.0",
|
|
41
41
|
"@types/iframe-resizer": "^3.5.9",
|
|
42
42
|
"@types/uuid": "^8.3.4",
|
|
43
43
|
"@typescript-eslint/eslint-plugin": "^5.39.0",
|