@authsignal/browser 0.1.7 → 0.1.8

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/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Authsignal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.js CHANGED
@@ -1537,7 +1537,7 @@ var PasskeyApiClient = /** @class */ (function () {
1537
1537
  return __generator(this, function (_b) {
1538
1538
  switch (_b.label) {
1539
1539
  case 0: return [4 /*yield*/, this.api.post("user-authenticators/passkey/registration-options", {
1540
- json: { userName: userName },
1540
+ json: { username: userName },
1541
1541
  headers: this.buildHeaders(token)
1542
1542
  })];
1543
1543
  case 1:
package/dist/index.min.js CHANGED
@@ -1,2 +1,2 @@
1
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: 65vh;\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 te=e=>{const t=(t,n)=>ee.create(t,L(e,n));for(const n of B)t[n]=(t,o)=>ee.create(t,L(e,o,{method:n}));return t.create=e=>te(L(e)),t.extend=t=>te(L(e,t)),t.stop=W,t};var ne=te(),oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.api=ne.create({prefixUrl:t})}return e.prototype.registrationOptions=function(e){var t=e.token,n=e.userName;return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey/registration-options",{json:{userName:n},headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.authenticationOptions=function(e){var t=e.token;return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey/authentication-options",{json:{},headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.addAuthenticator=function(e){var t=e.token,n=_(e,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey",{json:n,headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.verify=function(e){var t=e.token,n=_(e,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("verify/passkey",{json:n,headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.buildHeaders=function(e){return{Authorization:e?"Bearer ".concat(e):"Basic ".concat(window.btoa(encodeURIComponent(this.tenantId)))}},e}(),re=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.api=new oe({baseUrl:t,tenantId:n})}return e.prototype.signUp=function(e){var t=e.userName,n=e.token;return v(this,void 0,void 0,(function(){var e,o,r,i;return E(this,(function(s){switch(s.label){case 0:return[4,this.api.registrationOptions({userName:t,token:n})];case 1:e=s.sent(),s.label=2;case 2:return s.trys.push([2,5,,6]),[4,k(e.options)];case 3:return o=s.sent(),[4,this.api.addAuthenticator({challengeId:e.challengeId,registrationCredential:o,token:n})];case 4:return[2,null==(r=s.sent())?void 0:r.accessToken];case 5:return i=s.sent(),console.error(i),[3,6];case 6:return[2]}}))}))},e.prototype.signIn=function(e){return v(this,void 0,void 0,(function(){var t,n,o,r;return E(this,(function(i){switch(i.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("Autofill is not supported when providing a token");return[4,this.api.authenticationOptions({token:null==e?void 0:e.token})];case 1:t=i.sent(),i.label=2;case 2:return i.trys.push([2,5,,6]),[4,U(t.options,null==e?void 0:e.autofill)];case 3:return n=i.sent(),[4,this.api.verify({challengeId:t.challengeId,authenticationCredential:n,token:null==e?void 0:e.token})];case 4:return[2,null==(o=i.sent())?void 0:o.accessToken];case 5:return r=i.sent(),console.error(r),[3,6];case 6:return[2]}}))}))},e}(),ie=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,o=void 0===n?"__as_aid":n,r=e.baseUrl,i=void 0===r?"https://challenge.authsignal.com/v1":r,a=e.tenantId;this.anonymousId="",this.cookieDomain="",this.anonymousIdCookieName="",this._token=void 0,this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,this.passkey=new re({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(e){var t=e.name,n=e.value,o=e.expire,r=e.domain,i=e.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(t)+"="+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 t.prototype.launch=function(t,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(t,"&mode=popup");return i.show({url:s}),new Promise((function(t){i.on("hide",(function(){t({token:o._token})})),window.addEventListener("message",(function(t){var n=null;try{n=JSON.parse(t.data)}catch(e){}(null==n?void 0:n.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o._token=n.token,i.close())}),!1)}))}window.location.href=t},t}();return e.Authsignal=ie,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
2
+ /*! MIT License © Sindre Sorhus */const te=e=>{const t=(t,n)=>ee.create(t,L(e,n));for(const n of B)t[n]=(t,o)=>ee.create(t,L(e,o,{method:n}));return t.create=e=>te(L(e)),t.extend=t=>te(L(e,t)),t.stop=W,t};var ne=te(),oe=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.tenantId=n,this.api=ne.create({prefixUrl:t})}return e.prototype.registrationOptions=function(e){var t=e.token,n=e.userName;return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey/registration-options",{json:{username:n},headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.authenticationOptions=function(e){var t=e.token;return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey/authentication-options",{json:{},headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.addAuthenticator=function(e){var t=e.token,n=_(e,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("user-authenticators/passkey",{json:n,headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.verify=function(e){var t=e.token,n=_(e,["token"]);return v(this,void 0,void 0,(function(){return E(this,(function(e){switch(e.label){case 0:return[4,this.api.post("verify/passkey",{json:n,headers:this.buildHeaders(t)})];case 1:return[2,e.sent().json()]}}))}))},e.prototype.buildHeaders=function(e){return{Authorization:e?"Bearer ".concat(e):"Basic ".concat(window.btoa(encodeURIComponent(this.tenantId)))}},e}(),re=function(){function e(e){var t=e.baseUrl,n=e.tenantId;this.api=new oe({baseUrl:t,tenantId:n})}return e.prototype.signUp=function(e){var t=e.userName,n=e.token;return v(this,void 0,void 0,(function(){var e,o,r,i;return E(this,(function(s){switch(s.label){case 0:return[4,this.api.registrationOptions({userName:t,token:n})];case 1:e=s.sent(),s.label=2;case 2:return s.trys.push([2,5,,6]),[4,k(e.options)];case 3:return o=s.sent(),[4,this.api.addAuthenticator({challengeId:e.challengeId,registrationCredential:o,token:n})];case 4:return[2,null==(r=s.sent())?void 0:r.accessToken];case 5:return i=s.sent(),console.error(i),[3,6];case 6:return[2]}}))}))},e.prototype.signIn=function(e){return v(this,void 0,void 0,(function(){var t,n,o,r;return E(this,(function(i){switch(i.label){case 0:if((null==e?void 0:e.token)&&e.autofill)throw new Error("Autofill is not supported when providing a token");return[4,this.api.authenticationOptions({token:null==e?void 0:e.token})];case 1:t=i.sent(),i.label=2;case 2:return i.trys.push([2,5,,6]),[4,U(t.options,null==e?void 0:e.autofill)];case 3:return n=i.sent(),[4,this.api.verify({challengeId:t.challengeId,authenticationCredential:n,token:null==e?void 0:e.token})];case 4:return[2,null==(o=i.sent())?void 0:o.accessToken];case 5:return r=i.sent(),console.error(r),[3,6];case 6:return[2]}}))}))},e}(),ie=function(){function t(e){var t=e.cookieDomain,n=e.cookieName,o=void 0===n?"__as_aid":n,r=e.baseUrl,i=void 0===r?"https://challenge.authsignal.com/v1":r,a=e.tenantId;this.anonymousId="",this.cookieDomain="",this.anonymousIdCookieName="",this._token=void 0,this.cookieDomain=t||document.location.hostname.replace("www.",""),this.anonymousIdCookieName=o,this.passkey=new re({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(e){var t=e.name,n=e.value,o=e.expire,r=e.domain,i=e.secure,s=o===1/0?" expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+o;document.cookie=encodeURIComponent(t)+"="+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 t.prototype.launch=function(t,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(t,"&mode=popup");return i.show({url:s}),new Promise((function(t){i.on("hide",(function(){t({token:o._token})})),window.addEventListener("message",(function(t){var n=null;try{n=JSON.parse(t.data)}catch(e){}(null==n?void 0:n.event)===e.AuthsignalWindowMessage.AUTHSIGNAL_CLOSE_POPUP&&(o._token=n.token,i.close())}),!1)}))}window.location.href=t},t}();return e.Authsignal=ie,Object.defineProperty(e,"__esModule",{value:!0}),e}({});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@authsignal/browser",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.js",
@@ -9,7 +9,13 @@
9
9
  "authsignal",
10
10
  "mfa",
11
11
  "2fa",
12
- "authentication"
12
+ "authentication",
13
+ "passkeys",
14
+ "webauthn",
15
+ "passwordless",
16
+ "fido2",
17
+ "biometrics",
18
+ "typescript"
13
19
  ],
14
20
  "license": "MIT",
15
21
  "repository": "git://github.com/authsignal/authsignal-browser.git",