authhero 4.101.1 → 4.102.0

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/authhero.cjs CHANGED
@@ -83,7 +83,7 @@ ${t}`):e.set("log",t)}const dD=a.z.object({grant_type:a.z.literal("refresh_token
83
83
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function CD(e,t){if(e){if(typeof e=="string")return T1(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?T1(e,t):void 0}}function T1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}var TD=["MOBILE","PREMIUM_RATE","TOLL_FREE","SHARED_COST","VOIP","PERSONAL_NUMBER","PAGER","UAN","VOICEMAIL"];function L_(e,t,n){if(t=t||{},!(!e.country&&!e.countryCallingCode)){n=new Rt(n),n.selectNumberingPlan(e.country,e.countryCallingCode);var i=t.v2?e.nationalNumber:e.phone;if(Mi(i,n.nationalNumberPattern())){if(Ch(i,"FIXED_LINE",n))return n.type("MOBILE")&&n.type("MOBILE").pattern()===""||!n.type("MOBILE")||Ch(i,"MOBILE",n)?"FIXED_LINE_OR_MOBILE":"FIXED_LINE";for(var r=ED(TD),o;!(o=r()).done;){var s=o.value;if(Ch(i,s,n))return s}}}}function Ch(e,t,n){var i=n.type(t);return!i||!i.pattern()||i.possibleLengths()&&i.possibleLengths().indexOf(e.length)<0?!1:Mi(e,i.pattern())}function ID(e,t,n){if(t=t||{},n=new Rt(n),n.selectNumberingPlan(e.country,e.countryCallingCode),n.hasTypes())return L_(e,t,n.metadata)!==void 0;var i=t.v2?e.nationalNumber:e.phone;return Mi(i,n.nationalNumberPattern())}function $D(e,t,n){var i=new Rt(n),r=i.getCountryCodesForCallingCode(e);return r?r.filter(function(o){return zD(t,o,n)}):[]}function zD(e,t,n){var i=new Rt(n);return i.selectNumberingPlan(t),i.numberingPlan.possibleLengths().indexOf(e.length)>=0}var M_=2,PD=17,ND=3,Hn="0-90-9٠-٩۰-۹",jD="-‐-―−ー-",OD="//",RD="..",DD="  ­​⁠ ",BD="()()[]\\[\\]",LD="~⁓∼~",ap="".concat(jD).concat(OD).concat(RD).concat(DD).concat(BD).concat(LD),U_="++",MD=new RegExp("(["+Hn+"])");function UD(e,t,n,i){if(t){var r=new Rt(i);r.selectNumberingPlan(t,n);var o=new RegExp(r.IDDPrefix());if(e.search(o)===0){e=e.slice(e.match(o)[0].length);var s=e.match(MD);if(!(s&&s[1]!=null&&s[1].length>0&&s[1]==="0"))return e}}}function FD(e,t){if(e&&t.numberingPlan.nationalPrefixForParsing()){var n=new RegExp("^(?:"+t.numberingPlan.nationalPrefixForParsing()+")"),i=n.exec(e);if(i){var r,o,s=i.length-1,c=s>0&&i[s];if(t.nationalPrefixTransformRule()&&c)r=e.replace(n,t.nationalPrefixTransformRule()),s>1&&(o=i[1]);else{var l=i[0];r=e.slice(l.length),c&&(o=i[1])}var d;if(c){var u=e.indexOf(i[1]),p=e.slice(0,u);p===t.numberingPlan.nationalPrefix()&&(d=t.numberingPlan.nationalPrefix())}else d=i[0];return{nationalNumber:r,nationalPrefix:d,carrierCode:o}}}return{nationalNumber:e}}function qD(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=HD(e))||t){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
84
84
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HD(e,t){if(e){if(typeof e=="string")return I1(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?I1(e,t):void 0}}function I1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function KD(e,t){var n=t.countries,i=t.metadata;i=new Rt(i);for(var r=qD(n),o;!(o=r()).done;){var s=o.value;if(i.selectNumberingPlan(s),i.leadingDigits()){if(e&&e.search(i.leadingDigits())===0)return s}else if(L_({phone:e,country:s},void 0,i.metadata))return s}}function s6(e,t){var n=t.nationalNumber,i=t.metadata,r=i.getCountryCodesForCallingCode(e);if(r)return r.length===1?r[0]:KD(n,{countries:r,metadata:i.metadata})}function R0(e,t,n){var i=FD(e,n),r=i.carrierCode,o=i.nationalNumber;if(o!==e){if(!VD(e,o,n))return{nationalNumber:e};if(n.numberingPlan.possibleLengths()&&(t||(t=s6(n.numberingPlan.callingCode(),{nationalNumber:o,metadata:n})),!GD(o,t,n)))return{nationalNumber:e}}return{nationalNumber:o,carrierCode:r}}function VD(e,t,n){return!(Mi(e,n.nationalNumberPattern())&&!Mi(t,n.nationalNumberPattern()))}function GD(e,t,n){switch(B_(e,t,n)){case"TOO_SHORT":case"INVALID_LENGTH":return!1;default:return!0}}function WD(e,t,n,i,r){var o=n?D_(n,r):i;if(e.indexOf(o)===0){r=new Rt(r),r.selectNumberingPlan(n,o);var s=e.slice(o.length),c=R0(s,t,r),l=c.nationalNumber,d=R0(e,t,r),u=d.nationalNumber;if(!Mi(u,r.nationalNumberPattern())&&Mi(l,r.nationalNumberPattern())||B_(u,t,r)==="TOO_LONG")return{countryCallingCode:o,number:s}}return{number:e}}function c6(e,t,n,i,r){if(!e)return{};var o;if(e[0]!=="+"){var s=UD(e,n,i,r);if(s&&s!==e)o=!0,e="+"+s;else{if(n||i){var c=WD(e,t,n,i,r),l=c.countryCallingCode,d=c.number;if(l)return{countryCallingCodeSource:"FROM_NUMBER_WITHOUT_PLUS_SIGN",countryCallingCode:l,number:d}}return{number:e}}}if(e[1]==="0")return{};r=new Rt(r);for(var u=2;u-1<=ND&&u<=e.length;){var p=e.slice(1,u);if(r.hasCallingCode(p))return r.selectNumberingPlan(p),{countryCallingCodeSource:o?"FROM_NUMBER_WITH_IDD":"FROM_NUMBER_WITH_PLUS_SIGN",countryCallingCode:p,number:e.slice(u)};u++}return{}}function JD(e){return e.replace(new RegExp("[".concat(ap,"]+"),"g")," ").trim()}var QD=/(\$\d)/;function YD(e,t,n){var i=n.useInternationalFormat,r=n.withNationalPrefix,o=e.replace(new RegExp(t.pattern()),i?t.internationalFormat():r&&t.nationalPrefixFormattingRule()?t.format().replace(QD,t.nationalPrefixFormattingRule()):t.format());return i?JD(o):o}var ZD=/^[\d]+(?:[~\u2053\u223C\uFF5E][\d]+)?$/;function XD(e,t,n){var i=new Rt(n);if(i.selectNumberingPlan(e,t),i.defaultIDDPrefix())return i.defaultIDDPrefix();if(ZD.test(i.IDDPrefix()))return i.IDDPrefix()}var eB=";ext=",Ho=function(t){return"([".concat(Hn,"]{1,").concat(t,"})")};function l6(e){var t="20",n="15",i="9",r="6",o="[  \\t,]*",s="[:\\..]?[  \\t,-]*",c="#?",l="(?:e?xt(?:ensi(?:ó?|ó))?n?|e?xtn?|доб|anexo)",d="(?:[xx##~~]|int|int)",u="[- ]+",p="[  \\t]*",f="(?:,{2}|;)",h=eB+Ho(t),g=o+l+s+Ho(t)+c,m=o+d+s+Ho(i)+c,_=u+Ho(r)+"#",y=p+f+s+Ho(n)+c,w=p+"(?:,)+"+s+Ho(i)+c;return h+"|"+g+"|"+m+"|"+_+"|"+y+"|"+w}var tB="["+Hn+"]{"+M_+"}",nB="["+U_+"]{0,1}(?:["+ap+"]*["+Hn+"]){3,}["+ap+Hn+"]*",iB=new RegExp("^["+U_+"]{0,1}(?:["+ap+"]*["+Hn+"]){1,2}$","i"),rB=nB+"(?:"+l6()+")?",oB=new RegExp("^"+tB+"$|^"+rB+"$","i");function aB(e){return e.length>=M_&&oB.test(e)}function sB(e){return iB.test(e)}function cB(e){var t=e.number,n=e.ext;if(!t)return"";if(t[0]!=="+")throw new Error('"formatRFC3966()" expects "number" to be in E.164 format.');return"tel:".concat(t).concat(n?";ext="+n:"")}var $1={formatExtension:function(t,n,i){return"".concat(t).concat(i.ext()).concat(n)}};function lB(e,t,n,i){if(n?n=pB({},$1,n):n=$1,i=new Rt(i),e.country&&e.country!=="001"){if(!i.hasCountry(e.country))throw new Error("Unknown country: ".concat(e.country));i.selectNumberingPlan(e.country)}else if(e.countryCallingCode)i.selectNumberingPlan(e.countryCallingCode);else return e.phone||"";var r=i.countryCallingCode(),o=n.v2?e.nationalNumber:e.phone,s;switch(t){case"NATIONAL":return o?(s=sp(o,e.carrierCode,"NATIONAL",i,n),Th(s,e.ext,i,n.formatExtension)):"";case"INTERNATIONAL":return o?(s=sp(o,null,"INTERNATIONAL",i,n),s="+".concat(r," ").concat(s),Th(s,e.ext,i,n.formatExtension)):"+".concat(r);case"E.164":return"+".concat(r).concat(o);case"RFC3966":return cB({number:"+".concat(r).concat(o),ext:e.ext});case"IDD":if(!n.fromCountry)return;var c=uB(o,e.carrierCode,r,n.fromCountry,i);return c?Th(c,e.ext,i,n.formatExtension):void 0;default:throw new Error('Unknown "format" argument passed to "formatNumber()": "'.concat(t,'"'))}}function sp(e,t,n,i,r){var o=dB(i.formats(),e);return o?YD(e,o,{useInternationalFormat:n==="INTERNATIONAL",withNationalPrefix:!(o.nationalPrefixIsOptionalWhenFormattingInNationalFormat()&&r&&r.nationalPrefix===!1)}):e}function dB(e,t){return fB(e,function(n){if(n.leadingDigitsPatterns().length>0){var i=n.leadingDigitsPatterns()[n.leadingDigitsPatterns().length-1];if(t.search(i)!==0)return!1}return Mi(t,n.pattern())})}function Th(e,t,n,i){return t?i(e,t,n):e}function uB(e,t,n,i,r){var o=D_(i,r.metadata);if(o===n){var s=sp(e,t,"NATIONAL",r);return n==="1"?n+" "+s:s}var c=XD(i,void 0,r.metadata);if(c)return"".concat(c," ").concat(n," ").concat(sp(e,null,"INTERNATIONAL",r))}function pB(){for(var e=1,t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];for(;e<n.length;){if(n[e])for(var r in n[e])n[0][r]=n[e][r];e++}return n[0]}function fB(e,t){for(var n=0;n<e.length;){if(t(e[n]))return e[n];n++}}function Zc(e){"@babel/helpers - typeof";return Zc=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zc(e)}function z1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function P1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?z1(Object(n),!0).forEach(function(i){hB(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z1(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function hB(e,t,n){return(t=d6(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function gB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function mB(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,d6(i.key),i)}}function yB(e,t,n){return t&&mB(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function d6(e){var t=_B(e,"string");return Zc(t)=="symbol"?t:t+""}function _B(e,t){if(Zc(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(Zc(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var wB=(function(){function e(t,n,i){if(gB(this,e),!t)throw new TypeError("First argument is required");if(typeof t!="string")throw new TypeError("First argument must be a string");if(t[0]==="+"&&!n)throw new TypeError("`metadata` argument not passed");if(ka(n)&&ka(n.countries)){i=n;var r=t;if(!AB.test(r))throw new Error('Invalid `number` argument passed: must consist of a "+" followed by digits');var o=c6(r,void 0,void 0,void 0,i),s=o.countryCallingCode,c=o.number;if(n=c,t=s,!n)throw new Error("Invalid `number` argument passed: too short")}if(!n)throw new TypeError("`nationalNumber` argument is required");if(typeof n!="string")throw new TypeError("`nationalNumber` argument must be a string");i6(i);var l=bB(t,i),d=l.country,u=l.countryCallingCode;this.country=d,this.countryCallingCode=u,this.nationalNumber=n,this.number="+"+this.countryCallingCode+this.nationalNumber,this.getMetadata=function(){return i}}return yB(e,[{key:"setExt",value:function(n){this.ext=n}},{key:"getPossibleCountries",value:function(){return this.country?[this.country]:$D(this.countryCallingCode,this.nationalNumber,this.getMetadata())}},{key:"isPossible",value:function(){return xD(this,{v2:!0},this.getMetadata())}},{key:"isValid",value:function(){return ID(this,{v2:!0},this.getMetadata())}},{key:"isNonGeographic",value:function(){var n=new Rt(this.getMetadata());return n.isNonGeographicCallingCode(this.countryCallingCode)}},{key:"isEqual",value:function(n){return this.number===n.number&&this.ext===n.ext}},{key:"getType",value:function(){return L_(this,{v2:!0},this.getMetadata())}},{key:"format",value:function(n,i){return lB(this,n,i?P1(P1({},i),{},{v2:!0}):{v2:!0},this.getMetadata())}},{key:"formatNational",value:function(n){return this.format("NATIONAL",n)}},{key:"formatInternational",value:function(n){return this.format("INTERNATIONAL",n)}},{key:"getURI",value:function(n){return this.format("RFC3966",n)}}])})(),vB=function(t){return/^[A-Z]{2}$/.test(t)};function bB(e,t){var n,i,r=new Rt(t);return vB(e)?(n=e,r.selectNumberingPlan(n),i=r.countryCallingCode()):i=e,{country:n,countryCallingCode:i}}var AB=/^\+\d+$/;function D0(e){"@babel/helpers - typeof";return D0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},D0(e)}function kB(e,t,n){return Object.defineProperty(e,"prototype",{writable:!1}),e}function SB(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function xB(e,t,n){return t=el(t),EB(e,F_()?Reflect.construct(t,n||[],el(e).constructor):t.apply(e,n))}function EB(e,t){if(t&&(D0(t)=="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return CB(e)}function CB(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function TB(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&Xc(e,t)}function B0(e){var t=typeof Map=="function"?new Map:void 0;return B0=function(i){if(i===null||!$B(i))return i;if(typeof i!="function")throw new TypeError("Super expression must either be null or a function");if(t!==void 0){if(t.has(i))return t.get(i);t.set(i,r)}function r(){return IB(i,arguments,el(this).constructor)}return r.prototype=Object.create(i.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),Xc(r,i)},B0(e)}function IB(e,t,n){if(F_())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var r=new(e.bind.apply(e,i));return n&&Xc(r,n.prototype),r}function F_(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(F_=function(){return!!e})()}function $B(e){try{return Function.toString.call(e).indexOf("[native code]")!==-1}catch{return typeof e=="function"}}function Xc(e,t){return Xc=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,i){return n.__proto__=i,n},Xc(e,t)}function el(e){return el=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},el(e)}var Ci=(function(e){function t(n){var i;return SB(this,t),i=xB(this,t,[n]),Object.setPrototypeOf(i,t.prototype),i.name=i.constructor.name,i}return TB(t,e),kB(t)})(B0(Error)),N1=new RegExp("(?:"+l6()+")$","i");function zB(e){var t=e.search(N1);if(t<0)return{};for(var n=e.slice(0,t),i=e.match(N1),r=1;r<i.length;){if(i[r])return{number:n,ext:i[r]};r++}}var PB={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9","0":"0","1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","٠":"0","١":"1","٢":"2","٣":"3","٤":"4","٥":"5","٦":"6","٧":"7","٨":"8","٩":"9","۰":"0","۱":"1","۲":"2","۳":"3","۴":"4","۵":"5","۶":"6","۷":"7","۸":"8","۹":"9"};function NB(e){return PB[e]}function jB(e,t){var n=typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=OB(e))||t){n&&(e=n);var i=0;return function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
85
85
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function OB(e,t){if(e){if(typeof e=="string")return j1(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?j1(e,t):void 0}}function j1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function O1(e){for(var t="",n=jB(e.split("")),i;!(i=n()).done;){var r=i.value;t+=RB(r,t)||""}return t}function RB(e,t,n){return e==="+"?t?void 0:"+":NB(e)}var u6="+",DB="[\\-\\.\\(\\)]?",R1="(["+Hn+"]|"+DB+")",BB="^\\"+u6+R1+"*["+Hn+"]"+R1+"*$",LB=new RegExp(BB,"g"),L0=Hn,MB="["+L0+"]+((\\-)*["+L0+"])*",UB="a-zA-Z",FB="["+UB+"]+((\\-)*["+L0+"])*",qB="^("+MB+"\\.)*"+FB+"\\.?$",HB=new RegExp(qB,"g"),D1="tel:",M0=";phone-context=",KB=";isub=";function VB(e){var t=e.indexOf(M0);if(t<0)return null;var n=t+M0.length;if(n>=e.length)return"";var i=e.indexOf(";",n);return i>=0?e.substring(n,i):e.substring(n)}function GB(e){return e===null?!0:e.length===0?!1:LB.test(e)||HB.test(e)}function WB(e,t){var n=t.extractFormattedPhoneNumber,i=VB(e);if(!GB(i))throw new Ci("NOT_A_NUMBER");var r;if(i===null)r=n(e)||"";else{r="",i.charAt(0)===u6&&(r+=i);var o=e.indexOf(D1),s;o>=0?s=o+D1.length:s=0;var c=e.indexOf(M0);r+=e.substring(s,c)}var l=r.indexOf(KB);if(l>0&&(r=r.substring(0,l)),r!=="")return r}var JB=250,QB=new RegExp("["+U_+Hn+"]"),YB=new RegExp("[^"+Hn+"#]+$");function ZB(e,t,n){if(t=t||{},n=new Rt(n),t.defaultCountry&&!n.hasCountry(t.defaultCountry))throw t.v2?new Ci("INVALID_COUNTRY"):new Error("Unknown country: ".concat(t.defaultCountry));var i=eL(e,t.v2,t.extract),r=i.number,o=i.ext,s=i.error;if(!r){if(t.v2)throw s==="TOO_SHORT"?new Ci("TOO_SHORT"):new Ci("NOT_A_NUMBER");return{}}var c=nL(r,t.defaultCountry,t.defaultCallingCode,n),l=c.country,d=c.nationalNumber,u=c.countryCallingCode,p=c.countryCallingCodeSource,f=c.carrierCode;if(!n.hasSelectedNumberingPlan()){if(t.v2)throw new Ci("INVALID_COUNTRY");return{}}if(!d||d.length<M_){if(t.v2)throw new Ci("TOO_SHORT");return{}}if(d.length>PD){if(t.v2)throw new Ci("TOO_LONG");return{}}if(t.v2){var h=new wB(u,d,n.metadata);return l&&(h.country=l),f&&(h.carrierCode=f),o&&(h.ext=o),h.__countryCallingCodeSource=p,h}var g=(t.extended?n.hasSelectedNumberingPlan():l)?Mi(d,n.nationalNumberPattern()):!1;return t.extended?{country:l,countryCallingCode:u,carrierCode:f,valid:g,possible:g?!0:!!(t.extended===!0&&n.possibleLengths()&&a6(d,l,n)),phone:d,ext:o}:g?tL(l,d,o):{}}function XB(e,t,n){if(e){if(e.length>JB){if(n)throw new Ci("TOO_LONG");return}if(t===!1)return e;var i=e.search(QB);if(!(i<0))return e.slice(i).replace(YB,"")}}function eL(e,t,n){var i=WB(e,{extractFormattedPhoneNumber:function(s){return XB(s,n,t)}});if(!i)return{};if(!aB(i))return sB(i)?{error:"TOO_SHORT"}:{};var r=zB(i);return r.ext?r:{number:i}}function tL(e,t,n){var i={country:e,phone:t};return n&&(i.ext=n),i}function nL(e,t,n,i){var r=c6(O1(e),void 0,t,n,i.metadata),o=r.countryCallingCodeSource,s=r.countryCallingCode,c=r.number,l;if(s)i.selectNumberingPlan(s);else if(c&&(t||n))i.selectNumberingPlan(t,n),t&&(l=t),s=n||D_(t,i.metadata);else return{};if(!c)return{countryCallingCodeSource:o,countryCallingCode:s};var d=R0(O1(c),l,i),u=d.nationalNumber,p=d.carrierCode,f=s6(s,{nationalNumber:u,metadata:i});return f&&(l=f,f==="001"||i.selectNumberingPlan(l)),{country:l,countryCallingCode:s,countryCallingCodeSource:o,nationalNumber:u,carrierCode:p}}function tl(e){"@babel/helpers - typeof";return tl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tl(e)}function B1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function L1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?B1(Object(n),!0).forEach(function(i){iL(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):B1(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function iL(e,t,n){return(t=rL(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rL(e){var t=oL(e,"string");return tl(t)=="symbol"?t:t+""}function oL(e,t){if(tl(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(tl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function aL(e,t,n){return ZB(e,L1(L1({},t),{},{v2:!0}),n)}function nl(e){"@babel/helpers - typeof";return nl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nl(e)}function M1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function sL(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?M1(Object(n),!0).forEach(function(i){cL(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):M1(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function cL(e,t,n){return(t=lL(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function lL(e){var t=dL(e,"string");return nl(t)=="symbol"?t:t+""}function dL(e,t){if(nl(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(nl(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function uL(e,t){return gL(e)||hL(e,t)||fL(e,t)||pL()}function pL(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
86
- In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fL(e,t){if(e){if(typeof e=="string")return U1(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U1(e,t):void 0}}function U1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function hL(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,r,o,s,c=[],l=!0,d=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(i=o.call(n)).done)&&(c.push(i.value),c.length!==t);l=!0);}catch(u){d=!0,r=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return c}}function gL(e){if(Array.isArray(e))return e}function mL(e){var t=Array.prototype.slice.call(e),n=uL(t,4),i=n[0],r=n[1],o=n[2],s=n[3],c,l,d;if(typeof i=="string")c=i;else throw new TypeError("A text for parsing must be a string.");if(!r||typeof r=="string")s?(l=o,d=s):(l=void 0,d=o),r&&(l=sL({defaultCountry:r},l));else if(ka(r))o?(l=r,d=o):d=r;else throw new Error("Invalid second argument: ".concat(r));return{text:c,options:l,metadata:d}}function il(e){"@babel/helpers - typeof";return il=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},il(e)}function F1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function q1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?F1(Object(n),!0).forEach(function(i){yL(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):F1(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function yL(e,t,n){return(t=_L(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _L(e){var t=wL(e,"string");return il(t)=="symbol"?t:t+""}function wL(e,t){if(il(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(il(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vL(e,t,n){t&&t.defaultCountry&&!r6(t.defaultCountry,n)&&(t=q1(q1({},t),{},{defaultCountry:void 0}));try{return aL(e,t,n)}catch(i){if(!(i instanceof Ci))throw i}}function bL(){var e=mL(arguments),t=e.text,n=e.options,i=e.metadata;return vL(t,n,i)}function q_(){return n6(bL,arguments)}function AL(){return n6(r6,arguments)}function $r(e,t="US"){const n=e.trim();if(n.includes("@")){const i=n.toLowerCase(),r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i);return{connectionType:"email",normalized:r?i:null,isValid:r,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const i=q_(n,{defaultCountry:t});return i&&i.isValid()?{connectionType:"sms",normalized:i.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Ke}}function H_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function kL(e){const n=H_(e).split(".");return n.length!==4?!1:n.every(i=>/^\d+$/.test(i)&&Number(i)>=0&&Number(i)<=255)}function SL(e){const t=H_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function xL(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,i=t.match(n);if(i&&i[1])return i[1];const r=t.lastIndexOf(":");if(r!==-1){const o=t.slice(0,r),s=t.slice(r+1);/^[0-9.]+$/.test(o)&&/^\d+$/.test(s)&&(t=o)}return t}function H1(e){if(!e)return null;const t=H_(xL(e));return kL(t)?{family:4,normalized:t}:SL(t)?{family:6,normalized:t.toLowerCase()}:null}function K1(e){if(e.includes("::")){let[t,n]=e.split("::"),i=t?t.split(":").filter(Boolean):[],r=n?n.split(":").filter(Boolean):[],o=8-(i.length+r.length);return[...i.map(s=>s.toLowerCase()||"0"),...Array(o).fill("0"),...r.map(s=>s.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function EL(e,t,n=!0){const i=H1(e),r=H1(t);if(!i||!r||i.family!==r.family)return!1;if(i.family===4)return i.normalized===r.normalized;const o=K1(i.normalized),s=K1(r.normalized);return n?o.length===8&&s.length===8&&o.join(":")===s.join(":"):o.slice(0,4).join(":")===s.slice(0,4).join(":")}class rn extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=rn.name,this.location=t,this.status=n}}const CL=a.z.object({client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),otp:a.z.string(),authParams:Ic.optional(),enforceIpCheck:a.z.boolean().optional().default(!1)});async function p6(e,{client_id:t,username:n,otp:i,authParams:r,enforceIpCheck:o=!1}){const s=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:d}=$r(n,c);if(!d)throw new Y(400,{message:"Invalid username format"});e.set("connection",l);const u=await tt(e.env,t,e.var.tenant_id),{env:p}=e,f=await p.data.codes.get(u.tenant.id,i,"otp");if(!f)throw new Y(400,{message:ge("code_invalid"),userSafe:!0});if(f.expires_at<new Date().toISOString())throw new Y(400,{message:ge("code_expired"),userSafe:!0});if(f.used_at)throw new Y(400,{message:ge("code_used"),userSafe:!0});const h=await p.data.loginSessions.get(u.tenant.id,f.login_id);if(!h||h.authParams.username!==n)throw new Y(400,{message:"Code not found or expired",userSafe:!0});if(o&&h.ip&&s&&!EL(h.ip,s))throw new rn(`${Bt(e.env,e.var.custom_domain)}invalid-session?state=${h.id}`);const g=await Sp(e,{client:u,username:d,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await p.data.codes.used(u.tenant.id,i),{user:g,client:u,loginSession:h,connectionType:l,authConnection:l,session_id:h.session_id,authParams:{...h.authParams,...r||{}}}}async function Ul(e,t){const n=await p6(e,t);return Je(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authConnection:n.connectionType,authStrategy:{strategy:n.connectionType==="sms"?W.SMS:W.EMAIL,strategy_type:Mt.PASSWORDLESS}})}const V1=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),G1=a.z.union([t6.extend(V1.shape),a.z.object({grant_type:a.z.literal("authorization_code"),client_id:a.z.string(),code:a.z.string(),redirect_uri:a.z.string(),code_verifier:a.z.string().min(43).max(128),organization:a.z.string().optional()}),a.z.object({grant_type:a.z.literal("authorization_code"),code:a.z.string(),redirect_uri:a.z.string().optional(),organization:a.z.string().optional(),...V1.shape}),a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string().optional(),refresh_token:a.z.string(),redirect_uri:a.z.string().optional(),client_secret:a.z.string().optional(),organization:a.z.string().optional()}),a.z.object({grant_type:a.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:a.z.string(),username:a.z.string(),otp:a.z.string(),realm:a.z.enum(["email","sms"])})]);function TL(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[i,r]=atob(n).split(":");return{client_id:i,client_secret:r}}return{}}const IL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:G1},"application/json":{schema:G1}}}},responses:{200:{content:{"application/json":{schema:_y}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:a.z.object({Location:a.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),i=TL(e.req.header("Authorization")),r={...n,...i};if(!r.client_id)throw new P(400,{message:"client_id is required"});e.set("client_id",r.client_id);let o;switch(n.grant_type){case Rn.AuthorizationCode:o=await lD(e,cD.parse(r));break;case Rn.ClientCredential:o=await sD(e,t6.parse(r));break;case Rn.RefreshToken:o=await uD(e,dD.parse(r));break;case Rn.OTP:o=await p6(e,CL.parse(r));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}an(e,o.client.tenant.id);const s=new Headers;o.session_id&&Vu(o.client.tenant.id,o.session_id,e.var.host||"").forEach(p=>{s.append("Set-Cookie",p)});let c=[],l;if(o.authParams.audience)try{let u;if(n.grant_type===Rn.ClientCredential)u=await Jc(e,{grantType:Rn.ClientCredential,tenantId:o.client.tenant.id,clientId:o.client.client_id,audience:o.authParams.audience,requestedScopes:o.authParams.scope?.split(" ")||[],organizationId:o.organization?.id});else{if(!o.user?.user_id)throw new Y(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await Jc(e,{grantType:n.grant_type,tenantId:o.client.tenant.id,userId:o.user.user_id,clientId:o.client.client_id,audience:o.authParams.audience,requestedScopes:o.authParams.scope?.split(" ")||[],organizationId:o.organization?.id})}o.authParams.scope=u.scopes.join(" "),c=u.permissions,l=o.client.app_type==="spa"?u.token_lifetime_for_web??u.token_lifetime:u.token_lifetime}catch(u){if(u instanceof P)throw u;console.error("Error calculating scopes and permissions:",u)}const d=await Ef(e,{...o,grantType:n.grant_type,permissions:c.length>0?c:void 0,token_lifetime:l});return e.json(d,{headers:s})});async function bs(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new P(500,{message:"Email provider not found"});const i=e.env.data.emailService;if(!i)throw new P(500,{message:"Email service not configured"});await i.send({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function f6(e,t){if(!e.var.client_id)throw new P(500,{message:"Client not found"});const n=await tt(e.env,e.var.client_id),i=n.connections.find(o=>o.strategy===W.SMS);if(!i)throw new P(500,{message:"SMS provider not found"});const r=e.env.data.smsService;if(!r)throw new P(500,{message:"SMS service not configured"});await r.send({options:i.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function h6(e,t){const n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new P(500,{message:"Tenant not found"});const i=await e.env.data.branding.get(e.var.tenant_id),r=i?.logo_url||"",o=i?.colors?.primary||"#7d68f4",s={vendorName:n.friendly_name,lng:t||"en"};return{tenant:n,logo:r,buttonColor:o,options:s}}async function g6(e,t,n,i,r){const{tenant:o,logo:s,buttonColor:c,options:l}=await h6(e,r),d=`${Bt(e.env)}reset-password?state=${i}&code=${n}`;await bs(e,{to:t,subject:ge("reset_password_title",l),html:`Click here to reset your password: ${Bt(e.env)}reset-password?state=${i}&code=${n}`,template:"auth-password-reset",data:{vendorName:o.friendly_name,logo:s,passwordResetUrl:d,supportUrl:o.support_url||"https://support.sesamy.com",buttonColor:c,passwordResetTitle:ge("password_reset_title",l),resetPasswordEmailClickToReset:ge("reset_password_email_click_to_reset",l),resetPasswordEmailReset:ge("reset_password_email_reset",l),supportInfo:ge("support_info",l),contactUs:ge("contact_us",l),copyright:ge("copyright",l),tenantName:o.friendly_name,tenantId:o.id}}),L(e,o.id,{type:B.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function $L(e,t,n,i){const{tenant:r,logo:o,buttonColor:s,options:c}=await h6(e,i);await bs(e,{to:t,subject:ge("reset_password_title",c),html:`Your password reset code is: ${n}`,template:"auth-code",data:{code:n,vendorName:r.friendly_name,logo:o,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:s,welcomeToYourAccount:ge("password_reset_title",c),linkEmailClickToLogin:ge("reset_password_email_click_to_reset",c),linkEmailLogin:ge("reset_password_email_reset",c),linkEmailOrEnterCode:ge("link_email_or_enter_code",{...c,code:n}),codeValid30Mins:ge("code_valid_30_minutes",c),supportInfo:ge("support_info",c),contactUs:ge("contact_us",c),copyright:ge("copyright",c)}}),L(e,r.id,{type:B.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Fl(e,{to:t,code:n,language:i}){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new P(500,{message:"Tenant not found"});const{connectionType:o}=$r(t),s=await e.env.data.branding.get(e.var.tenant_id),c=s?.logo_url||"",l=s?.colors?.primary||"#7d68f4",d=new URL(Bt(e.env)),u={vendorName:r.friendly_name,vendorId:r.id,loginDomain:d.hostname,code:n,lng:i||"en"};o==="email"?await bs(e,{to:t,subject:ge("code_email_subject",u),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:r.friendly_name,logo:c,supportUrl:r.support_url||"",buttonColor:l,welcomeToYourAccount:ge("welcome_to_your_account",u),linkEmailClickToLogin:ge("link_email_click_to_login",u),linkEmailLogin:ge("link_email_login",u),linkEmailOrEnterCode:ge("link_email_or_enter_code",u),codeValid30Mins:ge("code_valid_30_minutes",u),supportInfo:ge("support_info",u),contactUs:ge("contact_us",u),copyright:ge("copyright",u)}}):o==="sms"&&await f6(e,{to:t,text:ge("sms_code_text",u),code:n,from:r.friendly_name}),L(e,r.id,{type:B.CODE_LINK_SENT,description:t})}async function ql(e,{to:t,code:n,authParams:i,language:r}){const o=await e.env.data.tenants.get(e.var.tenant_id);if(!o)throw new P(500,{message:"Tenant not found"});if(!i.redirect_uri)throw new P(400,{message:"redirect_uri is required"});const{connectionType:s}=$r(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"",u=new URL(Ze(e.env));u.pathname="passwordless/verify_redirect",u.searchParams.set("verification_code",n),u.searchParams.set("connection",s),u.searchParams.set("client_id",i.client_id),u.searchParams.set("redirect_uri",i.redirect_uri),u.searchParams.set("email",t),i.response_type&&u.searchParams.set("response_type",i.response_type),i.scope&&u.searchParams.set("scope",i.scope),i.state&&u.searchParams.set("state",i.state),i.nonce&&u.searchParams.set("nonce",i.nonce),i.code_challenge&&u.searchParams.set("code_challenge",i.code_challenge),i.code_challenge_method&&u.searchParams.set("code_challenge_method",i.code_challenge_method),i.audience&&u.searchParams.set("audience",i.audience);const p={vendorName:o.friendly_name,code:n,lng:r||"en"};if(s==="email")await bs(e,{to:t,subject:ge("code_email_subject",p),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:o.friendly_name,logo:l,supportUrl:o.support_url||"",magicLink:u.toString(),buttonColor:d,welcomeToYourAccount:ge("welcome_to_your_account",p),linkEmailClickToLogin:ge("link_email_click_to_login",p),linkEmailLogin:ge("link_email_login",p),linkEmailOrEnterCode:ge("link_email_or_enter_code",p),codeValid30Mins:ge("code_valid_30_minutes",p),supportInfo:ge("support_info",p),contactUs:ge("contact_us",p),copyright:ge("copyright",p)}});else if(s==="sms")await f6(e,{to:t,text:`${ge("link_sms_login",p)}: ${u.toString()}`,code:n,from:o.friendly_name});else throw new P(400,{message:"Only email and SMS connections are supported for magic links"});L(e,o.id,{type:B.CODE_LINK_SENT,description:t})}async function jf(e,t,n){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new P(500,{message:"Tenant not found"});if(!t.email)throw new P(400,{message:"User has no email"});const r=await e.env.data.branding.get(e.var.tenant_id),o=r?.logo_url||"",s=r?.colors?.primary||"#7d68f4",c={vendorName:i.friendly_name,lng:n||"en"};await bs(e,{to:t.email,subject:ge("welcome_to_your_account",c),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:i.friendly_name,logo:o,emailValidationUrl:`${Bt(e.env)}validate-email`,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:s,welcomeToYourAccount:ge("welcome_to_your_account",c),verifyEmailVerify:ge("verify_email_verify",c),supportInfo:ge("support_info",c),contactUs:ge("contact_us",c),copyright:ge("copyright",c)}})}async function zL(e,t,n,i,r){const o=await e.env.data.tenants.get(e.var.tenant_id);if(!o)throw new P(500,{message:"Tenant not found"});const s=await e.env.data.branding.get(e.var.tenant_id),c=s?.logo_url||"",l=s?.colors?.primary||"#7d68f4",d={vendorName:o.friendly_name,lng:"en"},u=`${Bt(e.env)}signup?state=${i}&code=${n}`;await bs(e,{to:t,subject:ge("register_password_account",d),html:`Click here to register: ${u}`,template:"auth-pre-signup-verification",data:{vendorName:o.friendly_name,logo:c,signupUrl:u,setPassword:ge("set_password",d),registerPasswordAccount:ge("register_password_account",d),clickToSignUpDescription:ge("click_to_sign_up_description",d),supportUrl:o.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:ge("welcome_to_your_account",d),verifyEmailVerify:ge("verify_email_verify",d),supportInfo:ge("support_info",d),contactUs:ge("contact_us",d),copyright:ge("copyright",d)}})}const PL=new a.OpenAPIHono().openapi(a.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.literal(W.USERNAME_PASSWORD),email:a.z.string().transform(e=>e.toLowerCase()),password:a.z.string()})}}}},responses:{200:{content:{"application/json":{schema:a.z.object({_id:a.z.string(),email:a.z.string().optional(),email_verified:a.z.boolean(),app_metadata:a.z.object({}),user_metadata:a.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:i}=e.req.valid("json"),r=await tt(e.env,i);e.set("client_id",r.client_id),an(e,r.tenant.id);const s=r.connections.find(f=>f.strategy===W.USERNAME_PASSWORD)?.name||W.USERNAME_PASSWORD,c=await hl(e.env.data,r.tenant.id,s);try{await fl(c,{tenantId:r.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(f){throw new P(400,{message:f?.message||"Password does not meet the requirements"})}if(await wn({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Ke}))throw new P(400,{message:"Invalid sign up"});const{hash:d,algorithm:u}=await jc(n),p=await e.env.data.users.create(r.tenant.id,{user_id:`${Ke}|${$o()}`,email:t,email_verified:!1,provider:Ke,connection:W.USERNAME_PASSWORD,is_social:!1,password:{hash:d,algorithm:u}});e.set("user_id",p.user_id),e.set("username",p.email),e.set("connection",p.connection);try{await jf(e,p)}catch(f){console.error("Failed to send verification email:",f)}return L(e,r.tenant.id,{type:B.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:p.user_id,email:p.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(a.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.literal(W.USERNAME_PASSWORD),email:a.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),i=await tt(e.env,n);if(e.set("client_id",i.client_id),an(e,i.tenant.id),!await Sr({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Ke}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const o={client_id:n,username:t},s=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:o,csrf_token:Ve(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:Li(e.get("auth0_client"))});return await g6(e,t,s.id,s.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function sn(){const e=new Uint8Array(6);crypto.getRandomValues(e);let t="";for(let n=0;n<6;n+=1)t+=(e[n]%10).toString();return t}const NL=new a.OpenAPIHono().openapi(a.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:a.z.union([a.z.object({connection:a.z.literal("email"),client_id:a.z.string(),email:a.z.string().transform(e=>e.toLowerCase()),send:a.z.enum(["link","code"]),authParams:Ic.omit({client_id:!0})}),a.z.object({client_id:a.z.string(),connection:a.z.literal("sms"),phone_number:a.z.string(),send:a.z.enum(["link","code"]),authParams:Ic.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:i,send:r,authParams:o,connection:s}=t,c=await tt(e.env,i);e.set("client_id",c.client_id),an(e,c.tenant.id);const l=s==="email"?t.email:t.phone_number,d=e.get("ip"),u=e.get("useragent"),p=e.get("auth0_client"),f=Li(p),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...o,client_id:i,username:l},expires_at:new Date(Date.now()+ba).toISOString(),csrf_token:Ve(),ip:d,useragent:u,auth0Client:f}),g=await n.data.codes.create(c.tenant.id,{code_id:sn(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+ba).toISOString(),redirect_uri:o.redirect_uri}),m=o?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];return r==="link"?await ql(e,{to:l,code:g.code_id,authParams:{...o,client_id:i},language:m}):await Fl(e,{to:l,code:g.code_id,language:m}),e.html("OK")}).openapi(a.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:a.z.object({scope:a.z.string(),response_type:a.z.nativeEnum(St),redirect_uri:a.z.string(),state:a.z.string(),nonce:a.z.string().optional(),verification_code:a.z.string(),connection:a.z.string(),client_id:a.z.string(),email:a.z.string().transform(e=>e.toLowerCase()),audience:a.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:a.z.object({Location:a.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:i,verification_code:r,redirect_uri:o,state:s,scope:c,audience:l,response_type:d,nonce:u}=e.req.valid("query"),p=await tt(t,n);e.set("client_id",p.client_id),an(e,p.tenant.id),e.set("connection","email");const f={client_id:n,redirect_uri:o,state:s,nonce:u,scope:c,audience:l,response_type:d};let h="Something went wrong. Please try again later.";try{const v=await Ul(e,{client_id:n,username:i,otp:r,authParams:f,enforceIpCheck:!0});if(v instanceof Response)return v;if(v&&typeof v=="object"&&"access_token"in v)return e.json(v)}catch(v){const k=v;"message"in k&&typeof k.message=="string"&&(h=k.message)}const g=e.get("ip"),m=e.get("useragent"),_=e.get("auth0_client"),y=Li(_),w=await t.data.loginSessions.create(p.tenant.id,{authParams:{...f,username:i},expires_at:new Date(Date.now()+ba).toISOString(),csrf_token:Ve(),ip:g,useragent:m,auth0Client:y});return e.redirect(`${Bt(e.env,e.var.custom_domain)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class aa extends P{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function jL(e,t,n){const i=n.app_metadata||{},r=i.failed_logins||[],o=Date.now(),s=[...r.filter(c=>o-c<1e3*60*5),o];i.failed_logins=s,await e.users.update(t,n.user_id,{app_metadata:i})}function OL(e){const n=(e.app_metadata||{}).failed_logins||[],i=Date.now();return n.filter(r=>i-r<1e3*60*5)}async function m6(e,t,n,i){const{data:r}=e.env,{username:o}=n;if(e.set("username",o),!o)throw new Y(400,{message:"Username is required"});const s=await Sr({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:o,provider:Ke});if(!s)throw L(e,t.tenant.id,{type:B.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new aa(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=s.linked_to?await r.users.get(t.tenant.id,s.linked_to):s;if(!c)throw new aa(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",s.connection),e.set("user_id",c.user_id),OL(c).length>=3)throw L(e,t.tenant.id,{type:B.FAILED_LOGIN,description:"Too many failed login attempts"}),new aa(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const d=await r.passwords.get(t.tenant.id,s.user_id);if(!(d&&await ts.compare(n.password,d.password)))throw L(e,t.tenant.id,{type:B.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),jL(r,t.tenant.id,c),new aa(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!s.email_verified&&t.client_metadata?.email_validation==="enforced"){const f=i?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await jf(e,s,f),L(e,t.tenant.id,{type:B.FAILED_LOGIN,description:"Email not verified"}),i&&await q7(e,t.tenant.id,i,"Email not verified"),new aa(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const p=c.app_metadata||{};return p.failed_logins&&p.failed_logins.length>0&&(p.failed_logins=[],r.users.update(t.tenant.id,c.user_id,{app_metadata:p})),{client:t,authParams:n,user:c,loginSession:i}}async function Hl(e,t,n,i,r){const o=await m6(e,t,n,i);return Je(e,{...o,ticketAuth:r,authConnection:e.get("connection")||W.USERNAME_PASSWORD,authStrategy:{strategy:W.USERNAME_PASSWORD,strategy_type:Mt.DATABASE}})}async function K_(e,t,n,i,r){await Sp(e,{client:t,username:n,provider:Ke,connection:W.USERNAME_PASSWORD,isSocial:!1,ip:e.var.ip});let o=sn(),s=await e.env.data.codes.get(t.tenant.id,o,"password_reset");for(;s;)o=sn(),s=await e.env.data.codes.get(t.tenant.id,o,"password_reset");let c=i;if(!await e.env.data.loginSessions.get(t.tenant.id,i)){const u=e.get("ip"),p=e.get("useragent"),f=e.get("auth0_client"),h=Li(f);c=(await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Rj).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Ve(),ip:u,useragent:p,auth0Client:h})).id}const d=await e.env.data.codes.create(t.tenant.id,{code_id:o,code_type:"password_reset",login_id:c,expires_at:new Date(Date.now()+Oj).toISOString()});r==="code"?await $L(e,n,d.code_id):await g6(e,n,d.code_id,c)}const RL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.union([a.z.object({credential_type:a.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:a.z.string(),client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),realm:a.z.enum([W.EMAIL]),scope:a.z.string().optional()}),a.z.object({credential_type:a.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),password:a.z.string(),realm:a.z.enum([W.USERNAME_PASSWORD]),scope:a.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:i}=t;e.set("username",i);const r=await tt(e.env,n);e.set("client_id",n),an(e,r.tenant.id);const o=i.toLocaleLowerCase(),s=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let d;if("otp"in t)d=await Ul(e,{client_id:n,username:o,otp:t.otp});else if("password"in t){const u=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:{client_id:n,username:o},csrf_token:Ve(),ip:s,useragent:c,auth0Client:Li(l)});d=await Hl(e,r,{username:o,password:t.password,client_id:n},u,!0)}else throw new P(400,{message:"Code or password required"});return d});function y6(e,t){if(!e||t.length===0)return!1;const n=Ih(e)?.host??null;if(!n)return!1;for(const i of t){let r;if(i.startsWith("http://")||i.startsWith("https://")?r=Ih(i)?.host??null:r=Ih("https://"+i)?.host??null,n===r)return!0}return!1}function Ih(e){try{return new URL(e)}catch{return null}}function DL(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),i=t*1e3;return Date.now()-n>i}async function BL({ctx:e,session:t,client:n,authParams:i,connection:r,login_hint:o,screen_hint:s}){const c=new URL(e.req.url);e.var.custom_domain&&(c.hostname=e.var.custom_domain);const{ip:l,auth0_client:d,useragent:u}=e.var,p=Li(d);DL(t,i.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:i,csrf_token:Ve(),authorization_url:c.toString(),ip:l,useragent:u,auth0Client:p}),h=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&o&&s!=="login"){const g=await e.env.data.users.get(n.tenant.id,t.user_id);if(g?.email===o)return Je(e,{client:n,loginSession:f,authParams:i,user:g,existingSessionIdToLink:t.id})}if(r===W.EMAIL&&o){const g=sn();return await e.env.data.codes.create(n.tenant.id,{code_id:g,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+yr*1e3).toISOString(),redirect_uri:i.redirect_uri}),await ql(e,{code:g,to:o,authParams:i}),e.redirect(`${h}/login/email-otp-challenge?state=${f.id}`)}if(t&&s!=="login")return e.redirect(`${h}/check-account?state=${f.id}`);if(h==="/u2"){const g=await e.env.data.promptSettings.get(n.tenant.id),m=to.parse(g||{}),_=n.connections.some(y=>y.strategy===W.USERNAME_PASSWORD);if(m.identifier_first===!1&&_)return e.redirect(`${h}/login?state=${f.id}`)}return e.redirect(`${h}/login/identifier?state=${f.id}`)}function LL(e){if(e===W.USERNAME_PASSWORD)return Ke;if(e===W.EMAIL)return W.EMAIL;throw new Y(403,{message:"Invalid realm"})}async function ML(e,t,n,i,r){const{env:o}=e;e.set("connection",r);const s=await o.data.codes.get(t,n,"ticket");if(!s||s.used_at)throw new Y(403,{message:"Ticket not found"});const c=await o.data.loginSessions.get(t,s.login_id);if(!c||!c.authParams.username)throw new Y(403,{message:"Session not found"});const l=await tt(o,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await o.data.codes.used(t,n);const d=LL(r),p=l.connections.find(g=>g.name===r)?.strategy||(d===Ke?W.USERNAME_PASSWORD:W.EMAIL),f=p===W.USERNAME_PASSWORD?Mt.DATABASE:Mt.PASSWORDLESS;let h=await Sp(e,{username:c.authParams.username,provider:d,client:l,connection:r,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),Je(e,{authParams:{scope:c.authParams?.scope,...i},loginSession:c,user:h,client:l,authConnection:r,authStrategy:{strategy:p,strategy_type:f}})}async function UL({ctx:e,client:t,session:n,redirect_uri:i,state:r,nonce:o,code_challenge_method:s,code_challenge:c,audience:l,scope:d,response_type:u,response_mode:p,organization:f,max_age:h}){const{env:g}=e,m=new URL(i),_=`${m.protocol}//${m.host}`,y=p===hn.WEB_MESSAGE;async function w(q="Login required"){const xe=new Headers;if(n&&(L(e,t.tenant.id,{type:B.FAILED_SILENT_AUTH,description:q}),uC(t.tenant.id,e.var.host).forEach(un=>{xe.append("set-cookie",un)})),y)return x0(e,_,JSON.stringify({error:"login_required",error_description:q,state:r}),xe);const me=new URL(i);if(u===St.TOKEN||u===St.TOKEN_ID_TOKEN){const Qe=new URLSearchParams;Qe.set("error","login_required"),Qe.set("error_description",q),r&&Qe.set("state",r),me.hash=Qe.toString()}else me.searchParams.set("error","login_required"),me.searchParams.set("error_description",q),r&&me.searchParams.set("state",r);const je={Location:me.toString()},et=xe.get("set-cookie");return et&&(je["set-cookie"]=et),new Response(null,{status:302,headers:je})}const v=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,k=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(v||k)return w();const b=await g.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),w("User not found");const S=b.linked_to?await g.data.users.get(t.tenant.id,b.linked_to):b;if(!S)return console.error("Linked primary user not found",b.linked_to),w("User not found");e.set("user_id",S.user_id),e.set("username",S.email),e.set("connection",S.connection);let E;if(f&&(E=await g.data.organizations.get(t.tenant.id,f),!E))return w("Organization not found");const z=l||t.tenant.audience;let T=d||"",N=[],I;if(z)try{const q=await Jc(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:z,requestedScopes:d?.split(" ")||[],organizationId:E?.id,userId:S.user_id});T=q.scopes.join(" "),N=q.permissions,I=t.app_type==="spa"&&q.token_lifetime_for_web?q.token_lifetime_for_web:q.token_lifetime}catch(q){if(q?.statusCode===403||q?.status===403){const xe=q?.body?.error_description||q?.message||"Access denied";return w(xe)}throw q}else if(E&&!(await g.data.userOrganizations.list(t.tenant.id,{q:`user_id:${S.user_id}`,per_page:1e3})).userOrganizations.some(me=>me.organization_id===E.id))return w("User is not a member of the specified organization");const $=await g.data.loginSessions.create(t.tenant.id,{csrf_token:Ve(),authParams:{client_id:t.client_id,audience:l,scope:d,state:r,nonce:o,response_type:u,redirect_uri:i,organization:f,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),j=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,R={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:s,code_challenge:c,scope:T,state:r,nonce:o,response_type:u,redirect_uri:i,max_age:h},user:S,session_id:n.id,auth_time:j,permissions:N,organization:E,token_lifetime:I},D=u===St.CODE?await KC(e,{user:S,client:t,authParams:R.authParams,login_id:$.id}):await Ef(e,R),H=t.tenant.idle_session_lifetime?new Date(Date.now()+t.tenant.idle_session_lifetime*60*60*1e3).toISOString():void 0;await g.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:$.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:H}),H&&await g.data.loginSessions.update(t.tenant.id,$.id,{expires_at:H}),L(e,t.tenant.id,{type:B.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const Q=new Headers;if(Vu(t.tenant.id,n.id,e.var.host).forEach(q=>{Q.append("set-cookie",q)}),y)return x0(e,_,JSON.stringify({...D,state:r}),Q);const ne=new URL(i);if(u===St.TOKEN||u===St.TOKEN_ID_TOKEN){const q=new URLSearchParams;Object.entries(D).forEach(([xe,me])=>{me!==void 0&&q.set(xe,String(me))}),r&&q.set("state",r),ne.hash=q.toString()}else Object.entries(D).forEach(([q,xe])=>{xe!==void 0&&ne.searchParams.set(q,String(xe))}),r&&ne.searchParams.set("state",r);const _e={Location:ne.toString()},Ie=Q.get("set-cookie");return Ie&&(_e["set-cookie"]=Ie),new Response(null,{status:302,headers:_e})}const FL=1024;function qL(e,t){const n=e.split(":")[0]?.split(".")??[],i=t.split(":")[0]?.split(".")??[];if(n.length<2||i.length<2)return!1;const r=n.slice(-2).join("."),o=i.slice(-2).join(".");return r===o}async function HL(e,t,n){return await e.env.data.customDomains.getByDomain(t)?!0:qL(t,n)}async function KL(e,t){const n=await e.env.data.loginSessions.get(e.var.tenant_id||"",t);if(!n)throw new Y(403,{message:"State not found"});const i=n.authorization_url;if(i&&i.length<=FL){let c=null;try{c=new URL(i)}catch{c=null}const l=e.var.host||"";if(c&&c.host&&c.host!==l&&await HL(e,c.host,l)){const u=new URL("/authorize/resume",c.origin);return u.searchParams.set("state",t),new Response(null,{status:302,headers:{location:u.toString()}})}}const r=await tt(e.env,n.authParams.client_id);an(e,r.tenant.id),e.set("client_id",r.client_id);const o=n.state||be.PENDING;if(o===be.PENDING)throw new Y(400,{error:"invalid_request",error_description:"Login session is not yet authenticated"});if(o===be.COMPLETED)throw new Y(409,{error:"invalid_request",error_description:"Login session has already been completed"});if(o===be.FAILED)throw new Y(400,{error:"access_denied",error_description:`Login session failed: ${n.failure_reason||"unknown reason"}`});if(o===be.EXPIRED)throw new Y(400,{error:"invalid_request",error_description:"Login session has expired"});if(!n.user_id)throw new Y(500,{message:"Authenticated login session has no user_id"});const s=await e.env.data.users.get(r.tenant.id,n.user_id);if(!s)throw new Y(500,{message:"Authenticated user not found"});return e.set("user_id",s.user_id),n.auth_connection&&e.set("connection",n.auth_connection),Je(e,{authParams:n.authParams,client:r,user:s,loginSession:n,authStrategy:n.auth_strategy,authConnection:n.auth_connection})}const VL=[W.EMAIL,W.SMS,W.USERNAME_PASSWORD],W1=a.z.object({client_id:a.z.string().optional(),vendor_id:a.z.string().optional(),redirect_uri:a.z.string().optional(),scope:a.z.string().optional(),state:a.z.string().optional(),prompt:a.z.string().optional(),response_mode:a.z.nativeEnum(hn).optional(),response_type:a.z.nativeEnum(St).optional(),audience:a.z.string().optional(),connection:a.z.string().optional(),nonce:a.z.string().optional(),max_age:a.z.string().optional(),acr_values:a.z.string().optional(),login_ticket:a.z.string().optional(),code_challenge_method:a.z.nativeEnum(vp).optional(),code_challenge:a.z.string().optional(),realm:a.z.string().optional(),auth0Client:a.z.string().optional(),organization:a.z.string().optional(),login_hint:a.z.string().optional(),screen_hint:a.z.string().optional(),ui_locales:a.z.string().optional()});function GL(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(lr.decode(t[1],{strict:!1})),i=JSON.parse(n);return typeof i!="object"||i===null?null:i}catch{return null}}const WL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:W1.extend({client_id:a.z.string(),screen_hint:a.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:a.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:a.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:_y}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let i={};if(n.request){const H=GL(n.request);if(H){const Q=W1.safeParse(H);Q.success&&(i=Q.data)}}const{client_id:r,vendor_id:o,redirect_uri:s,scope:c,state:l,audience:d,nonce:u,connection:p,response_type:f,response_mode:h,code_challenge:g,code_challenge_method:m,prompt:_,max_age:y,acr_values:w,login_ticket:v,realm:k,login_hint:b,ui_locales:S,organization:E,screen_hint:z}={...i,...n};e.set("log","authorize");const T=await tt(t,r);e.set("client_id",T.client_id),an(e,T.tenant.id);let N=s;typeof s=="string"&&(N=s.split("#")[0]);const I=e.req.header("origin");if(I&&!y6(I,T.web_origins||[]))throw new P(403,{message:`Origin ${I} not allowed`});if(!f){if(N){const H=new URL(N);return H.searchParams.set("error","invalid_request"),H.searchParams.set("error_description","Missing required parameter: response_type"),l&&H.searchParams.set("state",l),e.redirect(H.toString())}throw new P(400,{message:"Missing required parameter: response_type"})}const $={redirect_uri:N,scope:c,state:l,client_id:r,vendor_id:o,audience:d,nonce:u,prompt:_,response_type:f,response_mode:h,code_challenge:g,code_challenge_method:m,username:b,ui_locales:S,organization:E,max_age:y?parseInt(y,10):void 0,acr_values:w};if($.redirect_uri){const H=T.callbacks||[];if(e.var.host&&(H.push(`${Er(e.env,e.var.custom_domain)}/*`),H.push(`${Bt(e.env,e.var.custom_domain)}/*`)),!R_($.redirect_uri,H,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new P(400,{message:`Invalid redirect URI - ${$.redirect_uri}`})}let j;const R=Bj(T.tenant.id,e.req.header("cookie"));for(const H of R){const Q=await t.data.sessions.get(T.tenant.id,H);if(Q&&!Q.revoked_at){j=Q;break}}if(T.sso_disabled&&(j=void 0),_=="none"){if(!N||!l||!f)throw new P(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return UL({ctx:e,session:j||void 0,redirect_uri:N,state:l,response_type:f,response_mode:h,client:T,nonce:u,code_challenge_method:m,code_challenge:g,audience:d,scope:c,organization:E,max_age:y?parseInt(y,10):void 0})}if(T.connections.length===1&&T.connections[0]&&!VL.includes(T.connections[0].strategy||""))return w1(e,T,T.connections[0].name,$);if(p&&p!==W.EMAIL)return w1(e,T,p,$);if(v){const H=await ML(e,T.tenant.id,v,$,k);return H instanceof Response?H:e.json(H)}const D=await BL({ctx:e,client:T,authParams:$,session:j||void 0,connection:p,login_hint:b,screen_hint:z});return D instanceof Response?D:e.json(D)}).openapi(a.createRoute({tags:["oauth"],method:"get",path:"/resume",request:{query:a.z.object({state:a.z.string()})},responses:{302:{description:"Redirect to the client's redirect_uri (with cookie set), to a MFA/continuation UL screen, or to the original authorization host when the browser is on the wrong custom domain.",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Login session is in PENDING, FAILED, or EXPIRED state.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},403:{description:"Login session not found.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},409:{description:"Login session has already been completed (replay).",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{state:t}=e.req.valid("query");return KL(e,t)}),JL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:a.z.object({client_id:a.z.string(),redirect_url:a.z.string().optional(),login_hint:a.z.string().toLowerCase().optional(),screen_hint:a.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:i,login_hint:r,screen_hint:o}=e.req.valid("query");e.set("log","account");const s=await tt(t,n);e.set("client_id",s.client_id),an(e,s.tenant.id);const c={redirect_uri:i||e.req.url,client_id:n,username:r},l=e.req.header("origin");if(l&&!y6(l,s.web_origins||[]))throw new P(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=s.callbacks||[];if(e.var.host&&(w.push(`${Er(e.env,e.var.custom_domain)}/*`),w.push(`${Bt(e.env,e.var.custom_domain)}/*`)),!R_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new P(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const d=_r(s.tenant.id,e.req.header("cookie")),u=d?await t.data.sessions.get(s.tenant.id,d):void 0;let p=u&&!u.revoked_at?u:void 0;s.sso_disabled&&(p=void 0);const f=new URL(e.req.url);e.var.custom_domain&&(f.hostname=e.var.custom_domain);const{ip:h,auth0_client:g,useragent:m}=e.var,_=Li(g),y=await t.data.loginSessions.create(s.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:c,csrf_token:Ve(),authorization_url:f.toString(),ip:h,useragent:m,auth0Client:_});if(p){if(r&&(await t.data.users.get(s.tenant.id,p.user_id))?.email!==r)return e.redirect(`${Bt(e.env,e.var.custom_domain)}login/identifier?state=${encodeURIComponent(y.id)}`);if(await t.data.loginSessions.update(s.tenant.id,y.id,{session_id:p.id}),o==="change-email"){const v=new URL("/u2/account/profile",e.req.url);return v.searchParams.set("state",y.id),e.redirect(v.toString())}const w=new URL("/u2/account",e.req.url);return w.searchParams.set("state",y.id),e.redirect(w.toString())}return e.redirect(`${Bt(e.env,e.var.custom_domain)}login/identifier?state=${encodeURIComponent(y.id)}`)});function QL(e){const t=new a.OpenAPIHono;t.use(gs(e)),t.use(Ml({getOutbox:()=>e.dataAdapter.outbox,getDestinations:i=>[new Oo(e.dataAdapter.logs),new ws(e.dataAdapter.hooks,async r=>(await Ir(i,r,"webhook")).access_token),new vs(e.dataAdapter.users)]})),t.use(async(i,r)=>{const o=Dl(i,e.dataAdapter),s=e.dataAdapter.cache||_s({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Ll(o,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks","keys"],cache:s});return i.env.data=Bl(i,l),r()}),t.use("/oauth/token",e6({origin:i=>i||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ys).use(ms).use(bf(t));const n=t.route("/v2/logout",nD).route("/userinfo",oD).route("/.well-known",aD).route("/oauth/token",IL).route("/dbconnections",PL).route("/passwordless",NL).route("/co/authenticate",RL).route("/authorize",WL).route("/account",JL).route("/callback",eD);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),b_(n),n}var V_=Symbol("RENDERER"),U0=Symbol("ERROR_HANDLER"),rt=Symbol("STASH"),_6=Symbol("INTERNAL"),YL=Symbol("MEMO"),cp=Symbol("PERMALINK"),J1=e=>(e[_6]=!0,e),w6=e=>({value:t,children:n})=>{if(!n)return;const i={children:[{tag:J1(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?i.children.push(...n.flat()):i.children.push(n),i.children.push({tag:J1(()=>{e.pop()}),props:{}});const r={tag:"",props:i,type:""};return r[U0]=o=>{throw e.pop(),o},r},v6=e=>{const t=[e],n=w6(t);return n.values=t,n.Provider=n,Ga.push(n),n},Ga=[],b6=e=>{const t=[e],n=(i=>{t.push(i.value);let r;try{r=i.children?(Array.isArray(i.children)?new C6("",{},i.children):i.children).toString():""}catch(o){throw t.pop(),o}return r instanceof Promise?r.finally(()=>t.pop()).then(o=>mr(o,o.callbacks)):(t.pop(),mr(r))});return n.values=t,n.Provider=n,n[V_]=w6(t),Ga.push(n),n},As=e=>e.values.at(-1),lp={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},F0={},Kr="data-precedence",A6=e=>e.rel==="stylesheet"&&"precedence"in e,k6=(e,t)=>e==="link"?t:lp[e].length>0,Kl=e=>Array.isArray(e)?e:[e],Q1=new WeakMap,Y1=(e,t,n,i)=>({buffer:r,context:o})=>{if(!r)return;const s=Q1.get(o)||{};Q1.set(o,s);const c=s[e]||=[];let l=!1;const d=lp[e],u=k6(e,i!==void 0);if(u){e:for(const[,p]of c)if(!(e==="link"&&!(p.rel==="stylesheet"&&p[Kr]!==void 0))){for(const f of d)if((p?.[f]??null)===n?.[f]){l=!0;break e}}}if(l?r[0]=r[0].replaceAll(t,""):u||e==="link"?c.push([t,n,i]):c.unshift([t,n,i]),r[0].indexOf("</head>")!==-1){let p;if(e==="link"||i!==void 0){const f=[];p=c.map(([h,,g],m)=>{if(g===void 0)return[h,Number.MAX_SAFE_INTEGER,m];let _=f.indexOf(g);return _===-1&&(f.push(g),_=f.length-1),[h,_,m]}).sort((h,g)=>h[1]-g[1]||h[2]-g[2]).map(([h])=>h)}else p=c.map(([f])=>f);p.forEach(f=>{r[0]=r[0].replaceAll(f,"")}),r[0]=r[0].replace(/(?=<\/head>)/,p.join(""))}},Vl=(e,t,n)=>mr(new Fn(e,n,Kl(t??[])).toString()),Gl=(e,t,n,i)=>{if("itemProp"in n)return Vl(e,t,n);let{precedence:r,blocking:o,...s}=n;r=i?r??"":void 0,i&&(s[Kr]=r);const c=new Fn(e,s,Kl(t||[])).toString();return c instanceof Promise?c.then(l=>mr(c,[...l.callbacks||[],Y1(e,l,s,r)])):mr(c,[Y1(e,c,s,r)])},ZL=({children:e,...t})=>{const n=G_();if(n){const i=As(n);if(i==="svg"||i==="head")return new Fn("title",t,Kl(e??[]))}return Gl("title",e,t,!1)},XL=({children:e,...t})=>{const n=G_();return["src","async"].some(i=>!t[i])||n&&As(n)==="head"?Vl("script",e,t):Gl("script",e,t,!1)},eM=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,Gl("style",e,t,!0)):Vl("style",e,t),tM=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?Vl("link",e,t):Gl("link",e,t,A6(t)),nM=({children:e,...t})=>{const n=G_();return n&&As(n)==="head"?Vl("meta",e,t):Gl("meta",e,t,!1)},S6=(e,{children:t,...n})=>new Fn(e,n,Kl(t??[])),iM=e=>(typeof e.action=="function"&&(e.action=cp in e.action?e.action[cp]:void 0),S6("form",e)),x6=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=cp in t.formAction?t.formAction[cp]:void 0),S6(e,t)),rM=e=>x6("input",e),oM=e=>x6("button",e);const $h=Object.freeze(Object.defineProperty({__proto__:null,button:oM,form:iM,input:rM,link:tM,meta:nM,script:XL,style:eM,title:ZL},Symbol.toStringTag,{value:"Module"}));var aM=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),dp=e=>aM.get(e)||e,sM=/[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/,cM=e=>{const t=e.length;if(t===0)return!1;for(let n=0;n<t;n++){const i=e.charCodeAt(n);if(!(i>=97&&i<=122||i>=65&&i<=90||i>=48&&i<=57||i===45||i===95||i===46||i===58))return!sM.test(e)}return!0},E6=(e,t)=>{for(const[n,i]of Object.entries(e)){const r=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`);t(r,i==null?null:typeof i=="number"?r.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${i}`:`${i}px`:i)}},rl=void 0,G_=()=>rl,lM=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dM=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],uM=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],W_=(e,t)=>{for(let n=0,i=e.length;n<i;n++){const r=e[n];if(typeof r=="string")va(r,t);else{if(typeof r=="boolean"||r===null||r===void 0)continue;r instanceof Fn?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?t[0]+=r:r instanceof Promise?t.unshift("",r):W_(r,t)}}},Fn=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?fj(mr(e[0],e.callbacks)).toString():e[0]:pj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:i}=this;e[0]+=`<${t}`;const r=rl&&As(rl)==="svg"?o=>lM(dp(o)):o=>dp(o);for(let[o,s]of Object.entries(n))if(o=r(o),!!cM(o)&&o!=="children"){if(o==="style"&&typeof s=="object"){let c="";E6(s,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),e[0]+=' style="',va(c,e),e[0]+='"'}else if(typeof s=="string")e[0]+=` ${o}="`,va(s,e),e[0]+='"';else if(s!=null)if(typeof s=="number"||s.isEscaped)e[0]+=` ${o}="${s}"`;else if(typeof s=="boolean"&&uM.includes(o))s&&(e[0]+=` ${o}=""`);else if(o==="dangerouslySetInnerHTML"){if(i.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");i=[mr(s.__html)]}else if(s instanceof Promise)e[0]+=` ${o}="`,e.unshift('"',s);else if(typeof s=="function"){if(!o.startsWith("on")&&o!=="ref")throw new Error(`Invalid prop '${o}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${o}="`,va(s.toString(),e),e[0]+='"'}if(dM.includes(t)&&i.length===0){e[0]+="/>";return}e[0]+=">",W_(i,e),e[0]+=`</${t}>`}},zh=class extends Fn{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const i=this.tag.call(null,n);if(!(typeof i=="boolean"||i==null))if(i instanceof Promise)if(Ga.length===0)e.unshift("",i);else{const r=Ga.map(o=>[o,o.values.at(-1)]);e.unshift("",i.then(o=>(o instanceof Fn&&(o.localContexts=r),o)))}else i instanceof Fn?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?(e[0]+=i,i.callbacks&&(e.callbacks||=[],e.callbacks.push(...i.callbacks))):va(i,e)}},C6=class extends Fn{toStringToBuffer(e){W_(this.children,e)}},pM=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const i=t.key;delete t.key;const r=Bd(e,t,n);return r.key=i,r},Z1=!1,Bd=(e,t,n)=>{if(!Z1){for(const i in F0)$h[i][V_]=F0[i];Z1=!0}return typeof e=="function"?new zh(e,t,n):$h[e]?new zh($h[e],t,n):e==="svg"||e==="head"?(rl||=b6(""),new Fn(e,t,[new zh(rl,{value:e},n)])):new Fn(e,t,n)},Wa=({children:e})=>new C6("",{children:e},Array.isArray(e)?e:e?[e]:[]),fM=(e,t,...n)=>{let i;if(n.length>0)i=n;else{const r=e.props.children;i=Array.isArray(r)?r:[r]}return pM(e.tag,{...e.props,...t},...i)};function A(e,t,n){let i;if(!t||!("children"in t))i=Bd(e,t,[]);else{const r=t.children;i=Array.isArray(r)?Bd(e,t,r):Bd(e,t,[r])}return i.key=n,i}async function Be(e,t,n=!1){const{env:i}=e,r=await i.data.loginSessions.get(e.var.tenant_id||"",t);if(!r)throw new P(400,{message:"Login session not found"});e.set("loginSession",r);const o=await tt(i,r.authParams.client_id);e.set("client_id",o.client_id),an(e,o.tenant.id);const s=o.tenant;if(r.session_id&&!n){if(!r.authParams.redirect_uri)throw new P(400,{message:"Login session closed and no redirect URI available"});const f=new URL(r.authParams.redirect_uri);throw f.searchParams.set("error","access_denied"),f.searchParams.set("error_description","Login session closed"),r.authParams.state&&f.searchParams.set("state",r.authParams.state),new rn(f.toString(),302)}const[c,l]=await Promise.all([i.data.themes.get(s.id,"default"),i.data.branding.get(s.id)]),d=c??zc,u=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,p=r.authParams?.ui_locales?.split(" ")?.map(f=>f.split("-")[0])?.find(f=>{if(Array.isArray(M.options.supportedLngs))return M.options.supportedLngs.includes(f)});return await M.changeLanguage(p||"en"),{theme:d,branding:u,client:o,tenant:s,loginSession:r}}async function So(e,t,n){const{theme:i,branding:r,client:o,tenant:s,loginSession:c}=await Be(e,t,!0),l=_r(o.tenant.id,e.req.header("cookie")),d=l?await e.env.data.sessions.get(o.tenant.id,l):null;if(n?.continuationScope&&ip(c,n.continuationScope)){if(!c.user_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(o.tenant.id,c.user_id);if(!h)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const g=c.session_id?await e.env.data.sessions.get(o.tenant.id,c.session_id):null;return{theme:i,branding:r,client:o,user:h,tenant:s,loginSession:c,session:g,isContinuation:!0}}if(!d||d.revoked_at||!c.session_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const p=await e.env.data.sessions.get(o.tenant.id,c.session_id),f=await e.env.data.users.get(o.tenant.id,d.user_id);if(!f||p?.user_id!==d.user_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:i,branding:r,client:o,user:f,tenant:s,loginSession:c,session:p,isContinuation:!1}}const Ph={[W.USERNAME_PASSWORD]:"password",[W.EMAIL]:"email",[W.SMS]:"sms"};async function T6(e,t,n,i,r){if(i==="username"||r==="password")return"password";if(r==="code")return i==="sms"?"sms":"email";const s=(i==="email"?await xr({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await wn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:i==="sms"?"sms":Ke}))?.app_metadata?.strategy;if(s&&Ph[s])return Ph[s];const c=t.connections.map(d=>Ph[d.strategy]).filter(d=>d!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":i==="sms"?"sms":"email"}const J_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?A("div",{className:"inline-flex h-9 items-center",children:A("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):A(Wa,{})},I6=e=>A("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&A("div",{className:"text-xs text-gray-300",children:[M.t("agree_to")," ",A("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:M.t("terms")})]})});var Nh={exports:{}};var X1;function hM(){return X1||(X1=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var o="",s=0;s<arguments.length;s++){var c=arguments[s];c&&(o=r(o,i(c)))}return o}function i(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return n.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var s="";for(var c in o)t.call(o,c)&&o[c]&&(s=r(s,c));return s}function r(o,s){return s?o?o+" "+s:o+s:o}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(Nh)),Nh.exports}var gM=hM();const nt=Ty(gM),mM=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",ut=({name:e,size:t,className:n=""})=>{const i=mM(t);return A("span",{className:nt(`uicon-${e}`,n,i)})};function $6(e){const t=e.replace("#",""),n=parseInt(t,16);return[n>>16&255,n>>8&255,n&255]}function yM(e,t,n){return`#${(e<<16|t<<8|n).toString(16).padStart(6,"0")}`}const _M=(e,t)=>{const[n,i,r]=$6(e);return yM(Math.min(255,Math.round(n+(255-n)*t)),Math.min(255,Math.round(i+(255-i)*t)),Math.min(255,Math.round(r+(255-r)*t)))};function e2(e){const[t,n,i]=$6(e).map(r=>{const o=r/255;return o<=.04045?o/12.92:Math.pow((o+.055)/1.055,2.4)});return .2126*t+.7152*n+.0722*i}function q0(e,t){const n=e2(e),i=e2(t),r=Math.max(n,i),o=Math.min(n,i);return(r+.05)/(o+.05)}function t2(e,t="light"){const n=q0(e,"#ffffff"),i=q0(e,"#000000"),r=1.35;return t==="light"?i>n*r?"#000000":"#ffffff":i*r>n?"#000000":"#ffffff"}const Ja="mo784psi",wM=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",i=e?.colors?.base_hover_color||_M(n,.2),r=e?.colors?.primary_button_label,o=r&&q0(r,n)>=4.5,s=o?r:t2(n,"light"),c=o?r:t2(n,"dark"),l=s!==c?`
86
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function fL(e,t){if(e){if(typeof e=="string")return U1(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U1(e,t):void 0}}function U1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,i=Array(t);n<t;n++)i[n]=e[n];return i}function hL(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var i,r,o,s,c=[],l=!0,d=!1;try{if(o=(n=n.call(e)).next,t!==0)for(;!(l=(i=o.call(n)).done)&&(c.push(i.value),c.length!==t);l=!0);}catch(u){d=!0,r=u}finally{try{if(!l&&n.return!=null&&(s=n.return(),Object(s)!==s))return}finally{if(d)throw r}}return c}}function gL(e){if(Array.isArray(e))return e}function mL(e){var t=Array.prototype.slice.call(e),n=uL(t,4),i=n[0],r=n[1],o=n[2],s=n[3],c,l,d;if(typeof i=="string")c=i;else throw new TypeError("A text for parsing must be a string.");if(!r||typeof r=="string")s?(l=o,d=s):(l=void 0,d=o),r&&(l=sL({defaultCountry:r},l));else if(ka(r))o?(l=r,d=o):d=r;else throw new Error("Invalid second argument: ".concat(r));return{text:c,options:l,metadata:d}}function il(e){"@babel/helpers - typeof";return il=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},il(e)}function F1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),n.push.apply(n,i)}return n}function q1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?F1(Object(n),!0).forEach(function(i){yL(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):F1(Object(n)).forEach(function(i){Object.defineProperty(e,i,Object.getOwnPropertyDescriptor(n,i))})}return e}function yL(e,t,n){return(t=_L(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _L(e){var t=wL(e,"string");return il(t)=="symbol"?t:t+""}function wL(e,t){if(il(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var i=n.call(e,t);if(il(i)!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vL(e,t,n){t&&t.defaultCountry&&!r6(t.defaultCountry,n)&&(t=q1(q1({},t),{},{defaultCountry:void 0}));try{return aL(e,t,n)}catch(i){if(!(i instanceof Ci))throw i}}function bL(){var e=mL(arguments),t=e.text,n=e.options,i=e.metadata;return vL(t,n,i)}function q_(){return n6(bL,arguments)}function AL(){return n6(r6,arguments)}function $r(e,t="US"){const n=e.trim();if(n.includes("@")){const i=n.toLowerCase(),r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i);return{connectionType:"email",normalized:r?i:null,isValid:r,provider:"email"}}else if(/^\+?\d[\d\s\-().]*$/.test(n)){const i=q_(n,{defaultCountry:t});return i&&i.isValid()?{connectionType:"sms",normalized:i.number,isValid:!0,provider:"sms"}:{connectionType:"sms",normalized:null,isValid:!1,provider:"sms"}}else return{connectionType:"username",normalized:n,isValid:!0,provider:Ke}}function H_(e){let t=e.trim();t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const n=t.indexOf("%");return n!==-1&&(t=t.slice(0,n)),t}function kL(e){const n=H_(e).split(".");return n.length!==4?!1:n.every(i=>/^\d+$/.test(i)&&Number(i)>=0&&Number(i)<=255)}function SL(e){const t=H_(e);if(t.length<2||t.indexOf(":")===-1||!/^[0-9a-fA-F:.]+$/.test(t))return!1;const n=t.split(":");return t.includes("::")?n.length<=8:n.length===8}function xL(e){let t=e.trim();const n=/^\[([^\]]+)\](?::\d+)?$/,i=t.match(n);if(i&&i[1])return i[1];const r=t.lastIndexOf(":");if(r!==-1){const o=t.slice(0,r),s=t.slice(r+1);/^[0-9.]+$/.test(o)&&/^\d+$/.test(s)&&(t=o)}return t}function H1(e){if(!e)return null;const t=H_(xL(e));return kL(t)?{family:4,normalized:t}:SL(t)?{family:6,normalized:t.toLowerCase()}:null}function K1(e){if(e.includes("::")){let[t,n]=e.split("::"),i=t?t.split(":").filter(Boolean):[],r=n?n.split(":").filter(Boolean):[],o=8-(i.length+r.length);return[...i.map(s=>s.toLowerCase()||"0"),...Array(o).fill("0"),...r.map(s=>s.toLowerCase()||"0")]}else return e.split(":").map(t=>t.toLowerCase()||"0")}function EL(e,t,n=!0){const i=H1(e),r=H1(t);if(!i||!r||i.family!==r.family)return!1;if(i.family===4)return i.normalized===r.normalized;const o=K1(i.normalized),s=K1(r.normalized);return n?o.length===8&&s.length===8&&o.join(":")===s.join(":"):o.slice(0,4).join(":")===s.slice(0,4).join(":")}class rn extends Error{location;status;constructor(t,n=302){super(`Redirect to ${t}`),this.name=rn.name,this.location=t,this.status=n}}const CL=a.z.object({client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),otp:a.z.string(),authParams:Ic.optional(),enforceIpCheck:a.z.boolean().optional().default(!1)});async function p6(e,{client_id:t,username:n,otp:i,authParams:r,enforceIpCheck:o=!1}){const s=e.get("ip"),c=e.get("countryCode"),{connectionType:l,normalized:d}=$r(n,c);if(!d)throw new Y(400,{message:"Invalid username format"});e.set("connection",l);const u=await tt(e.env,t,e.var.tenant_id),{env:p}=e,f=await p.data.codes.get(u.tenant.id,i,"otp");if(!f)throw new Y(400,{message:ge("code_invalid"),userSafe:!0});if(f.expires_at<new Date().toISOString())throw new Y(400,{message:ge("code_expired"),userSafe:!0});if(f.used_at)throw new Y(400,{message:ge("code_used"),userSafe:!0});const h=await p.data.loginSessions.get(u.tenant.id,f.login_id);if(!h||h.authParams.username!==n)throw new Y(400,{message:"Code not found or expired",userSafe:!0});if(o&&h.ip&&s&&!EL(h.ip,s))throw new rn(`${Bt(e.env,e.var.custom_domain)}invalid-session?state=${h.id}`);const g=await Sp(e,{client:u,username:d,provider:l,connection:l,isSocial:!1,ip:e.var.ip});return await p.data.codes.used(u.tenant.id,i),{user:g,client:u,loginSession:h,connectionType:l,authConnection:l,session_id:h.session_id,authParams:{...h.authParams,...r||{}}}}async function Ul(e,t){const n=await p6(e,t);return Je(e,{authParams:n.authParams,client:n.client,user:n.user,loginSession:n.loginSession,authConnection:n.connectionType,authStrategy:{strategy:n.connectionType==="sms"?W.SMS:W.EMAIL,strategy_type:Mt.PASSWORDLESS}})}const V1=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),G1=a.z.union([t6.extend(V1.shape),a.z.object({grant_type:a.z.literal("authorization_code"),client_id:a.z.string(),code:a.z.string(),redirect_uri:a.z.string(),code_verifier:a.z.string().min(43).max(128),organization:a.z.string().optional()}),a.z.object({grant_type:a.z.literal("authorization_code"),code:a.z.string(),redirect_uri:a.z.string().optional(),organization:a.z.string().optional(),...V1.shape}),a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string().optional(),refresh_token:a.z.string(),redirect_uri:a.z.string().optional(),client_secret:a.z.string().optional(),organization:a.z.string().optional()}),a.z.object({grant_type:a.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:a.z.string(),username:a.z.string(),otp:a.z.string(),realm:a.z.enum(["email","sms"])})]);function TL(e){if(!e)return{};const[t,n]=e.split(" ");if(t?.toLowerCase()==="basic"&&n){const[i,r]=atob(n).split(":");return{client_id:i,client_secret:r}}return{}}const IL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:G1},"application/json":{schema:G1}}}},responses:{200:{content:{"application/json":{schema:_y}},description:"Tokens"},302:{description:"Redirect for further user interaction (e.g., MFA, consent).",headers:a.z.object({Location:a.z.string().url()}).openapi({})},400:{description:"Bad Request - The request was malformed or invalid.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},401:{description:"Unauthorized - Client authentication failed.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},403:{description:"Forbidden - User is not a member of the required organization.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}}}}),async e=>{const n=(e.req.header("Content-Type")||"").includes("application/json")?e.req.valid("json"):e.req.valid("form"),i=TL(e.req.header("Authorization")),r={...n,...i};if(!r.client_id)throw new P(400,{message:"client_id is required"});e.set("client_id",r.client_id);let o;switch(n.grant_type){case Rn.AuthorizationCode:o=await lD(e,cD.parse(r));break;case Rn.ClientCredential:o=await sD(e,t6.parse(r));break;case Rn.RefreshToken:o=await uD(e,dD.parse(r));break;case Rn.OTP:o=await p6(e,CL.parse(r));break;default:return e.json({error:"unsupported_grant_type",error_description:"Grant type not implemented"},400)}an(e,o.client.tenant.id);const s=new Headers;o.session_id&&Vu(o.client.tenant.id,o.session_id,e.var.host||"").forEach(p=>{s.append("Set-Cookie",p)});let c=[],l;if(o.authParams.audience)try{let u;if(n.grant_type===Rn.ClientCredential)u=await Jc(e,{grantType:Rn.ClientCredential,tenantId:o.client.tenant.id,clientId:o.client.client_id,audience:o.authParams.audience,requestedScopes:o.authParams.scope?.split(" ")||[],organizationId:o.organization?.id});else{if(!o.user?.user_id)throw new Y(400,{error:"invalid_request",error_description:"User ID is required for user-based grants"});u=await Jc(e,{grantType:n.grant_type,tenantId:o.client.tenant.id,userId:o.user.user_id,clientId:o.client.client_id,audience:o.authParams.audience,requestedScopes:o.authParams.scope?.split(" ")||[],organizationId:o.organization?.id})}o.authParams.scope=u.scopes.join(" "),c=u.permissions,l=o.client.app_type==="spa"?u.token_lifetime_for_web??u.token_lifetime:u.token_lifetime}catch(u){if(u instanceof P)throw u;console.error("Error calculating scopes and permissions:",u)}const d=await Ef(e,{...o,grantType:n.grant_type,permissions:c.length>0?c:void 0,token_lifetime:l});return e.json(d,{headers:s})});async function bs(e,t){const n=await e.env.data.emailProviders.get(e.var.tenant_id);if(!n)throw new P(500,{message:"Email provider not found"});const i=e.env.data.emailService;if(!i)throw new P(500,{message:"Email service not configured"});await i.send({emailProvider:n,...t,from:n.default_from_address||`login@${e.env.ISSUER}`})}async function f6(e,t){if(!e.var.client_id)throw new P(500,{message:"Client not found"});const n=await tt(e.env,e.var.client_id),i=n.connections.find(o=>o.strategy===W.SMS);if(!i)throw new P(500,{message:"SMS provider not found"});const r=e.env.data.smsService;if(!r)throw new P(500,{message:"SMS service not configured"});await r.send({options:i.options,to:t.to,from:t.from,text:t.text,template:"auth-code",data:{code:t.code,tenantName:n.tenant.friendly_name,tenantId:n.tenant.id}})}async function h6(e,t){const n=await e.env.data.tenants.get(e.var.tenant_id);if(!n)throw new P(500,{message:"Tenant not found"});const i=await e.env.data.branding.get(e.var.tenant_id),r=i?.logo_url||"",o=i?.colors?.primary||"#7d68f4",s={vendorName:n.friendly_name,lng:t||"en"};return{tenant:n,logo:r,buttonColor:o,options:s}}async function g6(e,t,n,i,r){const{tenant:o,logo:s,buttonColor:c,options:l}=await h6(e,r),d=`${Bt(e.env)}reset-password?state=${i}&code=${n}`;await bs(e,{to:t,subject:ge("reset_password_title",l),html:`Click here to reset your password: ${Bt(e.env)}reset-password?state=${i}&code=${n}`,template:"auth-password-reset",data:{vendorName:o.friendly_name,logo:s,passwordResetUrl:d,supportUrl:o.support_url||"https://support.sesamy.com",buttonColor:c,passwordResetTitle:ge("password_reset_title",l),resetPasswordEmailClickToReset:ge("reset_password_email_click_to_reset",l),resetPasswordEmailReset:ge("reset_password_email_reset",l),supportInfo:ge("support_info",l),contactUs:ge("contact_us",l),copyright:ge("copyright",l),tenantName:o.friendly_name,tenantId:o.id}}),L(e,o.id,{type:B.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function $L(e,t,n,i){const{tenant:r,logo:o,buttonColor:s,options:c}=await h6(e,i);await bs(e,{to:t,subject:ge("reset_password_title",c),html:`Your password reset code is: ${n}`,template:"auth-code",data:{code:n,vendorName:r.friendly_name,logo:o,supportUrl:r.support_url||"https://support.sesamy.com",buttonColor:s,welcomeToYourAccount:ge("password_reset_title",c),linkEmailClickToLogin:ge("reset_password_email_click_to_reset",c),linkEmailLogin:ge("reset_password_email_reset",c),linkEmailOrEnterCode:ge("link_email_or_enter_code",{...c,code:n}),codeValid30Mins:ge("code_valid_30_minutes",c),supportInfo:ge("support_info",c),contactUs:ge("contact_us",c),copyright:ge("copyright",c)}}),L(e,r.id,{type:B.SUCCESS_CHANGE_PASSWORD_REQUEST,description:t})}async function Fl(e,{to:t,code:n,language:i}){const r=await e.env.data.tenants.get(e.var.tenant_id);if(!r)throw new P(500,{message:"Tenant not found"});const{connectionType:o}=$r(t),s=await e.env.data.branding.get(e.var.tenant_id),c=s?.logo_url||"",l=s?.colors?.primary||"#7d68f4",d=new URL(Bt(e.env)),u={vendorName:r.friendly_name,vendorId:r.id,loginDomain:d.hostname,code:n,lng:i||"en"};o==="email"?await bs(e,{to:t,subject:ge("code_email_subject",u),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:r.friendly_name,logo:c,supportUrl:r.support_url||"",buttonColor:l,welcomeToYourAccount:ge("welcome_to_your_account",u),linkEmailClickToLogin:ge("link_email_click_to_login",u),linkEmailLogin:ge("link_email_login",u),linkEmailOrEnterCode:ge("link_email_or_enter_code",u),codeValid30Mins:ge("code_valid_30_minutes",u),supportInfo:ge("support_info",u),contactUs:ge("contact_us",u),copyright:ge("copyright",u)}}):o==="sms"&&await f6(e,{to:t,text:ge("sms_code_text",u),code:n,from:r.friendly_name}),L(e,r.id,{type:B.CODE_LINK_SENT,description:t})}async function ql(e,{to:t,code:n,authParams:i,language:r}){const o=await e.env.data.tenants.get(e.var.tenant_id);if(!o)throw new P(500,{message:"Tenant not found"});if(!i.redirect_uri)throw new P(400,{message:"redirect_uri is required"});const{connectionType:s}=$r(t),c=await e.env.data.branding.get(e.var.tenant_id),l=c?.logo_url||"",d=c?.colors?.primary||"",u=new URL(Ze(e.env));u.pathname="passwordless/verify_redirect",u.searchParams.set("verification_code",n),u.searchParams.set("connection",s),u.searchParams.set("client_id",i.client_id),u.searchParams.set("redirect_uri",i.redirect_uri),u.searchParams.set("email",t),i.response_type&&u.searchParams.set("response_type",i.response_type),i.scope&&u.searchParams.set("scope",i.scope),i.state&&u.searchParams.set("state",i.state),i.nonce&&u.searchParams.set("nonce",i.nonce),i.code_challenge&&u.searchParams.set("code_challenge",i.code_challenge),i.code_challenge_method&&u.searchParams.set("code_challenge_method",i.code_challenge_method),i.audience&&u.searchParams.set("audience",i.audience);const p={vendorName:o.friendly_name,code:n,lng:r||"en"};if(s==="email")await bs(e,{to:t,subject:ge("code_email_subject",p),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:o.friendly_name,logo:l,supportUrl:o.support_url||"",magicLink:u.toString(),buttonColor:d,welcomeToYourAccount:ge("welcome_to_your_account",p),linkEmailClickToLogin:ge("link_email_click_to_login",p),linkEmailLogin:ge("link_email_login",p),linkEmailOrEnterCode:ge("link_email_or_enter_code",p),codeValid30Mins:ge("code_valid_30_minutes",p),supportInfo:ge("support_info",p),contactUs:ge("contact_us",p),copyright:ge("copyright",p)}});else if(s==="sms")await f6(e,{to:t,text:`${ge("link_sms_login",p)}: ${u.toString()}`,code:n,from:o.friendly_name});else throw new P(400,{message:"Only email and SMS connections are supported for magic links"});L(e,o.id,{type:B.CODE_LINK_SENT,description:t})}async function jf(e,t,n){const i=await e.env.data.tenants.get(e.var.tenant_id);if(!i)throw new P(500,{message:"Tenant not found"});if(!t.email)throw new P(400,{message:"User has no email"});const r=await e.env.data.branding.get(e.var.tenant_id),o=r?.logo_url||"",s=r?.colors?.primary||"#7d68f4",c={vendorName:i.friendly_name,lng:n||"en"};await bs(e,{to:t.email,subject:ge("welcome_to_your_account",c),html:`Click here to validate your email: ${Bt(e.env)}validate-email`,template:"auth-verify-email",data:{vendorName:i.friendly_name,logo:o,emailValidationUrl:`${Bt(e.env)}validate-email`,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:s,welcomeToYourAccount:ge("welcome_to_your_account",c),verifyEmailVerify:ge("verify_email_verify",c),supportInfo:ge("support_info",c),contactUs:ge("contact_us",c),copyright:ge("copyright",c)}})}async function zL(e,t,n,i,r){const o=await e.env.data.tenants.get(e.var.tenant_id);if(!o)throw new P(500,{message:"Tenant not found"});const s=await e.env.data.branding.get(e.var.tenant_id),c=s?.logo_url||"",l=s?.colors?.primary||"#7d68f4",d={vendorName:o.friendly_name,lng:"en"},u=`${Bt(e.env)}signup?state=${i}&code=${n}`;await bs(e,{to:t,subject:ge("register_password_account",d),html:`Click here to register: ${u}`,template:"auth-pre-signup-verification",data:{vendorName:o.friendly_name,logo:c,signupUrl:u,setPassword:ge("set_password",d),registerPasswordAccount:ge("register_password_account",d),clickToSignUpDescription:ge("click_to_sign_up_description",d),supportUrl:o.support_url||"https://support.sesamy.com",buttonColor:l,welcomeToYourAccount:ge("welcome_to_your_account",d),verifyEmailVerify:ge("verify_email_verify",d),supportInfo:ge("support_info",d),contactUs:ge("contact_us",d),copyright:ge("copyright",d)}})}const PL=new a.OpenAPIHono().openapi(a.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.literal(W.USERNAME_PASSWORD),email:a.z.string().transform(e=>e.toLowerCase()),password:a.z.string()})}}}},responses:{200:{content:{"application/json":{schema:a.z.object({_id:a.z.string(),email:a.z.string().optional(),email_verified:a.z.boolean(),app_metadata:a.z.object({}),user_metadata:a.z.object({})})}},description:"Created user"}}}),async e=>{const{email:t,password:n,client_id:i}=e.req.valid("json"),r=await tt(e.env,i);e.set("client_id",r.client_id),an(e,r.tenant.id);const s=r.connections.find(f=>f.strategy===W.USERNAME_PASSWORD)?.name||W.USERNAME_PASSWORD,c=await hl(e.env.data,r.tenant.id,s);try{await fl(c,{tenantId:r.tenant.id,userId:"",newPassword:n,data:e.env.data})}catch(f){throw new P(400,{message:f?.message||"Password does not meet the requirements"})}if(await wn({userAdapter:e.env.data.users,tenant_id:r.tenant.id,username:t,provider:Ke}))throw new P(400,{message:"Invalid sign up"});const{hash:d,algorithm:u}=await jc(n),p=await e.env.data.users.create(r.tenant.id,{user_id:`${Ke}|${$o()}`,email:t,email_verified:!1,provider:Ke,connection:W.USERNAME_PASSWORD,is_social:!1,password:{hash:d,algorithm:u}});e.set("user_id",p.user_id),e.set("username",p.email),e.set("connection",p.connection);try{await jf(e,p)}catch(f){console.error("Failed to send verification email:",f)}return L(e,r.tenant.id,{type:B.SUCCESS_SIGNUP,description:"Successful signup"}),e.json({_id:p.user_id,email:p.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(a.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.literal(W.USERNAME_PASSWORD),email:a.z.string().transform(e=>e.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async e=>{const{email:t,client_id:n}=e.req.valid("json"),i=await tt(e.env,n);if(e.set("client_id",i.client_id),an(e,i.tenant.id),!await Sr({userAdapter:e.env.data.users,tenant_id:i.tenant.id,username:t,provider:Ke}))return e.html("If an account with that email exists, we've sent instructions to reset your password.");const o={client_id:n,username:t},s=await e.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:o,csrf_token:Ve(),ip:e.get("ip"),useragent:e.get("useragent"),auth0Client:Li(e.get("auth0_client"))});return await g6(e,t,s.id,s.authParams.state),e.html("If an account with that email exists, we've sent instructions to reset your password.")});function sn(){const e=new Uint8Array(6);crypto.getRandomValues(e);let t="";for(let n=0;n<6;n+=1)t+=(e[n]%10).toString();return t}const NL=new a.OpenAPIHono().openapi(a.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:a.z.union([a.z.object({connection:a.z.literal("email"),client_id:a.z.string(),email:a.z.string().transform(e=>e.toLowerCase()),send:a.z.enum(["link","code"]),authParams:Ic.omit({client_id:!0})}),a.z.object({client_id:a.z.string(),connection:a.z.literal("sms"),phone_number:a.z.string(),send:a.z.enum(["link","code"]),authParams:Ic.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async e=>{const t=e.req.valid("json"),{env:n}=e,{client_id:i,send:r,authParams:o,connection:s}=t,c=await tt(e.env,i);e.set("client_id",c.client_id),an(e,c.tenant.id);const l=s==="email"?t.email:t.phone_number,d=e.get("ip"),u=e.get("useragent"),p=e.get("auth0_client"),f=Li(p),h=await n.data.loginSessions.create(c.tenant.id,{authParams:{...o,client_id:i,username:l},expires_at:new Date(Date.now()+ba).toISOString(),csrf_token:Ve(),ip:d,useragent:u,auth0Client:f}),g=await n.data.codes.create(c.tenant.id,{code_id:sn(),code_type:"otp",login_id:h.id,expires_at:new Date(Date.now()+ba).toISOString(),redirect_uri:o.redirect_uri}),m=o?.ui_locales?.split(" ")?.map(_=>_.split("-")[0])[0];return r==="link"?await ql(e,{to:l,code:g.code_id,authParams:{...o,client_id:i},language:m}):await Fl(e,{to:l,code:g.code_id,language:m}),e.html("OK")}).openapi(a.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:a.z.object({scope:a.z.string(),response_type:a.z.nativeEnum(St),redirect_uri:a.z.string(),state:a.z.string(),nonce:a.z.string().optional(),verification_code:a.z.string(),connection:a.z.string(),client_id:a.z.string(),email:a.z.string().transform(e=>e.toLowerCase()),audience:a.z.string().optional()})},responses:{302:{description:"Successful verification, redirecting to continue flow.",headers:a.z.object({Location:a.z.string().url()}).openapi({})},400:{description:"Bad Request (e.g., invalid client, invalid code, missing parameters).",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}},500:{description:"Internal Server Error.",content:{"application/json":{schema:a.z.object({error:a.z.string(),error_description:a.z.string().optional()})}}}}}),async e=>{const{env:t}=e,{client_id:n,email:i,verification_code:r,redirect_uri:o,state:s,scope:c,audience:l,response_type:d,nonce:u}=e.req.valid("query"),p=await tt(t,n);e.set("client_id",p.client_id),an(e,p.tenant.id),e.set("connection","email");const f={client_id:n,redirect_uri:o,state:s,nonce:u,scope:c,audience:l,response_type:d};let h="Something went wrong. Please try again later.";try{const v=await Ul(e,{client_id:n,username:i,otp:r,authParams:f,enforceIpCheck:!0});if(v instanceof Response)return v;if(v&&typeof v=="object"&&"access_token"in v)return e.json(v)}catch(v){const k=v;"message"in k&&typeof k.message=="string"&&(h=k.message)}const g=e.get("ip"),m=e.get("useragent"),_=e.get("auth0_client"),y=Li(_),w=await t.data.loginSessions.create(p.tenant.id,{authParams:{...f,username:i},expires_at:new Date(Date.now()+ba).toISOString(),csrf_token:Ve(),ip:g,useragent:m,auth0Client:y});return e.redirect(`${Bt(e.env,e.var.custom_domain)}invalid-session?state=${w.id}&error=${encodeURIComponent(h)}`,302)});class aa extends P{_code;constructor(t,n){super(t,n),this._code=n?.code}get code(){return this._code}}async function jL(e,t,n){const i=n.app_metadata||{},r=i.failed_logins||[],o=Date.now(),s=[...r.filter(c=>o-c<1e3*60*5),o];i.failed_logins=s,await e.users.update(t,n.user_id,{app_metadata:i})}function OL(e){const n=(e.app_metadata||{}).failed_logins||[],i=Date.now();return n.filter(r=>i-r<1e3*60*5)}async function m6(e,t,n,i){const{data:r}=e.env,{username:o}=n;if(e.set("username",o),!o)throw new Y(400,{message:"Username is required"});const s=await Sr({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:o,provider:Ke});if(!s)throw L(e,t.tenant.id,{type:B.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"}),new aa(403,{message:"User not found",code:"USER_NOT_FOUND"});const c=s.linked_to?await r.users.get(t.tenant.id,s.linked_to):s;if(!c)throw new aa(403,{message:"User not found",code:"USER_NOT_FOUND"});if(e.set("connection",s.connection),e.set("user_id",c.user_id),OL(c).length>=3)throw L(e,t.tenant.id,{type:B.FAILED_LOGIN,description:"Too many failed login attempts"}),new aa(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"});const d=await r.passwords.get(t.tenant.id,s.user_id);if(!(d&&await ts.compare(n.password,d.password)))throw L(e,t.tenant.id,{type:B.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"}),jL(r,t.tenant.id,c),new aa(403,{message:"Invalid password",code:"INVALID_PASSWORD"});if(!s.email_verified&&t.client_metadata?.email_validation==="enforced"){const f=i?.authParams?.ui_locales?.split(" ")?.map(h=>h.split("-")[0])[0];throw await jf(e,s,f),L(e,t.tenant.id,{type:B.FAILED_LOGIN,description:"Email not verified"}),i&&await q7(e,t.tenant.id,i,"Email not verified"),new aa(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const p=c.app_metadata||{};return p.failed_logins&&p.failed_logins.length>0&&(p.failed_logins=[],r.users.update(t.tenant.id,c.user_id,{app_metadata:p})),{client:t,authParams:n,user:c,loginSession:i}}async function Hl(e,t,n,i,r){const o=await m6(e,t,n,i);return Je(e,{...o,ticketAuth:r,authConnection:e.get("connection")||W.USERNAME_PASSWORD,authStrategy:{strategy:W.USERNAME_PASSWORD,strategy_type:Mt.DATABASE}})}async function K_(e,t,n,i,r){await Sp(e,{client:t,username:n,provider:Ke,connection:W.USERNAME_PASSWORD,isSocial:!1,ip:e.var.ip});let o=sn(),s=await e.env.data.codes.get(t.tenant.id,o,"password_reset");for(;s;)o=sn(),s=await e.env.data.codes.get(t.tenant.id,o,"password_reset");let c=i;if(!await e.env.data.loginSessions.get(t.tenant.id,i)){const u=e.get("ip"),p=e.get("useragent"),f=e.get("auth0_client"),h=Li(f);c=(await e.env.data.loginSessions.create(t.tenant.id,{expires_at:new Date(Date.now()+Rj).toISOString(),authParams:{client_id:t.client_id,username:n},csrf_token:Ve(),ip:u,useragent:p,auth0Client:h})).id}const d=await e.env.data.codes.create(t.tenant.id,{code_id:o,code_type:"password_reset",login_id:c,expires_at:new Date(Date.now()+Oj).toISOString()});r==="code"?await $L(e,n,d.code_id):await g6(e,n,d.code_id,c)}const RL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.union([a.z.object({credential_type:a.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:a.z.string(),client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),realm:a.z.enum([W.EMAIL]),scope:a.z.string().optional()}),a.z.object({credential_type:a.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:a.z.string(),username:a.z.string().transform(e=>e.toLowerCase()),password:a.z.string(),realm:a.z.enum([W.USERNAME_PASSWORD]),scope:a.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async e=>{const t=e.req.valid("json"),{client_id:n,username:i}=t;e.set("username",i);const r=await tt(e.env,n);e.set("client_id",n),an(e,r.tenant.id);const o=i.toLocaleLowerCase(),s=e.get("ip"),c=e.get("useragent"),l=e.get("auth0_client");let d;if("otp"in t)d=await Ul(e,{client_id:n,username:o,otp:t.otp});else if("password"in t){const u=await e.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:{client_id:n,username:o},csrf_token:Ve(),ip:s,useragent:c,auth0Client:Li(l)});d=await Hl(e,r,{username:o,password:t.password,client_id:n},u,!0)}else throw new P(400,{message:"Code or password required"});return d});function y6(e,t){if(!e||t.length===0)return!1;const n=Ih(e)?.host??null;if(!n)return!1;for(const i of t){let r;if(i.startsWith("http://")||i.startsWith("https://")?r=Ih(i)?.host??null:r=Ih("https://"+i)?.host??null,n===r)return!0}return!1}function Ih(e){try{return new URL(e)}catch{return null}}function DL(e,t){if(!e||t===void 0)return!1;const n=new Date(e.authenticated_at).getTime(),i=t*1e3;return Date.now()-n>i}async function BL({ctx:e,session:t,client:n,authParams:i,connection:r,login_hint:o,screen_hint:s}){const c=new URL(e.req.url);e.var.custom_domain&&(c.hostname=e.var.custom_domain);const{ip:l,auth0_client:d,useragent:u}=e.var,p=Li(d);DL(t,i.max_age)&&(t=void 0);const f=await e.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:i,csrf_token:Ve(),authorization_url:c.toString(),ip:l,useragent:u,auth0Client:p}),h=n.client_metadata?.universal_login_version==="2"?"/u2":"/u";if(t&&o&&s!=="login"){const g=await e.env.data.users.get(n.tenant.id,t.user_id);if(g?.email===o)return Je(e,{client:n,loginSession:f,authParams:i,user:g,existingSessionIdToLink:t.id})}if(r===W.EMAIL&&o){const g=sn();return await e.env.data.codes.create(n.tenant.id,{code_id:g,code_type:"otp",login_id:f.id,expires_at:new Date(Date.now()+yr*1e3).toISOString(),redirect_uri:i.redirect_uri}),await ql(e,{code:g,to:o,authParams:i}),e.redirect(`${h}/login/email-otp-challenge?state=${f.id}`)}if(t&&s!=="login")return e.redirect(`${h}/check-account?state=${f.id}`);if(h==="/u2"){const g=await e.env.data.promptSettings.get(n.tenant.id),m=to.parse(g||{}),_=n.connections.some(y=>y.strategy===W.USERNAME_PASSWORD);if(m.identifier_first===!1&&_)return e.redirect(`${h}/login?state=${f.id}`)}return e.redirect(`${h}/login/identifier?state=${f.id}`)}function LL(e){if(e===W.USERNAME_PASSWORD)return Ke;if(e===W.EMAIL)return W.EMAIL;throw new Y(403,{message:"Invalid realm"})}async function ML(e,t,n,i,r){const{env:o}=e;e.set("connection",r);const s=await o.data.codes.get(t,n,"ticket");if(!s||s.used_at)throw new Y(403,{message:"Ticket not found"});const c=await o.data.loginSessions.get(t,s.login_id);if(!c||!c.authParams.username)throw new Y(403,{message:"Session not found"});const l=await tt(o,c.authParams.client_id,t);e.set("client_id",c.authParams.client_id),await o.data.codes.used(t,n);const d=LL(r),p=l.connections.find(g=>g.name===r)?.strategy||(d===Ke?W.USERNAME_PASSWORD:W.EMAIL),f=p===W.USERNAME_PASSWORD?Mt.DATABASE:Mt.PASSWORDLESS;let h=await Sp(e,{username:c.authParams.username,provider:d,client:l,connection:r,isSocial:!1,ip:e.var.ip});return e.set("username",h.email||h.phone_number),e.set("user_id",h.user_id),Je(e,{authParams:{scope:c.authParams?.scope,...i},loginSession:c,user:h,client:l,authConnection:r,authStrategy:{strategy:p,strategy_type:f}})}async function UL({ctx:e,client:t,session:n,redirect_uri:i,state:r,nonce:o,code_challenge_method:s,code_challenge:c,audience:l,scope:d,response_type:u,response_mode:p,organization:f,max_age:h}){const{env:g}=e,m=new URL(i),_=`${m.protocol}//${m.host}`,y=p===hn.WEB_MESSAGE;async function w(q="Login required"){const xe=new Headers;if(n&&(L(e,t.tenant.id,{type:B.FAILED_SILENT_AUTH,description:q}),uC(t.tenant.id,e.var.host).forEach(un=>{xe.append("set-cookie",un)})),y)return x0(e,_,JSON.stringify({error:"login_required",error_description:q,state:r}),xe);const me=new URL(i);if(u===St.TOKEN||u===St.TOKEN_ID_TOKEN){const Qe=new URLSearchParams;Qe.set("error","login_required"),Qe.set("error_description",q),r&&Qe.set("state",r),me.hash=Qe.toString()}else me.searchParams.set("error","login_required"),me.searchParams.set("error_description",q),r&&me.searchParams.set("state",r);const je={Location:me.toString()},et=xe.get("set-cookie");return et&&(je["set-cookie"]=et),new Response(null,{status:302,headers:je})}const v=!n||n?.expires_at&&new Date(n.expires_at)<new Date||n?.idle_expires_at&&new Date(n.idle_expires_at)<new Date,k=n&&h!==void 0&&Date.now()-new Date(n.authenticated_at).getTime()>h*1e3;if(v||k)return w();const b=await g.data.users.get(t.tenant.id,n.user_id);if(!b)return console.error("User not found",n.user_id),w("User not found");const S=b.linked_to?await g.data.users.get(t.tenant.id,b.linked_to):b;if(!S)return console.error("Linked primary user not found",b.linked_to),w("User not found");e.set("user_id",S.user_id),e.set("username",S.email),e.set("connection",S.connection);let E;if(f&&(E=await g.data.organizations.get(t.tenant.id,f),!E))return w("Organization not found");const z=l||t.tenant.audience;let T=d||"",N=[],I;if(z)try{const q=await Jc(e,{tenantId:t.tenant.id,clientId:t.client_id,audience:z,requestedScopes:d?.split(" ")||[],organizationId:E?.id,userId:S.user_id});T=q.scopes.join(" "),N=q.permissions,I=t.app_type==="spa"&&q.token_lifetime_for_web?q.token_lifetime_for_web:q.token_lifetime}catch(q){if(q?.statusCode===403||q?.status===403){const xe=q?.body?.error_description||q?.message||"Access denied";return w(xe)}throw q}else if(E&&!(await g.data.userOrganizations.list(t.tenant.id,{q:`user_id:${S.user_id}`,per_page:1e3})).userOrganizations.some(me=>me.organization_id===E.id))return w("User is not a member of the specified organization");const $=await g.data.loginSessions.create(t.tenant.id,{csrf_token:Ve(),authParams:{client_id:t.client_id,audience:l,scope:d,state:r,nonce:o,response_type:u,redirect_uri:i,organization:f,max_age:h},expires_at:new Date(Date.now()+300*1e3).toISOString(),session_id:n.id,ip:e.var.ip,useragent:e.var.useragent}),j=h!==void 0?Math.floor(new Date(n.authenticated_at).getTime()/1e3):void 0,R={client:t,authParams:{client_id:t.client_id,audience:l,code_challenge_method:s,code_challenge:c,scope:T,state:r,nonce:o,response_type:u,redirect_uri:i,max_age:h},user:S,session_id:n.id,auth_time:j,permissions:N,organization:E,token_lifetime:I},D=u===St.CODE?await KC(e,{user:S,client:t,authParams:R.authParams,login_id:$.id}):await Ef(e,R),H=t.tenant.idle_session_lifetime?new Date(Date.now()+t.tenant.idle_session_lifetime*60*60*1e3).toISOString():void 0;await g.data.sessions.update(t.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),login_session_id:$.id,device:{...n.device,last_ip:e.var.ip||"",last_user_agent:e.var.useragent||""},idle_expires_at:H}),H&&await g.data.loginSessions.update(t.tenant.id,$.id,{expires_at:H}),L(e,t.tenant.id,{type:B.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});const Q=new Headers;if(Vu(t.tenant.id,n.id,e.var.host).forEach(q=>{Q.append("set-cookie",q)}),y)return x0(e,_,JSON.stringify({...D,state:r}),Q);const ne=new URL(i);if(u===St.TOKEN||u===St.TOKEN_ID_TOKEN){const q=new URLSearchParams;Object.entries(D).forEach(([xe,me])=>{me!==void 0&&q.set(xe,String(me))}),r&&q.set("state",r),ne.hash=q.toString()}else Object.entries(D).forEach(([q,xe])=>{xe!==void 0&&ne.searchParams.set(q,String(xe))}),r&&ne.searchParams.set("state",r);const _e={Location:ne.toString()},Ie=Q.get("set-cookie");return Ie&&(_e["set-cookie"]=Ie),new Response(null,{status:302,headers:_e})}const FL=1024;function qL(e,t){const n=e.split(":")[0]?.split(".")??[],i=t.split(":")[0]?.split(".")??[];if(n.length<2||i.length<2)return!1;const r=n.slice(-2).join("."),o=i.slice(-2).join(".");return r===o}async function HL(e,t,n){return await e.env.data.customDomains.getByDomain(t)?!0:qL(t,n)}async function KL(e,t){const n=await e.env.data.loginSessions.get(e.var.tenant_id||"",t);if(!n)throw new Y(403,{message:"State not found"});const i=n.authorization_url;if(i&&i.length<=FL){let c=null;try{c=new URL(i)}catch{c=null}const l=e.var.host||"";if(c&&c.host&&c.host!==l&&await HL(e,c.host,l)){const u=new URL("/authorize/resume",c.origin);return u.searchParams.set("state",t),new Response(null,{status:302,headers:{location:u.toString()}})}}const r=await tt(e.env,n.authParams.client_id);an(e,r.tenant.id),e.set("client_id",r.client_id);const o=n.state||be.PENDING;if(o===be.PENDING)throw new Y(400,{error:"invalid_request",error_description:"Login session is not yet authenticated"});if(o===be.COMPLETED)throw new Y(409,{error:"invalid_request",error_description:"Login session has already been completed"});if(o===be.FAILED)throw new Y(400,{error:"access_denied",error_description:`Login session failed: ${n.failure_reason||"unknown reason"}`});if(o===be.EXPIRED)throw new Y(400,{error:"invalid_request",error_description:"Login session has expired"});if(!n.user_id)throw new Y(500,{message:"Authenticated login session has no user_id"});const s=await e.env.data.users.get(r.tenant.id,n.user_id);if(!s)throw new Y(500,{message:"Authenticated user not found"});return e.set("user_id",s.user_id),n.auth_connection&&e.set("connection",n.auth_connection),Je(e,{authParams:n.authParams,client:r,user:s,loginSession:n,authStrategy:n.auth_strategy,authConnection:n.auth_connection})}const VL=[W.EMAIL,W.SMS,W.USERNAME_PASSWORD],W1=a.z.object({client_id:a.z.string().optional(),vendor_id:a.z.string().optional(),redirect_uri:a.z.string().optional(),scope:a.z.string().optional(),state:a.z.string().optional(),prompt:a.z.string().optional(),response_mode:a.z.nativeEnum(hn).optional(),response_type:a.z.nativeEnum(St).optional(),audience:a.z.string().optional(),connection:a.z.string().optional(),nonce:a.z.string().optional(),max_age:a.z.string().optional(),acr_values:a.z.string().optional(),login_ticket:a.z.string().optional(),code_challenge_method:a.z.nativeEnum(vp).optional(),code_challenge:a.z.string().optional(),realm:a.z.string().optional(),auth0Client:a.z.string().optional(),organization:a.z.string().optional(),login_hint:a.z.string().optional(),screen_hint:a.z.string().optional(),ui_locales:a.z.string().optional()});function GL(e){try{const t=e.split(".");if(t.length<2||!t[1])return null;const n=new TextDecoder().decode(lr.decode(t[1],{strict:!1})),i=JSON.parse(n);return typeof i!="object"||i===null?null:i}catch{return null}}const WL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:W1.extend({client_id:a.z.string(),screen_hint:a.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),request:a.z.string().openapi({description:"JWT containing authorization request parameters (OpenID Connect Core Section 6.1)"}).optional()}).passthrough()},responses:{200:{description:"Successful authorization response. This can be an HTML page (e.g., for silent authentication iframe or universal login page) or a JSON object containing tokens (e.g., for response_mode=web_message).",content:{"text/html":{schema:a.z.string().openapi({example:"<html>...</html>"})},"application/json":{schema:_y}}},302:{description:"Redirect to the client's redirect URI, an authentication page, or an external identity provider.",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},403:{description:"Forbidden. The request is not allowed (e.g., invalid origin).",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{env:t}=e,n=e.req.valid("query");let i={};if(n.request){const H=GL(n.request);if(H){const Q=W1.safeParse(H);Q.success&&(i=Q.data)}}const{client_id:r,vendor_id:o,redirect_uri:s,scope:c,state:l,audience:d,nonce:u,connection:p,response_type:f,response_mode:h,code_challenge:g,code_challenge_method:m,prompt:_,max_age:y,acr_values:w,login_ticket:v,realm:k,login_hint:b,ui_locales:S,organization:E,screen_hint:z}={...i,...n};e.set("log","authorize");const T=await tt(t,r);e.set("client_id",T.client_id),an(e,T.tenant.id);let N=s;typeof s=="string"&&(N=s.split("#")[0]);const I=e.req.header("origin");if(I&&!y6(I,T.web_origins||[]))throw new P(403,{message:`Origin ${I} not allowed`});if(!f){if(N){const H=new URL(N);return H.searchParams.set("error","invalid_request"),H.searchParams.set("error_description","Missing required parameter: response_type"),l&&H.searchParams.set("state",l),e.redirect(H.toString())}throw new P(400,{message:"Missing required parameter: response_type"})}const $={redirect_uri:N,scope:c,state:l,client_id:r,vendor_id:o,audience:d,nonce:u,prompt:_,response_type:f,response_mode:h,code_challenge:g,code_challenge_method:m,username:b,ui_locales:S,organization:E,max_age:y?parseInt(y,10):void 0,acr_values:w};if($.redirect_uri){const H=T.callbacks||[];if(e.var.host&&(H.push(`${Er(e.env,e.var.custom_domain)}/*`),H.push(`${Bt(e.env,e.var.custom_domain)}/*`)),!R_($.redirect_uri,H,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new P(400,{message:`Invalid redirect URI - ${$.redirect_uri}`})}let j;const R=Bj(T.tenant.id,e.req.header("cookie"));for(const H of R){const Q=await t.data.sessions.get(T.tenant.id,H);if(Q&&!Q.revoked_at){j=Q;break}}if(T.sso_disabled&&(j=void 0),_=="none"){if(!N||!l||!f)throw new P(400,{message:"Missing required parameters for silent auth: redirect_uri, state, and response_type"});return UL({ctx:e,session:j||void 0,redirect_uri:N,state:l,response_type:f,response_mode:h,client:T,nonce:u,code_challenge_method:m,code_challenge:g,audience:d,scope:c,organization:E,max_age:y?parseInt(y,10):void 0})}if(T.connections.length===1&&T.connections[0]&&!VL.includes(T.connections[0].strategy||""))return w1(e,T,T.connections[0].name,$);if(p&&p!==W.EMAIL)return w1(e,T,p,$);if(v){const H=await ML(e,T.tenant.id,v,$,k);return H instanceof Response?H:e.json(H)}const D=await BL({ctx:e,client:T,authParams:$,session:j||void 0,connection:p,login_hint:b,screen_hint:z});return D instanceof Response?D:e.json(D)}).openapi(a.createRoute({tags:["oauth"],method:"get",path:"/resume",request:{query:a.z.object({state:a.z.string()})},responses:{302:{description:"Redirect to the client's redirect_uri (with cookie set), to a MFA/continuation UL screen, or to the original authorization host when the browser is on the wrong custom domain.",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Login session is in PENDING, FAILED, or EXPIRED state.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},403:{description:"Login session not found.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}},409:{description:"Login session has already been completed (replay).",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{state:t}=e.req.valid("query");return KL(e,t)}),JL=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:a.z.object({client_id:a.z.string(),redirect_url:a.z.string().optional(),login_hint:a.z.string().toLowerCase().optional(),screen_hint:a.z.enum(["account","change-email","change-phone","change-password"]).optional().default("account")})},responses:{302:{description:"Redirect to the account page with login session state or login page",headers:a.z.object({Location:a.z.string().url()})},400:{description:"Bad Request. Invalid parameters or other client-side errors.",content:{"application/json":{schema:a.z.object({message:a.z.string()})}}}}}),async e=>{const{env:t}=e,{client_id:n,redirect_url:i,login_hint:r,screen_hint:o}=e.req.valid("query");e.set("log","account");const s=await tt(t,n);e.set("client_id",s.client_id),an(e,s.tenant.id);const c={redirect_uri:i||e.req.url,client_id:n,username:r},l=e.req.header("origin");if(l&&!y6(l,s.web_origins||[]))throw new P(403,{message:`Origin ${l} not allowed`});if(c.redirect_uri){const w=s.callbacks||[];if(e.var.host&&(w.push(`${Er(e.env,e.var.custom_domain)}/*`),w.push(`${Bt(e.env,e.var.custom_domain)}/*`)),!R_(c.redirect_uri,w,{allowPathWildcards:!0,allowSubDomainWildcards:!0}))throw new P(400,{message:`Invalid redirect URI - ${c.redirect_uri}`})}const d=_r(s.tenant.id,e.req.header("cookie")),u=d?await t.data.sessions.get(s.tenant.id,d):void 0;let p=u&&!u.revoked_at?u:void 0;s.sso_disabled&&(p=void 0);const f=new URL(e.req.url);e.var.custom_domain&&(f.hostname=e.var.custom_domain);const{ip:h,auth0_client:g,useragent:m}=e.var,_=Li(g),y=await t.data.loginSessions.create(s.tenant.id,{expires_at:new Date(Date.now()+yr*1e3).toISOString(),authParams:c,csrf_token:Ve(),authorization_url:f.toString(),ip:h,useragent:m,auth0Client:_});if(p){if(r&&(await t.data.users.get(s.tenant.id,p.user_id))?.email!==r)return e.redirect(`${Bt(e.env,e.var.custom_domain)}login/identifier?state=${encodeURIComponent(y.id)}`);if(await t.data.loginSessions.update(s.tenant.id,y.id,{session_id:p.id}),o==="change-email"){const v=new URL("/u2/account/profile",e.req.url);return v.searchParams.set("state",y.id),e.redirect(v.toString())}const w=new URL("/u2/account",e.req.url);return w.searchParams.set("state",y.id),e.redirect(w.toString())}return e.redirect(`${Bt(e.env,e.var.custom_domain)}login/identifier?state=${encodeURIComponent(y.id)}`)});function QL(e){const t=new a.OpenAPIHono;t.use(gs(e)),t.use(Ml({getOutbox:()=>e.dataAdapter.outbox,getDestinations:i=>[new Oo(e.dataAdapter.logs),new ws(e.dataAdapter.hooks,async r=>(await Ir(i,r,"webhook")).access_token),new vs(e.dataAdapter.users)]})),t.use(async(i,r)=>{const o=Dl(i,e.dataAdapter),s=e.dataAdapter.cache||_s({defaultTtlSeconds:0,maxEntries:100,cleanupIntervalMs:0}),c=e.dataAdapter.cache?300:0,l=Ll(o,{defaultTtl:c,cacheEntities:["tenants","connections","clientConnections","customDomains","clients","branding","themes","promptSettings","forms","resourceServers","roles","organizations","userRoles","userPermissions","hooks","keys"],cache:s});return i.env.data=Bl(i,l),r()}),t.use("/oauth/token",e6({origin:i=>i||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),t.use(ys).use(ms).use(bf(t));const n=t.route("/v2/logout",nD).route("/userinfo",oD).route("/.well-known",aD).route("/oauth/token",IL).route("/dbconnections",PL).route("/passwordless",NL).route("/co/authenticate",RL).route("/authorize",WL).route("/account",JL).route("/callback",eD);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),b_(n),n}var V_=Symbol("RENDERER"),U0=Symbol("ERROR_HANDLER"),rt=Symbol("STASH"),_6=Symbol("INTERNAL"),YL=Symbol("MEMO"),cp=Symbol("PERMALINK"),J1=e=>(e[_6]=!0,e),w6=e=>({value:t,children:n})=>{if(!n)return;const i={children:[{tag:J1(()=>{e.push(t)}),props:{}}]};Array.isArray(n)?i.children.push(...n.flat()):i.children.push(n),i.children.push({tag:J1(()=>{e.pop()}),props:{}});const r={tag:"",props:i,type:""};return r[U0]=o=>{throw e.pop(),o},r},v6=e=>{const t=[e],n=w6(t);return n.values=t,n.Provider=n,Ga.push(n),n},Ga=[],b6=e=>{const t=[e],n=(i=>{t.push(i.value);let r;try{r=i.children?(Array.isArray(i.children)?new C6("",{},i.children):i.children).toString():""}catch(o){throw t.pop(),o}return r instanceof Promise?r.finally(()=>t.pop()).then(o=>mr(o,o.callbacks)):(t.pop(),mr(r))});return n.values=t,n.Provider=n,n[V_]=w6(t),Ga.push(n),n},As=e=>e.values.at(-1),lp={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},F0={},Kr="data-precedence",A6=e=>e.rel==="stylesheet"&&"precedence"in e,k6=(e,t)=>e==="link"?t:lp[e].length>0,Kl=e=>Array.isArray(e)?e:[e],Q1=new WeakMap,Y1=(e,t,n,i)=>({buffer:r,context:o})=>{if(!r)return;const s=Q1.get(o)||{};Q1.set(o,s);const c=s[e]||=[];let l=!1;const d=lp[e],u=k6(e,i!==void 0);if(u){e:for(const[,p]of c)if(!(e==="link"&&!(p.rel==="stylesheet"&&p[Kr]!==void 0))){for(const f of d)if((p?.[f]??null)===n?.[f]){l=!0;break e}}}if(l?r[0]=r[0].replaceAll(t,""):u||e==="link"?c.push([t,n,i]):c.unshift([t,n,i]),r[0].indexOf("</head>")!==-1){let p;if(e==="link"||i!==void 0){const f=[];p=c.map(([h,,g],m)=>{if(g===void 0)return[h,Number.MAX_SAFE_INTEGER,m];let _=f.indexOf(g);return _===-1&&(f.push(g),_=f.length-1),[h,_,m]}).sort((h,g)=>h[1]-g[1]||h[2]-g[2]).map(([h])=>h)}else p=c.map(([f])=>f);p.forEach(f=>{r[0]=r[0].replaceAll(f,"")}),r[0]=r[0].replace(/(?=<\/head>)/,p.join(""))}},Vl=(e,t,n)=>mr(new Fn(e,n,Kl(t??[])).toString()),Gl=(e,t,n,i)=>{if("itemProp"in n)return Vl(e,t,n);let{precedence:r,blocking:o,...s}=n;r=i?r??"":void 0,i&&(s[Kr]=r);const c=new Fn(e,s,Kl(t||[])).toString();return c instanceof Promise?c.then(l=>mr(c,[...l.callbacks||[],Y1(e,l,s,r)])):mr(c,[Y1(e,c,s,r)])},ZL=({children:e,...t})=>{const n=G_();if(n){const i=As(n);if(i==="svg"||i==="head")return new Fn("title",t,Kl(e??[]))}return Gl("title",e,t,!1)},XL=({children:e,...t})=>{const n=G_();return["src","async"].some(i=>!t[i])||n&&As(n)==="head"?Vl("script",e,t):Gl("script",e,t,!1)},eM=({children:e,...t})=>["href","precedence"].every(n=>n in t)?(t["data-href"]=t.href,delete t.href,Gl("style",e,t,!0)):Vl("style",e,t),tM=({children:e,...t})=>["onLoad","onError"].some(n=>n in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?Vl("link",e,t):Gl("link",e,t,A6(t)),nM=({children:e,...t})=>{const n=G_();return n&&As(n)==="head"?Vl("meta",e,t):Gl("meta",e,t,!1)},S6=(e,{children:t,...n})=>new Fn(e,n,Kl(t??[])),iM=e=>(typeof e.action=="function"&&(e.action=cp in e.action?e.action[cp]:void 0),S6("form",e)),x6=(e,t)=>(typeof t.formAction=="function"&&(t.formAction=cp in t.formAction?t.formAction[cp]:void 0),S6(e,t)),rM=e=>x6("input",e),oM=e=>x6("button",e);const $h=Object.freeze(Object.defineProperty({__proto__:null,button:oM,form:iM,input:rM,link:tM,meta:nM,script:XL,style:eM,title:ZL},Symbol.toStringTag,{value:"Module"}));var aM=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),dp=e=>aM.get(e)||e,sM=/[\s"'<>/=`\\\x00-\x1f\x7f-\x9f]/,cM=e=>{const t=e.length;if(t===0)return!1;for(let n=0;n<t;n++){const i=e.charCodeAt(n);if(!(i>=97&&i<=122||i>=65&&i<=90||i>=48&&i<=57||i===45||i===95||i===46||i===58))return!sM.test(e)}return!0},E6=(e,t)=>{for(const[n,i]of Object.entries(e)){const r=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,o=>`-${o.toLowerCase()}`);t(r,i==null?null:typeof i=="number"?r.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${i}`:`${i}px`:i)}},rl=void 0,G_=()=>rl,lM=e=>/[A-Z]/.test(e)&&e.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,dM=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],uM=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],W_=(e,t)=>{for(let n=0,i=e.length;n<i;n++){const r=e[n];if(typeof r=="string")va(r,t);else{if(typeof r=="boolean"||r===null||r===void 0)continue;r instanceof Fn?r.toStringToBuffer(t):typeof r=="number"||r.isEscaped?t[0]+=r:r instanceof Promise?t.unshift("",r):W_(r,t)}}},Fn=class{tag;props;key;children;isEscaped=!0;localContexts;constructor(e,t,n){this.tag=e,this.props=t,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){const e=[""];this.localContexts?.forEach(([t,n])=>{t.values.push(n)});try{this.toStringToBuffer(e)}finally{this.localContexts?.forEach(([t])=>{t.values.pop()})}return e.length===1?"callbacks"in e?fj(mr(e[0],e.callbacks)).toString():e[0]:pj(e,e.callbacks)}toStringToBuffer(e){const t=this.tag,n=this.props;let{children:i}=this;e[0]+=`<${t}`;const r=rl&&As(rl)==="svg"?o=>lM(dp(o)):o=>dp(o);for(let[o,s]of Object.entries(n))if(o=r(o),!!cM(o)&&o!=="children"){if(o==="style"&&typeof s=="object"){let c="";E6(s,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),e[0]+=' style="',va(c,e),e[0]+='"'}else if(typeof s=="string")e[0]+=` ${o}="`,va(s,e),e[0]+='"';else if(s!=null)if(typeof s=="number"||s.isEscaped)e[0]+=` ${o}="${s}"`;else if(typeof s=="boolean"&&uM.includes(o))s&&(e[0]+=` ${o}=""`);else if(o==="dangerouslySetInnerHTML"){if(i.length>0)throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");i=[mr(s.__html)]}else if(s instanceof Promise)e[0]+=` ${o}="`,e.unshift('"',s);else if(typeof s=="function"){if(!o.startsWith("on")&&o!=="ref")throw new Error(`Invalid prop '${o}' of type 'function' supplied to '${t}'.`)}else e[0]+=` ${o}="`,va(s.toString(),e),e[0]+='"'}if(dM.includes(t)&&i.length===0){e[0]+="/>";return}e[0]+=">",W_(i,e),e[0]+=`</${t}>`}},zh=class extends Fn{toStringToBuffer(e){const{children:t}=this,n={...this.props};t.length&&(n.children=t.length===1?t[0]:t);const i=this.tag.call(null,n);if(!(typeof i=="boolean"||i==null))if(i instanceof Promise)if(Ga.length===0)e.unshift("",i);else{const r=Ga.map(o=>[o,o.values.at(-1)]);e.unshift("",i.then(o=>(o instanceof Fn&&(o.localContexts=r),o)))}else i instanceof Fn?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?(e[0]+=i,i.callbacks&&(e.callbacks||=[],e.callbacks.push(...i.callbacks))):va(i,e)}},C6=class extends Fn{toStringToBuffer(e){W_(this.children,e)}},pM=(e,t,...n)=>{t??={},n.length&&(t.children=n.length===1?n[0]:n);const i=t.key;delete t.key;const r=Bd(e,t,n);return r.key=i,r},Z1=!1,Bd=(e,t,n)=>{if(!Z1){for(const i in F0)$h[i][V_]=F0[i];Z1=!0}return typeof e=="function"?new zh(e,t,n):$h[e]?new zh($h[e],t,n):e==="svg"||e==="head"?(rl||=b6(""),new Fn(e,t,[new zh(rl,{value:e},n)])):new Fn(e,t,n)},Wa=({children:e})=>new C6("",{children:e},Array.isArray(e)?e:e?[e]:[]),fM=(e,t,...n)=>{let i;if(n.length>0)i=n;else{const r=e.props.children;i=Array.isArray(r)?r:[r]}return pM(e.tag,{...e.props,...t},...i)};function A(e,t,n){let i;if(!t||!("children"in t))i=Bd(e,t,[]);else{const r=t.children;i=Array.isArray(r)?Bd(e,t,r):Bd(e,t,[r])}return i.key=n,i}async function Be(e,t,n=!1){const{env:i}=e,r=await i.data.loginSessions.get(e.var.tenant_id||"",t);if(!r)throw new P(400,{message:"Login session not found"});e.set("loginSession",r);const o=await tt(i,r.authParams.client_id);e.set("client_id",o.client_id),an(e,o.tenant.id);const s=o.tenant;if(r.session_id&&!n){if(!r.authParams.redirect_uri)throw new P(400,{message:"Login session closed and no redirect URI available"});const f=new URL(r.authParams.redirect_uri);throw f.searchParams.set("error","access_denied"),f.searchParams.set("error_description","Login session closed"),r.authParams.state&&f.searchParams.set("state",r.authParams.state),new rn(f.toString(),302)}const[c,l]=await Promise.all([i.data.themes.get(s.id,"default"),i.data.branding.get(s.id)]),d=c??zc,u=l?{...l,favicon_url:e.var.custom_domain?l.favicon_url:void 0}:null,p=r.authParams?.ui_locales?.split(" ")?.map(f=>f.split("-")[0])?.find(f=>{if(Array.isArray(M.options.supportedLngs))return M.options.supportedLngs.includes(f)});return await M.changeLanguage(p||"en"),{theme:d,branding:u,client:o,tenant:s,loginSession:r}}async function So(e,t,n){const{theme:i,branding:r,client:o,tenant:s,loginSession:c}=await Be(e,t,!0),l=_r(o.tenant.id,e.req.header("cookie")),d=l?await e.env.data.sessions.get(o.tenant.id,l):null;if(n?.continuationScope&&ip(c,n.continuationScope)){if(!c.user_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const h=await e.env.data.users.get(o.tenant.id,c.user_id);if(!h)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const g=c.session_id?await e.env.data.sessions.get(o.tenant.id,c.session_id):null;return{theme:i,branding:r,client:o,user:h,tenant:s,loginSession:c,session:g,isContinuation:!0}}if(!d||d.revoked_at||!c.session_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);const p=await e.env.data.sessions.get(o.tenant.id,c.session_id),f=await e.env.data.users.get(o.tenant.id,d.user_id);if(!f||p?.user_id!==d.user_id)throw new rn(`/u/login/identifier?state=${encodeURIComponent(t)}`);return{theme:i,branding:r,client:o,user:f,tenant:s,loginSession:c,session:p,isContinuation:!1}}const Ph={[W.USERNAME_PASSWORD]:"password",[W.EMAIL]:"email",[W.SMS]:"sms"};async function T6(e,t,n,i,r){if(i==="username"||r==="password")return"password";if(r==="code")return i==="sms"?"sms":"email";const s=(i==="email"?await xr({userAdapter:e.env.data.users,tenant_id:t.tenant.id,email:n}):await wn({userAdapter:e.env.data.users,tenant_id:t.tenant.id,username:n,provider:i==="sms"?"sms":Ke}))?.app_metadata?.strategy;if(s&&Ph[s])return Ph[s];const c=t.connections.map(d=>Ph[d.strategy]).filter(d=>d!==void 0);return c.length===1&&c[0]?c[0]:(await e.env.data.promptSettings.get(t.tenant.id)).password_first&&c.includes("password")?"password":i==="sms"?"sms":"email"}const J_=({theme:e,branding:t})=>{const n=e?.widget?.logo_url||t?.logo_url;return n?A("div",{className:"inline-flex h-9 items-center",children:A("img",{src:n,className:"h-full w-auto",alt:"Logo"})}):A(Wa,{})},I6=e=>A("div",{className:"mt-8",children:e.client?.client_metadata?.termsAndConditionsUrl&&A("div",{className:"text-xs text-gray-300",children:[M.t("agree_to")," ",A("a",{href:e.client.client_metadata.termsAndConditionsUrl,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:M.t("terms")})]})});var Nh={exports:{}};var X1;function hM(){return X1||(X1=1,(function(e){(function(){var t={}.hasOwnProperty;function n(){for(var o="",s=0;s<arguments.length;s++){var c=arguments[s];c&&(o=r(o,i(c)))}return o}function i(o){if(typeof o=="string"||typeof o=="number")return o;if(typeof o!="object")return"";if(Array.isArray(o))return n.apply(null,o);if(o.toString!==Object.prototype.toString&&!o.toString.toString().includes("[native code]"))return o.toString();var s="";for(var c in o)t.call(o,c)&&o[c]&&(s=r(s,c));return s}function r(o,s){return s?o?o+" "+s:o+s:o}e.exports?(n.default=n,e.exports=n):window.classNames=n})()})(Nh)),Nh.exports}var gM=hM();const nt=Ty(gM),mM=e=>e==="small"?"text-base":e==="medium"?"text-2xl":e==="large"?"text-3xl":"",ut=({name:e,size:t,className:n=""})=>{const i=mM(t);return A("span",{className:nt(`uicon-${e}`,n,i)})};function $6(e){const t=e.replace("#",""),n=parseInt(t,16);return[n>>16&255,n>>8&255,n&255]}function yM(e,t,n){return`#${(e<<16|t<<8|n).toString(16).padStart(6,"0")}`}const _M=(e,t)=>{const[n,i,r]=$6(e);return yM(Math.min(255,Math.round(n+(255-n)*t)),Math.min(255,Math.round(i+(255-i)*t)),Math.min(255,Math.round(r+(255-r)*t)))};function e2(e){const[t,n,i]=$6(e).map(r=>{const o=r/255;return o<=.04045?o/12.92:Math.pow((o+.055)/1.055,2.4)});return .2126*t+.7152*n+.0722*i}function q0(e,t){const n=e2(e),i=e2(t),r=Math.max(n,i),o=Math.min(n,i);return(r+.05)/(o+.05)}function t2(e,t="light"){const n=q0(e,"#ffffff"),i=q0(e,"#000000"),r=1.35;return t==="light"?i>n*r?"#000000":"#ffffff":i*r>n?"#000000":"#ffffff"}const Ja="mo7g9ojt",wM=(e,t)=>{const n=e?.colors?.primary_button||t?.colors?.primary||"#000000",i=e?.colors?.base_hover_color||_M(n,.2),r=e?.colors?.primary_button_label,o=r&&q0(r,n)>=4.5,s=o?r:t2(n,"light"),c=o?r:t2(n,"dark"),l=s!==c?`
87
87
  @media (prefers-color-scheme: dark) {
88
88
  body { --text-on-primary: ${c}; }
89
89
  }`:"";return`
package/dist/authhero.mjs CHANGED
@@ -38674,7 +38674,7 @@ function M1(e, t = "light") {
38674
38674
  const n = B0(e, "#ffffff"), i = B0(e, "#000000"), r = 1.35;
38675
38675
  return t === "light" ? i > n * r ? "#000000" : "#ffffff" : i * r > n ? "#000000" : "#ffffff";
38676
38676
  }
38677
- const Fa = "mo784psi", uM = (e, t) => {
38677
+ const Fa = "mo7g9ojt", uM = (e, t) => {
38678
38678
  const n = e?.colors?.primary_button || t?.colors?.primary || "#000000", i = e?.colors?.base_hover_color || dM(n, 0.2), r = e?.colors?.primary_button_label, o = r && B0(r, n) >= 4.5, s = o ? r : M1(n, "light"), c = o ? r : M1(n, "dark"), l = s !== c ? `
38679
38679
  @media (prefers-color-scheme: dark) {
38680
38680
  body { --text-on-primary: ${c}; }