authhero 0.67.0 → 0.68.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
@@ -146,7 +146,7 @@ PERFORMANCE OF THIS SOFTWARE.
146
146
  }};
147
147
  <\/script>
148
148
  </body>
149
- </html>`;return new Response(i,{headers:{"Content-Type":"text/html"}})}async function Jw(t,e,n,r,i){var m,y,f;if(!n.redirect_uri)throw new z(400,{message:"Missing redirect_uri in authParams"});const[s]=await t.env.data.keys.list();if(!s)throw new z(500,{message:"No signing key found"});if(!((m=e.addons)!=null&&m.samlp))throw new z(400,{message:`SAML Addon is not enabled for client ${e.id}`});const{recipient:o,audience:c}=e.addons.samlp,l=n.state||"";if(!o||!l||!r||!n.state)throw new z(400,{message:"Missing recipient or inResponseTo"});const u=JSON.parse(n.state),p=new URL(n.redirect_uri),h=await Zw(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:u.requestId,userId:((f=(y=r.app_metadata)==null?void 0:y.vimeo)==null?void 0:f.user_id)||r.user_id,email:r.email,sessionIndex:i,signature:{privateKeyPem:s.pkcs7,cert:s.cert,kid:s.kid}});return Gw(p.toString(),h,u.relayState)}async function Zw(t,e){const n=e.notBefore||new Date().toISOString(),r=e.notAfter||new Date(new Date(n).getTime()+10*60*1e3).toISOString(),i=e.issueInstant||n,s=e.sessionNotOnOrAfter||r,o=e.responseId||`_${qe()}`,c=e.assertionId||`_${qe()}`,l=[{"samlp:Response":[{"saml:Issuer":[{"#text":e.issuer}]},{"samlp:Status":[{"samlp:StatusCode":[],":@":{"@_Value":"urn:oasis:names:tc:SAML:2.0:status:Success"}}]},{"saml:Assertion":[{"saml:Issuer":[{"#text":e.issuer}]},{"saml:Subject":[{"saml:NameID":[{"#text":e.email}],":@":{"@_Format":"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"}},{"saml:SubjectConfirmation":[{"saml:SubjectConfirmationData":[],":@":{"@_InResponseTo":e.inResponseTo,"@_NotOnOrAfter":r,"@_Recipient":e.destination}}],":@":{"@_Method":"urn:oasis:names:tc:SAML:2.0:cm:bearer"}}]},{"saml:Conditions":[{"saml:AudienceRestriction":[{"saml:Audience":[{"#text":e.audience}]}]}],":@":{"@_NotBefore":n,"@_NotOnOrAfter":r}},{"saml:AuthnStatement":[{"saml:AuthnContext":[{"saml:AuthnContextClassRef":[{"#text":"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"}]}]}],":@":{"@_AuthnInstant":i,"@_SessionIndex":e.sessionIndex,"@_SessionNotOnOrAfter":s}},{"saml:AttributeStatement":[{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.userId}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_FriendlyName":"persistent","@_Name":"id","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.email}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"email","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"default-roles-master"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"offline_access"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"view-profile"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"uma_authorization"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account-links"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}}]}],":@":{"@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion","@_ID":c,"@_IssueInstant":i,"@_Version":"2.0"}}],":@":{"@_xmlns:samlp":"urn:oasis:names:tc:SAML:2.0:protocol","@_xmlns:saml":"urn:oasis:names:tc:SAML:2.0:assertion","@_Destination":e.destination,"@_ID":o,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let p=new Ww.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(l);if(e.signature){const m=await fetch(t.env.SAML_SIGN_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xmlContent:p,privateKey:e.signature.privateKeyPem,publicCert:e.signature.cert})});if(!m.ok)throw new Error(`Failed to sign SAML response: ${m.status}`);p=await m.text()}return e.encode===!1?p:btoa(p)}function Yw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),gn.encode(t,{includePadding:!1})}const Ap=["sub","iss","aud","exp","nbf","iat","jti"];async function Yl(t,e){var _,w;const{authParams:n,user:r,client:i,session_id:s}=e,c=(await t.env.data.keys.list()).filter(S=>!S.revoked_at||new Date(S.revoked_at)>new Date),l=c[c.length-1];if(!(l!=null&&l.pkcs7))throw new z(500,{message:"No signing key available"});const u=Ev(l.pkcs7),p={aud:n.audience||"default",scope:n.scope||"",sub:(r==null?void 0:r.user_id)||n.client_id,iss:t.env.ISSUER,tenant_id:t.var.tenant_id,sid:s},h=r&&((_=n.scope)!=null&&_.split(" ").includes("openid"))?{aud:n.client_id,sub:r.user_id,iss:t.env.ISSUER,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified}:void 0;(w=t.env.hooks)!=null&&w.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({client:i,user:r,scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(S,N)=>{if(Ap.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);p[S]=N}},idToken:{setCustomClaim:(S,N)=>{if(Ap.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);h&&(h[S]=N)}},access:{deny:S=>{throw new z(400,{message:`Access denied: ${S}`})}}});const m={includeIssuedTimestamp:!0,expiresIn:new Fl(1,"d"),headers:{kid:l.kid}},y=await vp("RS256",u,p,m),f=h?await vp("RS256",u,h,m):void 0;return{access_token:y,refresh_token:e.refresh_token,id_token:f,token_type:"Bearer",expires_in:86400}}async function Xw(t,e){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=e;return await t.env.data.refreshTokens.create(n.tenant.id,{id:qe(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+Mo*1e3).toISOString(),user_id:e.user.user_id,device:{last_ip:t.req.header("x-real-ip")||"",initial_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||"",initial_user_agent:t.req.header("user-agent")||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Bg(t,e){const{user:n,client:r,scope:i,audience:s}=e,o=await t.env.data.sessions.create(r.tenant.id,{id:qe(),user_id:n.user_id,idle_expires_at:new Date(Date.now()+Mo*1e3).toISOString(),device:{last_ip:t.req.header("x-real-ip")||"",initial_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||"",initial_user_agent:t.req.header("user-agent")||"",initial_asn:"",last_asn:""},clients:[r.id]}),c=i!=null&&i.split(" ").includes("offline_access")?await Xw(t,{...e,session_id:o.id,scope:i,audience:s}):void 0;return{...o,refresh_token:c}}async function Tn(t,e){var h;const{authParams:n,user:r,client:i}=e,s=be(t,{type:me.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id});if(Xe(t,t.env.data.logs.create(i.tenant.id,s)),Xe(t,t.env.data.users.update(i.tenant.id,r.user_id,{last_login:new Date().toISOString(),last_ip:t.req.header("x-real-ip")||"",login_count:r.login_count+1})),e!=null&&e.ticketAuth){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const m=Yw(),y=qe(12),f=await t.env.data.codes.create(i.tenant.id,{code_id:qe(),code_type:"ticket",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ry).toISOString(),code_verifier:[y,m].join("|")});return t.json({login_ticket:f.code_id,co_verifier:m,co_id:y})}let o=e.refreshToken,c=e.sessionId;if(!c){const m=await Bg(t,{user:r,client:i,scope:n.scope,audience:n.audience});c=m.id,o=(h=m.refresh_token)==null?void 0:h.id}if(e.authParams.response_mode===Jt.SAML_POST)return Jw(t,e.client,e.authParams,r,c);const l=await Yl(t,{authParams:n,user:r,client:i,session_id:c,refresh_token:o}),u=new Headers({"set-cookie":Eg(i.tenant.id,c)});if(n.response_mode===Jt.WEB_MESSAGE)return t.json(l,{headers:u});if((n.response_type||mn.CODE)===mn.CODE){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const m=await t.env.data.codes.create(i.tenant.id,{code_id:qe(),user_id:r.user_id,code_type:"authorization_code",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ty*1e3).toISOString()});u.set("location",`${n.redirect_uri}?state=${e.authParams.state}&code=${m.code_id}`)}return new Response("Redirecting",{status:302,headers:u})}function Qw(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await Zs({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)}}async function Tg(t,e,n){for await(const r of e)if(!(await fetch(r.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok){const s=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});await n.logs.create(t.var.tenant_id,s)}}function eb(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n);return await Tg(t,i,{tenant_id:n,user:r,trigger_id:"post-user-registration"}),r}}function tb(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n,{q:"trigger_id:pre-user-signup",page:0,per_page:100,include_totals:!1});await Tg(t,i,{tenant_id:n,email:r,trigger_id:"pre-user-signup"})}}function nb(t,e){return async(n,r)=>{let i=await Qw(e)(n,r);return await eb(t,e)(n,i),i}}async function Pg(t,e,n,r){if(e.disable_sign_ups&&!await Zs({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:r})){const s=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});throw await t.env.data.logs.create(e.tenant.id,s),new z(400,{message:"Signups are disabled for this client"})}await tb(t,n)(t.var.tenant_id||"",r)}function rb(t,e){return{...e,users:{...e.users,create:nb(t,e)}}}async function ib(t,e,n,r){if(!r.state)throw new z(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 z(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()+Xr*1e3).toISOString(),authParams:r,...Bn(t.req)}));const c=await kg(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()+Py*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Ep(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 z(403,{message:"State not found"});const s=await r.data.logins.get(t.var.tenant_id||"",i.login_id);if(!s)throw new z(403,{message:"Session not found"});const o=await Do(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 z(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 z(403,{message:"Redirect URI not defined"})}if(!Ho(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 z(403,{message:_})}const u=await kg(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);let y=await _n({userAdapter:r.data.users,tenant_id:o.tenant.id,email:m,provider:c.name});if(!y){try{await Pg(t,o,t.env.data,m)}catch(_){const w=_;throw new z(500,{message:`Failed to run preUserSignupHook: ${w.message}`})}y=await r.data.users.create(o.tenant.id,{user_id:`${c.name}|${p}`,email:m,name:m,provider:c.name,connection:c.name,email_verified:!0,last_ip:"",is_social:!0,last_login:new Date().toISOString(),profileData:JSON.stringify(h)}),t.set("user_id",y.user_id)}return Tn(t,{client:o,authParams:s.authParams,loginSession:s,user:y})}async function Ip(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 z(400,{message:"State not found"});const c=await t.env.data.logins.get(t.var.tenant_id,o.login_id);if(!c)throw new z(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new z(400,{message:"Redirect uri not found"});const u=be(t,{type:me.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});Xe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Oy(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 sb=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 Ip(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ep(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 Ip(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ep(t,{code:n,state:e})}),ob=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(!Ho(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new z(400,{message:"Invalid redirect uri"});const o=t.req.header("cookie");if(o){const l=Ag(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":Nv(r.tenant.id),location:s}})}),Cp=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()}),ab=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Cp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new z(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 z(404,{message:"User not found"});return t.json(Cp.parse({...e,sub:e.user_id}))}),cb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:sf}},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 Dl(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return Xc.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=${Ti}, stale-while-revalidate=${Ti*2}, stale-if-error=86400`}})}).openapi(a.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:ba}},description:"List of tenants"}}}),async t=>{const e=ba.parse({issuer:pv(t.env),authorization_endpoint:`${Ne(t.env)}authorize`,token_endpoint:`${Ne(t.env)}oauth/token`,device_authorization_endpoint:`${Ne(t.env)}oauth/device/code`,userinfo_endpoint:`${Ne(t.env)}userinfo`,mfa_challenge_endpoint:`${Ne(t.env)}mfa/challenge`,jwks_uri:`${Ne(t.env)}.well-known/jwks.json`,registration_endpoint:`${Ne(t.env)}oidc/register`,revocation_endpoint:`${Ne(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=${Ti}, stale-while-revalidate=${Ti*2}, stale-if-error=86400`}})});function Fi(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 Rg=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 lb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(403,{message:"Invalid client credentials"});if(n.client_secret&&!Fi(n.client_secret,e.client_secret))throw new z(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await Yl(t,{authParams:r,client:n});return t.json(i)}const ub=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 db(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(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 z(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new z(403,{message:"Code expired"});if(r.used_at)throw new z(403,{message:"Code already used"});const i=await t.env.data.logins.get(n.tenant.id,r.login_id);if(!i)throw new z(403,{message:"Invalid login"});if("client_secret"in e){const o=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Fi(n.client_secret,e.client_secret)&&!Fi(o==null?void 0:o.client_secret,e.client_secret))throw new z(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 Iv(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(o,i.authParams.code_challenge||""))throw new z(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new z(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new z(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),Tn(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Jt.WEB_MESSAGE}})}const pb=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 fb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(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 z(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new z(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 z(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 Tn(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:Jt.WEB_MESSAGE}})}const Np=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),hb=a.z.union([Rg.extend(Np.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(),...Np.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 gb(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 mb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:hb}}}},responses:{200:{content:{"application/json":{schema:df}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=gb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new z(400,{message:"client_id is required"});switch(e.grant_type){case jr.AuthorizationCode:return db(t,ub.parse(r));case jr.ClientCredential:return lb(t,Rg.parse(r));case jr.RefreshToken:return fb(t,pb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var Xl={exports:{}};const Ql=[{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}],Lg=(t,e=Ql,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};Xl.exports={passwordStrength:Lg,defaultOptions:Ql};var _b=Xl.exports.passwordStrength=Lg;Xl.exports.defaultOptions=Ql;function eu(t){return _b(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 Ko(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 z(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new z(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function Ug(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new z(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 Ko(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:fe("password_reset_title",o),resetPasswordEmailClickToReset:fe("reset_password_email_click_to_reset",o),resetPasswordEmailReset:fe("reset_password_email_reset",o),supportInfo:fe("support_info",o),contactUs:fe("contact_us",o),copyright:fe("copyright",o)}})}async function Vg(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new z(500,{message:"Tenant not found"});const i={vendorName:r.name,code:n,lng:r.language||"en"};await Ko(t,{to:e,subject:fe("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:`${Ne(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:fe("welcome_to_your_account",i),linkEmailClickToLogin:fe("link_email_click_to_login",i),linkEmailLogin:fe("link_email_login",i),linkEmailOrEnterCode:fe("link_email_or_enter_code",i),codeValid30Mins:fe("code_valid_30_minutes",i),supportInfo:fe("support_info",i),contactUs:fe("contact_us",i),copyright:fe("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Xe(t,t.env.data.logs.create(r.id,s))}async function tu(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new z(500,{message:"Tenant not found"});const i={vendorName:r.name,code:n,lng:r.language||"en"};await Ko(t,{to:e,subject:fe("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:`${Ne(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:fe("welcome_to_your_account",i),linkEmailClickToLogin:fe("link_email_click_to_login",i),linkEmailLogin:fe("link_email_login",i),linkEmailOrEnterCode:fe("link_email_or_enter_code",i),codeValid30Mins:fe("code_valid_30_minutes",i),supportInfo:fe("support_info",i),contactUs:fe("contact_us",i),copyright:fe("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Xe(t,t.env.data.logs.create(r.id,s))}async function nu(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new z(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Ko(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:fe("welcome_to_your_account",r),verifyEmailVerify:fe("verify_email_verify",r),supportInfo:fe("support_info",r),contactUs:fe("contact_us",r),copyright:fe("copyright",r)}})}const yb=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 z(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!eu(n))throw new z(400,{message:"Password does not meet the requirements"});if(await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const o=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${oi()}`,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 si.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:o.user_id,password:c,algorithm:"bcrypt"}),await nu(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 z(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await Kn({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()+Xr*1e3).toISOString(),authParams:s,...Bn(t.req)});return await Ug(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 ir(){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 ru(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 z(400,{message:"Code not found or expired"});if(c.expires_at<new Date().toISOString())throw new z(400,{message:"Code expired"});if(c.used_at)throw new z(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 z(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&&!Ho(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const p=await _n({userAdapter:o.data.users,tenant_id:e.tenant.id,email:r,provider:"email"});if(!p)throw new z(400,{message:"User not found"});return await o.data.codes.used(e.tenant.id,i),Tn(t,{user:p,client:e,loginSession:l,authParams:n,ticketAuth:s})}const vb=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:Yc.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 z(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()+qc).toISOString(),...Bn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:ir(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+qc).toISOString()});return s==="link"?await tu(t,i,u.code_id):await Vg(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(mn),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 Do(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),ru(t,h,{client_id:n,redirect_uri:s,state:o,nonce:p,scope:c,audience:l,response_type:u},r,i)});class Ir extends z{constructor(n,r){super(n,r);ee(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function iu(t,e,n,r,i){const{env:s}=t,o=n.username;if(t.set("username",o),!o)throw new z(400,{message:"Username is required"});const c=await Kn({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 Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(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 Ir(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 si.compare(n.password,u)){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(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 Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await nu(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 Ir(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const y=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Xe(t,t.env.data.logs.create(e.tenant.id,y)),Tn(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function wb(t,e,n,r){let i=await _n({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n,provider:"auth2"});if(!i){if(!(await el(t.env.data.users,e.tenant.id,n)).length)return;i=await t.env.data.users.create(e.tenant.id,{user_id:`email|${oi()}`,email:n,email_verified:!1,is_social:!1,provider:"auth2",connection:"Username-Password-Authentication"})}const s=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+Uy).toISOString(),authParams:{client_id:e.id,username:n},...Bn(t.req)});let o=ir(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");for(;c;)o=ir(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");const l=await t.env.data.codes.create(e.tenant.id,{code_id:o,code_type:"password_reset",login_id:s.login_id,expires_at:new Date(Date.now()+Ly).toISOString()});await Ug(t,n,l.code_id,r)}const bb=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 z(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 ru(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()+Xr*1e3).toISOString(),authParams:{client_id:n,username:s},...Bn(t.req)});return iu(t,i,{username:s,password:e.password,client_id:n},o,!0)}else throw new z(400,{message:"Code or password required"})});function xb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ua(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=ua(o))==null?void 0:i.host)??null:c=((s=ua("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function ua(t){try{return new URL(t)}catch{return null}}async function kb({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()+Xr*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 Tn(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=ir();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()+Xr*1e3).toISOString()}),await tu(t,s,c),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 Sb(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Ab(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 z(403,{message:"Ticket not found"});const c=await s.data.logins.get(e,o.login_id);if(!c||!c.authParams.username)throw new z(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new z(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const u=Sb(i);let p=await _n({userAdapter:s.data.users,tenant_id:e,email:c.authParams.username,provider:u});p||(p=await s.data.users.create(e,{user_id:`email|${oi()}`,email:c.authParams.username,name:c.authParams.username,provider:"email",connection:"email",email_verified:!0,is_social:!1,last_ip:"",last_login:new Date().toISOString()})),t.set("username",p.email),t.set("user_id",p.user_id);const h=await Bg(t,{user:p,client:l,scope:r.scope,audience:r.audience});return Tn(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function zp(t,e){return`<!DOCTYPE html>
149
+ </html>`;return new Response(i,{headers:{"Content-Type":"text/html"}})}async function Jw(t,e,n,r,i){var m,y,f;if(!n.redirect_uri)throw new z(400,{message:"Missing redirect_uri in authParams"});const[s]=await t.env.data.keys.list();if(!s)throw new z(500,{message:"No signing key found"});if(!((m=e.addons)!=null&&m.samlp))throw new z(400,{message:`SAML Addon is not enabled for client ${e.id}`});const{recipient:o,audience:c}=e.addons.samlp,l=n.state||"";if(!o||!l||!r||!n.state)throw new z(400,{message:"Missing recipient or inResponseTo"});const u=JSON.parse(n.state),p=new URL(n.redirect_uri),h=await Zw(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:u.requestId,userId:((f=(y=r.app_metadata)==null?void 0:y.vimeo)==null?void 0:f.user_id)||r.user_id,email:r.email,sessionIndex:i,signature:{privateKeyPem:s.pkcs7,cert:s.cert,kid:s.kid}});return Gw(p.toString(),h,u.relayState)}async function Zw(t,e){const n=e.notBefore||new Date().toISOString(),r=e.notAfter||new Date(new Date(n).getTime()+10*60*1e3).toISOString(),i=e.issueInstant||n,s=e.sessionNotOnOrAfter||r,o=e.responseId||`_${qe()}`,c=e.assertionId||`_${qe()}`,l=[{"samlp:Response":[{"saml:Issuer":[{"#text":e.issuer}]},{"samlp:Status":[{"samlp:StatusCode":[],":@":{"@_Value":"urn:oasis:names:tc:SAML:2.0:status:Success"}}]},{"saml:Assertion":[{"saml:Issuer":[{"#text":e.issuer}]},{"saml:Subject":[{"saml:NameID":[{"#text":e.email}],":@":{"@_Format":"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"}},{"saml:SubjectConfirmation":[{"saml:SubjectConfirmationData":[],":@":{"@_InResponseTo":e.inResponseTo,"@_NotOnOrAfter":r,"@_Recipient":e.destination}}],":@":{"@_Method":"urn:oasis:names:tc:SAML:2.0:cm:bearer"}}]},{"saml:Conditions":[{"saml:AudienceRestriction":[{"saml:Audience":[{"#text":e.audience}]}]}],":@":{"@_NotBefore":n,"@_NotOnOrAfter":r}},{"saml:AuthnStatement":[{"saml:AuthnContext":[{"saml:AuthnContextClassRef":[{"#text":"urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified"}]}]}],":@":{"@_AuthnInstant":i,"@_SessionIndex":e.sessionIndex,"@_SessionNotOnOrAfter":s}},{"saml:AttributeStatement":[{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.userId}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_FriendlyName":"persistent","@_Name":"id","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":e.email}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"email","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"default-roles-master"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"offline_access"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"view-profile"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"uma_authorization"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}},{"saml:Attribute":[{"saml:AttributeValue":[{"#text":"manage-account-links"}],":@":{"@_xmlns:xs":"http://www.w3.org/2001/XMLSchema","@_xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","@_xsi:type":"xs:string"}}],":@":{"@_Name":"Role","@_NameFormat":"urn:oasis:names:tc:SAML:2.0:attrname-format:basic"}}]}],":@":{"@_xmlns":"urn:oasis:names:tc:SAML:2.0:assertion","@_ID":c,"@_IssueInstant":i,"@_Version":"2.0"}}],":@":{"@_xmlns:samlp":"urn:oasis:names:tc:SAML:2.0:protocol","@_xmlns:saml":"urn:oasis:names:tc:SAML:2.0:assertion","@_Destination":e.destination,"@_ID":o,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let p=new Ww.XMLBuilder({ignoreAttributes:!1,suppressEmptyNode:!0,preserveOrder:!0}).build(l);if(e.signature){const m=await fetch(t.env.SAML_SIGN_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xmlContent:p,privateKey:e.signature.privateKeyPem,publicCert:e.signature.cert})});if(!m.ok)throw new Error(`Failed to sign SAML response: ${m.status}`);p=await m.text()}return e.encode===!1?p:btoa(p)}function Yw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),gn.encode(t,{includePadding:!1})}const Ap=["sub","iss","aud","exp","nbf","iat","jti"];async function Yl(t,e){var _,w;const{authParams:n,user:r,client:i,session_id:s}=e,c=(await t.env.data.keys.list()).filter(S=>!S.revoked_at||new Date(S.revoked_at)>new Date),l=c[c.length-1];if(!(l!=null&&l.pkcs7))throw new z(500,{message:"No signing key available"});const u=Ev(l.pkcs7),p={aud:n.audience||"default",scope:n.scope||"",sub:(r==null?void 0:r.user_id)||n.client_id,iss:t.env.ISSUER,tenant_id:t.var.tenant_id,sid:s},h=r&&((_=n.scope)!=null&&_.split(" ").includes("openid"))?{aud:n.client_id,sub:r.user_id,iss:t.env.ISSUER,sid:s,nonce:n.nonce,given_name:r.given_name,family_name:r.family_name,nickname:r.nickname,picture:r.picture,locale:r.locale,name:r.name,email:r.email,email_verified:r.email_verified}:void 0;(w=t.env.hooks)!=null&&w.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({client:i,user:r,scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(S,N)=>{if(Ap.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);p[S]=N}},idToken:{setCustomClaim:(S,N)=>{if(Ap.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);h&&(h[S]=N)}},access:{deny:S=>{throw new z(400,{message:`Access denied: ${S}`})}}});const m={includeIssuedTimestamp:!0,expiresIn:new Fl(1,"d"),headers:{kid:l.kid}},y=await vp("RS256",u,p,m),f=h?await vp("RS256",u,h,m):void 0;return{access_token:y,refresh_token:e.refresh_token,id_token:f,token_type:"Bearer",expires_in:86400}}async function Xw(t,e){const{client:n,scope:r,audience:i=n.tenant.audience,session_id:s}=e;return await t.env.data.refreshTokens.create(n.tenant.id,{id:qe(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+Mo*1e3).toISOString(),user_id:e.user.user_id,device:{last_ip:t.req.header("x-real-ip")||"",initial_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||"",initial_user_agent:t.req.header("user-agent")||"",initial_asn:"",last_asn:""},resource_servers:[{audience:i,scopes:r}],rotating:!1})}async function Bg(t,e){const{user:n,client:r,scope:i,audience:s}=e,o=await t.env.data.sessions.create(r.tenant.id,{id:qe(),user_id:n.user_id,idle_expires_at:new Date(Date.now()+Mo*1e3).toISOString(),device:{last_ip:t.req.header("x-real-ip")||"",initial_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||"",initial_user_agent:t.req.header("user-agent")||"",initial_asn:"",last_asn:""},clients:[r.id]}),c=i!=null&&i.split(" ").includes("offline_access")?await Xw(t,{...e,session_id:o.id,scope:i,audience:s}):void 0;return{...o,refresh_token:c}}async function Tn(t,e){var h;const{authParams:n,user:r,client:i}=e,s=be(t,{type:me.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id});if(Xe(t,t.env.data.logs.create(i.tenant.id,s)),Xe(t,t.env.data.users.update(i.tenant.id,r.user_id,{last_login:new Date().toISOString(),last_ip:t.req.header("x-real-ip")||"",login_count:r.login_count+1})),e!=null&&e.ticketAuth){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const m=Yw(),y=qe(12),f=await t.env.data.codes.create(i.tenant.id,{code_id:qe(),code_type:"ticket",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ry).toISOString(),code_verifier:[y,m].join("|")});return t.json({login_ticket:f.code_id,co_verifier:m,co_id:y})}let o=e.refreshToken,c=e.sessionId;if(!c){const m=await Bg(t,{user:r,client:i,scope:n.scope,audience:n.audience});c=m.id,o=(h=m.refresh_token)==null?void 0:h.id}if(e.authParams.response_mode===Jt.SAML_POST)return Jw(t,e.client,e.authParams,r,c);const l=await Yl(t,{authParams:n,user:r,client:i,session_id:c,refresh_token:o}),u=new Headers({"set-cookie":Eg(i.tenant.id,c)});if(n.response_mode===Jt.WEB_MESSAGE)return t.json(l,{headers:u});if((n.response_type||mn.CODE)===mn.CODE){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const m=await t.env.data.codes.create(i.tenant.id,{code_id:qe(),user_id:r.user_id,code_type:"authorization_code",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ty*1e3).toISOString()});u.set("location",`${n.redirect_uri}?state=${e.authParams.state}&code=${m.code_id}`)}return new Response("Redirecting",{status:302,headers:u})}function Qw(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await Zs({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)}}async function Tg(t,e,n){for await(const r of e)if(!(await fetch(r.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).ok){const s=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});await n.logs.create(t.var.tenant_id,s)}}function eb(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n);return await Tg(t,i,{tenant_id:n,user:r,trigger_id:"post-user-registration"}),r}}function tb(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n,{q:"trigger_id:pre-user-signup",page:0,per_page:100,include_totals:!1});await Tg(t,i,{tenant_id:n,email:r,trigger_id:"pre-user-signup"})}}function nb(t,e){return async(n,r)=>{let i=await Qw(e)(n,r);return await eb(t,e)(n,i),i}}async function Pg(t,e,n,r){if(e.disable_sign_ups&&!await Zs({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:r})){const s=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});throw await t.env.data.logs.create(e.tenant.id,s),new z(400,{message:"Signups are disabled for this client"})}await tb(t,n)(t.var.tenant_id||"",r)}function rb(t,e){return{...e,users:{...e.users,create:nb(t,e)}}}async function ib(t,e,n,r){if(!r.state)throw new z(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 z(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()+Xr*1e3).toISOString(),authParams:r,...Bn(t.req)}));const c=await kg(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()+Py*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Ep(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 z(403,{message:"State not found"});const s=await r.data.logins.get(t.var.tenant_id||"",i.login_id);if(!s)throw new z(403,{message:"Session not found"});const o=await Do(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 z(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 z(403,{message:"Redirect URI not defined"})}if(!Ho(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 z(403,{message:_})}const u=await kg(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);let y=await _n({userAdapter:r.data.users,tenant_id:o.tenant.id,email:m,provider:c.name});if(!y){try{await Pg(t,o,t.env.data,m)}catch(_){const w=_;throw new z(500,{message:`Failed to run preUserSignupHook: ${w.message}`})}y=await r.data.users.create(o.tenant.id,{user_id:`${c.name}|${p}`,email:m,name:m,provider:c.name,connection:c.name,email_verified:!0,last_ip:"",is_social:!0,last_login:new Date().toISOString(),profileData:JSON.stringify(h)}),t.set("user_id",y.user_id)}return Tn(t,{client:o,authParams:s.authParams,loginSession:s,user:y})}async function Ip(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 z(400,{message:"State not found"});const c=await t.env.data.logins.get(t.var.tenant_id,o.login_id);if(!c)throw new z(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new z(400,{message:"Redirect uri not found"});const u=be(t,{type:me.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});Xe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Oy(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 sb=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 Ip(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ep(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 Ip(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ep(t,{code:n,state:e})}),ob=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(!Ho(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new z(400,{message:"Invalid redirect uri"});const o=t.req.header("cookie");if(o){const l=Ag(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":Nv(r.tenant.id),location:s}})}),Cp=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()}),ab=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Cp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new z(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 z(404,{message:"User not found"});return t.json(Cp.parse({...e,sub:e.user_id}))}),cb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:sf}},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 Dl(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return Xc.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=${Ti}, stale-while-revalidate=${Ti*2}, stale-if-error=86400`}})}).openapi(a.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:ba}},description:"List of tenants"}}}),async t=>{const e=ba.parse({issuer:pv(t.env),authorization_endpoint:`${Ne(t.env)}authorize`,token_endpoint:`${Ne(t.env)}oauth/token`,device_authorization_endpoint:`${Ne(t.env)}oauth/device/code`,userinfo_endpoint:`${Ne(t.env)}userinfo`,mfa_challenge_endpoint:`${Ne(t.env)}mfa/challenge`,jwks_uri:`${Ne(t.env)}.well-known/jwks.json`,registration_endpoint:`${Ne(t.env)}oidc/register`,revocation_endpoint:`${Ne(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=${Ti}, stale-while-revalidate=${Ti*2}, stale-if-error=86400`}})});function Fi(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 Rg=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 lb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(403,{message:"Invalid client credentials"});if(n.client_secret&&!Fi(n.client_secret,e.client_secret))throw new z(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await Yl(t,{authParams:r,client:n});return t.json(i)}const ub=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 db(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(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 z(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new z(403,{message:"Code expired"});if(r.used_at)throw new z(403,{message:"Code already used"});const i=await t.env.data.logins.get(n.tenant.id,r.login_id);if(!i)throw new z(403,{message:"Invalid login"});if("client_secret"in e){const o=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Fi(n.client_secret,e.client_secret)&&!Fi(o==null?void 0:o.client_secret,e.client_secret))throw new z(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 Iv(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(o,i.authParams.code_challenge||""))throw new z(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new z(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new z(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),Tn(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Jt.WEB_MESSAGE}})}const pb=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 fb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new z(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 z(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new z(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 z(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 Tn(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:Jt.WEB_MESSAGE}})}const Np=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),hb=a.z.union([Rg.extend(Np.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(),...Np.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 gb(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 mb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:hb}}}},responses:{200:{content:{"application/json":{schema:df}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=gb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new z(400,{message:"client_id is required"});switch(e.grant_type){case jr.AuthorizationCode:return db(t,ub.parse(r));case jr.ClientCredential:return lb(t,Rg.parse(r));case jr.RefreshToken:return fb(t,pb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var Xl={exports:{}};const Ql=[{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}],Lg=(t,e=Ql,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};Xl.exports={passwordStrength:Lg,defaultOptions:Ql};var _b=Xl.exports.passwordStrength=Lg;Xl.exports.defaultOptions=Ql;function eu(t){return _b(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 Ko(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 z(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new z(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function Ug(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new z(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 Ko(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:fe("password_reset_title",o),resetPasswordEmailClickToReset:fe("reset_password_email_click_to_reset",o),resetPasswordEmailReset:fe("reset_password_email_reset",o),supportInfo:fe("support_info",o),contactUs:fe("contact_us",o),copyright:fe("copyright",o)}})}async function Vg(t,e,n){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new z(500,{message:"Tenant not found"});const i={vendorName:r.name,code:n,lng:r.language||"en"};await Ko(t,{to:e,subject:fe("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:`${Ne(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:fe("welcome_to_your_account",i),linkEmailClickToLogin:fe("link_email_click_to_login",i),linkEmailLogin:fe("link_email_login",i),linkEmailOrEnterCode:fe("link_email_or_enter_code",i),codeValid30Mins:fe("code_valid_30_minutes",i),supportInfo:fe("support_info",i),contactUs:fe("contact_us",i),copyright:fe("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Xe(t,t.env.data.logs.create(r.id,s))}async function tu(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new z(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new z(400,{message:"redirect_uri is required"});const s=new URL(Ne(t.env));s.pathname="passwordless/verify_redirect",s.searchParams.set("code",n),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 Ko(t,{to:e,subject:fe("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:fe("welcome_to_your_account",o),linkEmailClickToLogin:fe("link_email_click_to_login",o),linkEmailLogin:fe("link_email_login",o),linkEmailOrEnterCode:fe("link_email_or_enter_code",o),codeValid30Mins:fe("code_valid_30_minutes",o),supportInfo:fe("support_info",o),contactUs:fe("contact_us",o),copyright:fe("copyright",o)}});const c=be(t,{type:me.CODE_LINK_SENT,description:e});Xe(t,t.env.data.logs.create(i.id,c))}async function nu(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new z(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Ko(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:fe("welcome_to_your_account",r),verifyEmailVerify:fe("verify_email_verify",r),supportInfo:fe("support_info",r),contactUs:fe("contact_us",r),copyright:fe("copyright",r)}})}const yb=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 z(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!eu(n))throw new z(400,{message:"Password does not meet the requirements"});if(await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const o=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${oi()}`,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 si.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:o.user_id,password:c,algorithm:"bcrypt"}),await nu(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 z(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await Kn({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()+Xr*1e3).toISOString(),authParams:s,...Bn(t.req)});return await Ug(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 ir(){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 ru(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 z(400,{message:"Code not found or expired"});if(c.expires_at<new Date().toISOString())throw new z(400,{message:"Code expired"});if(c.used_at)throw new z(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 z(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&&!Ho(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const p=await _n({userAdapter:o.data.users,tenant_id:e.tenant.id,email:r,provider:"email"});if(!p)throw new z(400,{message:"User not found"});return await o.data.codes.used(e.tenant.id,i),Tn(t,{user:p,client:e,loginSession:l,authParams:n,ticketAuth:s})}const vb=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:Yc.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 z(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()+qc).toISOString(),...Bn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:ir(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+qc).toISOString()});return s==="link"?await tu(t,i,u.code_id,{...o,client_id:r}):await Vg(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(mn),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 Do(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),ru(t,h,{client_id:n,redirect_uri:s,state:o,nonce:p,scope:c,audience:l,response_type:u},r,i)});class Ir extends z{constructor(n,r){super(n,r);ee(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function iu(t,e,n,r,i){const{env:s}=t,o=n.username;if(t.set("username",o),!o)throw new z(400,{message:"Username is required"});const c=await Kn({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 Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(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 Ir(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 si.compare(n.password,u)){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(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 Xe(t,t.env.data.logs.create(e.tenant.id,f)),new Ir(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await nu(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 Ir(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const y=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Xe(t,t.env.data.logs.create(e.tenant.id,y)),Tn(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function wb(t,e,n,r){let i=await _n({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n,provider:"auth2"});if(!i){if(!(await el(t.env.data.users,e.tenant.id,n)).length)return;i=await t.env.data.users.create(e.tenant.id,{user_id:`email|${oi()}`,email:n,email_verified:!1,is_social:!1,provider:"auth2",connection:"Username-Password-Authentication"})}const s=await t.env.data.logins.create(e.tenant.id,{expires_at:new Date(Date.now()+Uy).toISOString(),authParams:{client_id:e.id,username:n},...Bn(t.req)});let o=ir(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");for(;c;)o=ir(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");const l=await t.env.data.codes.create(e.tenant.id,{code_id:o,code_type:"password_reset",login_id:s.login_id,expires_at:new Date(Date.now()+Ly).toISOString()});await Ug(t,n,l.code_id,r)}const bb=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 z(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 ru(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()+Xr*1e3).toISOString(),authParams:{client_id:n,username:s},...Bn(t.req)});return iu(t,i,{username:s,password:e.password,client_id:n},o,!0)}else throw new z(400,{message:"Code or password required"})});function xb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ua(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=ua(o))==null?void 0:i.host)??null:c=((s=ua("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function ua(t){try{return new URL(t)}catch{return null}}async function kb({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()+Xr*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 Tn(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=ir();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()+Xr*1e3).toISOString()}),await tu(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 Sb(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Ab(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 z(403,{message:"Ticket not found"});const c=await s.data.logins.get(e,o.login_id);if(!c||!c.authParams.username)throw new z(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new z(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const u=Sb(i);let p=await _n({userAdapter:s.data.users,tenant_id:e,email:c.authParams.username,provider:u});p||(p=await s.data.users.create(e,{user_id:`email|${oi()}`,email:c.authParams.username,name:c.authParams.username,provider:"email",connection:"email",email_verified:!0,is_social:!1,last_ip:"",last_login:new Date().toISOString()})),t.set("username",p.email),t.set("user_id",p.user_id);const h=await Bg(t,{user:p,client:l,scope:r.scope,audience:r.audience});return Tn(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function zp(t,e){return`<!DOCTYPE html>
150
150
  <html>
151
151
 
152
152
  <head>
@@ -219,7 +219,7 @@ PERFORMANCE OF THIS SOFTWARE.
219
219
  ${o?"invisible h-0":"visible h-auto"}
220
220
  `,children:t}),o&&v("div",{className:"absolute left-0 top-0 flex h-full w-full items-center justify-center",children:v(i1,{size:"medium"})})]})},Pi=({connection:t,text:e,icon:n=null,canResize:r=!1,session:i})=>{const s=new URLSearchParams({client_id:i.authParams.client_id,connection:t});i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.redirect_uri&&s.set("redirect_uri",i.authParams.redirect_uri),i.authParams.scope&&s.set("scope",i.authParams.scope),i.authParams.nonce&&s.set("nonce",i.authParams.nonce),i.authParams.response_type&&s.set("response_type",i.authParams.response_type),i.authParams.state&&s.set("state",i.login_id);const o=`/authorize?${s.toString()}`;return v(ni,{className:Et("border border-gray-200 bg-white hover:bg-gray-100 dark:border-gray-400 dark:bg-black dark:hover:bg-black/90",{"px-0 py-3 sm:px-10 sm:py-4 short:px-0 short:py-3":r,"px-10 py-3":!r}),variant:"custom","aria-label":e,Component:"a",href:o,children:[n||"",v("div",{className:Et("text-left text-black dark:text-white sm:text-base",{"hidden sm:inline short:hidden":r}),children:e})]})},s1=({...t})=>v("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",...t,children:[v("path",{d:"M44.1035 23.0123C44.1054 21.4791 43.9758 19.9486 43.716 18.4375H22.498V27.1028H34.6507C34.4021 28.4868 33.8757 29.8061 33.1034 30.9812C32.3311 32.1562 31.3289 33.1628 30.1571 33.9401V39.5649H37.41C41.6567 35.6494 44.1035 29.859 44.1035 23.0123Z",fill:"#4285F4"}),v("path",{d:"M22.4982 44.9997C28.5698 44.9997 33.6821 43.0061 37.4101 39.5687L30.1573 33.9439C28.1386 35.3126 25.5387 36.0938 22.4982 36.0938C16.6296 36.0938 11.6485 32.1377 9.86736 26.8066H2.39575V32.6033C4.26839 36.3297 7.13989 39.4622 10.6896 41.6512C14.2394 43.8402 18.3277 44.9995 22.4982 44.9997Z",fill:"#34A853"}),v("path",{d:"M9.86737 26.8073C8.92572 24.0138 8.92572 20.9886 9.86737 18.1951V12.3984H2.39576C0.820432 15.5332 0 18.9929 0 22.5012C0 26.0095 0.820432 29.4692 2.39576 32.604L9.86737 26.8073Z",fill:"#FBBC04"}),v("path",{d:"M22.4982 8.90741C25.7068 8.85499 28.8071 10.0673 31.1291 12.2823L37.5507 5.86064C33.4788 2.03602 28.0843 -0.0637686 22.4982 0.00147616C18.3277 0.00166623 14.2394 1.16098 10.6896 3.34999C7.13989 5.539 4.26839 8.67155 2.39575 12.3979L9.86736 18.1946C11.6485 12.8635 16.6296 8.90741 22.4982 8.90741Z",fill:"#EA4335"})]}),wr=({children:t,className:e})=>v(cu,{children:[v(ni,{className:e,id:"initial-btn",children:t}),v(ni,{className:Et(e,"hidden"),isLoading:!0,id:"loading-btn",disabled:!0,children:" "})]}),br=({children:t,className:e})=>v("form",{id:"form",method:"post",className:e,children:t}),o1=({...t})=>v("svg",{version:"1.1",id:"Layer_1",xmlns:"http://www.w3.org/2000/svg",x:"0px",y:"0px",viewBox:"0 0 48 48",enableBackground:"new 0 0 48 48",width:"45",height:"45",...t,children:[v("path",{fill:"#FF5B24",d:"M3.5,8h41c1.9,0,3.5,1.6,3.5,3.5v25c0,1.9-1.6,3.5-3.5,3.5h-41C1.6,40,0,38.4,0,36.5v-25C0,9.6,1.6,8,3.5,8z"}),v("path",{fillRule:"evenodd",clipRule:"evenodd",fill:"#FFFFFF",d:`M27.9,20.3c1.4,0,2.6-1,2.6-2.5h0c0-1.5-1.2-2.5-2.6-2.5c-1.4,0-2.6,1-2.6,2.5C25.3,19.2,26.5,20.3,27.9,20.3z
221
221
  M31.2,24.4c-1.7,2.2-3.5,3.8-6.7,3.8h0c-3.2,0-5.8-2-7.7-4.8c-0.8-1.2-2-1.4-2.9-0.8c-0.8,0.6-1,1.8-0.3,2.9
222
- c2.7,4.1,6.5,6.6,10.9,6.6c4,0,7.2-2,9.6-5.2c0.9-1.2,0.9-2.5,0-3.1C33.3,22.9,32.1,23.2,31.2,24.4z`})]}),Lp=({error:t,vendorSettings:e,session:n,email:r,client:i,impersonation:s})=>{const o=i.connections.map(({name:m})=>m),c=o.includes("facebook"),l=o.includes("google-oauth2"),u=o.includes("apple"),p=o.includes("vipps"),h=c||l||u||p;return v(qt,{title:U.t("welcome"),vendorSettings:e,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("welcome")}),v("div",{className:"mb-8 text-gray-300",children:U.t("login_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"mb-7",children:[v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:r||""}),s&&v("input",{type:"email",name:"act_as",placeholder:"Impersonate as",className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:""}),t&&v(vr,{children:t}),v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("continue")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})]}),h&&v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("continue_social_login")})]}),v("div",{className:"flex space-x-4 sm:flex-col sm:space-x-0 sm:space-y-4 short:flex-row short:space-x-4 short:space-y-0",children:[c&&v(Pi,{connection:"facebook",text:U.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:v(gt,{className:"text-xl text-[#1196F5] sm:absolute sm:left-4 sm:top-1/2 sm:-translate-y-1/2 sm:text-2xl short:static short:left-auto short:top-auto short:translate-y-0 short:text-xl",name:"facebook"}),session:n}),l&&v(Pi,{connection:"google-oauth2",text:U.t("continue_with",{provider:"Google"}),canResize:!0,icon:v(s1,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0"}),session:n}),u&&v(Pi,{connection:"apple",text:U.t("continue_with",{provider:"Apple"}),canResize:!0,icon:v(gt,{className:"text-xl text-black dark:text-white sm:absolute sm:left-4 sm:top-1/2 sm:-translate-y-1/2 sm:text-2xl short:static short:left-auto short:top-auto short:translate-y-0 short:text-xl",name:"apple"}),session:n}),p&&v(Pi,{connection:"vipps",text:U.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:v(o1,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0"}),session:n})]})]})]})},a1=["Auth0.swift"];function c1(t){if(!t)return"link";const e=atob(t),n=JSON.parse(e);return a1.includes(n.name)?"code":"link"}const l1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:a.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,impersonation:n}=t.req.valid("query"),{vendorSettings:r,session:i,client:s}=await rt(t,e);return t.html(v(Lp,{vendorSettings:r,session:i,client:s,email:i.authParams.username,impersonation:n==="true"}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({username:a.z.string().transform(t=>t.toLowerCase()),act_as:a.z.string().transform(t=>t.toLowerCase()).optional(),login_selection:a.z.enum(["code","password"]).optional()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form");t.set("body",r),t.set("username",r.username);const{client:i,session:s,vendorSettings:o}=await rt(t,n);t.set("client_id",i.id);const c=r.username,l=await Zs({userAdapter:e.data.users,tenant_id:i.tenant.id,email:c});if(l&&t.set("user_id",l.user_id),!l)try{await Pg(t,i,t.env.data,r.username)}catch{const y=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,y),t.html(v(Lp,{vendorSettings:o,session:s,error:U.t("user_account_does_not_exist"),email:r.username,client:i}),400)}if(s.authParams.username=r.username,s.authParams.act_as=r.act_as,await e.data.logins.update(i.tenant.id,s.login_id,s),await Gb(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=ir(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=ir(),p=await e.data.codes.get(i.tenant.id,u,"otp");const h=await t.env.data.codes.create(i.tenant.id,{code_id:u,code_type:"otp",login_id:s.login_id,expires_at:new Date(Date.now()+qc).toISOString()});return c1(s.auth0Client)==="link"&&!r.username.includes("online.no")?Xe(t,tu(t,r.username,h.code_id)):Xe(t,Vg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),Qt=t=>v("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/enter-email?state=${t.state}`,children:U.t("go_back")});var ri="_hp",u1={Change:"Input",DoubleClick:"DblClick"},d1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Wc=new WeakMap,or=void 0,p1=()=>or,zt=t=>"t"in t,fa={onClick:["click",!1]},Up=t=>{if(!t.startsWith("on"))return;if(fa[t])return fa[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return fa[t]=[(u1[n]||n).toLowerCase(),!!r]}},Vp=(t,e)=>or&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,f1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Fs(i);const o=Up(i);if(o){if((n==null?void 0:n[i])!==s&&(n&&t.removeEventListener(o[0],n[i],o[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${i}" is not a function`);t.addEventListener(o[0],s,o[1])}}else if(i==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(i==="ref"){let c;typeof s=="function"?c=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,c=()=>s.current=null),Wc.set(t,c)}else if(i==="style"){const c=t.style;typeof s=="string"?c.cssText=s:(c.cssText="",s!=null&&Gg(s,c.setProperty.bind(c)))}else{if(i==="value"){const l=t.nodeName;if(l==="INPUT"||l==="TEXTAREA"||l==="SELECT"){if(t.value=s==null||s===!1?null:s,l==="TEXTAREA"){t.textContent=s;continue}else if(l==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else(i==="checked"&&t.nodeName==="INPUT"||i==="selected"&&t.nodeName==="OPTION")&&(t[i]=s);const c=Vp(t,i);s==null||s===!1?t.removeAttribute(c):s===!0?t.setAttribute(c,""):typeof s=="string"||typeof s=="number"?t.setAttribute(c,s):t.setAttribute(c,s.toString())}}}if(n)for(let i in n){const s=n[i];if(i!=="children"&&!(i in e)){i=Fs(i);const o=Up(i);o?t.removeEventListener(o[0],s,o[1]):i==="ref"?(r=Wc.get(t))==null||r():t.removeAttribute(Vp(t,i))}}},h1=(t,e)=>{e[Se][0]=0,ii.push([t,e]);const n=e.tag[su]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{ii.pop()}},Xg=(t,e,n,r,i)=>{var s,o;(s=t.vR)!=null&&s.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&((o=t[Se][1][nm])==null||o.forEach(c=>i.push(c))),t.vC.forEach(c=>{var l;if(zt(c))n.push(c);else if(typeof c.tag=="function"||c.tag===""){c.c=e;const u=n.length;if(Xg(c,e,n,r,i),c.s){for(let p=u;p<n.length;p++)n[p].s=!0;c.s=!1}}else n.push(c),(l=c.vR)!=null&&l.length&&(r.push(...c.vR),delete c.vR)})},g1=t=>{for(;;t=t.tag===ri||!t.vC||!t.pP?t.nN:t.vC[0]){if(!t)return null;if(t.tag!==ri&&t.e)return t.e}},Qg=t=>{var e,n,r,i,s,o;zt(t)||((n=(e=t[Se])==null?void 0:e[1][nm])==null||n.forEach(c=>{var l;return(l=c[2])==null?void 0:l.call(c)}),(r=Wc.get(t.e))==null||r(),t.p===2&&((i=t.vC)==null||i.forEach(c=>c.p=2)),(s=t.vC)==null||s.forEach(Qg)),t.p||((o=t.e)==null||o.remove(),delete t.e),typeof t.tag=="function"&&(zr.delete(t),Ji.delete(t),delete t[Se][3],t.a=!0)},em=(t,e,n)=>{t.c=e,tm(t,e,n)},Mp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},qp=Symbol(),tm=(t,e,n)=>{var u;const r=[],i=[],s=[];Xg(t,e,r,i,s),i.forEach(Qg);const o=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!o.length)c=0;else{const p=Mp(o,g1(t.nN));p!==void 0?(l=o[p],c=p):c=Mp(o,(u=r.find(h=>h.tag!==ri&&h.e))==null?void 0:u.e)??-1,c===-1&&(n=!0)}for(let p=0,h=r.length;p<h;p++,c++){const m=r[p];let y;if(m.s&&m.e)y=m.e,m.s=!1;else{const f=n||!m.e;zt(m)?(m.e&&m.d&&(m.e.textContent=m.t),m.d=!1,y=m.e||(m.e=document.createTextNode(m.t))):(y=m.e||(m.e=m.n?document.createElementNS(m.n,m.tag):document.createElement(m.tag)),f1(y,m.props,m.pP),tm(m,y,f))}m.tag===ri?c--:n?y.parentNode||e.appendChild(y):o[c]!==y&&o[c-1]!==y&&(o[c+1]===y?e.appendChild(o[c]):e.insertBefore(y,l||o[c]||null))}if(t.pP&&delete t.pP,s.length){const p=[],h=[];s.forEach(([,m,,y,f])=>{m&&p.push(m),y&&h.push(y),f==null||f()}),p.forEach(m=>m()),h.length&&requestAnimationFrame(()=>{h.forEach(m=>m())})}},Ji=new WeakMap,Gc=(t,e,n)=>{var s,o,c,l,u,p;const r=!n&&e.pC;n&&(e.pC||(e.pC=e.vC));let i;try{n||(n=typeof e.tag=="function"?h1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Fc]&&(i=n[0][Fc],t[5].push([t,i,e]));const h=r?[...e.pC]:e.vC?[...e.vC]:void 0,m=[];let y;for(let f=0;f<n.length;f++){Array.isArray(n[f])&&n.splice(f,1,...n[f].flat());let _=m1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Dg]&&(sr.length>0&&(_[Se][2]=sr.map(S=>[S,S.values.at(-1)])),(o=t[5])!=null&&o.length&&(_[Se][3]=t[5].at(-1)));let w;if(h&&h.length){const S=h.findIndex(zt(_)?N=>zt(N):_.key!==void 0?N=>N.key===_.key&&N.tag===_.tag:N=>N.tag===_.tag);S!==-1&&(w=h[S],h.splice(S,1))}if(w)if(zt(_))w.t!==_.t&&(w.t=_.t,w.d=!0),_=w;else{const S=w.pP=w.props;w.props=_.props,w.f||(w.f=_.f||e.f),typeof _.tag=="function"&&(w[Se][2]=_[Se][2]||[],w[Se][3]=_[Se][3],!w.f&&((w.o||w)===_.o||(l=(c=w.tag)[jb])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!zt(_)&&or){const S=yr(or);S&&(_.n=S)}if(!zt(_)&&!_.s&&(Gc(t,_),delete _.f),m.push(_),y&&!y.s&&!_.s)for(let S=y;S&&!zt(S);S=(u=S.vC)==null?void 0:u.at(-1))S.nN=_;y=_}}e.vR=r?[...e.vC,...h||[]]:h||[],e.vC=m,r&&delete e.pC}catch(h){if(e.f=!0,h===qp){if(i)return;throw h}const[m,y,f]=((p=e[Se])==null?void 0:p[3])||[];if(y){const _=()=>Zi([0,!1,t[2]],f),w=Ji.get(f)||[];w.push(_),Ji.set(f,w);const S=y(h,()=>{const N=Ji.get(f);if(N){const B=N.indexOf(_);if(B!==-1)return N.splice(B,1),_()}});if(S){if(t[0]===1)t[1]=!0;else if(Gc(t,f,[S]),(y.length===1||t!==m)&&f.c){em(f,f.c,!1);return}throw qp}}throw h}finally{i&&t[5].pop()}},m1=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return{t:t.toString(),d:!0};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[Se]=[0,[]];else{const e=d1[t.tag];e&&(or||(or=Fg("")),t.props.children=[{tag:or,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Dp=(t,e)=>{var n,r;(n=e[Se][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Gc(t,e,void 0)}catch{return}if(e.a){delete e.a;return}(r=e[Se][2])==null||r.forEach(([i])=>{i.values.pop()}),(t[0]!==1||!t[1])&&em(e,e.c,!1)},zr=new WeakMap,Hp=[],Zi=async(t,e)=>{t[5]||(t[5]=[]);const n=zr.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if(zr.set(e,[r,()=>{t[2]?t[2](t,e,s=>{Dp(s,e)}).then(()=>r(e)):(Dp(t,e),r(e))}]),Hp.length)Hp.at(-1).add(e);else{await Promise.resolve();const s=zr.get(e);s&&(zr.delete(e),s[1]())}return i},_1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),ha=0,nm=1,ga=2,ma=3,_a=new WeakMap,rm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),y1=void 0,Fp=[],v1=t=>{var o;const e=()=>typeof t=="function"?t():t,n=ii.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=(o=r[Se][1])[ha]||(o[ha]=[]),s=r[Se][0]++;return i[s]||(i[s]=[e(),c=>{const l=y1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Fp.length){const[p,h]=Fp.at(-1);Promise.all([p===3?r:Zi([p,!1,l],r),h]).then(([m])=>{if(!m||!(p===2||p===3))return;const y=m.vC;requestAnimationFrame(()=>{setTimeout(()=>{y===m.vC&&Zi([p===3?1:0,!1,l],m)})})})}else Zi([0,!1,l],r)}])},lu=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t;const[,r]=n,i=(c=r[Se][1])[ga]||(c[ga]=[]),s=r[Se][0]++,o=i[s];return rm(o==null?void 0:o[1],e)?i[s]=[t,e]:t=i[s][0],t},w1=t=>{const e=_a.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>_a.set(t,[n]),n=>_a.set(t,[void 0,n])),t},b1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Se][1])[ma]||(c[ma]=[]),s=r[Se][0]++,o=i[s];return rm(o==null?void 0:o[1],e)&&(i[s]=[t(),e]),i[s][0]},x1=Fg({pending:!1,data:null,method:null,action:null}),Kp=new Set,k1=t=>{Kp.add(t),t.finally(()=>Kp.delete(t))},uu=(t,e)=>b1(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null)}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null}));const i=e(n);return()=>{i==null||i(),r==null||r()}},[t]),Un=Object.create(null),Ri=Object.create(null),Ci=(t,e,n,r,i)=>{if(e!=null&&e.itemProp)return{tag:t,props:e,type:t,ref:e.ref};const s=document.head;let{onLoad:o,onError:c,precedence:l,blocking:u,...p}=e,h=null,m=!1;const y=Ki[t];let f;if(y.length>0){const N=s.querySelectorAll(t);e:for(const B of N)for(const R of Ki[t])if(B.getAttribute(R)===e[R]){h=B;break e}if(!h){const B=y.reduce((R,te)=>e[te]===void 0?R:`${R}-${te}-${e[te]}`,t);m=!Ri[B],h=Ri[B]||(Ri[B]=(()=>{const R=document.createElement(t);for(const te of y)e[te]!==void 0&&R.setAttribute(te,e[te]),e.rel&&R.setAttribute("rel",e.rel);return R})())}}else f=s.querySelectorAll(t);l=r?l??"":void 0,r&&(p[Wi]=l);const _=lu(N=>{if(y.length>0){let B=!1;for(const R of s.querySelectorAll(t)){if(B&&R.getAttribute(Wi)!==l){s.insertBefore(N,R);return}R.getAttribute(Wi)===l&&(B=!0)}s.appendChild(N)}else if(f){let B=!1;for(const R of f)if(R===N){B=!0;break}B||s.insertBefore(N,s.contains(f[0])?f[0]:s.querySelector(t)),f=void 0}},[l]),w=uu(e.ref,N=>{var te;const B=y[0];if(n===2&&(N.innerHTML=""),(m||f)&&_(N),!c&&!o)return;let R=Un[te=N.getAttribute(B)]||(Un[te]=new Promise((pe,le)=>{N.addEventListener("load",pe),N.addEventListener("error",le)}));o&&(R=R.then(o)),c&&(R=R.catch(c)),R.catch(()=>{})});if(i&&u==="render"){const N=Ki[t][0];if(e[N]){const B=e[N],R=Un[B]||(Un[B]=new Promise((te,pe)=>{_(h),h.addEventListener("load",te),h.addEventListener("error",pe)}));w1(R)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),_1(S,s)},S1=t=>{const e=p1(),n=e&&yr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Ci("title",t,void 0,!1,!1)},A1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Ci("script",t,1,!1,!0),E1=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,Ci("style",t,2,!0,!0)),I1=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:Ci("link",t,1,"precedence"in t,!0),C1=t=>Ci("meta",t,void 0,!1,!1),im=Symbol(),N1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=v1([null,!1]),s=lu(async u=>{const p=u.isTrusted?e:u.detail[im];if(typeof p!="function")return;u.preventDefault();const h=new FormData(u.target);i([h,!0]);const m=p(h);m instanceof Promise&&(k1(m),await m),i([null,!0])},[]),o=uu(t.ref,u=>(u.addEventListener("submit",s),()=>{u.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:x1,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},sm=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=lu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[im]:e}}))},[]);n.ref=uu(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},z1=t=>sm("input",t),$1=t=>sm("button",t);Object.assign(Kc,{title:S1,script:A1,style:E1,link:I1,meta:C1,form:N1,input:z1,button:$1});new TextEncoder;const j1=t=>{const{i18nKey:e,values:n,components:r}=t,i=U.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,o=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,u,p]=l,h=i.substring(c,l.index);h&&o.push(h);const m=parseInt(u,10);o.push(Wb(r[m],{},p)),c=s.lastIndex}return c<i.length&&o.push(i.substring(c)),v(cu,{children:o})},Wp=6,Gp=({error:t,vendorSettings:e,email:n,state:r,client:i,hasPasswordLogin:s})=>{const o=new URLSearchParams({state:r}),l=i.connections.map(({name:u})=>u).includes("auth2");return v(qt,{title:U.t("verify_your_email"),vendorSettings:e,children:[v("div",{className:"mb-4 text-2xl font-medium",children:U.t("verify_your_email")}),v("div",{className:"mb-8 text-gray-300",children:v(j1,{i18nKey:"we_sent_a_code_to",components:[v("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"pt-2",children:[v("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:Wp,inputMode:"numeric",name:"code",placeholder:"******",className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:Wp,required:!0,id:"code-input"}),t&&v(vr,{children:t}),v("div",{className:"text-center sm:mt-2",children:v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("login")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),l&&v("div",{className:"text-center mb-12",children:[v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),v(ni,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${o.toString()}`,variant:"secondary",className:"block",children:U.t("enter_your_password_btn")})]})]}),v(Qt,{state:r})]})]})},O1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r,client:i}=await rt(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(v(Gp,{vendorSettings:n,email:r.authParams.username,state:e,client:i,hasPasswordLogin:!!s}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({code:a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{code:n}=t.req.valid("form"),{session:r,client:i,vendorSettings:s}=await rt(t,e);if(t.set("client_id",i.id),!r.authParams.username)throw new z(400,{message:"Username not found in state"});try{return await ru(t,i,r.authParams,r.authParams.username,n)}catch(o){const c=o,l=await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(v(Gp,{vendorSettings:s,email:r.authParams.username,state:e,client:i,error:c.message,hasPasswordLogin:!!l}),400)}}),B1=t=>{const{vendorSettings:e,state:n}=t;return v(qt,{title:U.t("unverified_email"),vendorSettings:e,children:[v("div",{className:"flex flex-1 flex-col justify-center",children:[v("p",{className:"mb-8 text-gray-300 text-lg",children:U.t("unverified_email")}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),v(Qt,{state:n})]}),v(Qt,{state:n})]})},ya=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return v(qt,{title:U.t("enter_password"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("enter_password")}),v("div",{className:"mb-6 text-gray-300",children:U.t("enter_password_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"mb-7",children:[v("input",{type:"text",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:r}),v("input",{type:"password",name:"password",placeholder:U.t("password")||"",className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0}),e&&v(vr,{children:e}),v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("login")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})]}),v("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:U.t("forgot_password_link")}),v("div",{className:"text-center mb-12",children:[v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),v("form",{method:"post",action:`/u/enter-email?${s.toString()}`,children:[v("input",{type:"hidden",name:"login_selection",value:"code"}),v("input",{type:"hidden",name:"username",value:r}),v(ni,{variant:"secondary",className:"block",children:U.t("enter_a_code_btn")})]})]}),v(Qt,{state:i})]})]})},T1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,client:r,session:i}=await rt(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(v(ya,{vendorSettings:n,email:i.authParams.username,state:e,client:r}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{password:r}=n,{vendorSettings:i,client:s,session:o}=await rt(t,e),{username:c}=o.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await iu(t,s,{...o.authParams,password:r},o)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(v(ya,{vendorSettings:i,email:c,error:U.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(v(B1,{vendorSettings:i,state:e}),400):t.html(v(ya,{vendorSettings:i,email:c,error:u.message,state:e,client:s}),400)}}),Cr=t=>{const{state:e,error:n,vendorSettings:r,email:i,code:s}=t;return v(qt,{title:U.t("create_account_title"),vendorSettings:r,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("create_account_title")}),v("div",{className:"mb-6 text-gray-300",children:U.t("create_account_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{children:[v("input",{type:"hidden",name:"code",value:s}),v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:i,disabled:!!i}),v("input",{type:"password",name:"password",placeholder:U.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),v("input",{type:"password",name:"re-enter-password",placeholder:U.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),n&&v(vr,{children:n}),v(wr,{className:"text-base sm:mt-2 md:text-base",children:U.t("continue")})]}),v(Qt,{state:e})]})]})},om=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return v(qt,{title:"Login",vendorSettings:n,children:[r?v("div",{className:"mb-6 text-gray-300",children:r}):"",v("div",{className:"flex flex-1 flex-col justify-center",children:e}),i?v(Qt,{state:i}):""]})},P1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().optional().openapi({description:"The code parameter from an email verification link"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{vendorSettings:r,session:i}=await rt(t,e),{username:s}=i.authParams;if(!s)throw new z(400,{message:"Username required"});return n?t.html(v(Cr,{state:e,vendorSettings:r,email:s,code:n})):t.html(v(Cr,{state:e,vendorSettings:r,email:s}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string(),"re-enter-password":a.z.string(),code:a.z.string().optional()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{env:r}=t,{vendorSettings:i,client:s,session:o}=await rt(t,e),c="Username-Password-Authentication";t.set("client_id",s.id),t.set("connection",c);const l=o.authParams.username;if(!l)throw new z(400,{message:"Username required"});if(n.password!==n["re-enter-password"])return t.html(v(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_passwords_didnt_match"),email:o.authParams.username}),400);if(!eu(n.password))return t.html(v(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_weak_password"),email:o.authParams.username}),400);const u=n.code?await r.data.codes.get(s.tenant.id,n.code,"email_verification"):void 0,p=u?await r.data.logins.get(s.tenant.id,u.login_id):void 0;try{if(await Kn({userAdapter:t.env.data.users,tenant_id:s.tenant.id,email:l,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const m=(p==null?void 0:p.authParams.username)===l,y=await t.env.data.users.create(s.tenant.id,{user_id:`auth2|${oi()}`,email:l,email_verified:m,provider:"auth2",connection:c,is_social:!1}),f=await Kn({userAdapter:t.env.data.users,tenant_id:s.tenant.id,email:l,provider:"auth2"});if(!f)throw new z(400,{message:"Invalid sign up"});return await r.data.passwords.create(s.tenant.id,{user_id:f.user_id,password:await si.hash(n.password,10),algorithm:"bcrypt"}),m?await iu(t,s,{...o.authParams,password:n.password},o):(await nu(t,y),t.html(v(om,{message:U.t("validate_email_body"),pageTitle:U.t("validate_email_title"),vendorSettings:i,state:e})))}catch(h){const m=await Zg(r,s.id,o.authParams.vendor_id),y=h;return t.html(v(Cr,{state:e,vendorSettings:m,error:y.message,email:l}),400)}}),Nr=t=>{const{error:e,vendorSettings:n,email:r}=t;return v(qt,{title:U.t("reset_password_title"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("reset_password_title")}),v("div",{className:"mb-6 text-gray-300",children:`${U.t("reset_password_description")} ${r}`}),v("div",{className:"flex flex-1 flex-col justify-center",children:v(br,{children:[v("input",{type:"password",name:"password",placeholder:U.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),v("input",{type:"password",name:"re-enter-password",placeholder:U.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),e&&v(vr,{children:e}),v(wr,{className:"text-base sm:mt-2 md:text-base",children:U.t("reset_password_cta")})]})})]})},R1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r}=await rt(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(v(Nr,{vendorSettings:n,email:r.authParams.username}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string(),"re-enter-password":a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{password:r,"re-enter-password":i}=t.req.valid("form"),{env:s}=t,{vendorSettings:o,client:c,session:l}=await rt(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(v(Nr,{error:U.t("create_account_passwords_didnt_match"),vendorSettings:o,email:l.authParams.username}),400);if(!eu(r))return t.html(v(Nr,{error:U.t("create_account_weak_password"),vendorSettings:o,email:l.authParams.username}),400);const u=await Kn({userAdapter:s.data.users,tenant_id:c.tenant.id,email:l.authParams.username,provider:"auth2"});if(!u)throw new z(400,{message:"User not found"});try{if(!await s.data.codes.get(c.tenant.id,n,"password_reset"))return t.html(v(Nr,{error:"Code not found or expired",vendorSettings:o,email:l.authParams.username}),400);console.log("got here");const h={user_id:u.user_id,password:await si.hash(r,10),algorithm:"bcrypt"};await s.data.passwords.get(c.tenant.id,u.user_id)?await s.data.passwords.update(c.tenant.id,h):await s.data.passwords.create(c.tenant.id,h),u.email_verified||await s.data.users.update(c.tenant.id,u.user_id,{email_verified:!0})}catch{return t.html(v(Nr,{error:"The password could not be reset",vendorSettings:o,email:l.authParams.username}),400)}return t.html(v(om,{message:U.t("password_has_been_reset"),vendorSettings:o,state:e}))}),L1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return v(qt,{title:U.t("forgot_password_title"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("forgot_password_title")}),v("div",{className:"mb-6 text-gray-300",children:U.t("forgot_password_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"pt-2",children:[v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:r,disabled:!!r}),e&&v(vr,{children:e}),v(wr,{className:"sm:mt-4",children:U.t("forgot_password_cta")})]}),v(Qt,{state:i})]})]})},U1=t=>{const{vendorSettings:e,state:n}=t;return v(qt,{title:"Login",vendorSettings:e,children:[v("div",{className:"flex flex-1 flex-col justify-center",children:[v("div",{children:U.t("forgot_password_email_sent")}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]})]}),v(Qt,{state:n})]})},V1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r}=await rt(t,e);return t.html(v(L1,{vendorSettings:n,state:e,email:r.authParams.username}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,client:r,session:i}=await rt(t,e);return await wb(t,r,i.authParams.username,i.login_id),t.html(v(U1,{vendorSettings:n,state:e}))});function M1(){const e=new a.OpenAPIHono().route("/enter-email",l1).route("/enter-code",O1).route("/enter-password",T1).route("/reset-password",R1).route("/forgot-password",V1).route("/signup",P1);return e.doc("/u/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Universal login"}}),e}const q1="Account detected",D1="We have detected that you have already created an account through",H1="By signing in, you agree to our",F1="and",K1="Callback URL mismatch",W1="The provided redirect_uri is not in the list of allowed callback URLs.",G1="continue with user",J1="Please click the button to create a new password account.",Z1="Enter the code at {{vendorName}} to complete the login",Y1="Welcome to {{vendorName}}! {{code}} is the login code",X1="Welcome to {{vendorName}}! {{code}} is the login code",Q1="The code is valid for 30 minutes",ex="Confirm password",tx="Need Help?",nx="Contact us",rx="or continue with social account",ix="Continue with {{provider}}",sx="Would you like to continue with your existing account?",ox="Copyright © 2023 SESAMY. All rights reserved.",ax="©2023 Sesamy",cx="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",lx="Please enter a valid email address.",ux="The passwords didn't match. Try again.",dx="Choose password",px="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",fx="Create new account",hx="Sign up with password",gx="You are currently logged in as <0>{{email}}</0>",mx="Email",_x="Email address",yx="Your email address has been validated",vx="Now enter your password to login again",wx="An email has been sent to <0>{{email}}</0> with a verification link. Please click the link to verify your email address and set a password.",bx="Email verification sent",xx="Enter a code",kx="We'll send you a verification link to ensure you own this email address.",Sx="Enter new password",Ax="Enter password",Ex="Enter your email address and password to login.",Ix="Enter your password",Cx="The magic link has expired. Please click on the button below to receive a new link in your inbox.",Nx="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",zx="Send password reset email",$x="Click the button below and we’ll send instructions on how to reset your password.",jx="Password reset email sent",Ox="Forgot password?",Bx="Forgot password?",Tx="Go back",Px="Invalid password",Rx=`The link is no longer valid.
222
+ c2.7,4.1,6.5,6.6,10.9,6.6c4,0,7.2-2,9.6-5.2c0.9-1.2,0.9-2.5,0-3.1C33.3,22.9,32.1,23.2,31.2,24.4z`})]}),Lp=({error:t,vendorSettings:e,session:n,email:r,client:i,impersonation:s})=>{const o=i.connections.map(({name:m})=>m),c=o.includes("facebook"),l=o.includes("google-oauth2"),u=o.includes("apple"),p=o.includes("vipps"),h=c||l||u||p;return v(qt,{title:U.t("welcome"),vendorSettings:e,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("welcome")}),v("div",{className:"mb-8 text-gray-300",children:U.t("login_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"mb-7",children:[v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:r||""}),s&&v("input",{type:"email",name:"act_as",placeholder:"Impersonate as",className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),required:!0,value:""}),t&&v(vr,{children:t}),v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("continue")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})]}),h&&v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("continue_social_login")})]}),v("div",{className:"flex space-x-4 sm:flex-col sm:space-x-0 sm:space-y-4 short:flex-row short:space-x-4 short:space-y-0",children:[c&&v(Pi,{connection:"facebook",text:U.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:v(gt,{className:"text-xl text-[#1196F5] sm:absolute sm:left-4 sm:top-1/2 sm:-translate-y-1/2 sm:text-2xl short:static short:left-auto short:top-auto short:translate-y-0 short:text-xl",name:"facebook"}),session:n}),l&&v(Pi,{connection:"google-oauth2",text:U.t("continue_with",{provider:"Google"}),canResize:!0,icon:v(s1,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0"}),session:n}),u&&v(Pi,{connection:"apple",text:U.t("continue_with",{provider:"Apple"}),canResize:!0,icon:v(gt,{className:"text-xl text-black dark:text-white sm:absolute sm:left-4 sm:top-1/2 sm:-translate-y-1/2 sm:text-2xl short:static short:left-auto short:top-auto short:translate-y-0 short:text-xl",name:"apple"}),session:n}),p&&v(Pi,{connection:"vipps",text:U.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:v(o1,{className:"h-5 w-5 sm:absolute sm:left-4 sm:top-1/2 sm:h-6 sm:w-6 sm:-translate-y-1/2 short:static short:left-auto short:top-auto short:h-5 short:w-5 short:translate-y-0"}),session:n})]})]})]})},a1=["Auth0.swift"];function c1(t){if(!t)return"link";const e=atob(t),n=JSON.parse(e);return a1.includes(n.name)?"code":"link"}const l1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:a.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,impersonation:n}=t.req.valid("query"),{vendorSettings:r,session:i,client:s}=await rt(t,e);return t.html(v(Lp,{vendorSettings:r,session:i,client:s,email:i.authParams.username,impersonation:n==="true"}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({username:a.z.string().transform(t=>t.toLowerCase()),act_as:a.z.string().transform(t=>t.toLowerCase()).optional(),login_selection:a.z.enum(["code","password"]).optional()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),r=t.req.valid("form");t.set("body",r),t.set("username",r.username);const{client:i,session:s,vendorSettings:o}=await rt(t,n);t.set("client_id",i.id);const c=r.username,l=await Zs({userAdapter:e.data.users,tenant_id:i.tenant.id,email:c});if(l&&t.set("user_id",l.user_id),!l)try{await Pg(t,i,t.env.data,r.username)}catch{const y=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,y),t.html(v(Lp,{vendorSettings:o,session:s,error:U.t("user_account_does_not_exist"),email:r.username,client:i}),400)}if(s.authParams.username=r.username,s.authParams.act_as=r.act_as,await e.data.logins.update(i.tenant.id,s.login_id,s),await Gb(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=ir(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=ir(),p=await e.data.codes.get(i.tenant.id,u,"otp");const h=await t.env.data.codes.create(i.tenant.id,{code_id:u,code_type:"otp",login_id:s.login_id,expires_at:new Date(Date.now()+qc).toISOString()});return c1(s.auth0Client)==="link"&&!r.username.includes("online.no")?Xe(t,tu(t,r.username,h.code_id,s.authParams)):Xe(t,Vg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),Qt=t=>v("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/enter-email?state=${t.state}`,children:U.t("go_back")});var ri="_hp",u1={Change:"Input",DoubleClick:"DblClick"},d1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Wc=new WeakMap,or=void 0,p1=()=>or,zt=t=>"t"in t,fa={onClick:["click",!1]},Up=t=>{if(!t.startsWith("on"))return;if(fa[t])return fa[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return fa[t]=[(u1[n]||n).toLowerCase(),!!r]}},Vp=(t,e)=>or&&t instanceof SVGElement&&/[A-Z]/.test(e)&&(e in t.style||e.match(/^(?:o|pai|str|u|ve)/))?e.replace(/([A-Z])/g,"-$1").toLowerCase():e,f1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Fs(i);const o=Up(i);if(o){if((n==null?void 0:n[i])!==s&&(n&&t.removeEventListener(o[0],n[i],o[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${i}" is not a function`);t.addEventListener(o[0],s,o[1])}}else if(i==="dangerouslySetInnerHTML"&&s)t.innerHTML=s.__html;else if(i==="ref"){let c;typeof s=="function"?c=s(t)||(()=>s(null)):s&&"current"in s&&(s.current=t,c=()=>s.current=null),Wc.set(t,c)}else if(i==="style"){const c=t.style;typeof s=="string"?c.cssText=s:(c.cssText="",s!=null&&Gg(s,c.setProperty.bind(c)))}else{if(i==="value"){const l=t.nodeName;if(l==="INPUT"||l==="TEXTAREA"||l==="SELECT"){if(t.value=s==null||s===!1?null:s,l==="TEXTAREA"){t.textContent=s;continue}else if(l==="SELECT"){t.selectedIndex===-1&&(t.selectedIndex=0);continue}}}else(i==="checked"&&t.nodeName==="INPUT"||i==="selected"&&t.nodeName==="OPTION")&&(t[i]=s);const c=Vp(t,i);s==null||s===!1?t.removeAttribute(c):s===!0?t.setAttribute(c,""):typeof s=="string"||typeof s=="number"?t.setAttribute(c,s):t.setAttribute(c,s.toString())}}}if(n)for(let i in n){const s=n[i];if(i!=="children"&&!(i in e)){i=Fs(i);const o=Up(i);o?t.removeEventListener(o[0],s,o[1]):i==="ref"?(r=Wc.get(t))==null||r():t.removeAttribute(Vp(t,i))}}},h1=(t,e)=>{e[Se][0]=0,ii.push([t,e]);const n=e.tag[su]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{ii.pop()}},Xg=(t,e,n,r,i)=>{var s,o;(s=t.vR)!=null&&s.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&((o=t[Se][1][nm])==null||o.forEach(c=>i.push(c))),t.vC.forEach(c=>{var l;if(zt(c))n.push(c);else if(typeof c.tag=="function"||c.tag===""){c.c=e;const u=n.length;if(Xg(c,e,n,r,i),c.s){for(let p=u;p<n.length;p++)n[p].s=!0;c.s=!1}}else n.push(c),(l=c.vR)!=null&&l.length&&(r.push(...c.vR),delete c.vR)})},g1=t=>{for(;;t=t.tag===ri||!t.vC||!t.pP?t.nN:t.vC[0]){if(!t)return null;if(t.tag!==ri&&t.e)return t.e}},Qg=t=>{var e,n,r,i,s,o;zt(t)||((n=(e=t[Se])==null?void 0:e[1][nm])==null||n.forEach(c=>{var l;return(l=c[2])==null?void 0:l.call(c)}),(r=Wc.get(t.e))==null||r(),t.p===2&&((i=t.vC)==null||i.forEach(c=>c.p=2)),(s=t.vC)==null||s.forEach(Qg)),t.p||((o=t.e)==null||o.remove(),delete t.e),typeof t.tag=="function"&&(zr.delete(t),Ji.delete(t),delete t[Se][3],t.a=!0)},em=(t,e,n)=>{t.c=e,tm(t,e,n)},Mp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},qp=Symbol(),tm=(t,e,n)=>{var u;const r=[],i=[],s=[];Xg(t,e,r,i,s),i.forEach(Qg);const o=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!o.length)c=0;else{const p=Mp(o,g1(t.nN));p!==void 0?(l=o[p],c=p):c=Mp(o,(u=r.find(h=>h.tag!==ri&&h.e))==null?void 0:u.e)??-1,c===-1&&(n=!0)}for(let p=0,h=r.length;p<h;p++,c++){const m=r[p];let y;if(m.s&&m.e)y=m.e,m.s=!1;else{const f=n||!m.e;zt(m)?(m.e&&m.d&&(m.e.textContent=m.t),m.d=!1,y=m.e||(m.e=document.createTextNode(m.t))):(y=m.e||(m.e=m.n?document.createElementNS(m.n,m.tag):document.createElement(m.tag)),f1(y,m.props,m.pP),tm(m,y,f))}m.tag===ri?c--:n?y.parentNode||e.appendChild(y):o[c]!==y&&o[c-1]!==y&&(o[c+1]===y?e.appendChild(o[c]):e.insertBefore(y,l||o[c]||null))}if(t.pP&&delete t.pP,s.length){const p=[],h=[];s.forEach(([,m,,y,f])=>{m&&p.push(m),y&&h.push(y),f==null||f()}),p.forEach(m=>m()),h.length&&requestAnimationFrame(()=>{h.forEach(m=>m())})}},Ji=new WeakMap,Gc=(t,e,n)=>{var s,o,c,l,u,p;const r=!n&&e.pC;n&&(e.pC||(e.pC=e.vC));let i;try{n||(n=typeof e.tag=="function"?h1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Fc]&&(i=n[0][Fc],t[5].push([t,i,e]));const h=r?[...e.pC]:e.vC?[...e.vC]:void 0,m=[];let y;for(let f=0;f<n.length;f++){Array.isArray(n[f])&&n.splice(f,1,...n[f].flat());let _=m1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Dg]&&(sr.length>0&&(_[Se][2]=sr.map(S=>[S,S.values.at(-1)])),(o=t[5])!=null&&o.length&&(_[Se][3]=t[5].at(-1)));let w;if(h&&h.length){const S=h.findIndex(zt(_)?N=>zt(N):_.key!==void 0?N=>N.key===_.key&&N.tag===_.tag:N=>N.tag===_.tag);S!==-1&&(w=h[S],h.splice(S,1))}if(w)if(zt(_))w.t!==_.t&&(w.t=_.t,w.d=!0),_=w;else{const S=w.pP=w.props;w.props=_.props,w.f||(w.f=_.f||e.f),typeof _.tag=="function"&&(w[Se][2]=_[Se][2]||[],w[Se][3]=_[Se][3],!w.f&&((w.o||w)===_.o||(l=(c=w.tag)[jb])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!zt(_)&&or){const S=yr(or);S&&(_.n=S)}if(!zt(_)&&!_.s&&(Gc(t,_),delete _.f),m.push(_),y&&!y.s&&!_.s)for(let S=y;S&&!zt(S);S=(u=S.vC)==null?void 0:u.at(-1))S.nN=_;y=_}}e.vR=r?[...e.vC,...h||[]]:h||[],e.vC=m,r&&delete e.pC}catch(h){if(e.f=!0,h===qp){if(i)return;throw h}const[m,y,f]=((p=e[Se])==null?void 0:p[3])||[];if(y){const _=()=>Zi([0,!1,t[2]],f),w=Ji.get(f)||[];w.push(_),Ji.set(f,w);const S=y(h,()=>{const N=Ji.get(f);if(N){const B=N.indexOf(_);if(B!==-1)return N.splice(B,1),_()}});if(S){if(t[0]===1)t[1]=!0;else if(Gc(t,f,[S]),(y.length===1||t!==m)&&f.c){em(f,f.c,!1);return}throw qp}}throw h}finally{i&&t[5].pop()}},m1=t=>{if(!(t==null||typeof t=="boolean")){if(typeof t=="string"||typeof t=="number")return{t:t.toString(),d:!0};if("vR"in t&&(t={tag:t.tag,props:t.props,key:t.key,f:t.f,type:t.tag,ref:t.props.ref,o:t.o||t}),typeof t.tag=="function")t[Se]=[0,[]];else{const e=d1[t.tag];e&&(or||(or=Fg("")),t.props.children=[{tag:or,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Dp=(t,e)=>{var n,r;(n=e[Se][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Gc(t,e,void 0)}catch{return}if(e.a){delete e.a;return}(r=e[Se][2])==null||r.forEach(([i])=>{i.values.pop()}),(t[0]!==1||!t[1])&&em(e,e.c,!1)},zr=new WeakMap,Hp=[],Zi=async(t,e)=>{t[5]||(t[5]=[]);const n=zr.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if(zr.set(e,[r,()=>{t[2]?t[2](t,e,s=>{Dp(s,e)}).then(()=>r(e)):(Dp(t,e),r(e))}]),Hp.length)Hp.at(-1).add(e);else{await Promise.resolve();const s=zr.get(e);s&&(zr.delete(e),s[1]())}return i},_1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),ha=0,nm=1,ga=2,ma=3,_a=new WeakMap,rm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),y1=void 0,Fp=[],v1=t=>{var o;const e=()=>typeof t=="function"?t():t,n=ii.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=(o=r[Se][1])[ha]||(o[ha]=[]),s=r[Se][0]++;return i[s]||(i[s]=[e(),c=>{const l=y1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Fp.length){const[p,h]=Fp.at(-1);Promise.all([p===3?r:Zi([p,!1,l],r),h]).then(([m])=>{if(!m||!(p===2||p===3))return;const y=m.vC;requestAnimationFrame(()=>{setTimeout(()=>{y===m.vC&&Zi([p===3?1:0,!1,l],m)})})})}else Zi([0,!1,l],r)}])},lu=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t;const[,r]=n,i=(c=r[Se][1])[ga]||(c[ga]=[]),s=r[Se][0]++,o=i[s];return rm(o==null?void 0:o[1],e)?i[s]=[t,e]:t=i[s][0],t},w1=t=>{const e=_a.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>_a.set(t,[n]),n=>_a.set(t,[void 0,n])),t},b1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Se][1])[ma]||(c[ma]=[]),s=r[Se][0]++,o=i[s];return rm(o==null?void 0:o[1],e)&&(i[s]=[t(),e]),i[s][0]},x1=Fg({pending:!1,data:null,method:null,action:null}),Kp=new Set,k1=t=>{Kp.add(t),t.finally(()=>Kp.delete(t))},uu=(t,e)=>b1(()=>n=>{let r;t&&(typeof t=="function"?r=t(n)||(()=>{t(null)}):t&&"current"in t&&(t.current=n,r=()=>{t.current=null}));const i=e(n);return()=>{i==null||i(),r==null||r()}},[t]),Un=Object.create(null),Ri=Object.create(null),Ci=(t,e,n,r,i)=>{if(e!=null&&e.itemProp)return{tag:t,props:e,type:t,ref:e.ref};const s=document.head;let{onLoad:o,onError:c,precedence:l,blocking:u,...p}=e,h=null,m=!1;const y=Ki[t];let f;if(y.length>0){const N=s.querySelectorAll(t);e:for(const B of N)for(const R of Ki[t])if(B.getAttribute(R)===e[R]){h=B;break e}if(!h){const B=y.reduce((R,te)=>e[te]===void 0?R:`${R}-${te}-${e[te]}`,t);m=!Ri[B],h=Ri[B]||(Ri[B]=(()=>{const R=document.createElement(t);for(const te of y)e[te]!==void 0&&R.setAttribute(te,e[te]),e.rel&&R.setAttribute("rel",e.rel);return R})())}}else f=s.querySelectorAll(t);l=r?l??"":void 0,r&&(p[Wi]=l);const _=lu(N=>{if(y.length>0){let B=!1;for(const R of s.querySelectorAll(t)){if(B&&R.getAttribute(Wi)!==l){s.insertBefore(N,R);return}R.getAttribute(Wi)===l&&(B=!0)}s.appendChild(N)}else if(f){let B=!1;for(const R of f)if(R===N){B=!0;break}B||s.insertBefore(N,s.contains(f[0])?f[0]:s.querySelector(t)),f=void 0}},[l]),w=uu(e.ref,N=>{var te;const B=y[0];if(n===2&&(N.innerHTML=""),(m||f)&&_(N),!c&&!o)return;let R=Un[te=N.getAttribute(B)]||(Un[te]=new Promise((pe,le)=>{N.addEventListener("load",pe),N.addEventListener("error",le)}));o&&(R=R.then(o)),c&&(R=R.catch(c)),R.catch(()=>{})});if(i&&u==="render"){const N=Ki[t][0];if(e[N]){const B=e[N],R=Un[B]||(Un[B]=new Promise((te,pe)=>{_(h),h.addEventListener("load",te),h.addEventListener("error",pe)}));w1(R)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),_1(S,s)},S1=t=>{const e=p1(),n=e&&yr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Ci("title",t,void 0,!1,!1)},A1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Ci("script",t,1,!1,!0),E1=t=>!t||!["href","precedence"].every(e=>e in t)?{tag:"style",props:t,type:"style",ref:t.ref}:(t["data-href"]=t.href,delete t.href,Ci("style",t,2,!0,!0)),I1=t=>!t||["onLoad","onError"].some(e=>e in t)||t.rel==="stylesheet"&&(!("precedence"in t)||"disabled"in t)?{tag:"link",props:t,type:"link",ref:t.ref}:Ci("link",t,1,"precedence"in t,!0),C1=t=>Ci("meta",t,void 0,!1,!1),im=Symbol(),N1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=v1([null,!1]),s=lu(async u=>{const p=u.isTrusted?e:u.detail[im];if(typeof p!="function")return;u.preventDefault();const h=new FormData(u.target);i([h,!0]);const m=p(h);m instanceof Promise&&(k1(m),await m),i([null,!0])},[]),o=uu(t.ref,u=>(u.addEventListener("submit",s),()=>{u.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:x1,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:o},type:"form",ref:o}},f:l}},sm=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=lu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[im]:e}}))},[]);n.ref=uu(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},z1=t=>sm("input",t),$1=t=>sm("button",t);Object.assign(Kc,{title:S1,script:A1,style:E1,link:I1,meta:C1,form:N1,input:z1,button:$1});new TextEncoder;const j1=t=>{const{i18nKey:e,values:n,components:r}=t,i=U.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,o=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,u,p]=l,h=i.substring(c,l.index);h&&o.push(h);const m=parseInt(u,10);o.push(Wb(r[m],{},p)),c=s.lastIndex}return c<i.length&&o.push(i.substring(c)),v(cu,{children:o})},Wp=6,Gp=({error:t,vendorSettings:e,email:n,state:r,client:i,hasPasswordLogin:s})=>{const o=new URLSearchParams({state:r}),l=i.connections.map(({name:u})=>u).includes("auth2");return v(qt,{title:U.t("verify_your_email"),vendorSettings:e,children:[v("div",{className:"mb-4 text-2xl font-medium",children:U.t("verify_your_email")}),v("div",{className:"mb-8 text-gray-300",children:v(j1,{i18nKey:"we_sent_a_code_to",components:[v("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"pt-2",children:[v("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:Wp,inputMode:"numeric",name:"code",placeholder:"******",className:Et("mb-2 w-full rounded-lg border bg-gray-100 px-4 pb-2 pt-2.5 text-center indent-[5px] font-mono text-3xl placeholder:text-gray-300 dark:bg-gray-600 md:text-3xl",{"border-red":t,"border-gray-100 dark:border-gray-500":!t}),minLength:Wp,required:!0,id:"code-input"}),t&&v(vr,{children:t}),v("div",{className:"text-center sm:mt-2",children:v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("login")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),l&&v("div",{className:"text-center mb-12",children:[v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),v(ni,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${o.toString()}`,variant:"secondary",className:"block",children:U.t("enter_your_password_btn")})]})]}),v(Qt,{state:r})]})]})},O1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r,client:i}=await rt(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(v(Gp,{vendorSettings:n,email:r.authParams.username,state:e,client:i,hasPasswordLogin:!!s}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({code:a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{code:n}=t.req.valid("form"),{session:r,client:i,vendorSettings:s}=await rt(t,e);if(t.set("client_id",i.id),!r.authParams.username)throw new z(400,{message:"Username not found in state"});try{return await ru(t,i,r.authParams,r.authParams.username,n)}catch(o){const c=o,l=await _n({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(v(Gp,{vendorSettings:s,email:r.authParams.username,state:e,client:i,error:c.message,hasPasswordLogin:!!l}),400)}}),B1=t=>{const{vendorSettings:e,state:n}=t;return v(qt,{title:U.t("unverified_email"),vendorSettings:e,children:[v("div",{className:"flex flex-1 flex-col justify-center",children:[v("p",{className:"mb-8 text-gray-300 text-lg",children:U.t("unverified_email")}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),v(Qt,{state:n})]}),v(Qt,{state:n})]})},ya=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return v(qt,{title:U.t("enter_password"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("enter_password")}),v("div",{className:"mb-6 text-gray-300",children:U.t("enter_password_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"mb-7",children:[v("input",{type:"text",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:r}),v("input",{type:"password",name:"password",placeholder:U.t("password")||"",className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0}),e&&v(vr,{children:e}),v(wr,{className:"text-base sm:mt-4 md:text-base",children:v("div",{className:"flex items-center space-x-2",children:[v("span",{children:U.t("login")}),v(gt,{className:"text-xs",name:"arrow-right"})]})})]}),v("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:U.t("forgot_password_link")}),v("div",{className:"text-center mb-12",children:[v("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[v("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),v("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),v("form",{method:"post",action:`/u/enter-email?${s.toString()}`,children:[v("input",{type:"hidden",name:"login_selection",value:"code"}),v("input",{type:"hidden",name:"username",value:r}),v(ni,{variant:"secondary",className:"block",children:U.t("enter_a_code_btn")})]})]}),v(Qt,{state:i})]})]})},T1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,client:r,session:i}=await rt(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(v(ya,{vendorSettings:n,email:i.authParams.username,state:e,client:r}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{password:r}=n,{vendorSettings:i,client:s,session:o}=await rt(t,e),{username:c}=o.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await iu(t,s,{...o.authParams,password:r},o)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(v(ya,{vendorSettings:i,email:c,error:U.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(v(B1,{vendorSettings:i,state:e}),400):t.html(v(ya,{vendorSettings:i,email:c,error:u.message,state:e,client:s}),400)}}),Cr=t=>{const{state:e,error:n,vendorSettings:r,email:i,code:s}=t;return v(qt,{title:U.t("create_account_title"),vendorSettings:r,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("create_account_title")}),v("div",{className:"mb-6 text-gray-300",children:U.t("create_account_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{children:[v("input",{type:"hidden",name:"code",value:s}),v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",required:!0,value:i,disabled:!!i}),v("input",{type:"password",name:"password",placeholder:U.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),v("input",{type:"password",name:"re-enter-password",placeholder:U.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),n&&v(vr,{children:n}),v(wr,{className:"text-base sm:mt-2 md:text-base",children:U.t("continue")})]}),v(Qt,{state:e})]})]})},om=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return v(qt,{title:"Login",vendorSettings:n,children:[r?v("div",{className:"mb-6 text-gray-300",children:r}):"",v("div",{className:"flex flex-1 flex-col justify-center",children:e}),i?v(Qt,{state:i}):""]})},P1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().optional().openapi({description:"The code parameter from an email verification link"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{vendorSettings:r,session:i}=await rt(t,e),{username:s}=i.authParams;if(!s)throw new z(400,{message:"Username required"});return n?t.html(v(Cr,{state:e,vendorSettings:r,email:s,code:n})):t.html(v(Cr,{state:e,vendorSettings:r,email:s}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string(),"re-enter-password":a.z.string(),code:a.z.string().optional()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),n=t.req.valid("form"),{env:r}=t,{vendorSettings:i,client:s,session:o}=await rt(t,e),c="Username-Password-Authentication";t.set("client_id",s.id),t.set("connection",c);const l=o.authParams.username;if(!l)throw new z(400,{message:"Username required"});if(n.password!==n["re-enter-password"])return t.html(v(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_passwords_didnt_match"),email:o.authParams.username}),400);if(!eu(n.password))return t.html(v(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_weak_password"),email:o.authParams.username}),400);const u=n.code?await r.data.codes.get(s.tenant.id,n.code,"email_verification"):void 0,p=u?await r.data.logins.get(s.tenant.id,u.login_id):void 0;try{if(await Kn({userAdapter:t.env.data.users,tenant_id:s.tenant.id,email:l,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const m=(p==null?void 0:p.authParams.username)===l,y=await t.env.data.users.create(s.tenant.id,{user_id:`auth2|${oi()}`,email:l,email_verified:m,provider:"auth2",connection:c,is_social:!1}),f=await Kn({userAdapter:t.env.data.users,tenant_id:s.tenant.id,email:l,provider:"auth2"});if(!f)throw new z(400,{message:"Invalid sign up"});return await r.data.passwords.create(s.tenant.id,{user_id:f.user_id,password:await si.hash(n.password,10),algorithm:"bcrypt"}),m?await iu(t,s,{...o.authParams,password:n.password},o):(await nu(t,y),t.html(v(om,{message:U.t("validate_email_body"),pageTitle:U.t("validate_email_title"),vendorSettings:i,state:e})))}catch(h){const m=await Zg(r,s.id,o.authParams.vendor_id),y=h;return t.html(v(Cr,{state:e,vendorSettings:m,error:y.message,email:l}),400)}}),Nr=t=>{const{error:e,vendorSettings:n,email:r}=t;return v(qt,{title:U.t("reset_password_title"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("reset_password_title")}),v("div",{className:"mb-6 text-gray-300",children:`${U.t("reset_password_description")} ${r}`}),v("div",{className:"flex flex-1 flex-col justify-center",children:v(br,{children:[v("input",{type:"password",name:"password",placeholder:U.t("enter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),v("input",{type:"password",name:"re-enter-password",placeholder:U.t("reenter_new_password_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base"}),e&&v(vr,{children:e}),v(wr,{className:"text-base sm:mt-2 md:text-base",children:U.t("reset_password_cta")})]})})]})},R1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r}=await rt(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(v(Nr,{vendorSettings:n,email:r.authParams.username}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"}),code:a.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:a.z.object({password:a.z.string(),"re-enter-password":a.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e,code:n}=t.req.valid("query"),{password:r,"re-enter-password":i}=t.req.valid("form"),{env:s}=t,{vendorSettings:o,client:c,session:l}=await rt(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(v(Nr,{error:U.t("create_account_passwords_didnt_match"),vendorSettings:o,email:l.authParams.username}),400);if(!eu(r))return t.html(v(Nr,{error:U.t("create_account_weak_password"),vendorSettings:o,email:l.authParams.username}),400);const u=await Kn({userAdapter:s.data.users,tenant_id:c.tenant.id,email:l.authParams.username,provider:"auth2"});if(!u)throw new z(400,{message:"User not found"});try{if(!await s.data.codes.get(c.tenant.id,n,"password_reset"))return t.html(v(Nr,{error:"Code not found or expired",vendorSettings:o,email:l.authParams.username}),400);console.log("got here");const h={user_id:u.user_id,password:await si.hash(r,10),algorithm:"bcrypt"};await s.data.passwords.get(c.tenant.id,u.user_id)?await s.data.passwords.update(c.tenant.id,h):await s.data.passwords.create(c.tenant.id,h),u.email_verified||await s.data.users.update(c.tenant.id,u.user_id,{email_verified:!0})}catch{return t.html(v(Nr,{error:"The password could not be reset",vendorSettings:o,email:l.authParams.username}),400)}return t.html(v(om,{message:U.t("password_has_been_reset"),vendorSettings:o,state:e}))}),L1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return v(qt,{title:U.t("forgot_password_title"),vendorSettings:n,children:[v("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("forgot_password_title")}),v("div",{className:"mb-6 text-gray-300",children:U.t("forgot_password_description")}),v("div",{className:"flex flex-1 flex-col justify-center",children:[v(br,{className:"pt-2",children:[v("input",{type:"email",name:"username",placeholder:U.t("email_placeholder"),className:"mb-2 w-full rounded-lg bg-gray-100 px-4 py-5 text-base placeholder:text-gray-300 dark:bg-gray-600 md:text-base",value:r,disabled:!!r}),e&&v(vr,{children:e}),v(wr,{className:"sm:mt-4",children:U.t("forgot_password_cta")})]}),v(Qt,{state:i})]})]})},U1=t=>{const{vendorSettings:e,state:n}=t;return v(qt,{title:"Login",vendorSettings:e,children:[v("div",{className:"flex flex-1 flex-col justify-center",children:[v("div",{children:U.t("forgot_password_email_sent")}),v("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[v(gt,{className:"text-base",name:"info-bubble"}),v("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]})]}),v(Qt,{state:n})]})},V1=new a.OpenAPIHono().openapi(a.createRoute({tags:["login"],method:"get",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,session:r}=await rt(t,e);return t.html(v(L1,{vendorSettings:n,state:e,email:r.authParams.username}))}).openapi(a.createRoute({tags:["login"],method:"post",path:"/",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,client:r,session:i}=await rt(t,e);return await wb(t,r,i.authParams.username,i.login_id),t.html(v(U1,{vendorSettings:n,state:e}))});function M1(){const e=new a.OpenAPIHono().route("/enter-email",l1).route("/enter-code",O1).route("/enter-password",T1).route("/reset-password",R1).route("/forgot-password",V1).route("/signup",P1);return e.doc("/u/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Universal login"}}),e}const q1="Account detected",D1="We have detected that you have already created an account through",H1="By signing in, you agree to our",F1="and",K1="Callback URL mismatch",W1="The provided redirect_uri is not in the list of allowed callback URLs.",G1="continue with user",J1="Please click the button to create a new password account.",Z1="Enter the code at {{vendorName}} to complete the login",Y1="Welcome to {{vendorName}}! {{code}} is the login code",X1="Welcome to {{vendorName}}! {{code}} is the login code",Q1="The code is valid for 30 minutes",ex="Confirm password",tx="Need Help?",nx="Contact us",rx="or continue with social account",ix="Continue with {{provider}}",sx="Would you like to continue with your existing account?",ox="Copyright © 2023 SESAMY. All rights reserved.",ax="©2023 Sesamy",cx="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",lx="Please enter a valid email address.",ux="The passwords didn't match. Try again.",dx="Choose password",px="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",fx="Create new account",hx="Sign up with password",gx="You are currently logged in as <0>{{email}}</0>",mx="Email",_x="Email address",yx="Your email address has been validated",vx="Now enter your password to login again",wx="An email has been sent to <0>{{email}}</0> with a verification link. Please click the link to verify your email address and set a password.",bx="Email verification sent",xx="Enter a code",kx="We'll send you a verification link to ensure you own this email address.",Sx="Enter new password",Ax="Enter password",Ex="Enter your email address and password to login.",Ix="Enter your password",Cx="The magic link has expired. Please click on the button below to receive a new link in your inbox.",Nx="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",zx="Send password reset email",$x="Click the button below and we’ll send instructions on how to reset your password.",jx="Password reset email sent",Ox="Forgot password?",Bx="Forgot password?",Tx="Go back",Px="Invalid password",Rx=`The link is no longer valid.
223
223
 
224
224
  Please make sure to open the login link in the same browser you started the login with.
225
225
 
@@ -6706,9 +6706,9 @@ export declare function init(config: AuthHeroConfig): {
6706
6706
  auth0Client?: string | undefined;
6707
6707
  login_ticket?: string | undefined;
6708
6708
  code_challenge_method?: CodeChallengeMethod | undefined;
6709
+ code_challenge?: string | undefined;
6709
6710
  vendor_id?: string | undefined;
6710
6711
  prompt?: string | undefined;
6711
- code_challenge?: string | undefined;
6712
6712
  ui_locales?: string | undefined;
6713
6713
  realm?: string | undefined;
6714
6714
  login_hint?: string | undefined;
@@ -6733,9 +6733,9 @@ export declare function init(config: AuthHeroConfig): {
6733
6733
  auth0Client?: string | undefined;
6734
6734
  login_ticket?: string | undefined;
6735
6735
  code_challenge_method?: CodeChallengeMethod | undefined;
6736
+ code_challenge?: string | undefined;
6736
6737
  vendor_id?: string | undefined;
6737
6738
  prompt?: string | undefined;
6738
- code_challenge?: string | undefined;
6739
6739
  ui_locales?: string | undefined;
6740
6740
  realm?: string | undefined;
6741
6741
  login_hint?: string | undefined;
@@ -6790,10 +6790,10 @@ export declare function init(config: AuthHeroConfig): {
6790
6790
  state?: string | undefined;
6791
6791
  redirect_uri?: string | undefined;
6792
6792
  code_challenge_method?: CodeChallengeMethod | undefined;
6793
+ code_challenge?: string | undefined;
6793
6794
  vendor_id?: string | undefined;
6794
6795
  act_as?: string | undefined;
6795
6796
  prompt?: string | undefined;
6796
- code_challenge?: string | undefined;
6797
6797
  ui_locales?: string | undefined;
6798
6798
  };
6799
6799
  send: "code" | "link";
package/dist/authhero.mjs CHANGED
@@ -18772,42 +18772,49 @@ async function kg(t, e, n) {
18772
18772
  });
18773
18773
  et(t, t.env.data.logs.create(r.id, s));
18774
18774
  }
18775
- async function Zl(t, e, n) {
18776
- const r = await t.env.data.tenants.get(t.var.tenant_id);
18777
- if (!r)
18775
+ async function Zl(t, e, n, r) {
18776
+ const i = await t.env.data.tenants.get(t.var.tenant_id);
18777
+ if (!i)
18778
18778
  throw new $(500, { message: "Tenant not found" });
18779
- const i = {
18780
- vendorName: r.name,
18779
+ if (!r.redirect_uri)
18780
+ throw new $(400, { message: "redirect_uri is required" });
18781
+ const s = new URL(je(t.env));
18782
+ s.pathname = "passwordless/verify_redirect", s.searchParams.set("code", n), 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(
18783
+ "code_challenge_method",
18784
+ r.code_challenge_method
18785
+ ), r.audience && s.searchParams.set("audience", r.audience);
18786
+ const o = {
18787
+ vendorName: i.name,
18781
18788
  code: n,
18782
- lng: r.language || "en"
18789
+ lng: i.language || "en"
18783
18790
  };
18784
18791
  await Lo(t, {
18785
18792
  to: e,
18786
- subject: ge("code_email_subject", i),
18793
+ subject: ge("code_email_subject", o),
18787
18794
  html: `Click here to validate your email: ${Et(t.env)}validate-email`,
18788
18795
  template: "auth-link",
18789
18796
  data: {
18790
18797
  code: n,
18791
- vendorName: r.name,
18792
- logo: r.logo || "",
18793
- supportUrl: r.support_url || "",
18794
- magicLink: `${je(t.env)}passwordless/verify_redirect?ticket=${n}`,
18795
- buttonColor: r.primary_color || "",
18796
- welcomeToYourAccount: ge("welcome_to_your_account", i),
18797
- linkEmailClickToLogin: ge("link_email_click_to_login", i),
18798
- linkEmailLogin: ge("link_email_login", i),
18799
- linkEmailOrEnterCode: ge("link_email_or_enter_code", i),
18800
- codeValid30Mins: ge("code_valid_30_minutes", i),
18801
- supportInfo: ge("support_info", i),
18802
- contactUs: ge("contact_us", i),
18803
- copyright: ge("copyright", i)
18798
+ vendorName: i.name,
18799
+ logo: i.logo || "",
18800
+ supportUrl: i.support_url || "",
18801
+ magicLink: s.toString(),
18802
+ buttonColor: i.primary_color || "",
18803
+ welcomeToYourAccount: ge("welcome_to_your_account", o),
18804
+ linkEmailClickToLogin: ge("link_email_click_to_login", o),
18805
+ linkEmailLogin: ge("link_email_login", o),
18806
+ linkEmailOrEnterCode: ge("link_email_or_enter_code", o),
18807
+ codeValid30Mins: ge("code_valid_30_minutes", o),
18808
+ supportInfo: ge("support_info", o),
18809
+ contactUs: ge("contact_us", o),
18810
+ copyright: ge("copyright", o)
18804
18811
  }
18805
18812
  });
18806
- const s = ke(t, {
18813
+ const a = ke(t, {
18807
18814
  type: ve.CODE_LINK_SENT,
18808
18815
  description: e
18809
18816
  });
18810
- et(t, t.env.data.logs.create(r.id, s));
18817
+ et(t, t.env.data.logs.create(i.id, a));
18811
18818
  }
18812
18819
  async function Yl(t, e) {
18813
18820
  const n = await t.env.data.tenants.get(t.var.tenant_id);
@@ -19080,7 +19087,7 @@ const fb = new pe().openapi(
19080
19087
  login_id: l.login_id,
19081
19088
  expires_at: new Date(Date.now() + Uc).toISOString()
19082
19089
  });
19083
- return s === "link" ? await Zl(t, i, u.code_id) : await kg(t, i, u.code_id), t.html("OK");
19090
+ return s === "link" ? await Zl(t, i, u.code_id, { ...o, client_id: r }) : await kg(t, i, u.code_id), t.html("OK");
19084
19091
  }
19085
19092
  ).openapi(
19086
19093
  D({
@@ -19432,7 +19439,7 @@ async function _b({
19432
19439
  expires_at: new Date(
19433
19440
  Date.now() + Qr * 1e3
19434
19441
  ).toISOString()
19435
- }), await Zl(t, s, a), t.redirect(`/u/enter-code?state=${o.login_id}`);
19442
+ }), await Zl(t, s, a, r), t.redirect(`/u/enter-code?state=${o.login_id}`);
19436
19443
  }
19437
19444
  return e ? t.redirect(`/u/check-account?state=${o.login_id}`) : t.redirect(`/u/enter-email?state=${o.login_id}`);
19438
19445
  }
@@ -20884,7 +20891,15 @@ const r1 = new pe().openapi(
20884
20891
  login_id: s.login_id,
20885
20892
  expires_at: new Date(Date.now() + Uc).toISOString()
20886
20893
  });
20887
- return n1(s.auth0Client) === "link" && !r.username.includes("online.no") ? et(t, Zl(t, r.username, h.code_id)) : et(t, kg(t, r.username, h.code_id)), t.redirect(`/u/enter-code?state=${n}`);
20894
+ return n1(s.auth0Client) === "link" && !r.username.includes("online.no") ? et(
20895
+ t,
20896
+ Zl(
20897
+ t,
20898
+ r.username,
20899
+ h.code_id,
20900
+ s.authParams
20901
+ )
20902
+ ) : et(t, kg(t, r.username, h.code_id)), t.redirect(`/u/enter-code?state=${n}`);
20888
20903
  }
20889
20904
  ), Qt = (t) => /* @__PURE__ */ v(
20890
20905
  "a",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authhero",
3
- "version": "0.67.0",
3
+ "version": "0.68.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],