authhero 0.77.0 → 0.79.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
@@ -2,7 +2,7 @@
2
2
  * @license bcrypt.js (c) 2013 Daniel Wirtz <dcode@dcode.io>
3
3
  * Released under the Apache License, Version 2.0
4
4
  * see: https://github.com/dcodeIO/bcrypt.js for details
5
- */(function(e,n){typeof t_=="function"&&t&&t.exports?t.exports=n():(e.dcodeIO=e.dcodeIO||{}).bcrypt=n()})(os,function(){var e={},n=null;function r(j){if(t&&t.exports)try{return i_.randomBytes(j)}catch{}try{var z;return(self.crypto||self.msCrypto).getRandomValues(z=new Uint32Array(j)),Array.prototype.slice.call(z)}catch{}if(!n)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return n(j)}var i=!1;try{r(1),i=!0}catch{}n=null,e.setRandomFallback=function(j){n=j},e.genSaltSync=function(j,z){if(j=j||_,typeof j!="number")throw Error("Illegal arguments: "+typeof j+", "+typeof z);j<4?j=4:j>31&&(j=31);var E=[];return E.push("$2a$"),j<10&&E.push("0"),E.push(j.toString()),E.push("$"),E.push(h(r(f),f)),E.join("")},e.genSalt=function(j,z,E){if(typeof z=="function"&&(E=z,z=void 0),typeof j=="function"&&(E=j,j=void 0),typeof j>"u")j=_;else if(typeof j!="number")throw Error("illegal arguments: "+typeof j);function x(k){o(function(){try{k(null,e.genSaltSync(j))}catch($){k($)}})}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);x(E)}else return new Promise(function(k,$){x(function(L,X){if(L){$(L);return}k(X)})})},e.hashSync=function(j,z){if(typeof z>"u"&&(z=_),typeof z=="number"&&(z=e.genSaltSync(z)),typeof j!="string"||typeof z!="string")throw Error("Illegal arguments: "+typeof j+", "+typeof z);return Ge(j,z)},e.hash=function(j,z,E,x){function k($){typeof j=="string"&&typeof z=="number"?e.genSalt(z,function(L,X){Ge(j,X,$,x)}):typeof j=="string"&&typeof z=="string"?Ge(j,z,$,x):o($.bind(this,Error("Illegal arguments: "+typeof j+", "+typeof z)))}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);k(E)}else return new Promise(function($,L){k(function(X,G){if(X){L(X);return}$(G)})})};function s(j,z){for(var E=0,x=0,k=0,$=j.length;k<$;++k)j.charCodeAt(k)===z.charCodeAt(k)?++E:++x;return E<0?!1:x===0}e.compareSync=function(j,z){if(typeof j!="string"||typeof z!="string")throw Error("Illegal arguments: "+typeof j+", "+typeof z);return z.length!==60?!1:s(e.hashSync(j,z.substr(0,z.length-31)),z)},e.compare=function(j,z,E,x){function k($){if(typeof j!="string"||typeof z!="string"){o($.bind(this,Error("Illegal arguments: "+typeof j+", "+typeof z)));return}if(z.length!==60){o($.bind(this,null,!1));return}e.hash(j,z.substr(0,29),function(L,X){L?$(L):$(null,s(X,z))},x)}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);k(E)}else return new Promise(function($,L){k(function(X,G){if(X){L(X);return}$(G)})})},e.getRounds=function(j){if(typeof j!="string")throw Error("Illegal arguments: "+typeof j);return parseInt(j.split("$")[2],10)},e.getSalt=function(j){if(typeof j!="string")throw Error("Illegal arguments: "+typeof j);if(j.length!==60)throw Error("Illegal hash length: "+j.length+" != 60");return j.substring(0,29)};var o=typeof process<"u"&&process&&typeof process.nextTick=="function"?typeof setImmediate=="function"?setImmediate:process.nextTick:setTimeout;function c(j){var z=[],E=0;return v.encodeUTF16toUTF8(function(){return E>=j.length?null:j.charCodeAt(E++)},function(x){z.push(x)}),z}var l="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),u=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1],p=String.fromCharCode;function h(j,z){var E=0,x=[],k,$;if(z<=0||z>j.length)throw Error("Illegal len: "+z);for(;E<z;){if(k=j[E++]&255,x.push(l[k>>2&63]),k=(k&3)<<4,E>=z){x.push(l[k&63]);break}if($=j[E++]&255,k|=$>>4&15,x.push(l[k&63]),k=($&15)<<2,E>=z){x.push(l[k&63]);break}$=j[E++]&255,k|=$>>6&3,x.push(l[k&63]),x.push(l[$&63])}return x.join("")}function m(j,z){var E=0,x=j.length,k=0,$=[],L,X,G,ie,ce,H;if(z<=0)throw Error("Illegal len: "+z);for(;E<x-1&&k<z&&(H=j.charCodeAt(E++),L=H<u.length?u[H]:-1,H=j.charCodeAt(E++),X=H<u.length?u[H]:-1,!(L==-1||X==-1||(ce=L<<2>>>0,ce|=(X&48)>>4,$.push(p(ce)),++k>=z||E>=x)||(H=j.charCodeAt(E++),G=H<u.length?u[H]:-1,G==-1)||(ce=(X&15)<<4>>>0,ce|=(G&60)>>2,$.push(p(ce)),++k>=z||E>=x)));)H=j.charCodeAt(E++),ie=H<u.length?u[H]:-1,ce=(G&3)<<6>>>0,ce|=ie,$.push(p(ce)),++k;var Ie=[];for(E=0;E<k;E++)Ie.push($[E].charCodeAt(0));return Ie}var v=function(){var j={};return j.MAX_CODEPOINT=1114111,j.encodeUTF8=function(z,E){var x=null;for(typeof z=="number"&&(x=z,z=function(){return null});x!==null||(x=z())!==null;)x<128?E(x&127):x<2048?(E(x>>6&31|192),E(x&63|128)):x<65536?(E(x>>12&15|224),E(x>>6&63|128),E(x&63|128)):(E(x>>18&7|240),E(x>>12&63|128),E(x>>6&63|128),E(x&63|128)),x=null},j.decodeUTF8=function(z,E){for(var x,k,$,L,X=function(G){G=G.slice(0,G.indexOf(null));var ie=Error(G.toString());throw ie.name="TruncatedError",ie.bytes=G,ie};(x=z())!==null;)if(!(x&128))E(x);else if((x&224)===192)(k=z())===null&&X([x,k]),E((x&31)<<6|k&63);else if((x&240)===224)((k=z())===null||($=z())===null)&&X([x,k,$]),E((x&15)<<12|(k&63)<<6|$&63);else if((x&248)===240)((k=z())===null||($=z())===null||(L=z())===null)&&X([x,k,$,L]),E((x&7)<<18|(k&63)<<12|($&63)<<6|L&63);else throw RangeError("Illegal starting byte: "+x)},j.UTF16toUTF8=function(z,E){for(var x,k=null;(x=k!==null?k:z())!==null;){if(x>=55296&&x<=57343&&(k=z())!==null&&k>=56320&&k<=57343){E((x-55296)*1024+k-56320+65536),k=null;continue}E(x)}k!==null&&E(k)},j.UTF8toUTF16=function(z,E){var x=null;for(typeof z=="number"&&(x=z,z=function(){return null});x!==null||(x=z())!==null;)x<=65535?E(x):(x-=65536,E((x>>10)+55296),E(x%1024+56320)),x=null},j.encodeUTF16toUTF8=function(z,E){j.UTF16toUTF8(z,function(x){j.encodeUTF8(x,E)})},j.decodeUTF8toUTF16=function(z,E){j.decodeUTF8(z,function(x){j.UTF8toUTF16(x,E)})},j.calculateCodePoint=function(z){return z<128?1:z<2048?2:z<65536?3:4},j.calculateUTF8=function(z){for(var E,x=0;(E=z())!==null;)x+=j.calculateCodePoint(E);return x},j.calculateUTF16asUTF8=function(z){var E=0,x=0;return j.UTF16toUTF8(z,function(k){++E,x+=j.calculateCodePoint(k)}),[E,x]},j}();Date.now=Date.now||function(){return+new Date};var f=16,_=10,w=16,S=100,C=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],B=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],R=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function te(j,z,E,x){var k,$=j[z],L=j[z+1];return $^=E[0],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[1],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[2],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[3],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[4],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[5],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[6],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[7],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[8],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[9],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[10],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[11],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[12],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[13],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[14],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[15],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[16],j[z]=L^E[w+1],j[z+1]=$,j}function fe(j,z){for(var E=0,x=0;E<4;++E)x=x<<8|j[z]&255,z=(z+1)%j.length;return{key:x,offp:z}}function le(j,z,E){for(var x=0,k=[0,0],$=z.length,L=E.length,X,G=0;G<$;G++)X=fe(j,x),x=X.offp,z[G]=z[G]^X.key;for(G=0;G<$;G+=2)k=te(k,0,z,E),z[G]=k[0],z[G+1]=k[1];for(G=0;G<L;G+=2)k=te(k,0,z,E),E[G]=k[0],E[G+1]=k[1]}function Ue(j,z,E,x){for(var k=0,$=[0,0],L=E.length,X=x.length,G,ie=0;ie<L;ie++)G=fe(z,k),k=G.offp,E[ie]=E[ie]^G.key;for(k=0,ie=0;ie<L;ie+=2)G=fe(j,k),k=G.offp,$[0]^=G.key,G=fe(j,k),k=G.offp,$[1]^=G.key,$=te($,0,E,x),E[ie]=$[0],E[ie+1]=$[1];for(ie=0;ie<X;ie+=2)G=fe(j,k),k=G.offp,$[0]^=G.key,G=fe(j,k),k=G.offp,$[1]^=G.key,$=te($,0,E,x),x[ie]=$[0],x[ie+1]=$[1]}function at(j,z,E,x,k){var $=R.slice(),L=$.length,X;if(E<4||E>31)if(X=Error("Illegal number of rounds (4-31): "+E),x){o(x.bind(this,X));return}else throw X;if(z.length!==f)if(X=Error("Illegal salt length: "+z.length+" != "+f),x){o(x.bind(this,X));return}else throw X;E=1<<E>>>0;var G,ie,ce=0,H;Int32Array?(G=new Int32Array(C),ie=new Int32Array(B)):(G=C.slice(),ie=B.slice()),Ue(z,j,G,ie);function Ie(){if(k&&k(ce/E),ce<E)for(var he=Date.now();ce<E&&(ce=ce+1,le(j,G,ie),le(z,G,ie),!(Date.now()-he>S)););else{for(ce=0;ce<64;ce++)for(H=0;H<L>>1;H++)te($,H<<1,G,ie);var xe=[];for(ce=0;ce<L;ce++)xe.push(($[ce]>>24&255)>>>0),xe.push(($[ce]>>16&255)>>>0),xe.push(($[ce]>>8&255)>>>0),xe.push(($[ce]&255)>>>0);if(x){x(null,xe);return}else return xe}x&&o(Ie)}if(typeof x<"u")Ie();else for(var ln;;)if(typeof(ln=Ie())<"u")return ln||[]}function Ge(j,z,E,x){var k;if(typeof j!="string"||typeof z!="string")if(k=Error("Invalid string / salt: Not a string"),E){o(E.bind(this,k));return}else throw k;var $,L;if(z.charAt(0)!=="$"||z.charAt(1)!=="2")if(k=Error("Invalid salt version: "+z.substring(0,2)),E){o(E.bind(this,k));return}else throw k;if(z.charAt(2)==="$")$="\0",L=3;else{if($=z.charAt(2),$!=="a"&&$!=="b"&&$!=="y"||z.charAt(3)!=="$")if(k=Error("Invalid salt revision: "+z.substring(2,4)),E){o(E.bind(this,k));return}else throw k;L=4}if(z.charAt(L+2)>"$")if(k=Error("Missing salt rounds"),E){o(E.bind(this,k));return}else throw k;var X=parseInt(z.substring(L,L+1),10)*10,G=parseInt(z.substring(L+1,L+2),10),ie=X+G,ce=z.substring(L+3,L+25);j+=$>="a"?"\0":"";var H=c(j),Ie=m(ce,f);function ln(he){var xe=[];return xe.push("$2"),$>="a"&&xe.push($),xe.push("$"),ie<10&&xe.push("0"),xe.push(ie.toString()),xe.push("$"),xe.push(h(Ie,Ie.length)),xe.push(h(he,R.length*4-1)),xe.join("")}if(typeof E>"u")return ln(at(H,Ie,ie));at(H,Ie,ie,function(he,xe){he?E(he,null):E(null,ln(xe))},x)}return e.encodeBase64=h,e.decodeBase64=m,e})})(kf);var s_=kf.exports;const ii=bf(s_),o_="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let a_=t=>crypto.getRandomValues(new Uint8Array(t)),c_=(t,e,n)=>{let r=(2<<Math.log2(t.length-1))-1,i=-~(1.6*r*e/t.length);return(s=e)=>{let o="";for(;;){let c=n(i),l=i;for(;l--;)if(o+=t[c[l]&r]||"",o.length===s)return o}}},l_=(t,e=21)=>c_(t,e,a_),qe=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+=o_[n[t]&63];return e};const u_=24;function Ys(){return l_("0123456789abcdef",u_)()}function Tu(t){if(!t.includes("|"))return console.error("Invalid user_id format"),t;const[,e]=t.split("|");return e}function d_(t){return async(e,n)=>{if(console.log("got here"),!n.email||!n.email_verified)return t.users.create(e,n);const r=await to({userAdapter:t.users,tenant_id:e,email:n.email});return r?(await t.users.create(e,{...n,linked_to:r.user_id}),r):t.users.create(e,n)}}function be(t,e){return{type:e.type,description:e.description||"",ip:t.req.header("x-real-ip")||"",user_agent:t.req.header("user-agent")||"",date:new Date().toISOString(),details:{request:{method:t.req.method,path:t.req.path,qs:t.req.queries(),body:e.body||t.var.body||""}},isMobile:!1,client_id:t.var.client_id,client_name:"",user_id:e.userId||t.var.user_id||"",hostname:t.req.header("host")||"",user_name:t.var.username||"",connection_id:"",connection:t.var.connection||"",strategy:e.strategy||"",strategy_type:e.strategy_type||"",audience:"",scope:[]}}class il{constructor(e,n){ee(this,"value");ee(this,"unit");this.value=e,this.unit=n}milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(e){return new il(Math.round(this.milliseconds()*e),"ms")}}class p_{constructor(e){ee(this,"hash");this.hash=e}async verify(e,n,r){const i=await crypto.subtle.importKey("spki",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(e,n){const r=await crypto.subtle.importKey("pkcs8",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(e){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:e??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function xf(t){return await crypto.subtle.digest("SHA-256",t)}const Pu="0123456789abcdef";function Ia(t){const e=new Uint8Array(t);let n="";for(let r=0;r<e.length;r++){const i=e[r]>>4;n+=Pu[i];const s=e[r]&15;n+=Pu[s]}return n}class Sf{constructor(e,n){ee(this,"alphabet");ee(this,"padding");ee(this,"decodeMap",new Map);if(e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=(n==null?void 0:n.padding)??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),(n==null?void 0:n.includePadding)??!0){const c=(8-r.length%8)%8;for(let l=0;l<c;l++)r+="="}return r}decode(e,n){const r=(n==null?void 0:n.strict)??!0,i=Math.ceil(e.length/8),s=[];for(let o=0;o<i;o++){let c=0;const l=[];for(let p=0;p<8;p++){const h=e[o*8+p];if(h==="="){if(o+1!==i)throw new Error(`Invalid character: ${h}`);c+=1;continue}if(h===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const m=this.decodeMap.get(h)??null;if(m===null)throw new Error(`Invalid character: ${h}`);l.push(m)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const p=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(p)}if(c<4){const p=((l[3]&255)<<4)+(l[4]>>1);s.push(p)}if(c<3){const p=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(p)}if(c<1){const p=((l[6]&7)<<5)+l[7];s.push(p)}}return Uint8Array.from(s)}}new Sf("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Sf("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Af{constructor(e,n){ee(this,"alphabet");ee(this,"padding");ee(this,"decodeMap",new Map);if(e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=(n==null?void 0:n.padding)??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),(n==null?void 0:n.includePadding)??!0){const c=(4-r.length%4)%4;for(let l=0;l<c;l++)r+="="}return r}decode(e,n){const r=(n==null?void 0:n.strict)??!0,i=Math.ceil(e.length/4),s=[];for(let o=0;o<i;o++){let c=0,l=0;for(let u=0;u<4;u++){const p=e[o*4+u];if(p==="="){if(o+1!==i)throw new Error(`Invalid character: ${p}`);c+=1;continue}if(p===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const h=this.decodeMap.get(p)??null;if(h===null)throw new Error(`Invalid character: ${p}`);l+=h<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const f_=new Af("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),mn=new Af("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function Ru(t,e,n,r){const i={alg:t,typ:"JWT",...r==null?void 0:r.headers},s={...n};(r==null?void 0:r.audiences)!==void 0&&(s.aud=r.audiences),(r==null?void 0:r.subject)!==void 0&&(s.sub=r.subject),(r==null?void 0:r.issuer)!==void 0&&(s.iss=r.issuer),(r==null?void 0:r.jwtId)!==void 0&&(s.jti=r.jwtId),(r==null?void 0:r.expiresIn)!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),(r==null?void 0:r.notBefore)!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const o=new TextEncoder,c=mn.encode(o.encode(JSON.stringify(i)),{includePadding:!1}),l=mn.encode(o.encode(JSON.stringify(s)),{includePadding:!1}),u=o.encode([c,l].join(".")),p=await g_(t).sign(e,u),h=mn.encode(new Uint8Array(p),{includePadding:!1});return[c,l,h].join(".")}function h_(t){const e=t.split(".");return e.length!==3?null:e}function sl(t){const e=h_(t);if(!e)return null;const n=new TextDecoder,r=mn.decode(e[0],{strict:!1}),i=mn.decode(e[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!m_(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const o=JSON.parse(n.decode(i));if(typeof o!="object"||o===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in o){if(typeof o.exp!="number")return null;c.expiresAt=new Date(o.exp*1e3)}if("iss"in o){if(typeof o.iss!="string")return null;c.issuer=o.iss}if("sub"in o){if(typeof o.sub!="string")return null;c.subject=o.sub}if("aud"in o)if(Array.isArray(o.aud)){for(const l of o.aud)if(typeof l!="string")return null;c.audiences=o.aud}else{if(typeof o.aud!="string")return null;c.audiences=[o.aud]}if("nbf"in o){if(typeof o.nbf!="number")return null;c.notBefore=new Date(o.nbf*1e3)}if("iat"in o){if(typeof o.iat!="number")return null;c.issuedAt=new Date(o.iat*1e3)}if("jti"in o){if(typeof o.jti!="string")return null;c.jwtId=o.jti}return{value:t,header:{...s,typ:"JWT",alg:s.alg},payload:{...o},parts:e,...c}}function g_(t){return new p_(__[t])}function m_(t){return typeof t!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(t)}const __={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function y_(){const t=new Uint8Array(32);return crypto.getRandomValues(t),mn.encode(t,{includePadding:!1})}function v_(t){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(t);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{t=t.replace(/./g,"\0")}}async function w_(t,e){if(e==="plain")return t;const n=new TextEncoder().encode(t),r=await xf(n);return mn.encode(new Uint8Array(r),{includePadding:!1})}const Ni=60*5,Xs=30*24*60*60,Ur=24*60*60,b_="auth-token",za=30*60*1e3,k_=5*60,x_=5*60,S_=30*60*1e3,A_=30*60*1e3,E_=24*60*60*1e3;function Ef(t,e,n){const r=[];return r.push([encodeURIComponent(t),encodeURIComponent(e)]),(n==null?void 0:n.domain)!==void 0&&r.push(["Domain",n.domain]),(n==null?void 0:n.expires)!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n!=null&&n.httpOnly&&r.push(["HttpOnly"]),(n==null?void 0:n.maxAge)!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),(n==null?void 0:n.path)!==void 0&&r.push(["Path",n.path]),(n==null?void 0:n.sameSite)==="lax"&&r.push(["SameSite","Lax"]),(n==null?void 0:n.sameSite)==="none"&&r.push(["SameSite","None"]),(n==null?void 0:n.sameSite)==="strict"&&r.push(["SameSite","Strict"]),n!=null&&n.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function I_(t){const e=new Map,n=t.split("; ");for(const r of n){const i=r.split("="),s=i[0],o=i[1]??"";s&&e.set(decodeURIComponent(s),decodeURIComponent(o))}return e}function ol(t){return`${t}-${b_}`}function as(t,e){return e?I_(e).get(ol(t)):void 0}function z_(t){const e={path:"/",httpOnly:!0,secure:!0,maxAge:0};return Ef(ol(t),"",{...e,sameSite:"none"})}function If(t,e){const n={path:"/",httpOnly:!0,secure:!0,maxAge:Xs};return Ef(ol(t),e,{...n,sameSite:"none"})}var al={},Qs={};(function(t){const e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const u=[];let p=l.exec(c);for(;p;){const h=[];h.startIndex=l.lastIndex-p[0].length;const m=p.length;for(let v=0;v<m;v++)h.push(p[v]);u.push(h),p=l.exec(c)}return u},o=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,l,u){if(l){const p=Object.keys(l),h=p.length;for(let m=0;m<h;m++)u==="strict"?c[p[m]]=[l[p[m]]]:c[p[m]]=l[p[m]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=o,t.getAllMatches=s,t.nameRegexp=r})(Qs);const cl=Qs,C_={allowBooleanAttributes:!1,unpairedTags:[]};al.validate=function(t,e){e=Object.assign({},C_,e);const n=[];let r=!1,i=!1;t[0]==="\uFEFF"&&(t=t.substr(1));for(let s=0;s<t.length;s++)if(t[s]==="<"&&t[s+1]==="?"){if(s+=2,s=Uu(t,s),s.err)return s}else if(t[s]==="<"){let o=s;if(s++,t[s]==="!"){s=Vu(t,s);continue}else{let c=!1;t[s]==="/"&&(c=!0,s++);let l="";for(;s<t.length&&t[s]!==">"&&t[s]!==" "&&t[s]!==" "&&t[s]!==`
5
+ */(function(e,n){typeof t_=="function"&&t&&t.exports?t.exports=n():(e.dcodeIO=e.dcodeIO||{}).bcrypt=n()})(os,function(){var e={},n=null;function r(j){if(t&&t.exports)try{return i_.randomBytes(j)}catch{}try{var z;return(self.crypto||self.msCrypto).getRandomValues(z=new Uint32Array(j)),Array.prototype.slice.call(z)}catch{}if(!n)throw Error("Neither WebCryptoAPI nor a crypto module is available. Use bcrypt.setRandomFallback to set an alternative");return n(j)}var i=!1;try{r(1),i=!0}catch{}n=null,e.setRandomFallback=function(j){n=j},e.genSaltSync=function(j,z){if(j=j||_,typeof j!="number")throw Error("Illegal arguments: "+typeof j+", "+typeof z);j<4?j=4:j>31&&(j=31);var E=[];return E.push("$2a$"),j<10&&E.push("0"),E.push(j.toString()),E.push("$"),E.push(h(r(f),f)),E.join("")},e.genSalt=function(j,z,E){if(typeof z=="function"&&(E=z,z=void 0),typeof j=="function"&&(E=j,j=void 0),typeof j>"u")j=_;else if(typeof j!="number")throw Error("illegal arguments: "+typeof j);function x(k){o(function(){try{k(null,e.genSaltSync(j))}catch($){k($)}})}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);x(E)}else return new Promise(function(k,$){x(function(L,X){if(L){$(L);return}k(X)})})},e.hashSync=function(j,z){if(typeof z>"u"&&(z=_),typeof z=="number"&&(z=e.genSaltSync(z)),typeof j!="string"||typeof z!="string")throw Error("Illegal arguments: "+typeof j+", "+typeof z);return Ge(j,z)},e.hash=function(j,z,E,x){function k($){typeof j=="string"&&typeof z=="number"?e.genSalt(z,function(L,X){Ge(j,X,$,x)}):typeof j=="string"&&typeof z=="string"?Ge(j,z,$,x):o($.bind(this,Error("Illegal arguments: "+typeof j+", "+typeof z)))}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);k(E)}else return new Promise(function($,L){k(function(X,G){if(X){L(X);return}$(G)})})};function s(j,z){for(var E=0,x=0,k=0,$=j.length;k<$;++k)j.charCodeAt(k)===z.charCodeAt(k)?++E:++x;return E<0?!1:x===0}e.compareSync=function(j,z){if(typeof j!="string"||typeof z!="string")throw Error("Illegal arguments: "+typeof j+", "+typeof z);return z.length!==60?!1:s(e.hashSync(j,z.substr(0,z.length-31)),z)},e.compare=function(j,z,E,x){function k($){if(typeof j!="string"||typeof z!="string"){o($.bind(this,Error("Illegal arguments: "+typeof j+", "+typeof z)));return}if(z.length!==60){o($.bind(this,null,!1));return}e.hash(j,z.substr(0,29),function(L,X){L?$(L):$(null,s(X,z))},x)}if(E){if(typeof E!="function")throw Error("Illegal callback: "+typeof E);k(E)}else return new Promise(function($,L){k(function(X,G){if(X){L(X);return}$(G)})})},e.getRounds=function(j){if(typeof j!="string")throw Error("Illegal arguments: "+typeof j);return parseInt(j.split("$")[2],10)},e.getSalt=function(j){if(typeof j!="string")throw Error("Illegal arguments: "+typeof j);if(j.length!==60)throw Error("Illegal hash length: "+j.length+" != 60");return j.substring(0,29)};var o=typeof process<"u"&&process&&typeof process.nextTick=="function"?typeof setImmediate=="function"?setImmediate:process.nextTick:setTimeout;function c(j){var z=[],E=0;return v.encodeUTF16toUTF8(function(){return E>=j.length?null:j.charCodeAt(E++)},function(x){z.push(x)}),z}var l="./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),u=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,54,55,56,57,58,59,60,61,62,63,-1,-1,-1,-1,-1,-1,-1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,-1,-1,-1,-1,-1,-1,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,-1,-1,-1,-1,-1],p=String.fromCharCode;function h(j,z){var E=0,x=[],k,$;if(z<=0||z>j.length)throw Error("Illegal len: "+z);for(;E<z;){if(k=j[E++]&255,x.push(l[k>>2&63]),k=(k&3)<<4,E>=z){x.push(l[k&63]);break}if($=j[E++]&255,k|=$>>4&15,x.push(l[k&63]),k=($&15)<<2,E>=z){x.push(l[k&63]);break}$=j[E++]&255,k|=$>>6&3,x.push(l[k&63]),x.push(l[$&63])}return x.join("")}function m(j,z){var E=0,x=j.length,k=0,$=[],L,X,G,ie,ce,H;if(z<=0)throw Error("Illegal len: "+z);for(;E<x-1&&k<z&&(H=j.charCodeAt(E++),L=H<u.length?u[H]:-1,H=j.charCodeAt(E++),X=H<u.length?u[H]:-1,!(L==-1||X==-1||(ce=L<<2>>>0,ce|=(X&48)>>4,$.push(p(ce)),++k>=z||E>=x)||(H=j.charCodeAt(E++),G=H<u.length?u[H]:-1,G==-1)||(ce=(X&15)<<4>>>0,ce|=(G&60)>>2,$.push(p(ce)),++k>=z||E>=x)));)H=j.charCodeAt(E++),ie=H<u.length?u[H]:-1,ce=(G&3)<<6>>>0,ce|=ie,$.push(p(ce)),++k;var Ie=[];for(E=0;E<k;E++)Ie.push($[E].charCodeAt(0));return Ie}var v=function(){var j={};return j.MAX_CODEPOINT=1114111,j.encodeUTF8=function(z,E){var x=null;for(typeof z=="number"&&(x=z,z=function(){return null});x!==null||(x=z())!==null;)x<128?E(x&127):x<2048?(E(x>>6&31|192),E(x&63|128)):x<65536?(E(x>>12&15|224),E(x>>6&63|128),E(x&63|128)):(E(x>>18&7|240),E(x>>12&63|128),E(x>>6&63|128),E(x&63|128)),x=null},j.decodeUTF8=function(z,E){for(var x,k,$,L,X=function(G){G=G.slice(0,G.indexOf(null));var ie=Error(G.toString());throw ie.name="TruncatedError",ie.bytes=G,ie};(x=z())!==null;)if(!(x&128))E(x);else if((x&224)===192)(k=z())===null&&X([x,k]),E((x&31)<<6|k&63);else if((x&240)===224)((k=z())===null||($=z())===null)&&X([x,k,$]),E((x&15)<<12|(k&63)<<6|$&63);else if((x&248)===240)((k=z())===null||($=z())===null||(L=z())===null)&&X([x,k,$,L]),E((x&7)<<18|(k&63)<<12|($&63)<<6|L&63);else throw RangeError("Illegal starting byte: "+x)},j.UTF16toUTF8=function(z,E){for(var x,k=null;(x=k!==null?k:z())!==null;){if(x>=55296&&x<=57343&&(k=z())!==null&&k>=56320&&k<=57343){E((x-55296)*1024+k-56320+65536),k=null;continue}E(x)}k!==null&&E(k)},j.UTF8toUTF16=function(z,E){var x=null;for(typeof z=="number"&&(x=z,z=function(){return null});x!==null||(x=z())!==null;)x<=65535?E(x):(x-=65536,E((x>>10)+55296),E(x%1024+56320)),x=null},j.encodeUTF16toUTF8=function(z,E){j.UTF16toUTF8(z,function(x){j.encodeUTF8(x,E)})},j.decodeUTF8toUTF16=function(z,E){j.decodeUTF8(z,function(x){j.UTF8toUTF16(x,E)})},j.calculateCodePoint=function(z){return z<128?1:z<2048?2:z<65536?3:4},j.calculateUTF8=function(z){for(var E,x=0;(E=z())!==null;)x+=j.calculateCodePoint(E);return x},j.calculateUTF16asUTF8=function(z){var E=0,x=0;return j.UTF16toUTF8(z,function(k){++E,x+=j.calculateCodePoint(k)}),[E,x]},j}();Date.now=Date.now||function(){return+new Date};var f=16,_=10,w=16,S=100,C=[608135816,2242054355,320440878,57701188,2752067618,698298832,137296536,3964562569,1160258022,953160567,3193202383,887688300,3232508343,3380367581,1065670069,3041331479,2450970073,2306472731],B=[3509652390,2564797868,805139163,3491422135,3101798381,1780907670,3128725573,4046225305,614570311,3012652279,134345442,2240740374,1667834072,1901547113,2757295779,4103290238,227898511,1921955416,1904987480,2182433518,2069144605,3260701109,2620446009,720527379,3318853667,677414384,3393288472,3101374703,2390351024,1614419982,1822297739,2954791486,3608508353,3174124327,2024746970,1432378464,3864339955,2857741204,1464375394,1676153920,1439316330,715854006,3033291828,289532110,2706671279,2087905683,3018724369,1668267050,732546397,1947742710,3462151702,2609353502,2950085171,1814351708,2050118529,680887927,999245976,1800124847,3300911131,1713906067,1641548236,4213287313,1216130144,1575780402,4018429277,3917837745,3693486850,3949271944,596196993,3549867205,258830323,2213823033,772490370,2760122372,1774776394,2652871518,566650946,4142492826,1728879713,2882767088,1783734482,3629395816,2517608232,2874225571,1861159788,326777828,3124490320,2130389656,2716951837,967770486,1724537150,2185432712,2364442137,1164943284,2105845187,998989502,3765401048,2244026483,1075463327,1455516326,1322494562,910128902,469688178,1117454909,936433444,3490320968,3675253459,1240580251,122909385,2157517691,634681816,4142456567,3825094682,3061402683,2540495037,79693498,3249098678,1084186820,1583128258,426386531,1761308591,1047286709,322548459,995290223,1845252383,2603652396,3431023940,2942221577,3202600964,3727903485,1712269319,422464435,3234572375,1170764815,3523960633,3117677531,1434042557,442511882,3600875718,1076654713,1738483198,4213154764,2393238008,3677496056,1014306527,4251020053,793779912,2902807211,842905082,4246964064,1395751752,1040244610,2656851899,3396308128,445077038,3742853595,3577915638,679411651,2892444358,2354009459,1767581616,3150600392,3791627101,3102740896,284835224,4246832056,1258075500,768725851,2589189241,3069724005,3532540348,1274779536,3789419226,2764799539,1660621633,3471099624,4011903706,913787905,3497959166,737222580,2514213453,2928710040,3937242737,1804850592,3499020752,2949064160,2386320175,2390070455,2415321851,4061277028,2290661394,2416832540,1336762016,1754252060,3520065937,3014181293,791618072,3188594551,3933548030,2332172193,3852520463,3043980520,413987798,3465142937,3030929376,4245938359,2093235073,3534596313,375366246,2157278981,2479649556,555357303,3870105701,2008414854,3344188149,4221384143,3956125452,2067696032,3594591187,2921233993,2428461,544322398,577241275,1471733935,610547355,4027169054,1432588573,1507829418,2025931657,3646575487,545086370,48609733,2200306550,1653985193,298326376,1316178497,3007786442,2064951626,458293330,2589141269,3591329599,3164325604,727753846,2179363840,146436021,1461446943,4069977195,705550613,3059967265,3887724982,4281599278,3313849956,1404054877,2845806497,146425753,1854211946,1266315497,3048417604,3681880366,3289982499,290971e4,1235738493,2632868024,2414719590,3970600049,1771706367,1449415276,3266420449,422970021,1963543593,2690192192,3826793022,1062508698,1531092325,1804592342,2583117782,2714934279,4024971509,1294809318,4028980673,1289560198,2221992742,1669523910,35572830,157838143,1052438473,1016535060,1802137761,1753167236,1386275462,3080475397,2857371447,1040679964,2145300060,2390574316,1461121720,2956646967,4031777805,4028374788,33600511,2920084762,1018524850,629373528,3691585981,3515945977,2091462646,2486323059,586499841,988145025,935516892,3367335476,2599673255,2839830854,265290510,3972581182,2759138881,3795373465,1005194799,847297441,406762289,1314163512,1332590856,1866599683,4127851711,750260880,613907577,1450815602,3165620655,3734664991,3650291728,3012275730,3704569646,1427272223,778793252,1343938022,2676280711,2052605720,1946737175,3164576444,3914038668,3967478842,3682934266,1661551462,3294938066,4011595847,840292616,3712170807,616741398,312560963,711312465,1351876610,322626781,1910503582,271666773,2175563734,1594956187,70604529,3617834859,1007753275,1495573769,4069517037,2549218298,2663038764,504708206,2263041392,3941167025,2249088522,1514023603,1998579484,1312622330,694541497,2582060303,2151582166,1382467621,776784248,2618340202,3323268794,2497899128,2784771155,503983604,4076293799,907881277,423175695,432175456,1378068232,4145222326,3954048622,3938656102,3820766613,2793130115,2977904593,26017576,3274890735,3194772133,1700274565,1756076034,4006520079,3677328699,720338349,1533947780,354530856,688349552,3973924725,1637815568,332179504,3949051286,53804574,2852348879,3044236432,1282449977,3583942155,3416972820,4006381244,1617046695,2628476075,3002303598,1686838959,431878346,2686675385,1700445008,1080580658,1009431731,832498133,3223435511,2605976345,2271191193,2516031870,1648197032,4164389018,2548247927,300782431,375919233,238389289,3353747414,2531188641,2019080857,1475708069,455242339,2609103871,448939670,3451063019,1395535956,2413381860,1841049896,1491858159,885456874,4264095073,4001119347,1565136089,3898914787,1108368660,540939232,1173283510,2745871338,3681308437,4207628240,3343053890,4016749493,1699691293,1103962373,3625875870,2256883143,3830138730,1031889488,3479347698,1535977030,4236805024,3251091107,2132092099,1774941330,1199868427,1452454533,157007616,2904115357,342012276,595725824,1480756522,206960106,497939518,591360097,863170706,2375253569,3596610801,1814182875,2094937945,3421402208,1082520231,3463918190,2785509508,435703966,3908032597,1641649973,2842273706,3305899714,1510255612,2148256476,2655287854,3276092548,4258621189,236887753,3681803219,274041037,1734335097,3815195456,3317970021,1899903192,1026095262,4050517792,356393447,2410691914,3873677099,3682840055,3913112168,2491498743,4132185628,2489919796,1091903735,1979897079,3170134830,3567386728,3557303409,857797738,1136121015,1342202287,507115054,2535736646,337727348,3213592640,1301675037,2528481711,1895095763,1721773893,3216771564,62756741,2142006736,835421444,2531993523,1442658625,3659876326,2882144922,676362277,1392781812,170690266,3921047035,1759253602,3611846912,1745797284,664899054,1329594018,3901205900,3045908486,2062866102,2865634940,3543621612,3464012697,1080764994,553557557,3656615353,3996768171,991055499,499776247,1265440854,648242737,3940784050,980351604,3713745714,1749149687,3396870395,4211799374,3640570775,1161844396,3125318951,1431517754,545492359,4268468663,3499529547,1437099964,2702547544,3433638243,2581715763,2787789398,1060185593,1593081372,2418618748,4260947970,69676912,2159744348,86519011,2512459080,3838209314,1220612927,3339683548,133810670,1090789135,1078426020,1569222167,845107691,3583754449,4072456591,1091646820,628848692,1613405280,3757631651,526609435,236106946,48312990,2942717905,3402727701,1797494240,859738849,992217954,4005476642,2243076622,3870952857,3732016268,765654824,3490871365,2511836413,1685915746,3888969200,1414112111,2273134842,3281911079,4080962846,172450625,2569994100,980381355,4109958455,2819808352,2716589560,2568741196,3681446669,3329971472,1835478071,660984891,3704678404,4045999559,3422617507,3040415634,1762651403,1719377915,3470491036,2693910283,3642056355,3138596744,1364962596,2073328063,1983633131,926494387,3423689081,2150032023,4096667949,1749200295,3328846651,309677260,2016342300,1779581495,3079819751,111262694,1274766160,443224088,298511866,1025883608,3806446537,1145181785,168956806,3641502830,3584813610,1689216846,3666258015,3200248200,1692713982,2646376535,4042768518,1618508792,1610833997,3523052358,4130873264,2001055236,3610705100,2202168115,4028541809,2961195399,1006657119,2006996926,3186142756,1430667929,3210227297,1314452623,4074634658,4101304120,2273951170,1399257539,3367210612,3027628629,1190975929,2062231137,2333990788,2221543033,2438960610,1181637006,548689776,2362791313,3372408396,3104550113,3145860560,296247880,1970579870,3078560182,3769228297,1714227617,3291629107,3898220290,166772364,1251581989,493813264,448347421,195405023,2709975567,677966185,3703036547,1463355134,2715995803,1338867538,1343315457,2802222074,2684532164,233230375,2599980071,2000651841,3277868038,1638401717,4028070440,3237316320,6314154,819756386,300326615,590932579,1405279636,3267499572,3150704214,2428286686,3959192993,3461946742,1862657033,1266418056,963775037,2089974820,2263052895,1917689273,448879540,3550394620,3981727096,150775221,3627908307,1303187396,508620638,2975983352,2726630617,1817252668,1876281319,1457606340,908771278,3720792119,3617206836,2455994898,1729034894,1080033504,976866871,3556439503,2881648439,1522871579,1555064734,1336096578,3548522304,2579274686,3574697629,3205460757,3593280638,3338716283,3079412587,564236357,2993598910,1781952180,1464380207,3163844217,3332601554,1699332808,1393555694,1183702653,3581086237,1288719814,691649499,2847557200,2895455976,3193889540,2717570544,1781354906,1676643554,2592534050,3230253752,1126444790,2770207658,2633158820,2210423226,2615765581,2414155088,3127139286,673620729,2805611233,1269405062,4015350505,3341807571,4149409754,1057255273,2012875353,2162469141,2276492801,2601117357,993977747,3918593370,2654263191,753973209,36408145,2530585658,25011837,3520020182,2088578344,530523599,2918365339,1524020338,1518925132,3760827505,3759777254,1202760957,3985898139,3906192525,674977740,4174734889,2031300136,2019492241,3983892565,4153806404,3822280332,352677332,2297720250,60907813,90501309,3286998549,1016092578,2535922412,2839152426,457141659,509813237,4120667899,652014361,1966332200,2975202805,55981186,2327461051,676427537,3255491064,2882294119,3433927263,1307055953,942726286,933058658,2468411793,3933900994,4215176142,1361170020,2001714738,2830558078,3274259782,1222529897,1679025792,2729314320,3714953764,1770335741,151462246,3013232138,1682292957,1483529935,471910574,1539241949,458788160,3436315007,1807016891,3718408830,978976581,1043663428,3165965781,1927990952,4200891579,2372276910,3208408903,3533431907,1412390302,2931980059,4132332400,1947078029,3881505623,4168226417,2941484381,1077988104,1320477388,886195818,18198404,3786409e3,2509781533,112762804,3463356488,1866414978,891333506,18488651,661792760,1628790961,3885187036,3141171499,876946877,2693282273,1372485963,791857591,2686433993,3759982718,3167212022,3472953795,2716379847,445679433,3561995674,3504004811,3574258232,54117162,3331405415,2381918588,3769707343,4154350007,1140177722,4074052095,668550556,3214352940,367459370,261225585,2610173221,4209349473,3468074219,3265815641,314222801,3066103646,3808782860,282218597,3406013506,3773591054,379116347,1285071038,846784868,2669647154,3771962079,3550491691,2305946142,453669953,1268987020,3317592352,3279303384,3744833421,2610507566,3859509063,266596637,3847019092,517658769,3462560207,3443424879,370717030,4247526661,2224018117,4143653529,4112773975,2788324899,2477274417,1456262402,2901442914,1517677493,1846949527,2295493580,3734397586,2176403920,1280348187,1908823572,3871786941,846861322,1172426758,3287448474,3383383037,1655181056,3139813346,901632758,1897031941,2986607138,3066810236,3447102507,1393639104,373351379,950779232,625454576,3124240540,4148612726,2007998917,544563296,2244738638,2330496472,2058025392,1291430526,424198748,50039436,29584100,3605783033,2429876329,2791104160,1057563949,3255363231,3075367218,3463963227,1469046755,985887462],R=[1332899944,1700884034,1701343084,1684370003,1668446532,1869963892];function te(j,z,E,x){var k,$=j[z],L=j[z+1];return $^=E[0],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[1],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[2],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[3],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[4],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[5],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[6],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[7],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[8],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[9],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[10],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[11],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[12],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[13],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[14],k=x[$>>>24],k+=x[256|$>>16&255],k^=x[512|$>>8&255],k+=x[768|$&255],L^=k^E[15],k=x[L>>>24],k+=x[256|L>>16&255],k^=x[512|L>>8&255],k+=x[768|L&255],$^=k^E[16],j[z]=L^E[w+1],j[z+1]=$,j}function fe(j,z){for(var E=0,x=0;E<4;++E)x=x<<8|j[z]&255,z=(z+1)%j.length;return{key:x,offp:z}}function le(j,z,E){for(var x=0,k=[0,0],$=z.length,L=E.length,X,G=0;G<$;G++)X=fe(j,x),x=X.offp,z[G]=z[G]^X.key;for(G=0;G<$;G+=2)k=te(k,0,z,E),z[G]=k[0],z[G+1]=k[1];for(G=0;G<L;G+=2)k=te(k,0,z,E),E[G]=k[0],E[G+1]=k[1]}function Ue(j,z,E,x){for(var k=0,$=[0,0],L=E.length,X=x.length,G,ie=0;ie<L;ie++)G=fe(z,k),k=G.offp,E[ie]=E[ie]^G.key;for(k=0,ie=0;ie<L;ie+=2)G=fe(j,k),k=G.offp,$[0]^=G.key,G=fe(j,k),k=G.offp,$[1]^=G.key,$=te($,0,E,x),E[ie]=$[0],E[ie+1]=$[1];for(ie=0;ie<X;ie+=2)G=fe(j,k),k=G.offp,$[0]^=G.key,G=fe(j,k),k=G.offp,$[1]^=G.key,$=te($,0,E,x),x[ie]=$[0],x[ie+1]=$[1]}function at(j,z,E,x,k){var $=R.slice(),L=$.length,X;if(E<4||E>31)if(X=Error("Illegal number of rounds (4-31): "+E),x){o(x.bind(this,X));return}else throw X;if(z.length!==f)if(X=Error("Illegal salt length: "+z.length+" != "+f),x){o(x.bind(this,X));return}else throw X;E=1<<E>>>0;var G,ie,ce=0,H;Int32Array?(G=new Int32Array(C),ie=new Int32Array(B)):(G=C.slice(),ie=B.slice()),Ue(z,j,G,ie);function Ie(){if(k&&k(ce/E),ce<E)for(var he=Date.now();ce<E&&(ce=ce+1,le(j,G,ie),le(z,G,ie),!(Date.now()-he>S)););else{for(ce=0;ce<64;ce++)for(H=0;H<L>>1;H++)te($,H<<1,G,ie);var xe=[];for(ce=0;ce<L;ce++)xe.push(($[ce]>>24&255)>>>0),xe.push(($[ce]>>16&255)>>>0),xe.push(($[ce]>>8&255)>>>0),xe.push(($[ce]&255)>>>0);if(x){x(null,xe);return}else return xe}x&&o(Ie)}if(typeof x<"u")Ie();else for(var ln;;)if(typeof(ln=Ie())<"u")return ln||[]}function Ge(j,z,E,x){var k;if(typeof j!="string"||typeof z!="string")if(k=Error("Invalid string / salt: Not a string"),E){o(E.bind(this,k));return}else throw k;var $,L;if(z.charAt(0)!=="$"||z.charAt(1)!=="2")if(k=Error("Invalid salt version: "+z.substring(0,2)),E){o(E.bind(this,k));return}else throw k;if(z.charAt(2)==="$")$="\0",L=3;else{if($=z.charAt(2),$!=="a"&&$!=="b"&&$!=="y"||z.charAt(3)!=="$")if(k=Error("Invalid salt revision: "+z.substring(2,4)),E){o(E.bind(this,k));return}else throw k;L=4}if(z.charAt(L+2)>"$")if(k=Error("Missing salt rounds"),E){o(E.bind(this,k));return}else throw k;var X=parseInt(z.substring(L,L+1),10)*10,G=parseInt(z.substring(L+1,L+2),10),ie=X+G,ce=z.substring(L+3,L+25);j+=$>="a"?"\0":"";var H=c(j),Ie=m(ce,f);function ln(he){var xe=[];return xe.push("$2"),$>="a"&&xe.push($),xe.push("$"),ie<10&&xe.push("0"),xe.push(ie.toString()),xe.push("$"),xe.push(h(Ie,Ie.length)),xe.push(h(he,R.length*4-1)),xe.join("")}if(typeof E>"u")return ln(at(H,Ie,ie));at(H,Ie,ie,function(he,xe){he?E(he,null):E(null,ln(xe))},x)}return e.encodeBase64=h,e.decodeBase64=m,e})})(kf);var s_=kf.exports;const ii=bf(s_),o_="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let a_=t=>crypto.getRandomValues(new Uint8Array(t)),c_=(t,e,n)=>{let r=(2<<Math.log2(t.length-1))-1,i=-~(1.6*r*e/t.length);return(s=e)=>{let o="";for(;;){let c=n(i),l=i;for(;l--;)if(o+=t[c[l]&r]||"",o.length===s)return o}}},l_=(t,e=21)=>c_(t,e,a_),qe=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t));for(;t--;)e+=o_[n[t]&63];return e};const u_=24;function Ys(){return l_("0123456789abcdef",u_)()}function Tu(t){if(!t.includes("|"))return console.error("Invalid user_id format"),t;const[,e]=t.split("|");return e}function d_(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await to({userAdapter:t.users,tenant_id:e,email:n.email});return r?(await t.users.create(e,{...n,linked_to:r.user_id}),r):t.users.create(e,n)}}function be(t,e){return{type:e.type,description:e.description||"",ip:t.req.header("x-real-ip")||"",user_agent:t.req.header("user-agent")||"",date:new Date().toISOString(),details:{request:{method:t.req.method,path:t.req.path,qs:t.req.queries(),body:e.body||t.var.body||""}},isMobile:!1,client_id:t.var.client_id,client_name:"",user_id:e.userId||t.var.user_id||"",hostname:t.req.header("host")||"",user_name:t.var.username||"",connection_id:"",connection:t.var.connection||"",strategy:e.strategy||"",strategy_type:e.strategy_type||"",audience:"",scope:[]}}class il{constructor(e,n){ee(this,"value");ee(this,"unit");this.value=e,this.unit=n}milliseconds(){return this.unit==="ms"?this.value:this.unit==="s"?this.value*1e3:this.unit==="m"?this.value*1e3*60:this.unit==="h"?this.value*1e3*60*60:this.unit==="d"?this.value*1e3*60*60*24:this.value*1e3*60*60*24*7}seconds(){return this.milliseconds()/1e3}transform(e){return new il(Math.round(this.milliseconds()*e),"ms")}}class p_{constructor(e){ee(this,"hash");this.hash=e}async verify(e,n,r){const i=await crypto.subtle.importKey("spki",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["verify"]);return await crypto.subtle.verify("RSASSA-PKCS1-v1_5",i,n,r)}async sign(e,n){const r=await crypto.subtle.importKey("pkcs8",e,{name:"RSASSA-PKCS1-v1_5",hash:this.hash},!1,["sign"]);return await crypto.subtle.sign("RSASSA-PKCS1-v1_5",r,n)}async generateKeyPair(e){const n=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",hash:this.hash,modulusLength:e??2048,publicExponent:new Uint8Array([1,0,1])},!0,["sign"]),r=await crypto.subtle.exportKey("pkcs8",n.privateKey),i=await crypto.subtle.exportKey("spki",n.publicKey);return{privateKey:r,publicKey:i}}}async function xf(t){return await crypto.subtle.digest("SHA-256",t)}const Pu="0123456789abcdef";function Ia(t){const e=new Uint8Array(t);let n="";for(let r=0;r<e.length;r++){const i=e[r]>>4;n+=Pu[i];const s=e[r]&15;n+=Pu[s]}return n}class Sf{constructor(e,n){ee(this,"alphabet");ee(this,"padding");ee(this,"decodeMap",new Map);if(e.length!==32)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=(n==null?void 0:n.padding)??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[c],s+=8;s>=5;)s-=5,r+=this.alphabet[i>>s&31];if(s>0&&(r+=this.alphabet[i<<5-s&31]),(n==null?void 0:n.includePadding)??!0){const c=(8-r.length%8)%8;for(let l=0;l<c;l++)r+="="}return r}decode(e,n){const r=(n==null?void 0:n.strict)??!0,i=Math.ceil(e.length/8),s=[];for(let o=0;o<i;o++){let c=0;const l=[];for(let p=0;p<8;p++){const h=e[o*8+p];if(h==="="){if(o+1!==i)throw new Error(`Invalid character: ${h}`);c+=1;continue}if(h===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const m=this.decodeMap.get(h)??null;if(m===null)throw new Error(`Invalid character: ${h}`);l.push(m)}if(c===8||c===7||c===5||c===2)throw new Error("Invalid padding");const u=(l[0]<<3)+(l[1]>>2);if(s.push(u),c<6){const p=((l[1]&3)<<6)+(l[2]<<1)+(l[3]>>4);s.push(p)}if(c<4){const p=((l[3]&255)<<4)+(l[4]>>1);s.push(p)}if(c<3){const p=((l[4]&1)<<7)+(l[5]<<2)+(l[6]>>3);s.push(p)}if(c<1){const p=((l[6]&7)<<5)+l[7];s.push(p)}}return Uint8Array.from(s)}}new Sf("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567");new Sf("0123456789ABCDEFGHIJKLMNOPQRSTUV");class Af{constructor(e,n){ee(this,"alphabet");ee(this,"padding");ee(this,"decodeMap",new Map);if(e.length!==64)throw new Error("Invalid alphabet");if(this.alphabet=e,this.padding=(n==null?void 0:n.padding)??"=",this.alphabet.includes(this.padding)||this.padding.length!==1)throw new Error("Invalid padding");for(let r=0;r<e.length;r++)this.decodeMap.set(e[r],r)}encode(e,n){let r="",i=0,s=0;for(let c=0;c<e.length;c++)for(i=i<<8|e[c],s+=8;s>=6;)s+=-6,r+=this.alphabet[i>>s&63];if(s>0&&(r+=this.alphabet[i<<6-s&63]),(n==null?void 0:n.includePadding)??!0){const c=(4-r.length%4)%4;for(let l=0;l<c;l++)r+="="}return r}decode(e,n){const r=(n==null?void 0:n.strict)??!0,i=Math.ceil(e.length/4),s=[];for(let o=0;o<i;o++){let c=0,l=0;for(let u=0;u<4;u++){const p=e[o*4+u];if(p==="="){if(o+1!==i)throw new Error(`Invalid character: ${p}`);c+=1;continue}if(p===void 0){if(r)throw new Error("Invalid data");c+=1;continue}const h=this.decodeMap.get(p)??null;if(h===null)throw new Error(`Invalid character: ${p}`);l+=h<<6*(3-u)}s.push(l>>16&255),c<2&&s.push(l>>8&255),c<1&&s.push(l&255)}return Uint8Array.from(s)}}const f_=new Af("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),mn=new Af("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");async function Ru(t,e,n,r){const i={alg:t,typ:"JWT",...r==null?void 0:r.headers},s={...n};(r==null?void 0:r.audiences)!==void 0&&(s.aud=r.audiences),(r==null?void 0:r.subject)!==void 0&&(s.sub=r.subject),(r==null?void 0:r.issuer)!==void 0&&(s.iss=r.issuer),(r==null?void 0:r.jwtId)!==void 0&&(s.jti=r.jwtId),(r==null?void 0:r.expiresIn)!==void 0&&(s.exp=Math.floor(Date.now()/1e3)+r.expiresIn.seconds()),(r==null?void 0:r.notBefore)!==void 0&&(s.nbf=Math.floor(r.notBefore.getTime()/1e3)),s.iat=Math.floor(Date.now()/1e3);const o=new TextEncoder,c=mn.encode(o.encode(JSON.stringify(i)),{includePadding:!1}),l=mn.encode(o.encode(JSON.stringify(s)),{includePadding:!1}),u=o.encode([c,l].join(".")),p=await g_(t).sign(e,u),h=mn.encode(new Uint8Array(p),{includePadding:!1});return[c,l,h].join(".")}function h_(t){const e=t.split(".");return e.length!==3?null:e}function sl(t){const e=h_(t);if(!e)return null;const n=new TextDecoder,r=mn.decode(e[0],{strict:!1}),i=mn.decode(e[1],{strict:!1}),s=JSON.parse(n.decode(r));if(typeof s!="object"||s===null||!("alg"in s)||!m_(s.alg)||"typ"in s&&s.typ!=="JWT")return null;const o=JSON.parse(n.decode(i));if(typeof o!="object"||o===null)return null;const c={algorithm:s.alg,expiresAt:null,subject:null,issuedAt:null,issuer:null,jwtId:null,audiences:null,notBefore:null};if("exp"in o){if(typeof o.exp!="number")return null;c.expiresAt=new Date(o.exp*1e3)}if("iss"in o){if(typeof o.iss!="string")return null;c.issuer=o.iss}if("sub"in o){if(typeof o.sub!="string")return null;c.subject=o.sub}if("aud"in o)if(Array.isArray(o.aud)){for(const l of o.aud)if(typeof l!="string")return null;c.audiences=o.aud}else{if(typeof o.aud!="string")return null;c.audiences=[o.aud]}if("nbf"in o){if(typeof o.nbf!="number")return null;c.notBefore=new Date(o.nbf*1e3)}if("iat"in o){if(typeof o.iat!="number")return null;c.issuedAt=new Date(o.iat*1e3)}if("jti"in o){if(typeof o.jti!="string")return null;c.jwtId=o.jti}return{value:t,header:{...s,typ:"JWT",alg:s.alg},payload:{...o},parts:e,...c}}function g_(t){return new p_(__[t])}function m_(t){return typeof t!="string"?!1:["HS256","HS384","HS512","RS256","RS384","RS512","ES256","ES384","ES512","PS256","PS384","PS512"].includes(t)}const __={RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"};function y_(){const t=new Uint8Array(32);return crypto.getRandomValues(t),mn.encode(t,{includePadding:!1})}function v_(t){try{const n=/-----BEGIN (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----([^-]*)-----END (?:RSA )?(?:PRIVATE|PUBLIC) KEY-----/.exec(t);if(!n||!n[1])throw new Error("Invalid PEM format");return Uint8Array.from(atob(n[1].replace(/\s/g,"")),r=>r.charCodeAt(0)).buffer}finally{t=t.replace(/./g,"\0")}}async function w_(t,e){if(e==="plain")return t;const n=new TextEncoder().encode(t),r=await xf(n);return mn.encode(new Uint8Array(r),{includePadding:!1})}const Ni=60*5,Xs=30*24*60*60,Ur=24*60*60,b_="auth-token",za=30*60*1e3,k_=5*60,x_=5*60,S_=30*60*1e3,A_=30*60*1e3,E_=24*60*60*1e3;function Ef(t,e,n){const r=[];return r.push([encodeURIComponent(t),encodeURIComponent(e)]),(n==null?void 0:n.domain)!==void 0&&r.push(["Domain",n.domain]),(n==null?void 0:n.expires)!==void 0&&r.push(["Expires",n.expires.toUTCString()]),n!=null&&n.httpOnly&&r.push(["HttpOnly"]),(n==null?void 0:n.maxAge)!==void 0&&r.push(["Max-Age",n.maxAge.toString()]),(n==null?void 0:n.path)!==void 0&&r.push(["Path",n.path]),(n==null?void 0:n.sameSite)==="lax"&&r.push(["SameSite","Lax"]),(n==null?void 0:n.sameSite)==="none"&&r.push(["SameSite","None"]),(n==null?void 0:n.sameSite)==="strict"&&r.push(["SameSite","Strict"]),n!=null&&n.secure&&r.push(["Secure"]),r.map(i=>i.join("=")).join("; ")}function I_(t){const e=new Map,n=t.split("; ");for(const r of n){const i=r.split("="),s=i[0],o=i[1]??"";s&&e.set(decodeURIComponent(s),decodeURIComponent(o))}return e}function ol(t){return`${t}-${b_}`}function as(t,e){return e?I_(e).get(ol(t)):void 0}function z_(t){const e={path:"/",httpOnly:!0,secure:!0,maxAge:0};return Ef(ol(t),"",{...e,sameSite:"none"})}function If(t,e){const n={path:"/",httpOnly:!0,secure:!0,maxAge:Xs};return Ef(ol(t),e,{...n,sameSite:"none"})}var al={},Qs={};(function(t){const e=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",n=e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",r="["+e+"]["+n+"]*",i=new RegExp("^"+r+"$"),s=function(c,l){const u=[];let p=l.exec(c);for(;p;){const h=[];h.startIndex=l.lastIndex-p[0].length;const m=p.length;for(let v=0;v<m;v++)h.push(p[v]);u.push(h),p=l.exec(c)}return u},o=function(c){const l=i.exec(c);return!(l===null||typeof l>"u")};t.isExist=function(c){return typeof c<"u"},t.isEmptyObject=function(c){return Object.keys(c).length===0},t.merge=function(c,l,u){if(l){const p=Object.keys(l),h=p.length;for(let m=0;m<h;m++)u==="strict"?c[p[m]]=[l[p[m]]]:c[p[m]]=l[p[m]]}},t.getValue=function(c){return t.isExist(c)?c:""},t.isName=o,t.getAllMatches=s,t.nameRegexp=r})(Qs);const cl=Qs,C_={allowBooleanAttributes:!1,unpairedTags:[]};al.validate=function(t,e){e=Object.assign({},C_,e);const n=[];let r=!1,i=!1;t[0]==="\uFEFF"&&(t=t.substr(1));for(let s=0;s<t.length;s++)if(t[s]==="<"&&t[s+1]==="?"){if(s+=2,s=Uu(t,s),s.err)return s}else if(t[s]==="<"){let o=s;if(s++,t[s]==="!"){s=Vu(t,s);continue}else{let c=!1;t[s]==="/"&&(c=!0,s++);let l="";for(;s<t.length&&t[s]!==">"&&t[s]!==" "&&t[s]!==" "&&t[s]!==`
6
6
  `&&t[s]!=="\r";s++)l+=t[s];if(l=l.trim(),l[l.length-1]==="/"&&(l=l.substring(0,l.length-1),s--),!R_(l)){let h;return l.trim().length===0?h="Invalid space after '<'.":h="Tag '"+l+"' is an invalid name.",we("InvalidTag",h,Pe(t,s))}const u=$_(t,s);if(u===!1)return we("InvalidAttr","Attributes for '"+l+"' have open quote.",Pe(t,s));let p=u.value;if(s=u.index,p[p.length-1]==="/"){const h=s-p.length;p=p.substring(0,p.length-1);const m=Mu(p,e);if(m===!0)r=!0;else return we(m.err.code,m.err.msg,Pe(t,h+m.err.line))}else if(c)if(u.tagClosed){if(p.trim().length>0)return we("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Pe(t,o));if(n.length===0)return we("InvalidTag","Closing tag '"+l+"' has not been opened.",Pe(t,o));{const h=n.pop();if(l!==h.tagName){let m=Pe(t,h.tagStartPos);return we("InvalidTag","Expected closing tag '"+h.tagName+"' (opened in line "+m.line+", col "+m.col+") instead of closing tag '"+l+"'.",Pe(t,o))}n.length==0&&(i=!0)}}else return we("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Pe(t,s));else{const h=Mu(p,e);if(h!==!0)return we(h.err.code,h.err.msg,Pe(t,s-p.length+h.err.line));if(i===!0)return we("InvalidXml","Multiple possible root nodes found.",Pe(t,s));e.unpairedTags.indexOf(l)!==-1||n.push({tagName:l,tagStartPos:o}),r=!0}for(s++;s<t.length;s++)if(t[s]==="<")if(t[s+1]==="!"){s++,s=Vu(t,s);continue}else if(t[s+1]==="?"){if(s=Uu(t,++s),s.err)return s}else break;else if(t[s]==="&"){const h=T_(t,s);if(h==-1)return we("InvalidChar","char '&' is not expected.",Pe(t,s));s=h}else if(i===!0&&!Lu(t[s]))return we("InvalidXml","Extra text at the end",Pe(t,s));t[s]==="<"&&s--}}else{if(Lu(t[s]))continue;return we("InvalidChar","char '"+t[s]+"' is not expected.",Pe(t,s))}if(r){if(n.length==1)return we("InvalidTag","Unclosed tag '"+n[0].tagName+"'.",Pe(t,n[0].tagStartPos));if(n.length>0)return we("InvalidXml","Invalid '"+JSON.stringify(n.map(s=>s.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return we("InvalidXml","Start tag expected.",1);return!0};function Lu(t){return t===" "||t===" "||t===`
7
7
  `||t==="\r"}function Uu(t,e){const n=e;for(;e<t.length;e++)if(t[e]=="?"||t[e]==" "){const r=t.substr(n,e-n);if(e>5&&r==="xml")return we("InvalidXml","XML declaration allowed only at the start of the document.",Pe(t,e));if(t[e]=="?"&&t[e+1]==">"){e++;break}else continue}return e}function Vu(t,e){if(t.length>e+5&&t[e+1]==="-"&&t[e+2]==="-"){for(e+=3;e<t.length;e++)if(t[e]==="-"&&t[e+1]==="-"&&t[e+2]===">"){e+=2;break}}else if(t.length>e+8&&t[e+1]==="D"&&t[e+2]==="O"&&t[e+3]==="C"&&t[e+4]==="T"&&t[e+5]==="Y"&&t[e+6]==="P"&&t[e+7]==="E"){let n=1;for(e+=8;e<t.length;e++)if(t[e]==="<")n++;else if(t[e]===">"&&(n--,n===0))break}else if(t.length>e+9&&t[e+1]==="["&&t[e+2]==="C"&&t[e+3]==="D"&&t[e+4]==="A"&&t[e+5]==="T"&&t[e+6]==="A"&&t[e+7]==="["){for(e+=8;e<t.length;e++)if(t[e]==="]"&&t[e+1]==="]"&&t[e+2]===">"){e+=2;break}}return e}const N_='"',j_="'";function $_(t,e){let n="",r="",i=!1;for(;e<t.length;e++){if(t[e]===N_||t[e]===j_)r===""?r=t[e]:r!==t[e]||(r="");else if(t[e]===">"&&r===""){i=!0;break}n+=t[e]}return r!==""?!1:{value:n,index:e,tagClosed:i}}const O_=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function Mu(t,e){const n=cl.getAllMatches(t,O_),r={};for(let i=0;i<n.length;i++){if(n[i][1].length===0)return we("InvalidAttr","Attribute '"+n[i][2]+"' has no space in starting.",xr(n[i]));if(n[i][3]!==void 0&&n[i][4]===void 0)return we("InvalidAttr","Attribute '"+n[i][2]+"' is without value.",xr(n[i]));if(n[i][3]===void 0&&!e.allowBooleanAttributes)return we("InvalidAttr","boolean attribute '"+n[i][2]+"' is not allowed.",xr(n[i]));const s=n[i][2];if(!P_(s))return we("InvalidAttr","Attribute '"+s+"' is an invalid name.",xr(n[i]));if(!r.hasOwnProperty(s))r[s]=1;else return we("InvalidAttr","Attribute '"+s+"' is repeated.",xr(n[i]))}return!0}function B_(t,e){let n=/\d/;for(t[e]==="x"&&(e++,n=/[\da-fA-F]/);e<t.length;e++){if(t[e]===";")return e;if(!t[e].match(n))break}return-1}function T_(t,e){if(e++,t[e]===";")return-1;if(t[e]==="#")return e++,B_(t,e);let n=0;for(;e<t.length;e++,n++)if(!(t[e].match(/\w/)&&n<20)){if(t[e]===";")break;return-1}return e}function we(t,e,n){return{err:{code:t,msg:e,line:n.line||n,col:n.col}}}function P_(t){return cl.isName(t)}function R_(t){return cl.isName(t)}function Pe(t,e){const n=t.substring(0,e).split(/\r?\n/);return{line:n.length,col:n[n.length-1].length+1}}function xr(t){return t.startIndex+t[1].length}var ll={};const zf={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t}},L_=function(t){return Object.assign({},zf,t)};ll.buildOptions=L_;ll.defaultOptions=zf;class U_{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}add(e,n){e==="__proto__"&&(e="#__proto__"),this.child.push({[e]:n})}addChild(e){e.tagname==="__proto__"&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child})}}var V_=U_;const M_=Qs;function q_(t,e){const n={};if(t[e+3]==="O"&&t[e+4]==="C"&&t[e+5]==="T"&&t[e+6]==="Y"&&t[e+7]==="P"&&t[e+8]==="E"){e=e+9;let r=1,i=!1,s=!1,o="";for(;e<t.length;e++)if(t[e]==="<"&&!s){if(i&&F_(t,e)){e+=7;let c,l;[c,l,e]=D_(t,e+1),l.indexOf("&")===-1&&(n[J_(c)]={regx:RegExp(`&${c};`,"g"),val:l})}else if(i&&K_(t,e))e+=8;else if(i&&W_(t,e))e+=8;else if(i&&G_(t,e))e+=9;else if(H_)s=!0;else throw new Error("Invalid DOCTYPE");r++,o=""}else if(t[e]===">"){if(s?t[e-1]==="-"&&t[e-2]==="-"&&(s=!1,r--):r--,r===0)break}else t[e]==="["?i=!0:o+=t[e];if(r!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:n,i:e}}function D_(t,e){let n="";for(;e<t.length&&t[e]!=="'"&&t[e]!=='"';e++)n+=t[e];if(n=n.trim(),n.indexOf(" ")!==-1)throw new Error("External entites are not supported");const r=t[e++];let i="";for(;e<t.length&&t[e]!==r;e++)i+=t[e];return[n,i,e]}function H_(t,e){return t[e+1]==="!"&&t[e+2]==="-"&&t[e+3]==="-"}function F_(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="N"&&t[e+4]==="T"&&t[e+5]==="I"&&t[e+6]==="T"&&t[e+7]==="Y"}function K_(t,e){return t[e+1]==="!"&&t[e+2]==="E"&&t[e+3]==="L"&&t[e+4]==="E"&&t[e+5]==="M"&&t[e+6]==="E"&&t[e+7]==="N"&&t[e+8]==="T"}function W_(t,e){return t[e+1]==="!"&&t[e+2]==="A"&&t[e+3]==="T"&&t[e+4]==="T"&&t[e+5]==="L"&&t[e+6]==="I"&&t[e+7]==="S"&&t[e+8]==="T"}function G_(t,e){return t[e+1]==="!"&&t[e+2]==="N"&&t[e+3]==="O"&&t[e+4]==="T"&&t[e+5]==="A"&&t[e+6]==="T"&&t[e+7]==="I"&&t[e+8]==="O"&&t[e+9]==="N"}function J_(t){if(M_.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}var Z_=q_;const Y_=/^[-+]?0x[a-fA-F0-9]+$/,X_=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt);!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);const Q_={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function e0(t,e={}){if(e=Object.assign({},Q_,e),!t||typeof t!="string")return t;let n=t.trim();if(e.skipLike!==void 0&&e.skipLike.test(n))return t;if(e.hex&&Y_.test(n))return Number.parseInt(n,16);{const r=X_.exec(n);if(r){const i=r[1],s=r[2];let o=t0(r[3]);const c=r[4]||r[6];if(!e.leadingZeros&&s.length>0&&i&&n[2]!==".")return t;if(!e.leadingZeros&&s.length>0&&!i&&n[1]!==".")return t;{const l=Number(n),u=""+l;return u.search(/[eE]/)!==-1||c?e.eNotation?l:t:n.indexOf(".")!==-1?u==="0"&&o===""||u===o||i&&u==="-"+o?l:t:s?o===u||i+o===u?l:t:n===u||n===i+u?l:t}}else return t}}function t0(t){return t&&t.indexOf(".")!==-1&&(t=t.replace(/0+$/,""),t==="."?t="0":t[0]==="."?t="0"+t:t[t.length-1]==="."&&(t=t.substr(0,t.length-1))),t}var n0=e0;function r0(t){return typeof t=="function"?t:Array.isArray(t)?e=>{for(const n of t)if(typeof n=="string"&&e===n||n instanceof RegExp&&n.test(e))return!0}:()=>!1}var Cf=r0;const Nf=Qs,Sr=V_,i0=Z_,s0=n0,o0=Cf;let a0=class{constructor(e){this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(n,r)=>String.fromCharCode(Number.parseInt(r,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(n,r)=>String.fromCharCode(Number.parseInt(r,16))}},this.addExternalEntities=c0,this.parseXml=f0,this.parseTextData=l0,this.resolveNameSpace=u0,this.buildAttributesMap=p0,this.isItStopNode=_0,this.replaceEntitiesValue=g0,this.readStopNodeData=v0,this.saveTextToParentTag=m0,this.addChild=h0,this.ignoreAttributesFn=o0(this.options.ignoreAttributes)}};function c0(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];this.lastEntities[r]={regex:new RegExp("&"+r+";","g"),val:t[r]}}}function l0(t,e,n,r,i,s,o){if(t!==void 0&&(this.options.trimValues&&!r&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t));const c=this.options.tagValueProcessor(e,t,n,i,s);return c==null?t:typeof c!=typeof t||c!==t?c:this.options.trimValues?Na(t,this.options.parseTagValue,this.options.numberParseOptions):t.trim()===t?Na(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function u0(t){if(this.options.removeNSPrefix){const e=t.split(":"),n=t.charAt(0)==="/"?"/":"";if(e[0]==="xmlns")return"";e.length===2&&(t=n+e[1])}return t}const d0=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function p0(t,e,n){if(this.options.ignoreAttributes!==!0&&typeof t=="string"){const r=Nf.getAllMatches(t,d0),i=r.length,s={};for(let o=0;o<i;o++){const c=this.resolveNameSpace(r[o][1]);if(this.ignoreAttributesFn(c,e))continue;let l=r[o][4],u=this.options.attributeNamePrefix+c;if(c.length)if(this.options.transformAttributeName&&(u=this.options.transformAttributeName(u)),u==="__proto__"&&(u="#__proto__"),l!==void 0){this.options.trimValues&&(l=l.trim()),l=this.replaceEntitiesValue(l);const p=this.options.attributeValueProcessor(c,l,e);p==null?s[u]=l:typeof p!=typeof l||p!==l?s[u]=p:s[u]=Na(l,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(s[u]=!0)}if(!Object.keys(s).length)return;if(this.options.attributesGroupName){const o={};return o[this.options.attributesGroupName]=s,o}return s}}const f0=function(t){t=t.replace(/\r\n?/g,`
8
8
  `);const e=new Sr("!xml");let n=e,r="",i="";for(let s=0;s<t.length;s++)if(t[s]==="<")if(t[s+1]==="/"){const c=fn(t,">",s,"Closing Tag is not closed.");let l=t.substring(s+2,c).trim();if(this.options.removeNSPrefix){const h=l.indexOf(":");h!==-1&&(l=l.substr(h+1))}this.options.transformTagName&&(l=this.options.transformTagName(l)),n&&(r=this.saveTextToParentTag(r,n,i));const u=i.substring(i.lastIndexOf(".")+1);if(l&&this.options.unpairedTags.indexOf(l)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${l}>`);let p=0;u&&this.options.unpairedTags.indexOf(u)!==-1?(p=i.lastIndexOf(".",i.lastIndexOf(".")-1),this.tagsNodeStack.pop()):p=i.lastIndexOf("."),i=i.substring(0,p),n=this.tagsNodeStack.pop(),r="",s=c}else if(t[s+1]==="?"){let c=Ca(t,s,!1,"?>");if(!c)throw new Error("Pi Tag is not closed.");if(r=this.saveTextToParentTag(r,n,i),!(this.options.ignoreDeclaration&&c.tagName==="?xml"||this.options.ignorePiTags)){const l=new Sr(c.tagName);l.add(this.options.textNodeName,""),c.tagName!==c.tagExp&&c.attrExpPresent&&(l[":@"]=this.buildAttributesMap(c.tagExp,i,c.tagName)),this.addChild(n,l,i)}s=c.closeIndex+1}else if(t.substr(s+1,3)==="!--"){const c=fn(t,"-->",s+4,"Comment is not closed.");if(this.options.commentPropName){const l=t.substring(s+4,c-2);r=this.saveTextToParentTag(r,n,i),n.add(this.options.commentPropName,[{[this.options.textNodeName]:l}])}s=c}else if(t.substr(s+1,2)==="!D"){const c=i0(t,s);this.docTypeEntities=c.entities,s=c.i}else if(t.substr(s+1,2)==="!["){const c=fn(t,"]]>",s,"CDATA is not closed.")-2,l=t.substring(s+9,c);r=this.saveTextToParentTag(r,n,i);let u=this.parseTextData(l,n.tagname,i,!0,!1,!0,!0);u==null&&(u=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:l}]):n.add(this.options.textNodeName,u),s=c+2}else{let c=Ca(t,s,this.options.removeNSPrefix),l=c.tagName;const u=c.rawTagName;let p=c.tagExp,h=c.attrExpPresent,m=c.closeIndex;this.options.transformTagName&&(l=this.options.transformTagName(l)),n&&r&&n.tagname!=="!xml"&&(r=this.saveTextToParentTag(r,n,i,!1));const v=n;if(v&&this.options.unpairedTags.indexOf(v.tagname)!==-1&&(n=this.tagsNodeStack.pop(),i=i.substring(0,i.lastIndexOf("."))),l!==e.tagname&&(i+=i?"."+l:l),this.isItStopNode(this.options.stopNodes,i,l)){let f="";if(p.length>0&&p.lastIndexOf("/")===p.length-1)l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),p=l):p=p.substr(0,p.length-1),s=c.closeIndex;else if(this.options.unpairedTags.indexOf(l)!==-1)s=c.closeIndex;else{const w=this.readStopNodeData(t,u,m+1);if(!w)throw new Error(`Unexpected end of ${u}`);s=w.i,f=w.tagContent}const _=new Sr(l);l!==p&&h&&(_[":@"]=this.buildAttributesMap(p,i,l)),f&&(f=this.parseTextData(f,l,i,!0,h,!0,!0)),i=i.substr(0,i.lastIndexOf(".")),_.add(this.options.textNodeName,f),this.addChild(n,_,i)}else{if(p.length>0&&p.lastIndexOf("/")===p.length-1){l[l.length-1]==="/"?(l=l.substr(0,l.length-1),i=i.substr(0,i.length-1),p=l):p=p.substr(0,p.length-1),this.options.transformTagName&&(l=this.options.transformTagName(l));const f=new Sr(l);l!==p&&h&&(f[":@"]=this.buildAttributesMap(p,i,l)),this.addChild(n,f,i),i=i.substr(0,i.lastIndexOf("."))}else{const f=new Sr(l);this.tagsNodeStack.push(n),l!==p&&h&&(f[":@"]=this.buildAttributesMap(p,i,l)),this.addChild(n,f,i),n=f}r="",s=m}}else r+=t[s];return e.child};function h0(t,e,n){const r=this.options.updateTag(e.tagname,n,e[":@"]);r===!1||(typeof r=="string"&&(e.tagname=r),t.addChild(e))}const g0=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const n=this.docTypeEntities[e];t=t.replace(n.regx,n.val)}for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function m0(t,e,n,r){return t&&(r===void 0&&(r=Object.keys(e.child).length===0),t=this.parseTextData(t,e.tagname,n,!1,e[":@"]?Object.keys(e[":@"]).length!==0:!1,r),t!==void 0&&t!==""&&e.add(this.options.textNodeName,t),t=""),t}function _0(t,e,n){const r="*."+n;for(const i in t){const s=t[i];if(r===s||e===s)return!0}return!1}function y0(t,e,n=">"){let r,i="";for(let s=e;s<t.length;s++){let o=t[s];if(r)o===r&&(r="");else if(o==='"'||o==="'")r=o;else if(o===n[0])if(n[1]){if(t[s+1]===n[1])return{data:i,index:s}}else return{data:i,index:s};else o===" "&&(o=" ");i+=o}}function fn(t,e,n,r){const i=t.indexOf(e,n);if(i===-1)throw new Error(r);return i+e.length-1}function Ca(t,e,n,r=">"){const i=y0(t,e+1,r);if(!i)return;let s=i.data;const o=i.index,c=s.search(/\s/);let l=s,u=!0;c!==-1&&(l=s.substring(0,c),s=s.substring(c+1).trimStart());const p=l;if(n){const h=l.indexOf(":");h!==-1&&(l=l.substr(h+1),u=l!==i.data.substr(h+1))}return{tagName:l,tagExp:s,closeIndex:o,attrExpPresent:u,rawTagName:p}}function v0(t,e,n){const r=n;let i=1;for(;n<t.length;n++)if(t[n]==="<")if(t[n+1]==="/"){const s=fn(t,">",n,`${e} is not closed`);if(t.substring(n+2,s).trim()===e&&(i--,i===0))return{tagContent:t.substring(r,n),i:s};n=s}else if(t[n+1]==="?")n=fn(t,"?>",n+1,"StopNode is not closed.");else if(t.substr(n+1,3)==="!--")n=fn(t,"-->",n+3,"StopNode is not closed.");else if(t.substr(n+1,2)==="![")n=fn(t,"]]>",n,"StopNode is not closed.")-2;else{const s=Ca(t,n,">");s&&((s&&s.tagName)===e&&s.tagExp[s.tagExp.length-1]!=="/"&&i++,n=s.closeIndex)}}function Na(t,e,n){if(e&&typeof t=="string"){const r=t.trim();return r==="true"?!0:r==="false"?!1:s0(t,n)}else return Nf.isExist(t)?t:""}var w0=a0,jf={};function b0(t,e){return $f(t,e)}function $f(t,e,n){let r;const i={};for(let s=0;s<t.length;s++){const o=t[s],c=k0(o);let l="";if(n===void 0?l=c:l=n+"."+c,c===e.textNodeName)r===void 0?r=o[c]:r+=""+o[c];else{if(c===void 0)continue;if(o[c]){let u=$f(o[c],e,l);const p=S0(u,e);o[":@"]?x0(u,o[":@"],l,e):Object.keys(u).length===1&&u[e.textNodeName]!==void 0&&!e.alwaysCreateTextNode?u=u[e.textNodeName]:Object.keys(u).length===0&&(e.alwaysCreateTextNode?u[e.textNodeName]="":u=""),i[c]!==void 0&&i.hasOwnProperty(c)?(Array.isArray(i[c])||(i[c]=[i[c]]),i[c].push(u)):e.isArray(c,l,p)?i[c]=[u]:i[c]=u}}}return typeof r=="string"?r.length>0&&(i[e.textNodeName]=r):r!==void 0&&(i[e.textNodeName]=r),i}function k0(t){const e=Object.keys(t);for(let n=0;n<e.length;n++){const r=e[n];if(r!==":@")return r}}function x0(t,e,n,r){if(e){const i=Object.keys(e),s=i.length;for(let o=0;o<s;o++){const c=i[o];r.isArray(c,n+"."+c,!0,!0)?t[c]=[e[c]]:t[c]=e[c]}}}function S0(t,e){const{textNodeName:n}=e,r=Object.keys(t).length;return!!(r===0||r===1&&(t[n]||typeof t[n]=="boolean"||t[n]===0))}jf.prettify=b0;const{buildOptions:A0}=ll,E0=w0,{prettify:I0}=jf,z0=al;let C0=class{constructor(e){this.externalEntities={},this.options=A0(e)}parse(e,n){if(typeof e!="string")if(e.toString)e=e.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(n){n===!0&&(n={});const s=z0.validate(e,n);if(s!==!0)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}const r=new E0(this.options);r.addExternalEntities(this.externalEntities);const i=r.parseXml(e);return this.options.preserveOrder||i===void 0?i:I0(i,this.options)}addEntity(e,n){if(n.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(e.indexOf("&")!==-1||e.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(n==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=n}};var N0=C0;const j0=`
@@ -146,7 +146,7 @@ PERFORMANCE OF THIS SOFTWARE.
146
146
  `,i=0;for(;i<n.length;)i+64<=n.length?r+=n.substr(i,64)+`\r
147
147
  `:r+=n.substr(i)+`\r
148
148
  `,i+=64;return r+=`-----END ${t} KEY-----\r
149
- `,r}async function rw(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return Ia(await xf(s))}const iw=1e3*60*60*24,sw=new a.OpenAPIHono().openapi(a.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.array(Ea)}},description:"List of keys"}}}),async t=>{const n=(await t.env.data.keys.list()).filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(a.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({kid:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ea}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),r=(await t.env.data.keys.list()).find(i=>i.kid===e);if(!r)throw new N(404,{message:"Key not found"});return t.json(r)}).openapi(a.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const e=await t.env.data.keys.list();for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+iw).toISOString()});const n=await Gc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(n),t.text("OK",{status:201})}).openapi(a.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({kid:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new N(404,{message:"Key not found"});const r=await Gc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),ow=new a.OpenAPIHono().openapi(a.createRoute({tags:["users"],method:"get",path:"/",request:{query:a.z.object({email:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:a.z.array(Qc)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await Lf(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),aw=nn.extend({clients:a.z.array(pn)}),cw=new a.OpenAPIHono().openapi(a.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([aw,a.z.array(pn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:o}=t.req.valid("query"),l=(await t.env.data.applications.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o})).applications;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(a.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:pn}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=(await t.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(s=>s.id===n);if(!i)throw new N(404);return t.json(i)}).openapi(a.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.applications.remove(e,n))throw new N(404,{message:"Application not found"});return t.text("OK")}).openapi(a.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(ts.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:pn}},description:"The update application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.applications.update(e,n,i);const s=await t.env.data.applications.get(e,n);if(!s)throw new N(404,{message:"Application not found"});return t.json(s)}).openapi(a.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(ts.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:a.z.object(pn.shape)}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||qe(),client_secret:n.client_secret||qe()},i=await t.env.data.applications.create(e,r);return t.json(i,{status:201})});a.z.object({start:a.z.number(),limit:a.z.number(),length:a.z.number()});Gs.extend({email:a.z.string(),login_count:a.z.number(),multifactor:a.z.array(a.z.string()).optional(),last_ip:a.z.string().optional(),last_login:a.z.string().optional(),user_id:a.z.string()}).catchall(a.z.any());const lw=nn.extend({tenants:a.z.array(Hn)}),uw=new a.OpenAPIHono().openapi(a.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Yt},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:a.z.union([a.z.array(Hn),lw])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),o=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:cr(i),q:s});return r?t.json(o):t.json(o.tenants)}).openapi(a.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Hn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new N(404);return t.json(n)}).openapi(a.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(a.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(rs.shape).partial()}}},params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(a.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(rs.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Hn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),dw=nn.extend({logs:a.z.array(ss)}),pw=new a.OpenAPIHono().openapi(a.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(ss),dw])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":o}=t.req.valid("header"),c=await t.env.data.logs.list(o,{page:e,per_page:n,include_totals:r,sort:cr(i),q:s});return r?t.json(c):t.json(c.logs)}).openapi(a.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ss}},description:"A log entry"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.logs.get(e,n);if(!r)throw new N(404);return t.json(r)}),fw=nn.extend({hooks:a.z.array(qn)}),hw=new a.OpenAPIHono().openapi(a.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(qn),fw])}},description:"List of hooks"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:o}=t.req.valid("query"),c=await t.env.data.hooks.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o});return i?t.json(c):t.json(c.hooks)}).openapi(a.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(is.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:qn}},description:"The created hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.hooks.create(e,n);return t.json(r,{status:201})}).openapi(a.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()}),body:{content:{"application/json":{schema:a.z.object(is.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:qn.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=t.req.valid("json");await t.env.data.hooks.update(e,n,r);const i=await t.env.data.hooks.get(e,n);if(!i)throw new N(404,{message:"Hook not found"});return t.json(i)}).openapi(a.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:qn}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=await t.env.data.hooks.get(e,n);if(!r)throw new N(404,{message:"Hook not found"});return t.json(r)}).openapi(a.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param");if(!await t.env.data.hooks.remove(e,n))throw new N(404,{message:"Hook not found"});return t.text("OK")}),gw=nn.extend({connections:a.z.array(Dt)}),mw=new a.OpenAPIHono().openapi(a.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(Dt),gw])}},description:"List of connectionss"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:o}=t.req.valid("query"),c=await t.env.data.connections.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o});return i?t.json(c):t.json(c.connections)}).openapi(a.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Dt}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.connections.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.connections.remove(e,n))throw new N(404,{message:"Connection not found"});return t.text("OK")}).openapi(a.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(ns.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Dt}},description:"The updated connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.connections.update(e,n,r))throw new N(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new N(404,{message:"Connection not found"});return t.json(s)}).openapi(a.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(ns.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Dt}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.connections.create(e,n);return t.json(r,{status:201})}),_w=new a.OpenAPIHono().openapi(a.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ri}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Ri.parse({}))}).openapi(a.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Ri.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let wp=!1;function Cg(t){t.use(async(e,n)=>(wp||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),wp=!0),await n()))}a.z.object({alg:a.z.literal("RS256"),kty:a.z.literal("RSA"),use:a.z.literal("sig"),n:a.z.string(),e:a.z.string(),kid:a.z.string(),x5t:a.z.string(),x5c:a.z.array(a.z.string())});async function yw(t){try{const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new N(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function vw(t,e){const r=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),i=new Uint8Array(Array.from(e.signature).map(l=>l.charCodeAt(0))),o=(await yw(t.env)).find(l=>l.kid===e.header.kid);if(!o)return console.log("No matching kid found"),!1;const c=await crypto.subtle.importKey("jwk",o,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",c,i,r)}function ww(t){const[e,n,r]=t.split(".");if(!e||!n||!r)return null;const i=JSON.parse(atob(e)),s=JSON.parse(atob(n)),o=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return{header:i,payload:s,signature:o,raw:{header:e,payload:n,signature:r}}}function Ng(t){return async(e,n)=>{var i,s,o;const r=t.openAPIRegistry.definitions.find(c=>"route"in c&&c.route.path===e.req.path&&c.route.method.toUpperCase()===e.req.method);if(r&&"route"in r){const c=(s=(i=r.route.security)==null?void 0:i[0])==null?void 0:s.Bearer;if(!(c!=null&&c.length))return await n();const l=e.req.header("authorization")||"",[u,p]=l.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!p)throw new N(401,{message:"Missing bearer token"});const h=ww(p);if(!h||!await vw(e,h))throw new N(403,{message:"Invalid JWT signature"});e.set("user_id",h.payload.sub),e.set("user",h.payload);const m=h.payload.permissions||[],v=((o=h.payload.scope)==null?void 0:o.split(" "))||[];if(c.length&&!(c.some(f=>m.includes(f))||c.some(f=>v.includes(f))))throw new N(403,{message:"Unauthorized"})}return await n()}}const bw=new a.OpenAPIHono().openapi(a.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new N(404,{message:"Email provider not found"});return t.json(n)}).openapi(a.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Li.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(a.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),kw=new a.OpenAPIHono().openapi(a.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.sessions.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.remove(e,n))throw new N(404,{message:"Session not found"});return t.text("OK")}).openapi(a.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.update(e,n,{revoked_at:new Date().toDateString()}))throw new N(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),xw=new a.OpenAPIHono().openapi(a.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:rl}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.refreshTokens.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(e,n))throw new N(404,{message:"Session not found"});return t.text("OK")}),Sw=new a.OpenAPIHono().openapi(a.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.array(Mn)}},description:"List of custom domains"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.customDomains.list(e);return t.json(n)}).openapi(a.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.customDomains.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.customDomains.remove(e,n))throw new N(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(a.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(Mn.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"The updated custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.customDomains.update(e,n,r))throw new N(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new N(404);return t.json(s)}).openapi(a.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(tl.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Mn}},description:"The created custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.customDomains.create(e,n);return t.json(r,{status:201})});function Aw(){const t=new a.OpenAPIHono;Cg(t),t.use(Ng(t));const e=t.route("/branding",Qm).route("/custom-domains",Sw).route("/email/providers",bw).route("/users",ay).route("/keys",sw).route("/users-by-email",ow).route("/clients",cw).route("/tenants",uw).route("/logs",pw).route("/hooks",hw).route("/connections",mw).route("/prompts",_w).route("/sessions",kw).route("/refresh_tokens",xw);return e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),e}function Ew(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}function Bn(t){var e,n,r;return{auth0Client:(e=t.query("auth0Client"))==null?void 0:e.slice(0,255),ip:(n=t.header("x-real-ip"))==null?void 0:n.slice(0,45),useragent:(r=t.header("user-agent"))==null?void 0:r.slice(0,512)}}var bp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(bp||(bp={}));var kp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(kp||(kp={}));function Iw(t){return $g(t,zw,Xr.Include)}function jg(t){return $g(t,Cw,Xr.None)}function $g(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,o=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],o+=8;for(let c=0;c<4;c++)o>=6?(r+=e[s>>o-6&63],o-=6):o>0?(r+=e[s<<6-o&63],o=0):n===Xr.Include&&(r+="=")}return r}const zw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Xr;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Xr||(Xr={}));var xp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(xp||(xp={}));class Nw{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Sp=new Nw;function wt(t,e){return(t<<32-e|t>>>e)>>>0}function jw(t){const e=new $w;return e.update(t),e.digest()}class $w{constructor(){ee(this,"blockSize",64);ee(this,"size",32);ee(this,"blocks",new Uint8Array(64));ee(this,"currentBlockSize",0);ee(this,"H",new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]));ee(this,"l",0n);ee(this,"w",new Uint32Array(64))}update(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),Sp.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Sp.putUint32(e,this.H[n],n*4);return e}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const p=(wt(this.w[u-2],17)^wt(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,h=(wt(this.w[u-15],7)^wt(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=p+this.w[u-7]+h+this.w[u-16]|0}let e=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],o=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const p=(wt(s,6)^wt(s,11)^wt(s,25))>>>0,h=(s&o^~s&c)>>>0,m=l+p+h+Ow[u]+this.w[u]|0,v=(wt(e,2)^wt(e,13)^wt(e,22))>>>0,f=(e&n^e&r^n&r)>>>0,_=v+f|0;l=c,c=o,o=s,s=i+m|0,i=r,r=n,n=e,e=m+_|0}this.H[0]=e+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=o+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const Ow=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class Bw{constructor(e){ee(this,"data");this.data=e}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function Tw(t){const e=jw(new TextEncoder().encode(t));return jg(e)}function Pw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),jg(t)}function Pr(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function fa(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Iw(n)}async function Ds(t){let e;try{e=await fetch(t)}catch(n){throw new Bg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Di(e.status)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);let r;try{r=Og(n)}catch{throw new Wn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Di(e.status)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);return new Bw(n)}throw e.body!==null&&await e.body.cancel(),new Di(e.status)}async function Rw(t){let e;try{e=await fetch(t)}catch(n){throw new Bg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Wn(e.status,null)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);let r;try{r=Og(n)}catch{throw new Wn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Di(e.status)}function Og(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new Lw(e,n,r,i)}class Bg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class Lw extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);ee(this,"code");ee(this,"description");ee(this,"uri");ee(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Di extends Error{constructor(n){super("Unexpected error response");ee(this,"status");this.status=n}}class Wn extends Error{constructor(n,r){super("Unexpected error response body");ee(this,"status");ee(this,"data");this.status=n,this.data=r}}class eu{constructor(e,n,r){ee(this,"clientId");ee(this,"clientPassword");ee(this,"redirectURI");this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(e,n,r,i,s){const o=new URL(e);if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&o.searchParams.set("redirect_uri",this.redirectURI),o.searchParams.set("state",n),r===Qr.S256){const c=Tw(i);o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("code_challenge",c)}else r===Qr.Plain&&(o.searchParams.set("code_challenge_method","plain"),o.searchParams.set("code_challenge",i));return s.length>0&&o.searchParams.set("scope",s.join(" ")),o}async validateAuthorizationCode(e,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Pr(e,i);if(this.clientPassword!==null){const c=fa(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ds(s)}async refreshAccessToken(e,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Pr(e,i);if(this.clientPassword!==null){const c=fa(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ds(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Pr(e,r);if(this.clientPassword!==null){const s=fa(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await Rw(i)}}var Qr;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(Qr||(Qr={}));var Ap;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ap||(Ap={}));var Ep;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ep||(Ep={}));function Rr(t){return Uw(t,Vw,Hs.None)}function Uw(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,o=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],o+=8;for(let c=0;c<4;c++)o>=6?(r+=e[s>>o-6&63],o-=6):o>0?(r+=e[s<<6-o&63],o=0):n===Hs.Include&&(r+="=")}return r}const Vw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Hs;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Hs||(Hs={}));var Ip;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ip||(Ip={}));function Mw(t,e,n){const r=Rr(new TextEncoder().encode(t)),i=Rr(new TextEncoder().encode(e)),s=Rr(n);return r+"."+i+"."+s}function qw(t,e){const n=Rr(new TextEncoder().encode(t)),r=Rr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const Dw="https://appleid.apple.com/auth/authorize",Hw="https://appleid.apple.com/auth/token";class Tg{constructor(e,n,r,i,s){ee(this,"clientId");ee(this,"teamId");ee(this,"keyId");ee(this,"pkcs8PrivateKey");ee(this,"redirectURI");this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(Dw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Pr(Hw,n);return await Ds(i)}async createClientSecret(){const e=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+5*60,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,qw(r,i)));return Mw(r,i,s)}}const Fw="https://www.facebook.com/v16.0/dialog/oauth",Kw="https://graph.facebook.com/v16.0/oauth/access_token";class Pg{constructor(e,n,r){ee(this,"clientId");ee(this,"clientSecret");ee(this,"redirectURI");this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(Fw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Pr(Kw,n);return await Ds(r)}}const Ww="https://accounts.google.com/o/oauth2/v2/auth",zp="https://oauth2.googleapis.com/token",Gw="https://oauth2.googleapis.com/revoke";let Rg=class{constructor(e,n,r){ee(this,"client");this.client=new eu(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(Ww,e,Qr.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(zp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(zp,e,[])}async revokeToken(e){await this.client.revokeToken(Gw,e)}};const Wo=a.z.object({iss:a.z.string().url(),sub:a.z.string(),aud:a.z.string(),exp:a.z.number(),email:a.z.string().optional(),given_name:a.z.string().optional(),family_name:a.z.string().optional(),name:a.z.string().optional(),iat:a.z.number(),auth_time:a.z.number().optional(),nonce:a.z.string().optional(),acr:a.z.string().optional(),amr:a.z.array(a.z.string()).optional(),azp:a.z.string().optional(),at_hash:a.z.string().optional(),c_hash:a.z.string().optional()}).passthrough();Wo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Jw(t){return t.ISSUER}function At(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function Ce(t){return t.OAUTH_API_URL||t.ISSUER}function Lg(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:e,keyArray:i}}async function Zw(t,e){var l,u;const{options:n,keyArray:r}=Lg(e),i=new Tg(n.client_id,n.team_id,n.kid,r,`${Ce(t.env)}callback`),s=qe(),o=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((u=n.scope)==null?void 0:u.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&o.searchParams.set("response_mode","form_post"),{redirectUrl:o.href,code:s}}async function Yw(t,e,n){const{options:r,keyArray:i}=Lg(e),o=await new Tg(r.client_id,r.team_id,r.kid,i,`${Ce(t.env)}callback`).validateAuthorizationCode(n),c=sl(o.idToken());if(!c)throw new Error("Invalid ID token");const l=Wo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const Xw=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Zw,validateAuthorizationCodeAndGetUser:Yw},Symbol.toStringTag,{value:"Module"}));async function Qw(t,e){var o;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Pg(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe();return{redirectUrl:r.createAuthorizationURL(i,((o=n.scope)==null?void 0:o.split(" "))||["email"]).href,code:i}}async function eb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Pg(r.client_id,r.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode(n),o=await fetch("https://graph.facebook.com/v16.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!o.ok)throw new Error("Failed to fetch user info");const c=await o.json();return t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const tb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Qw,validateAuthorizationCodeAndGetUser:eb},Symbol.toStringTag,{value:"Module"}));async function nb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Rg(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe(),s=Pw();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function rb(t,e,n,r){const{options:i}=e;if(!(i!=null&&i.client_id)||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const o=await new Rg(i.client_id,i.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode(n,r),c=sl(o.idToken());if(!c)throw new Error("Invalid ID token");const l=Wo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const ib=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:nb,validateAuthorizationCodeAndGetUser:rb},Symbol.toStringTag,{value:"Module"}));async function sb(t,e){var o;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new eu(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,((o=n.scope)==null?void 0:o.split(" "))||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function ob(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new eu(r.client_id,r.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),o=sl(s.idToken());if(!o)throw new Error("Invalid ID token");const c=Wo.parse(o.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new N(400,{message:"Failed to get user from vipps"});return await l.json()}const ab=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:sb,validateAuthorizationCodeAndGetUser:ob},Symbol.toStringTag,{value:"Module"}));function Ug(t,e){const n=t.env.STRATEGIES||{},i={apple:Xw,facebook:tb,"google-oauth2":ib,vipps:ab,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Go(t,e){const n=await t.data.clients.get(e);if(!n)throw new N(403,{message:"Client not found"});const r=t.DEFAULT_CLIENT_ID?await t.data.clients.get(t.DEFAULT_CLIENT_ID):void 0,i=await t.data.connections.list(n.tenant.id),s=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},o=i.connections.map(c=>{var p;const l=(p=s.connections)==null?void 0:p.find(h=>h.name===c.name);return l!=null&&l.options?Dt.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${At(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${At(t)}info`],connections:o,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Jo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return cb(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function cb(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function lb(t,e,n,r){if(!r.state)throw new N(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i){t.set("client_id",e.id);const l=be(t,{type:me.FAILED_LOGIN,description:"Connection not found"});throw await t.env.data.logs.create(e.tenant.id,l),new N(403,{message:"Connection Not Found"})}let s=await t.env.data.logins.get(e.tenant.id,r.state);s||(s=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:r,...Bn(t.req)}));const c=await Ug(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.login_id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+x_*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Cp(t,{code:e,state:n}){var f;const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new N(403,{message:"State not found"});const s=await r.data.logins.get(t.var.tenant_id||"",i.login_id);if(!s)throw new N(403,{message:"Session not found"});const o=await Go(r,s.authParams.client_id);t.set("client_id",o.id),t.set("tenant_id",o.tenant.id);const c=o.connections.find(_=>_.id===i.connection_id);if(!c){const _=be(t,{type:me.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(o.tenant.id,_),new N(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=be(t,{type:me.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(o.tenant.id,_),new N(403,{message:"Redirect URI not defined"})}if(!Jo(s.authParams.redirect_uri,o.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,w=be(t,{type:me.FAILED_LOGIN,description:_});throw await r.data.logs.create(o.tenant.id,w),new N(403,{message:_})}const u=await Ug(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...h}=u;t.set("user_id",p);const m=((f=u.email)==null?void 0:f.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const v=await no(t,{client:o,email:m,provider:c.strategy,connection:c.name,userId:p,profileData:h,isSocial:!0,ip:t.req.header("x-real-ip")});return sn(t,{client:o,authParams:s.authParams,loginSession:s,user:v})}async function Np(t,e,n,r,i,s){const o=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!o)throw new N(400,{message:"State not found"});const c=await t.env.data.logins.get(t.var.tenant_id,o.login_id);if(!c)throw new N(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new N(400,{message:"Redirect uri not found"});const u=be(t,{type:me.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});Qe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Ew(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${At(t.env)}enter-email?state=${c.login_id}&error=${n}`)}const ub=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string(),code:a.z.string().optional(),scope:a.z.string().optional(),hd:a.z.string().optional(),error:a.z.string().optional(),error_description:a.z.string().optional(),error_code:a.z.string().optional(),error_reason:a.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:o}=t.req.valid("query");if(r)return Np(t,e,r,i,s,o);if(!n)throw new N(400,{message:"Code is required"});return Cp(t,{code:n,state:e})}).openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({state:a.z.string(),code:a.z.string().optional(),scope:a.z.string().optional(),hd:a.z.string().optional(),error:a.z.string().optional(),error_description:a.z.string().optional(),error_code:a.z.string().optional(),error_reason:a.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:o}=t.req.valid("form");if(r)return Np(t,e,r,i,s,o);if(!n)throw new N(400,{message:"Code is required"});return Cp(t,{code:n,state:e})}),db=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:a.z.object({client_id:a.z.string(),returnTo:a.z.string().optional()}),header:a.z.object({cookie:a.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async t=>{const{client_id:e,returnTo:n}=t.req.valid("query"),r=await t.env.data.clients.get(e);if(!r)return t.text("OK");const i=await t.env.data.clients.get("DEFAULT_CLIENT");t.set("client_id",e),t.set("tenant_id",r.tenant.id);const s=n||t.req.header("referer");if(!s)return t.text("OK");if(!Jo(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new N(400,{message:"Invalid redirect uri"});const o=t.req.header("cookie");if(o){const l=as(r.tenant.id,o);if(l){const u=await t.env.data.sessions.get(r.tenant.id,l);if(u){const p=await t.env.data.users.get(r.tenant.id,u.user_id);p&&(t.set("user_id",p.user_id),t.set("connection",p.connection))}await t.env.data.sessions.remove(r.tenant.id,l)}}const c=be(t,{type:me.SUCCESS_LOGOUT,description:"User successfully logged out"});return await t.env.data.logs.create(r.tenant.id,c),new Response("Redirecting",{status:302,headers:{"set-cookie":z_(r.tenant.id),location:s}})}),jp=a.z.object({sub:a.z.string(),email:a.z.string().optional(),family_name:a.z.string().optional(),given_name:a.z.string().optional(),email_verified:a.z.boolean()}),pb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:jp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new N(404,{message:"User not found"});const e=await t.env.data.users.get(t.var.user.tenant_id,t.var.user.sub);if(!e)throw new N(404,{message:"User not found"});return t.json(jp.parse({...e,sub:e.user_id}))}),fb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:cf}},description:"List of tenants"}}}),async t=>{const e=await t.env.data.keys.list(),n=await Promise.all(e.map(async r=>{const s=await new Ql(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return nl.parse({...o,kid:r.kid})}));return t.json({keys:n},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ni}, stale-while-revalidate=${Ni*2}, stale-if-error=86400`}})}).openapi(a.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Aa}},description:"List of tenants"}}}),async t=>{const e=Aa.parse({issuer:Jw(t.env),authorization_endpoint:`${Ce(t.env)}authorize`,token_endpoint:`${Ce(t.env)}oauth/token`,device_authorization_endpoint:`${Ce(t.env)}oauth/device/code`,userinfo_endpoint:`${Ce(t.env)}userinfo`,mfa_challenge_endpoint:`${Ce(t.env)}mfa/challenge`,jwks_uri:`${Ce(t.env)}.well-known/jwks.json`,registration_endpoint:`${Ce(t.env)}oidc/register`,revocation_endpoint:`${Ce(t.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return t.json(e,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ni}, stale-while-revalidate=${Ni*2}, stale-if-error=86400`}})});function Hi(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const Vg=a.z.object({grant_type:a.z.literal("client_credentials"),scope:a.z.string().optional(),client_secret:a.z.string(),client_id:a.z.string(),audience:a.z.string().optional()});async function hb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Invalid client credentials"});if(n.client_secret&&!Hi(n.client_secret,e.client_secret))throw new N(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await eo(t,{authParams:r,client:n});return t.json(i)}const gb=a.z.object({grant_type:a.z.literal("authorization_code"),client_id:a.z.string(),code:a.z.string(),redirect_uri:a.z.string().optional(),client_secret:a.z.string().optional(),code_verifier:a.z.string().optional()}).refine(t=>"client_secret"in t&&!("code_verifier"in t)||!("client_secret"in t)&&"code_verifier"in t,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function mb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Client not found"});const r=await t.env.data.codes.get(n.tenant.id,e.code,"authorization_code");if(!r||!r.user_id)throw new N(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new N(403,{message:"Code expired"});if(r.used_at)throw new N(403,{message:"Code already used"});const i=await t.env.data.logins.get(n.tenant.id,r.login_id);if(!i)throw new N(403,{message:"Invalid login"});if("client_secret"in e){const o=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Hi(n.client_secret,e.client_secret)&&!Hi(o==null?void 0:o.client_secret,e.client_secret))throw new N(403,{message:"Invalid client credentials"})}else if("code_verifier"in e&&typeof e.code_verifier=="string"&&"code_challenge_method"in i.authParams&&typeof i.authParams.code_challenge_method=="string"){const o=await w_(e.code_verifier,i.authParams.code_challenge_method);if(!Hi(o,i.authParams.code_challenge||""))throw new N(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new N(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new N(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),sn(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Zt.WEB_MESSAGE}})}const _b=a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string(),redirect_uri:a.z.string().optional(),refresh_token:a.z.string()});async function yb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Client not found"});const r=await t.env.data.refreshTokens.get(n.tenant.id,e.refresh_token);if(r){if(r.expires_at&&new Date(r.expires_at)<new Date||r.idle_expires_at&&new Date(r.idle_expires_at)<new Date)throw new N(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new N(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Invalid refresh token"})});const i=await t.env.data.users.get(n.tenant.id,r.user_id);if(!i)throw new N(403,{message:"User not found"});const s=r.resource_servers[0];if(r.idle_expires_at){const o=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:o.toISOString(),last_exchanged_at:new Date().toISOString(),device:{...r.device,last_ip:t.req.header["x-real-ip"]||"",last_user_agent:t.req.header["user-agent"]||""}})}return sn(t,{user:i,client:n,refreshToken:r.id,sessionId:r.session_id,authParams:{client_id:n.id,audience:s==null?void 0:s.audience,scope:s==null?void 0:s.scopes,response_mode:Zt.WEB_MESSAGE}})}const $p=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),vb=a.z.union([Vg.extend($p.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)}),a.z.object({grant_type:a.z.literal("authorization_code"),code:a.z.string(),redirect_uri:a.z.string().optional(),...$p.shape}),a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string(),refresh_token:a.z.string(),redirect_uri:a.z.string().optional()})]);function wb(t){if(!t)return{};const[e,n]=t.split(" ");if((e==null?void 0:e.toLowerCase())==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const bb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:vb}}}},responses:{200:{content:{"application/json":{schema:hf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=wb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new N(400,{message:"client_id is required"});switch(e.grant_type){case jr.AuthorizationCode:return mb(t,gb.parse(r));case jr.ClientCredential:return hb(t,Vg.parse(r));case jr.RefreshToken:return yb(t,_b.parse(r));default:throw new N(400,{message:"Not implemented"})}});var tu={exports:{}};const nu=[{id:0,value:"Too weak",minDiversity:0,minLength:0},{id:1,value:"Weak",minDiversity:2,minLength:6},{id:2,value:"Medium",minDiversity:4,minLength:8},{id:3,value:"Strong",minDiversity:4,minLength:10}],Mg=(t,e=nu,n="!\"#$%&'()*+,-./:;<=>?@[\\\\\\]^_`{|}~")=>{let r=t||"";e[0].minDiversity=0,e[0].minLength=0;const i=[{regex:"[a-z]",message:"lowercase"},{regex:"[A-Z]",message:"uppercase"},{regex:"[0-9]",message:"number"}];n&&i.push({regex:`[${n}]`,message:"symbol"});let s={};s.contains=i.filter(c=>new RegExp(`${c.regex}`).test(r)).map(c=>c.message),s.length=r.length;let o=e.filter(c=>s.contains.length>=c.minDiversity).filter(c=>s.length>=c.minLength).sort((c,l)=>l.id-c.id).map(c=>({id:c.id,value:c.value}));return Object.assign(s,o[0]),s};tu.exports={passwordStrength:Mg,defaultOptions:nu};var kb=tu.exports.passwordStrength=Mg;tu.exports.defaultOptions=nu;function ru(t){return kb(t).id<2?!1:t.length>=8&&/[a-z]/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t)&&/[^A-Za-z0-9]/.test(t)}async function Zo(t,e){var i;const n=await t.env.data.emailProviders.get(t.var.tenant_id)||(t.env.DEFAULT_TENANT_ID?await t.env.data.emailProviders.get(t.env.DEFAULT_TENANT_ID):null);if(!n)throw new N(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new N(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function qg(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new N(500,{message:"Tenant not found"});const s=`${At(t.env)}reset-password?state=${r}&code=${n}`,o={vendorName:i.name,lng:i.language||"en"};await Zo(t,{to:e,subject:"Reset your password",html:`Click here to reset your password: ${At(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:de("password_reset_title",o),resetPasswordEmailClickToReset:de("reset_password_email_click_to_reset",o),resetPasswordEmailReset:de("reset_password_email_reset",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}})}async function Dg(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new N(500,{message:"Tenant not found"});const i={vendorName:r.name,code:n,lng:r.language||"en"};await Zo(t,{to:e,subject:de("code_email_subject",i),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",magicLink:`${Ce(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",i),linkEmailClickToLogin:de("link_email_click_to_login",i),linkEmailLogin:de("link_email_login",i),linkEmailOrEnterCode:de("link_email_or_enter_code",i),codeValid30Mins:de("code_valid_30_minutes",i),supportInfo:de("support_info",i),contactUs:de("contact_us",i),copyright:de("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(r.id,s))}async function iu(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new N(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new N(400,{message:"redirect_uri is required"});const s=new URL(Ce(t.env));s.pathname="passwordless/verify_redirect",s.searchParams.set("verification_code",n),s.searchParams.set("connection","email"),s.searchParams.set("client_id",r.client_id),s.searchParams.set("redirect_uri",r.redirect_uri),s.searchParams.set("email",e),r.response_type&&s.searchParams.set("response_type",r.response_type),r.scope&&s.searchParams.set("scope",r.scope),r.state&&s.searchParams.set("state",r.state),r.nonce&&s.searchParams.set("nonce",r.nonce),r.code_challenge&&s.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&s.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&s.searchParams.set("audience",r.audience);const o={vendorName:i.name,code:n,lng:i.language||"en"};await Zo(t,{to:e,subject:de("code_email_subject",o),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:s.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",o),linkEmailClickToLogin:de("link_email_click_to_login",o),linkEmailLogin:de("link_email_login",o),linkEmailOrEnterCode:de("link_email_or_enter_code",o),codeValid30Mins:de("code_valid_30_minutes",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}});const c=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(i.id,c))}async function su(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new N(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Zo(t,{to:e.email,subject:"Validate your email address",html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${At(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:de("welcome_to_your_account",r),verifyEmailVerify:de("verify_email_verify",r),supportInfo:de("support_info",r),contactUs:de("contact_us",r),copyright:de("copyright",r)}})}const xb=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("Username-Password-Authentication"),email:a.z.string().transform(t=>t.toLowerCase()),password:a.z.string()})}}}},responses:{200:{content:{"application/json":{schema:a.z.object({_id:a.z.string(),email:a.z.string(),email_verified:a.z.boolean(),app_metadata:a.z.object({}),user_metadata:a.z.object({})})}},description:"Created user"}}}),async t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.clients.get(r);if(!i)throw new N(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!ru(n))throw new N(400,{message:"Password does not meet the requirements"});if(await cs({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new N(400,{message:"Invalid sign up"});const o=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Ys()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",o.user_id),t.set("username",o.email),t.set("connection",o.connection);const c=await ii.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:o.user_id,password:c,algorithm:"bcrypt"}),await su(t,o);const l=be(t,{type:me.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:o.user_id,email:o.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("Username-Password-Authentication"),email:a.z.string().transform(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.clients.get(n);if(!r)throw new N(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await si({userAdapter:t.env.data.users,tenant_id:r.tenant.id,email:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},o=await t.env.data.logins.create(r.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:s,...Bn(t.req)});return await qg(t,e,o.login_id,o.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function sr(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}async function ou(t,e,n,r,i,s){const{env:o}=t,c=await o.data.codes.get(e.tenant.id,i,"otp");if(!c)throw new N(400,{message:"Code not found or expired"});if(c.expires_at<new Date().toISOString())throw new N(400,{message:"Code expired"});if(c.used_at)throw new N(400,{message:"Code already used"});const l=await o.data.logins.get(e.tenant.id,c.login_id);if(!l||l.authParams.username!==r)throw new N(400,{message:"Code not found or expired"});const u=Bn(t.req);if(l.ip!==u.ip)return t.redirect(`${At(t.env)}invalid-session?state=${l.login_id}`);if(n.redirect_uri&&!Jo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new N(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const p=await no(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await o.data.codes.used(e.tenant.id,i),sn(t,{user:p,client:e,loginSession:l,authParams:n,ticketAuth:s})}const Sb=new a.OpenAPIHono().openapi(a.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.string(),email:a.z.string().transform(t=>t.toLowerCase()),send:a.z.enum(["link","code"]),authParams:el.omit({client_id:!0})})}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,email:i,send:s,authParams:o}=e,c=await t.env.data.clients.get(r);if(!c)throw new N(400,{message:"Client not found"});t.set("client_id",c.id),t.set("tenant_id",c.tenant.id);const l=await n.data.logins.create(c.tenant.id,{authParams:{...o,client_id:r,username:i},expires_at:new Date(Date.now()+za).toISOString(),...Bn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:sr(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+za).toISOString()});return s==="link"?await iu(t,i,u.code_id,{...o,client_id:r}):await Dg(t,i,u.code_id),t.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(Jt),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(t=>t.toLowerCase()),audience:a.z.string().optional()})},responses:{302:{description:"Status"}}}),async t=>{const{env:e}=t,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:o,scope:c,audience:l,response_type:u,nonce:p}=t.req.valid("query"),h=await Go(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),ou(t,h,{client_id:n,redirect_uri:s,state:o,nonce:p,scope:c,audience:l,response_type:u},r,i)});class Er extends N{constructor(n,r){super(n,r);ee(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function au(t,e,n,r,i){const{env:s}=t,o=n.username;if(t.set("username",o),!o)throw new N(400,{message:"Username is required"});const c=await si({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:o,provider:"auth2"});if(!c){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"User not found",code:"USER_NOT_FOUND"})}const l=c.linked_to?await s.data.users.get(e.tenant.id,c.linked_to):c;if(!l)throw new Er(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const{password:u}=await s.data.passwords.get(e.tenant.id,c.user_id);if(!await ii.compare(n.password,u)){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"Invalid password",code:"INVALID_PASSWORD"})}if((await s.data.logs.list(e.tenant.id,{page:0,per_page:10,include_totals:!1,q:`user_id:${l.user_id}`})).logs.filter(f=>f.type===me.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(f.date)>new Date(Date.now()-1e3*60*5)).length>=3){const f=be(t,{type:me.FAILED_LOGIN,description:"Too many failed login attempts"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await su(t,c);const f=be(t,{type:me.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,f),new Er(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const v=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Qe(t,t.env.data.logs.create(e.tenant.id,v)),sn(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Ab(t,e,n,r){await no(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=sr(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=sr(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const o=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+E_).toISOString(),authParams:{client_id:e.id,username:n},...Bn(t.req)}),c=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:o.login_id,expires_at:new Date(Date.now()+A_).toISOString()});await qg(t,n,c.code_id,r)}const Eb=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(t=>t.toLowerCase()),realm:a.z.enum(["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(t=>t.toLowerCase()),password:a.z.string(),realm:a.z.enum(["Username-Password-Authentication"]),scope:a.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async t=>{const e=t.req.valid("json"),{client_id:n,username:r}=e;t.set("username",r);const i=await t.env.data.clients.get(n);if(!i)throw new N(400,{message:"Client not found"});t.set("client_id",n),t.set("tenant_id",i.tenant.id);const s=r.toLocaleLowerCase();if("otp"in e)return ou(t,i,{client_id:n,username:s},s,e.otp,!0);if("password"in e){const o=await t.env.data.logins.create(i.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:{client_id:n,username:s},...Bn(t.req)});return au(t,i,{username:s,password:e.password,client_id:n},o,!0)}else throw new N(400,{message:"Code or password required"})});function Ib(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ha(t))==null?void 0:r.host)??null;if(!n)return!1;for(const o of e){let c;if(o.startsWith("http://")||o.startsWith("https://")?c=((i=ha(o))==null?void 0:i.host)??null:c=((s=ha("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function ha(t){try{return new URL(t)}catch{return null}}async function zb({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const o=await t.env.data.logins.create(n.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:r,...Bn(t.req)});if(e&&s){const c=await t.env.data.users.get(n.tenant.id,e.user_id);if((c==null?void 0:c.email)===s)return sn(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=sr();return await t.env.data.codes.create(n.tenant.id,{code_id:c,code_type:"otp",login_id:o.login_id,expires_at:new Date(Date.now()+Ur*1e3).toISOString()}),await iu(t,s,c,r),t.redirect(`/u/enter-code?state=${o.login_id}`)}return e?t.redirect(`/u/check-account?state=${o.login_id}`):t.redirect(`/u/enter-email?state=${o.login_id}`)}function Cb(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new N(403,{message:"Invalid realm"})}async function Nb(t,e,n,r,i){var m;const{env:s}=t;t.set("connection",i);const o=await s.data.codes.get(e,n,"ticket");if(!o||o.used_at)throw new N(403,{message:"Ticket not found"});const c=await s.data.logins.get(e,o.login_id);if(!c||!c.authParams.username)throw new N(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new N(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const u=Cb(i);let p=await no(t,{email:c.authParams.username,provider:u,client:l,connection:u==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email),t.set("user_id",p.user_id);const h=await Tf(t,{user:p,client:l,scope:r.scope,audience:r.audience});return sn(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function Op(t,e){return`<!DOCTYPE html>
149
+ `,r}async function rw(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return Ia(await xf(s))}const iw=1e3*60*60*24,sw=new a.OpenAPIHono().openapi(a.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.array(Ea)}},description:"List of keys"}}}),async t=>{const n=(await t.env.data.keys.list()).filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(a.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({kid:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ea}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),r=(await t.env.data.keys.list()).find(i=>i.kid===e);if(!r)throw new N(404,{message:"Key not found"});return t.json(r)}).openapi(a.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const e=await t.env.data.keys.list();for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+iw).toISOString()});const n=await Gc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(n),t.text("OK",{status:201})}).openapi(a.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({kid:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new N(404,{message:"Key not found"});const r=await Gc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),ow=new a.OpenAPIHono().openapi(a.createRoute({tags:["users"],method:"get",path:"/",request:{query:a.z.object({email:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:a.z.array(Qc)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await Lf(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),aw=nn.extend({clients:a.z.array(pn)}),cw=new a.OpenAPIHono().openapi(a.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([aw,a.z.array(pn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:o}=t.req.valid("query"),l=(await t.env.data.applications.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o})).applications;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(a.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:pn}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=(await t.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(s=>s.id===n);if(!i)throw new N(404);return t.json(i)}).openapi(a.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.applications.remove(e,n))throw new N(404,{message:"Application not found"});return t.text("OK")}).openapi(a.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(ts.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:pn}},description:"The update application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.applications.update(e,n,i);const s=await t.env.data.applications.get(e,n);if(!s)throw new N(404,{message:"Application not found"});return t.json(s)}).openapi(a.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(ts.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:a.z.object(pn.shape)}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||qe(),client_secret:n.client_secret||qe()},i=await t.env.data.applications.create(e,r);return t.json(i,{status:201})});a.z.object({start:a.z.number(),limit:a.z.number(),length:a.z.number()});Gs.extend({email:a.z.string(),login_count:a.z.number(),multifactor:a.z.array(a.z.string()).optional(),last_ip:a.z.string().optional(),last_login:a.z.string().optional(),user_id:a.z.string()}).catchall(a.z.any());const lw=nn.extend({tenants:a.z.array(Hn)}),uw=new a.OpenAPIHono().openapi(a.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Yt},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:a.z.union([a.z.array(Hn),lw])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),o=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:cr(i),q:s});return r?t.json(o):t.json(o.tenants)}).openapi(a.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Hn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new N(404);return t.json(n)}).openapi(a.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(a.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(rs.shape).partial()}}},params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(a.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(rs.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Hn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),dw=nn.extend({logs:a.z.array(ss)}),pw=new a.OpenAPIHono().openapi(a.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(ss),dw])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":o}=t.req.valid("header"),c=await t.env.data.logs.list(o,{page:e,per_page:n,include_totals:r,sort:cr(i),q:s});return r?t.json(c):t.json(c.logs)}).openapi(a.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:ss}},description:"A log entry"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.logs.get(e,n);if(!r)throw new N(404);return t.json(r)}),fw=nn.extend({hooks:a.z.array(qn)}),hw=new a.OpenAPIHono().openapi(a.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(qn),fw])}},description:"List of hooks"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:o}=t.req.valid("query"),c=await t.env.data.hooks.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o});return i?t.json(c):t.json(c.hooks)}).openapi(a.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(is.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:qn}},description:"The created hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.hooks.create(e,n);return t.json(r,{status:201})}).openapi(a.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()}),body:{content:{"application/json":{schema:a.z.object(is.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:qn.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=t.req.valid("json");await t.env.data.hooks.update(e,n,r);const i=await t.env.data.hooks.get(e,n);if(!i)throw new N(404,{message:"Hook not found"});return t.json(i)}).openapi(a.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:qn}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=await t.env.data.hooks.get(e,n);if(!r)throw new N(404,{message:"Hook not found"});return t.json(r)}).openapi(a.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:a.z.object({"tenant-id":a.z.string()}),params:a.z.object({hook_id:a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param");if(!await t.env.data.hooks.remove(e,n))throw new N(404,{message:"Hook not found"});return t.text("OK")}),gw=nn.extend({connections:a.z.array(Dt)}),mw=new a.OpenAPIHono().openapi(a.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.union([a.z.array(Dt),gw])}},description:"List of connectionss"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:o}=t.req.valid("query"),c=await t.env.data.connections.list(e,{page:n,per_page:r,include_totals:i,sort:cr(s),q:o});return i?t.json(c):t.json(c.connections)}).openapi(a.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Dt}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.connections.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.connections.remove(e,n))throw new N(404,{message:"Connection not found"});return t.text("OK")}).openapi(a.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(ns.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Dt}},description:"The updated connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.connections.update(e,n,r))throw new N(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new N(404,{message:"Connection not found"});return t.json(s)}).openapi(a.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(ns.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Dt}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.connections.create(e,n);return t.json(r,{status:201})}),_w=new a.OpenAPIHono().openapi(a.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ri}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Ri.parse({}))}).openapi(a.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Ri.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let wp=!1;function Cg(t){t.use(async(e,n)=>(wp||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),wp=!0),await n()))}a.z.object({alg:a.z.literal("RS256"),kty:a.z.literal("RSA"),use:a.z.literal("sig"),n:a.z.string(),e:a.z.string(),kid:a.z.string(),x5t:a.z.string(),x5c:a.z.array(a.z.string())});async function yw(t){try{const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new N(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function vw(t,e){const r=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),i=new Uint8Array(Array.from(e.signature).map(l=>l.charCodeAt(0))),o=(await yw(t.env)).find(l=>l.kid===e.header.kid);if(!o)return console.log("No matching kid found"),!1;const c=await crypto.subtle.importKey("jwk",o,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",c,i,r)}function ww(t){const[e,n,r]=t.split(".");if(!e||!n||!r)return null;const i=JSON.parse(atob(e)),s=JSON.parse(atob(n)),o=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return{header:i,payload:s,signature:o,raw:{header:e,payload:n,signature:r}}}function Ng(t){return async(e,n)=>{var i,s,o;const r=t.openAPIRegistry.definitions.find(c=>"route"in c&&c.route.path===e.req.path&&c.route.method.toUpperCase()===e.req.method);if(r&&"route"in r){const c=(s=(i=r.route.security)==null?void 0:i[0])==null?void 0:s.Bearer;if(!(c!=null&&c.length))return await n();const l=e.req.header("authorization")||"",[u,p]=l.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!p)throw new N(401,{message:"Missing bearer token"});const h=ww(p);if(!h||!await vw(e,h))throw new N(403,{message:"Invalid JWT signature"});e.set("user_id",h.payload.sub),e.set("user",h.payload);const m=h.payload.permissions||[],v=((o=h.payload.scope)==null?void 0:o.split(" "))||[];if(c.length&&!(c.some(f=>m.includes(f))||c.some(f=>v.includes(f))))throw new N(403,{message:"Unauthorized"})}return await n()}}const bw=new a.OpenAPIHono().openapi(a.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new N(404,{message:"Email provider not found"});return t.json(n)}).openapi(a.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Li.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(a.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:a.z.object({"tenant-id":a.z.string()}),body:{content:{"application/json":{schema:a.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),kw=new a.OpenAPIHono().openapi(a.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Zs}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.sessions.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.remove(e,n))throw new N(404,{message:"Session not found"});return t.text("OK")}).openapi(a.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.update(e,n,{revoked_at:new Date().toDateString()}))throw new N(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),xw=new a.OpenAPIHono().openapi(a.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:rl}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.refreshTokens.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(e,n))throw new N(404,{message:"Session not found"});return t.text("OK")}),Sw=new a.OpenAPIHono().openapi(a.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Yt,headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:a.z.array(Mn)}},description:"List of custom domains"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.customDomains.list(e);return t.json(n)}).openapi(a.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.customDomains.get(e,n);if(!r)throw new N(404);return t.json(r)}).openapi(a.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.customDomains.remove(e,n))throw new N(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(a.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:a.z.object(Mn.shape).partial()}}},params:a.z.object({id:a.z.string()}),headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Mn}},description:"The updated custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.customDomains.update(e,n,r))throw new N(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new N(404);return t.json(s)}).openapi(a.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:a.z.object(tl.shape)}}},headers:a.z.object({"tenant-id":a.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Mn}},description:"The created custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.customDomains.create(e,n);return t.json(r,{status:201})});function Aw(){const t=new a.OpenAPIHono;Cg(t),t.use(Ng(t));const e=t.route("/branding",Qm).route("/custom-domains",Sw).route("/email/providers",bw).route("/users",ay).route("/keys",sw).route("/users-by-email",ow).route("/clients",cw).route("/tenants",uw).route("/logs",pw).route("/hooks",hw).route("/connections",mw).route("/prompts",_w).route("/sessions",kw).route("/refresh_tokens",xw);return e.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),e}function Ew(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}function Bn(t){var e,n,r;return{auth0Client:(e=t.query("auth0Client"))==null?void 0:e.slice(0,255),ip:(n=t.header("x-real-ip"))==null?void 0:n.slice(0,45),useragent:(r=t.header("user-agent"))==null?void 0:r.slice(0,512)}}var bp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(bp||(bp={}));var kp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(kp||(kp={}));function Iw(t){return $g(t,zw,Xr.Include)}function jg(t){return $g(t,Cw,Xr.None)}function $g(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,o=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],o+=8;for(let c=0;c<4;c++)o>=6?(r+=e[s>>o-6&63],o-=6):o>0?(r+=e[s<<6-o&63],o=0):n===Xr.Include&&(r+="=")}return r}const zw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Cw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Xr;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Xr||(Xr={}));var xp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(xp||(xp={}));class Nw{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Sp=new Nw;function wt(t,e){return(t<<32-e|t>>>e)>>>0}function jw(t){const e=new $w;return e.update(t),e.digest()}class $w{constructor(){ee(this,"blockSize",64);ee(this,"size",32);ee(this,"blocks",new Uint8Array(64));ee(this,"currentBlockSize",0);ee(this,"H",new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]));ee(this,"l",0n);ee(this,"w",new Uint32Array(64))}update(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),Sp.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Sp.putUint32(e,this.H[n],n*4);return e}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const p=(wt(this.w[u-2],17)^wt(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,h=(wt(this.w[u-15],7)^wt(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=p+this.w[u-7]+h+this.w[u-16]|0}let e=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],o=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const p=(wt(s,6)^wt(s,11)^wt(s,25))>>>0,h=(s&o^~s&c)>>>0,m=l+p+h+Ow[u]+this.w[u]|0,v=(wt(e,2)^wt(e,13)^wt(e,22))>>>0,f=(e&n^e&r^n&r)>>>0,_=v+f|0;l=c,c=o,o=s,s=i+m|0,i=r,r=n,n=e,e=m+_|0}this.H[0]=e+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=o+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const Ow=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class Bw{constructor(e){ee(this,"data");this.data=e}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function Tw(t){const e=jw(new TextEncoder().encode(t));return jg(e)}function Pw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),jg(t)}function Pr(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function fa(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Iw(n)}async function Ds(t){let e;try{e=await fetch(t)}catch(n){throw new Bg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Di(e.status)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);let r;try{r=Og(n)}catch{throw new Wn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Di(e.status)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);return new Bw(n)}throw e.body!==null&&await e.body.cancel(),new Di(e.status)}async function Rw(t){let e;try{e=await fetch(t)}catch(n){throw new Bg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Wn(e.status,null)}if(typeof n!="object"||n===null)throw new Wn(e.status,n);let r;try{r=Og(n)}catch{throw new Wn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Di(e.status)}function Og(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new Lw(e,n,r,i)}class Bg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class Lw extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);ee(this,"code");ee(this,"description");ee(this,"uri");ee(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Di extends Error{constructor(n){super("Unexpected error response");ee(this,"status");this.status=n}}class Wn extends Error{constructor(n,r){super("Unexpected error response body");ee(this,"status");ee(this,"data");this.status=n,this.data=r}}class eu{constructor(e,n,r){ee(this,"clientId");ee(this,"clientPassword");ee(this,"redirectURI");this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(e,n,r,i,s){const o=new URL(e);if(o.searchParams.set("response_type","code"),o.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&o.searchParams.set("redirect_uri",this.redirectURI),o.searchParams.set("state",n),r===Qr.S256){const c=Tw(i);o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("code_challenge",c)}else r===Qr.Plain&&(o.searchParams.set("code_challenge_method","plain"),o.searchParams.set("code_challenge",i));return s.length>0&&o.searchParams.set("scope",s.join(" ")),o}async validateAuthorizationCode(e,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Pr(e,i);if(this.clientPassword!==null){const c=fa(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ds(s)}async refreshAccessToken(e,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Pr(e,i);if(this.clientPassword!==null){const c=fa(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ds(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Pr(e,r);if(this.clientPassword!==null){const s=fa(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await Rw(i)}}var Qr;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(Qr||(Qr={}));var Ap;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ap||(Ap={}));var Ep;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ep||(Ep={}));function Rr(t){return Uw(t,Vw,Hs.None)}function Uw(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,o=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],o+=8;for(let c=0;c<4;c++)o>=6?(r+=e[s>>o-6&63],o-=6):o>0?(r+=e[s<<6-o&63],o=0):n===Hs.Include&&(r+="=")}return r}const Vw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Hs;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Hs||(Hs={}));var Ip;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ip||(Ip={}));function Mw(t,e,n){const r=Rr(new TextEncoder().encode(t)),i=Rr(new TextEncoder().encode(e)),s=Rr(n);return r+"."+i+"."+s}function qw(t,e){const n=Rr(new TextEncoder().encode(t)),r=Rr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const Dw="https://appleid.apple.com/auth/authorize",Hw="https://appleid.apple.com/auth/token";class Tg{constructor(e,n,r,i,s){ee(this,"clientId");ee(this,"teamId");ee(this,"keyId");ee(this,"pkcs8PrivateKey");ee(this,"redirectURI");this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(Dw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Pr(Hw,n);return await Ds(i)}async createClientSecret(){const e=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+5*60,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,qw(r,i)));return Mw(r,i,s)}}const Fw="https://www.facebook.com/v16.0/dialog/oauth",Kw="https://graph.facebook.com/v16.0/oauth/access_token";class Pg{constructor(e,n,r){ee(this,"clientId");ee(this,"clientSecret");ee(this,"redirectURI");this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(Fw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Pr(Kw,n);return await Ds(r)}}const Ww="https://accounts.google.com/o/oauth2/v2/auth",zp="https://oauth2.googleapis.com/token",Gw="https://oauth2.googleapis.com/revoke";let Rg=class{constructor(e,n,r){ee(this,"client");this.client=new eu(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(Ww,e,Qr.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(zp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(zp,e,[])}async revokeToken(e){await this.client.revokeToken(Gw,e)}};const Wo=a.z.object({iss:a.z.string().url(),sub:a.z.string(),aud:a.z.string(),exp:a.z.number(),email:a.z.string().optional(),given_name:a.z.string().optional(),family_name:a.z.string().optional(),name:a.z.string().optional(),iat:a.z.number(),auth_time:a.z.number().optional(),nonce:a.z.string().optional(),acr:a.z.string().optional(),amr:a.z.array(a.z.string()).optional(),azp:a.z.string().optional(),at_hash:a.z.string().optional(),c_hash:a.z.string().optional()}).passthrough();Wo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Jw(t){return t.ISSUER}function At(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function Ce(t){return t.OAUTH_API_URL||t.ISSUER}function Lg(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:e,keyArray:i}}async function Zw(t,e){var l,u;const{options:n,keyArray:r}=Lg(e),i=new Tg(n.client_id,n.team_id,n.kid,r,`${Ce(t.env)}callback`),s=qe(),o=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((u=n.scope)==null?void 0:u.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&o.searchParams.set("response_mode","form_post"),{redirectUrl:o.href,code:s}}async function Yw(t,e,n){const{options:r,keyArray:i}=Lg(e),o=await new Tg(r.client_id,r.team_id,r.kid,i,`${Ce(t.env)}callback`).validateAuthorizationCode(n),c=sl(o.idToken());if(!c)throw new Error("Invalid ID token");const l=Wo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const Xw=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Zw,validateAuthorizationCodeAndGetUser:Yw},Symbol.toStringTag,{value:"Module"}));async function Qw(t,e){var o;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new Pg(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe();return{redirectUrl:r.createAuthorizationURL(i,((o=n.scope)==null?void 0:o.split(" "))||["email"]).href,code:i}}async function eb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new Pg(r.client_id,r.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode(n),o=await fetch("https://graph.facebook.com/v16.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!o.ok)throw new Error("Failed to fetch user info");const c=await o.json();return t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const tb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Qw,validateAuthorizationCodeAndGetUser:eb},Symbol.toStringTag,{value:"Module"}));async function nb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Rg(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe(),s=Pw();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function rb(t,e,n,r){const{options:i}=e;if(!(i!=null&&i.client_id)||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const o=await new Rg(i.client_id,i.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode(n,r),c=sl(o.idToken());if(!c)throw new Error("Invalid ID token");const l=Wo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const ib=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:nb,validateAuthorizationCodeAndGetUser:rb},Symbol.toStringTag,{value:"Module"}));async function sb(t,e){var o;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new eu(n.client_id,n.client_secret,`${Ce(t.env)}callback`),i=qe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,((o=n.scope)==null?void 0:o.split(" "))||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function ob(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new eu(r.client_id,r.client_secret,`${Ce(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),o=sl(s.idToken());if(!o)throw new Error("Invalid ID token");const c=Wo.parse(o.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new N(400,{message:"Failed to get user from vipps"});return await l.json()}const ab=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:sb,validateAuthorizationCodeAndGetUser:ob},Symbol.toStringTag,{value:"Module"}));function Ug(t,e){const n=t.env.STRATEGIES||{},i={apple:Xw,facebook:tb,"google-oauth2":ib,vipps:ab,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Go(t,e){const n=await t.data.clients.get(e);if(!n)throw new N(403,{message:"Client not found"});const r=t.DEFAULT_CLIENT_ID?await t.data.clients.get(t.DEFAULT_CLIENT_ID):void 0,i=await t.data.connections.list(n.tenant.id),s=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},o=i.connections.map(c=>{var p;const l=(p=s.connections)==null?void 0:p.find(h=>h.name===c.name);return l!=null&&l.options?Dt.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${At(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${At(t)}info`],connections:o,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Jo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return cb(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function cb(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function lb(t,e,n,r){if(!r.state)throw new N(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i){t.set("client_id",e.id);const l=be(t,{type:me.FAILED_LOGIN,description:"Connection not found"});throw await t.env.data.logs.create(e.tenant.id,l),new N(403,{message:"Connection Not Found"})}let s=await t.env.data.logins.get(e.tenant.id,r.state);s||(s=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:r,...Bn(t.req)}));const c=await Ug(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.login_id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+x_*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Cp(t,{code:e,state:n}){var f;const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new N(403,{message:"State not found"});const s=await r.data.logins.get(t.var.tenant_id||"",i.login_id);if(!s)throw new N(403,{message:"Session not found"});const o=await Go(r,s.authParams.client_id);t.set("client_id",o.id),t.set("tenant_id",o.tenant.id);const c=o.connections.find(_=>_.id===i.connection_id);if(!c){const _=be(t,{type:me.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(o.tenant.id,_),new N(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=be(t,{type:me.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(o.tenant.id,_),new N(403,{message:"Redirect URI not defined"})}if(!Jo(s.authParams.redirect_uri,o.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,w=be(t,{type:me.FAILED_LOGIN,description:_});throw await r.data.logs.create(o.tenant.id,w),new N(403,{message:_})}const u=await Ug(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...h}=u;t.set("user_id",p);const m=((f=u.email)==null?void 0:f.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const v=await no(t,{client:o,email:m,provider:c.strategy,connection:c.name,userId:p,profileData:h,isSocial:!0,ip:t.req.header("x-real-ip")});return sn(t,{client:o,authParams:s.authParams,loginSession:s,user:v})}async function Np(t,e,n,r,i,s){const o=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!o)throw new N(400,{message:"State not found"});const c=await t.env.data.logins.get(t.var.tenant_id,o.login_id);if(!c)throw new N(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new N(400,{message:"Redirect uri not found"});const u=be(t,{type:me.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});Qe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Ew(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${At(t.env)}enter-email?state=${c.login_id}&error=${n}`)}const ub=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string(),code:a.z.string().optional(),scope:a.z.string().optional(),hd:a.z.string().optional(),error:a.z.string().optional(),error_description:a.z.string().optional(),error_code:a.z.string().optional(),error_reason:a.z.string().optional()})},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:o}=t.req.valid("query");if(r)return Np(t,e,r,i,s,o);if(!n)throw new N(400,{message:"Code is required"});return Cp(t,{code:n,state:e})}).openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({state:a.z.string(),code:a.z.string().optional(),scope:a.z.string().optional(),hd:a.z.string().optional(),error:a.z.string().optional(),error_description:a.z.string().optional(),error_code:a.z.string().optional(),error_reason:a.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:o}=t.req.valid("form");if(r)return Np(t,e,r,i,s,o);if(!n)throw new N(400,{message:"Code is required"});return Cp(t,{code:n,state:e})}),db=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:a.z.object({client_id:a.z.string(),returnTo:a.z.string().optional()}),header:a.z.object({cookie:a.z.string().optional()})},responses:{302:{description:"Log the user out"}}}),async t=>{const{client_id:e,returnTo:n}=t.req.valid("query"),r=await t.env.data.clients.get(e);if(!r)return t.text("OK");const i=await t.env.data.clients.get("DEFAULT_CLIENT");t.set("client_id",e),t.set("tenant_id",r.tenant.id);const s=n||t.req.header("referer");if(!s)return t.text("OK");if(!Jo(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new N(400,{message:"Invalid redirect uri"});const o=t.req.header("cookie");if(o){const l=as(r.tenant.id,o);if(l){const u=await t.env.data.sessions.get(r.tenant.id,l);if(u){const p=await t.env.data.users.get(r.tenant.id,u.user_id);p&&(t.set("user_id",p.user_id),t.set("connection",p.connection))}await t.env.data.sessions.remove(r.tenant.id,l)}}const c=be(t,{type:me.SUCCESS_LOGOUT,description:"User successfully logged out"});return await t.env.data.logs.create(r.tenant.id,c),new Response("Redirecting",{status:302,headers:{"set-cookie":z_(r.tenant.id),location:s}})}),jp=a.z.object({sub:a.z.string(),email:a.z.string().optional(),family_name:a.z.string().optional(),given_name:a.z.string().optional(),email_verified:a.z.boolean()}),pb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:jp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new N(404,{message:"User not found"});const e=await t.env.data.users.get(t.var.user.tenant_id,t.var.user.sub);if(!e)throw new N(404,{message:"User not found"});return t.json(jp.parse({...e,sub:e.user_id}))}),fb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:cf}},description:"List of tenants"}}}),async t=>{const e=await t.env.data.keys.list(),n=await Promise.all(e.map(async r=>{const s=await new Ql(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return nl.parse({...o,kid:r.kid})}));return t.json({keys:n},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ni}, stale-while-revalidate=${Ni*2}, stale-if-error=86400`}})}).openapi(a.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Aa}},description:"List of tenants"}}}),async t=>{const e=Aa.parse({issuer:Jw(t.env),authorization_endpoint:`${Ce(t.env)}authorize`,token_endpoint:`${Ce(t.env)}oauth/token`,device_authorization_endpoint:`${Ce(t.env)}oauth/device/code`,userinfo_endpoint:`${Ce(t.env)}userinfo`,mfa_challenge_endpoint:`${Ce(t.env)}mfa/challenge`,jwks_uri:`${Ce(t.env)}.well-known/jwks.json`,registration_endpoint:`${Ce(t.env)}oidc/register`,revocation_endpoint:`${Ce(t.env)}oauth/revoke`,scopes_supported:["openid","profile","offline_access","name","given_name","family_name","nickname","email","email_verified","picture","created_at","identities","phone","address"],response_types_supported:["code","token","id_token","code token","code id_token","token id_token","code token id_token"],code_challenge_methods_supported:["S256","plain"],response_modes_supported:["query","fragment","form_post"],subject_types_supported:["public"],id_token_signing_alg_values_supported:["RS256"],token_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post"],claims_supported:["aud","auth_time","created_at","email","email_verified","exp","family_name","given_name","iat","identities","iss","name","nickname","phone_number","picture","sub"],request_uri_parameter_supported:!1,request_parameter_supported:!1,token_endpoint_auth_signing_alg_values_supported:["RS256","RS384","PS256"]});return t.json(e,{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${Ni}, stale-while-revalidate=${Ni*2}, stale-if-error=86400`}})});function Hi(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const Vg=a.z.object({grant_type:a.z.literal("client_credentials"),scope:a.z.string().optional(),client_secret:a.z.string(),client_id:a.z.string(),audience:a.z.string().optional()});async function hb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Invalid client credentials"});if(n.client_secret&&!Hi(n.client_secret,e.client_secret))throw new N(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await eo(t,{authParams:r,client:n});return t.json(i)}const gb=a.z.object({grant_type:a.z.literal("authorization_code"),client_id:a.z.string(),code:a.z.string(),redirect_uri:a.z.string().optional(),client_secret:a.z.string().optional(),code_verifier:a.z.string().optional()}).refine(t=>"client_secret"in t&&!("code_verifier"in t)||!("client_secret"in t)&&"code_verifier"in t,{message:"Must provide either client_secret (standard flow) or code_verifier/code_verifier_mode (PKCE flow), but not both"});async function mb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Client not found"});const r=await t.env.data.codes.get(n.tenant.id,e.code,"authorization_code");if(!r||!r.user_id)throw new N(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new N(403,{message:"Code expired"});if(r.used_at)throw new N(403,{message:"Code already used"});const i=await t.env.data.logins.get(n.tenant.id,r.login_id);if(!i)throw new N(403,{message:"Invalid login"});if("client_secret"in e){const o=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Hi(n.client_secret,e.client_secret)&&!Hi(o==null?void 0:o.client_secret,e.client_secret))throw new N(403,{message:"Invalid client credentials"})}else if("code_verifier"in e&&typeof e.code_verifier=="string"&&"code_challenge_method"in i.authParams&&typeof i.authParams.code_challenge_method=="string"){const o=await w_(e.code_verifier,i.authParams.code_challenge_method);if(!Hi(o,i.authParams.code_challenge||""))throw new N(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new N(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new N(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),sn(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Zt.WEB_MESSAGE}})}const _b=a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string(),redirect_uri:a.z.string().optional(),refresh_token:a.z.string()});async function yb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new N(403,{message:"Client not found"});const r=await t.env.data.refreshTokens.get(n.tenant.id,e.refresh_token);if(r){if(r.expires_at&&new Date(r.expires_at)<new Date||r.idle_expires_at&&new Date(r.idle_expires_at)<new Date)throw new N(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new N(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Invalid refresh token"})});const i=await t.env.data.users.get(n.tenant.id,r.user_id);if(!i)throw new N(403,{message:"User not found"});const s=r.resource_servers[0];if(r.idle_expires_at){const o=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:o.toISOString(),last_exchanged_at:new Date().toISOString(),device:{...r.device,last_ip:t.req.header["x-real-ip"]||"",last_user_agent:t.req.header["user-agent"]||""}})}return sn(t,{user:i,client:n,refreshToken:r.id,sessionId:r.session_id,authParams:{client_id:n.id,audience:s==null?void 0:s.audience,scope:s==null?void 0:s.scopes,response_mode:Zt.WEB_MESSAGE}})}const $p=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),vb=a.z.union([Vg.extend($p.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)}),a.z.object({grant_type:a.z.literal("authorization_code"),code:a.z.string(),redirect_uri:a.z.string().optional(),...$p.shape}),a.z.object({grant_type:a.z.literal("refresh_token"),client_id:a.z.string(),refresh_token:a.z.string(),redirect_uri:a.z.string().optional()})]);function wb(t){if(!t)return{};const[e,n]=t.split(" ");if((e==null?void 0:e.toLowerCase())==="basic"&&n){const[r,i]=atob(n).split(":");return{client_id:r,client_secret:i}}return{}}const bb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:vb}}}},responses:{200:{content:{"application/json":{schema:hf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=wb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new N(400,{message:"client_id is required"});switch(e.grant_type){case jr.AuthorizationCode:return mb(t,gb.parse(r));case jr.ClientCredential:return hb(t,Vg.parse(r));case jr.RefreshToken:return yb(t,_b.parse(r));default:throw new N(400,{message:"Not implemented"})}});var tu={exports:{}};const nu=[{id:0,value:"Too weak",minDiversity:0,minLength:0},{id:1,value:"Weak",minDiversity:2,minLength:6},{id:2,value:"Medium",minDiversity:4,minLength:8},{id:3,value:"Strong",minDiversity:4,minLength:10}],Mg=(t,e=nu,n="!\"#$%&'()*+,-./:;<=>?@[\\\\\\]^_`{|}~")=>{let r=t||"";e[0].minDiversity=0,e[0].minLength=0;const i=[{regex:"[a-z]",message:"lowercase"},{regex:"[A-Z]",message:"uppercase"},{regex:"[0-9]",message:"number"}];n&&i.push({regex:`[${n}]`,message:"symbol"});let s={};s.contains=i.filter(c=>new RegExp(`${c.regex}`).test(r)).map(c=>c.message),s.length=r.length;let o=e.filter(c=>s.contains.length>=c.minDiversity).filter(c=>s.length>=c.minLength).sort((c,l)=>l.id-c.id).map(c=>({id:c.id,value:c.value}));return Object.assign(s,o[0]),s};tu.exports={passwordStrength:Mg,defaultOptions:nu};var kb=tu.exports.passwordStrength=Mg;tu.exports.defaultOptions=nu;function ru(t){return kb(t).id<2?!1:t.length>=8&&/[a-z]/.test(t)&&/[A-Z]/.test(t)&&/[0-9]/.test(t)&&/[^A-Za-z0-9]/.test(t)}async function Zo(t,e){var i;const n=await t.env.data.emailProviders.get(t.var.tenant_id)||(t.env.DEFAULT_TENANT_ID?await t.env.data.emailProviders.get(t.env.DEFAULT_TENANT_ID):null);if(!n)throw new N(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new N(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function qg(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new N(500,{message:"Tenant not found"});const s=`${At(t.env)}reset-password?state=${r}&code=${n}`,o={vendorName:i.name,lng:i.language||"en"};await Zo(t,{to:e,subject:"Reset your password",html:`Click here to reset your password: ${At(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:de("password_reset_title",o),resetPasswordEmailClickToReset:de("reset_password_email_click_to_reset",o),resetPasswordEmailReset:de("reset_password_email_reset",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}})}async function Dg(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new N(500,{message:"Tenant not found"});const i={vendorName:r.name,code:n,lng:r.language||"en"};await Zo(t,{to:e,subject:de("code_email_subject",i),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",magicLink:`${Ce(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",i),linkEmailClickToLogin:de("link_email_click_to_login",i),linkEmailLogin:de("link_email_login",i),linkEmailOrEnterCode:de("link_email_or_enter_code",i),codeValid30Mins:de("code_valid_30_minutes",i),supportInfo:de("support_info",i),contactUs:de("contact_us",i),copyright:de("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(r.id,s))}async function iu(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new N(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new N(400,{message:"redirect_uri is required"});const s=new URL(Ce(t.env));s.pathname="passwordless/verify_redirect",s.searchParams.set("verification_code",n),s.searchParams.set("connection","email"),s.searchParams.set("client_id",r.client_id),s.searchParams.set("redirect_uri",r.redirect_uri),s.searchParams.set("email",e),r.response_type&&s.searchParams.set("response_type",r.response_type),r.scope&&s.searchParams.set("scope",r.scope),r.state&&s.searchParams.set("state",r.state),r.nonce&&s.searchParams.set("nonce",r.nonce),r.code_challenge&&s.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&s.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&s.searchParams.set("audience",r.audience);const o={vendorName:i.name,code:n,lng:i.language||"en"};await Zo(t,{to:e,subject:de("code_email_subject",o),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:s.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",o),linkEmailClickToLogin:de("link_email_click_to_login",o),linkEmailLogin:de("link_email_login",o),linkEmailOrEnterCode:de("link_email_or_enter_code",o),codeValid30Mins:de("code_valid_30_minutes",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}});const c=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(i.id,c))}async function su(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new N(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Zo(t,{to:e.email,subject:"Validate your email address",html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${At(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:de("welcome_to_your_account",r),verifyEmailVerify:de("verify_email_verify",r),supportInfo:de("support_info",r),contactUs:de("contact_us",r),copyright:de("copyright",r)}})}const xb=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("Username-Password-Authentication"),email:a.z.string().transform(t=>t.toLowerCase()),password:a.z.string()})}}}},responses:{200:{content:{"application/json":{schema:a.z.object({_id:a.z.string(),email:a.z.string(),email_verified:a.z.boolean(),app_metadata:a.z.object({}),user_metadata:a.z.object({})})}},description:"Created user"}}}),async t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.clients.get(r);if(!i)throw new N(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!ru(n))throw new N(400,{message:"Password does not meet the requirements"});if(await cs({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new N(400,{message:"Invalid sign up"});const o=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Ys()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",o.user_id),t.set("username",o.email),t.set("connection",o.connection);const c=await ii.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:o.user_id,password:c,algorithm:"bcrypt"}),await su(t,o);const l=be(t,{type:me.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:o.user_id,email:o.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("Username-Password-Authentication"),email:a.z.string().transform(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.clients.get(n);if(!r)throw new N(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await si({userAdapter:t.env.data.users,tenant_id:r.tenant.id,email:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},o=await t.env.data.logins.create(r.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:s,...Bn(t.req)});return await qg(t,e,o.login_id,o.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function sr(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}async function ou(t,e,n,r,i,s,o){const{env:c}=t,l=await c.data.codes.get(e.tenant.id,i,"otp");if(!l)throw new N(400,{message:"Code not found or expired"});if(l.expires_at<new Date().toISOString())throw new N(400,{message:"Code expired"});if(l.used_at)throw new N(400,{message:"Code already used"});const u=await c.data.logins.get(e.tenant.id,l.login_id);if(!u||u.authParams.username!==r)throw new N(400,{message:"Code not found or expired"});const p=Bn(t.req);if(o&&u.ip!==p.ip)return t.redirect(`${At(t.env)}invalid-session?state=${u.login_id}`);if(n.redirect_uri&&!Jo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new N(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const h=await no(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),sn(t,{user:h,client:e,loginSession:u,authParams:n,ticketAuth:s})}const Sb=new a.OpenAPIHono().openapi(a.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:a.z.object({client_id:a.z.string(),connection:a.z.string(),email:a.z.string().transform(t=>t.toLowerCase()),send:a.z.enum(["link","code"]),authParams:el.omit({client_id:!0})})}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,email:i,send:s,authParams:o}=e,c=await t.env.data.clients.get(r);if(!c)throw new N(400,{message:"Client not found"});t.set("client_id",c.id),t.set("tenant_id",c.tenant.id);const l=await n.data.logins.create(c.tenant.id,{authParams:{...o,client_id:r,username:i},expires_at:new Date(Date.now()+za).toISOString(),...Bn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:sr(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+za).toISOString()});return s==="link"?await iu(t,i,u.code_id,{...o,client_id:r}):await Dg(t,i,u.code_id),t.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(Jt),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(t=>t.toLowerCase()),audience:a.z.string().optional()})},responses:{302:{description:"Status"}}}),async t=>{const{env:e}=t,{client_id:n,email:r,verification_code:i,redirect_uri:s,state:o,scope:c,audience:l,response_type:u,nonce:p}=t.req.valid("query"),h=await Go(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),ou(t,h,{client_id:n,redirect_uri:s,state:o,nonce:p,scope:c,audience:l,response_type:u},r,i,!1,!0)});class Er extends N{constructor(n,r){super(n,r);ee(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function au(t,e,n,r,i){const{env:s}=t,o=n.username;if(t.set("username",o),!o)throw new N(400,{message:"Username is required"});const c=await si({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:o,provider:"auth2"});if(!c){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"User not found",code:"USER_NOT_FOUND"})}const l=c.linked_to?await s.data.users.get(e.tenant.id,c.linked_to):c;if(!l)throw new Er(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const u=await s.data.passwords.get(e.tenant.id,c.user_id);if(!(u&&await ii.compare(n.password,u.password))){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"Invalid password",code:"INVALID_PASSWORD"})}if((await s.data.logs.list(e.tenant.id,{page:0,per_page:10,include_totals:!1,q:`user_id:${l.user_id}`})).logs.filter(f=>f.type===me.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(f.date)>new Date(Date.now()-1e3*60*5)).length>=3){const f=be(t,{type:me.FAILED_LOGIN,description:"Too many failed login attempts"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new Er(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await su(t,c);const f=be(t,{type:me.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,f),new Er(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const v=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Qe(t,t.env.data.logs.create(e.tenant.id,v)),sn(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Ab(t,e,n,r){await no(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=sr(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=sr(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const o=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+E_).toISOString(),authParams:{client_id:e.id,username:n},...Bn(t.req)}),c=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:o.login_id,expires_at:new Date(Date.now()+A_).toISOString()});await qg(t,n,c.code_id,r)}const Eb=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(t=>t.toLowerCase()),realm:a.z.enum(["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(t=>t.toLowerCase()),password:a.z.string(),realm:a.z.enum(["Username-Password-Authentication"]),scope:a.z.string().optional()})])}}}},responses:{200:{description:"List of tenants"}}}),async t=>{const e=t.req.valid("json"),{client_id:n,username:r}=e;t.set("username",r);const i=await t.env.data.clients.get(n);if(!i)throw new N(400,{message:"Client not found"});t.set("client_id",n),t.set("tenant_id",i.tenant.id);const s=r.toLocaleLowerCase();if("otp"in e)return ou(t,i,{client_id:n,username:s},s,e.otp,!0);if("password"in e){const o=await t.env.data.logins.create(i.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:{client_id:n,username:s},...Bn(t.req)});return au(t,i,{username:s,password:e.password,client_id:n},o,!0)}else throw new N(400,{message:"Code or password required"})});function Ib(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ha(t))==null?void 0:r.host)??null;if(!n)return!1;for(const o of e){let c;if(o.startsWith("http://")||o.startsWith("https://")?c=((i=ha(o))==null?void 0:i.host)??null:c=((s=ha("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function ha(t){try{return new URL(t)}catch{return null}}async function zb({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const o=await t.env.data.logins.create(n.tenant.id,{expires_at:new Date(Date.now()+Ur*1e3).toISOString(),authParams:r,...Bn(t.req)});if(e&&s){const c=await t.env.data.users.get(n.tenant.id,e.user_id);if((c==null?void 0:c.email)===s)return sn(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=sr();return await t.env.data.codes.create(n.tenant.id,{code_id:c,code_type:"otp",login_id:o.login_id,expires_at:new Date(Date.now()+Ur*1e3).toISOString()}),await iu(t,s,c,r),t.redirect(`/u/enter-code?state=${o.login_id}`)}return e?t.redirect(`/u/check-account?state=${o.login_id}`):t.redirect(`/u/enter-email?state=${o.login_id}`)}function Cb(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new N(403,{message:"Invalid realm"})}async function Nb(t,e,n,r,i){var m;const{env:s}=t;t.set("connection",i);const o=await s.data.codes.get(e,n,"ticket");if(!o||o.used_at)throw new N(403,{message:"Ticket not found"});const c=await s.data.logins.get(e,o.login_id);if(!c||!c.authParams.username)throw new N(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new N(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const u=Cb(i);let p=await no(t,{email:c.authParams.username,provider:u,client:l,connection:u==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email),t.set("user_id",p.user_id);const h=await Tf(t,{user:p,client:l,scope:r.scope,audience:r.audience});return sn(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function Op(t,e){return`<!DOCTYPE html>
150
150
  <html>
151
151
 
152
152
  <head>
@@ -4509,7 +4509,7 @@ export interface CodesAdapter {
4509
4509
  export interface PasswordsAdapter {
4510
4510
  create: (tenant_id: string, params: PasswordInsert) => Promise<Password>;
4511
4511
  update: (tenant_id: string, params: PasswordInsert) => Promise<boolean>;
4512
- get: (tenant_id: string, user_id: string) => Promise<Password>;
4512
+ get: (tenant_id: string, user_id: string) => Promise<Password | null>;
4513
4513
  }
4514
4514
  export interface ListSesssionsResponse extends Totals {
4515
4515
  sessions: Session[];
package/dist/authhero.mjs CHANGED
@@ -3676,7 +3676,7 @@ function Ou(t) {
3676
3676
  }
3677
3677
  function o_(t) {
3678
3678
  return async (e, n) => {
3679
- if (console.log("got here"), !n.email || !n.email_verified)
3679
+ if (!n.email || !n.email_verified)
3680
3680
  return t.users.create(e, n);
3681
3681
  const r = await Ks({
3682
3682
  userAdapter: t.users,
@@ -19247,36 +19247,36 @@ function ir() {
19247
19247
  e += t[Math.floor(Math.random() * 10)];
19248
19248
  return e.toString();
19249
19249
  }
19250
- async function eu(t, e, n, r, i, s) {
19251
- const { env: o } = t, c = await o.data.codes.get(
19250
+ async function eu(t, e, n, r, i, s, o) {
19251
+ const { env: c } = t, l = await c.data.codes.get(
19252
19252
  e.tenant.id,
19253
19253
  i,
19254
19254
  "otp"
19255
19255
  );
19256
- if (!c)
19256
+ if (!l)
19257
19257
  throw new j(400, {
19258
19258
  message: "Code not found or expired"
19259
19259
  });
19260
- if (c.expires_at < (/* @__PURE__ */ new Date()).toISOString())
19260
+ if (l.expires_at < (/* @__PURE__ */ new Date()).toISOString())
19261
19261
  throw new j(400, {
19262
19262
  message: "Code expired"
19263
19263
  });
19264
- if (c.used_at)
19264
+ if (l.used_at)
19265
19265
  throw new j(400, {
19266
19266
  message: "Code already used"
19267
19267
  });
19268
- const l = await o.data.logins.get(
19268
+ const u = await c.data.logins.get(
19269
19269
  e.tenant.id,
19270
- c.login_id
19270
+ l.login_id
19271
19271
  );
19272
- if (!l || l.authParams.username !== r)
19272
+ if (!u || u.authParams.username !== r)
19273
19273
  throw new j(400, {
19274
19274
  message: "Code not found or expired"
19275
19275
  });
19276
- const u = Tn(t.req);
19277
- if (l.ip !== u.ip)
19276
+ const p = Tn(t.req);
19277
+ if (o && u.ip !== p.ip)
19278
19278
  return t.redirect(
19279
- `${Et(t.env)}invalid-session?state=${l.login_id}`
19279
+ `${Et(t.env)}invalid-session?state=${u.login_id}`
19280
19280
  );
19281
19281
  if (n.redirect_uri && !Mo(n.redirect_uri, e.callbacks, {
19282
19282
  allowPathWildcards: !0
@@ -19284,7 +19284,7 @@ async function eu(t, e, n, r, i, s) {
19284
19284
  throw new j(400, {
19285
19285
  message: `Invalid redirect URI - ${n.redirect_uri}`
19286
19286
  });
19287
- const p = await Ws(t, {
19287
+ const h = await Ws(t, {
19288
19288
  client: e,
19289
19289
  email: r,
19290
19290
  provider: "email",
@@ -19292,10 +19292,10 @@ async function eu(t, e, n, r, i, s) {
19292
19292
  isSocial: !1,
19293
19293
  ip: t.req.header("x-real-ip")
19294
19294
  });
19295
- return await o.data.codes.used(e.tenant.id, i), nn(t, {
19296
- user: p,
19295
+ return await c.data.codes.used(e.tenant.id, i), nn(t, {
19296
+ user: h,
19297
19297
  client: e,
19298
- loginSession: l,
19298
+ loginSession: u,
19299
19299
  authParams: n,
19300
19300
  ticketAuth: s
19301
19301
  });
@@ -19395,7 +19395,9 @@ const vb = new le().openapi(
19395
19395
  response_type: u
19396
19396
  },
19397
19397
  r,
19398
- i
19398
+ i,
19399
+ !1,
19400
+ !0
19399
19401
  );
19400
19402
  }
19401
19403
  );
@@ -19436,11 +19438,8 @@ async function tu(t, e, n, r, i) {
19436
19438
  code: "USER_NOT_FOUND"
19437
19439
  });
19438
19440
  t.set("connection", c.connection), t.set("user_id", l.user_id);
19439
- const { password: u } = await s.data.passwords.get(
19440
- e.tenant.id,
19441
- c.user_id
19442
- );
19443
- if (!await si.compare(n.password, u)) {
19441
+ const u = await s.data.passwords.get(e.tenant.id, c.user_id);
19442
+ if (!(u && await si.compare(n.password, u.password))) {
19444
19443
  const f = xe(t, {
19445
19444
  type: ve.FAILED_LOGIN_INCORRECT_PASSWORD,
19446
19445
  description: "Invalid password"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authhero",
3
- "version": "0.77.0",
3
+ "version": "0.79.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],
@@ -25,7 +25,7 @@
25
25
  "vite": "^5.4.11",
26
26
  "vite-plugin-dts": "^4.3.0",
27
27
  "vitest": "^2.1.5",
28
- "@authhero/kysely-adapter": "^9.0.0"
28
+ "@authhero/kysely-adapter": "^9.1.0"
29
29
  },
30
30
  "dependencies": {
31
31
  "@peculiar/x509": "^1.12.3",
@@ -37,7 +37,7 @@
37
37
  "i18next": "^24.2.0",
38
38
  "nanoid": "^5.0.8",
39
39
  "oslo": "^1.2.1",
40
- "@authhero/adapter-interfaces": "^0.47.0"
40
+ "@authhero/adapter-interfaces": "^0.48.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@hono/zod-openapi": "^0.18.0",