authhero 0.70.0 → 0.72.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 +2 -2
- package/dist/authhero.d.ts +1 -1
- package/dist/authhero.mjs +29 -27
- package/package.json +1 -1
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 Zw(t,e,n,r,i){var m,v,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 Yw(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:u.requestId,userId:((f=(v=r.app_metadata)==null?void 0:v.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 Jw(p.toString(),h,u.relayState)}async function Yw(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||`_${Re()}`,c=e.assertionId||`_${Re()}`,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 Gw.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 Xw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),mn.encode(t,{includePadding:!1})}const Ep=["sub","iss","aud","exp","nbf","iat","jti"];async function Xl(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=Iv(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(Ep.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);p[S]=N}},idToken:{setCustomClaim:(S,N)=>{if(Ep.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 Kl(1,"d"),headers:{kid:l.kid}},v=await wp("RS256",u,p,m),f=h?await wp("RS256",u,h,m):void 0;return{access_token:v,refresh_token:e.refresh_token,id_token:f,token_type:"Bearer",expires_in:86400}}async function Qw(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:Re(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+qo*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:Re(),user_id:n.user_id,idle_expires_at:new Date(Date.now()+qo*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 Qw(t,{...e,session_id:o.id,scope:i,audience:s}):void 0;return{...o,refresh_token:c}}async function on(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(Qe(t,t.env.data.logs.create(i.tenant.id,s)),Qe(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=Xw(),v=Re(12),f=await t.env.data.codes.create(i.tenant.id,{code_id:Re(),code_type:"ticket",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ly).toISOString(),code_verifier:[v,m].join("|")});return t.json({login_ticket:f.code_id,co_verifier:m,co_id:v})}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 Zw(t,e.client,e.authParams,r,c);const l=await Xl(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||_n.CODE)===_n.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:Re(),user_id:r.user_id,code_type:"authorization_code",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Py*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 eb(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await Ys({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 tb(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 nb(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 rb(t,e){return async(n,r)=>{let i=await eb(e)(n,r);return await tb(t,e)(n,i),i}}async function Pg(t,e,n,r){if(e.disable_sign_ups&&!await Ys({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 nb(t,n)(t.var.tenant_id||"",r)}function ib(t,e){return{...e,users:{...e.users,create:rb(t,e)}}}async function sb(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,...Tn(t.req)}));const c=await Sg(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()+Ry*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Ip(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 Ho(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(!Fo(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 Sg(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 v=await yn({userAdapter:r.data.users,tenant_id:o.tenant.id,email:m,provider:c.name});if(!v){try{await Pg(t,o,t.env.data,m)}catch(_){const w=_;throw new z(500,{message:`Failed to run preUserSignupHook: ${w.message}`})}v=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",v.user_id)}return on(t,{client:o,authParams:s.authParams,loginSession:s,user:v})}async function Cp(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}`});Qe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return By(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 ob=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 Cp(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ip(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 Cp(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ip(t,{code:n,state:e})}),ab=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(!Fo(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=Hs(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":zv(r.tenant.id),location:s}})}),Np=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()}),cb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Np}},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(Np.parse({...e,sub:e.user_id}))}),lb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:of}},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 Hl(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return Qc.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:ka}},description:"List of tenants"}}}),async t=>{const e=ka.parse({issuer:fv(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 ub(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 Xl(t,{authParams:r,client:n});return t.json(i)}const db=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 pb(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 Cv(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),on(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Jt.WEB_MESSAGE}})}const fb=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 hb(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 on(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 zp=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),gb=a.z.union([Rg.extend(zp.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(),...zp.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 mb(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 _b=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:gb}}}},responses:{200:{content:{"application/json":{schema:pf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=mb(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 pb(t,db.parse(r));case jr.ClientCredential:return ub(t,Rg.parse(r));case jr.RefreshToken:return hb(t,fb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var Ql={exports:{}};const eu=[{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=eu,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};Ql.exports={passwordStrength:Lg,defaultOptions:eu};var yb=Ql.exports.passwordStrength=Lg;Ql.exports.defaultOptions=eu;function tu(t){return yb(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 Wo(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 Wo(t,{to:e,subject:"Reset your password",html:`Click here to reset your password: ${At(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:de("password_reset_title",o),resetPasswordEmailClickToReset:de("reset_password_email_click_to_reset",o),resetPasswordEmailReset:de("reset_password_email_reset",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}})}async function 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 Wo(t,{to:e,subject:de("code_email_subject",i),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",magicLink:`${Ne(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",i),linkEmailClickToLogin:de("link_email_click_to_login",i),linkEmailLogin:de("link_email_login",i),linkEmailOrEnterCode:de("link_email_or_enter_code",i),codeValid30Mins:de("code_valid_30_minutes",i),supportInfo:de("support_info",i),contactUs:de("contact_us",i),copyright:de("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(r.id,s))}async function nu(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("verification_code",n),s.searchParams.set("connection","email"),s.searchParams.set("client_id",r.client_id),s.searchParams.set("redirect_uri",r.redirect_uri),s.searchParams.set("email",e),r.response_type&&s.searchParams.set("response_type",r.response_type),r.scope&&s.searchParams.set("scope",r.scope),r.state&&s.searchParams.set("state",r.state),r.nonce&&s.searchParams.set("nonce",r.nonce),r.code_challenge&&s.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&s.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&s.searchParams.set("audience",r.audience);const o={vendorName:i.name,code:n,lng:i.language||"en"};await Wo(t,{to:e,subject:de("code_email_subject",o),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:s.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",o),linkEmailClickToLogin:de("link_email_click_to_login",o),linkEmailLogin:de("link_email_login",o),linkEmailOrEnterCode:de("link_email_or_enter_code",o),codeValid30Mins:de("code_valid_30_minutes",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}});const c=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(i.id,c))}async function ru(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 Wo(t,{to:e.email,subject:"Validate your email address",html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${At(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:de("welcome_to_your_account",r),verifyEmailVerify:de("verify_email_verify",r),supportInfo:de("support_info",r),contactUs:de("contact_us",r),copyright:de("copyright",r)}})}const vb=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),!tu(n))throw new z(400,{message:"Password does not meet the requirements"});if(await yn({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 ru(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 Gn({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,...Tn(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 or(){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 iu(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=Tn(t.req);if(l.ip!==u.ip)return t.redirect(`${At(t.env)}invalid-session?state=${l.login_id}`);if(n.redirect_uri&&!Fo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});let p=await yn({userAdapter:o.data.users,tenant_id:e.tenant.id,email:r,provider:"email"});if(!p){if(e.disable_sign_ups)throw new z(400,{message:"User not found"});p=await o.data.users.create(e.tenant.id,{email:r,email_verified:!0,connection:"email",provider:"email",is_social:!1,user_id:`email|${Re()}`})}return await o.data.codes.used(e.tenant.id,i),on(t,{user:p,client:e,loginSession:l,authParams:n,ticketAuth:s})}const wb=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:Xc.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()+Dc).toISOString(),...Tn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:or(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+Dc).toISOString()});return s==="link"?await nu(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(_n),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 Ho(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),iu(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 su(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 Gn({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:o,provider:"auth2"});if(!c){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new 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 Qe(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 Qe(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 ru(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 v=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Qe(t,t.env.data.logs.create(e.tenant.id,v)),on(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function bb(t,e,n,r){let i=await yn({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n,provider:"auth2"});if(!i){if(!(await tl(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()+Vy).toISOString(),authParams:{client_id:e.id,username:n},...Tn(t.req)});let o=or(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");for(;c;)o=or(),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()+Uy).toISOString()});await Ug(t,n,l.code_id,r)}const kb=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 iu(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},...Tn(t.req)});return su(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=da(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=da(o))==null?void 0:i.host)??null:c=((s=da("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function da(t){try{return new URL(t)}catch{return null}}async function Sb({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,...Tn(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 on(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=or();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 nu(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 Ab(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Eb(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=Ab(i);let p=await yn({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 on(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function $p(t,e){return`<!DOCTYPE html>
|
|
149
|
+
</html>`;return new Response(i,{headers:{"Content-Type":"text/html"}})}async function Zw(t,e,n,r,i){var m,v,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 Yw(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:u.requestId,userId:((f=(v=r.app_metadata)==null?void 0:v.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 Jw(p.toString(),h,u.relayState)}async function Yw(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||`_${Re()}`,c=e.assertionId||`_${Re()}`,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 Gw.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 Xw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),mn.encode(t,{includePadding:!1})}const Ep=["sub","iss","aud","exp","nbf","iat","jti"];async function Xl(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=Iv(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(Ep.includes(S))throw new Error(`Cannot overwrite reserved claim '${S}'`);p[S]=N}},idToken:{setCustomClaim:(S,N)=>{if(Ep.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 Kl(1,"d"),headers:{kid:l.kid}},v=await wp("RS256",u,p,m),f=h?await wp("RS256",u,h,m):void 0;return{access_token:v,refresh_token:e.refresh_token,id_token:f,token_type:"Bearer",expires_in:86400}}async function Qw(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:Re(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+qo*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:Re(),user_id:n.user_id,idle_expires_at:new Date(Date.now()+qo*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 Qw(t,{...e,session_id:o.id,scope:i,audience:s}):void 0;return{...o,refresh_token:c}}async function on(t,e){var m;const{authParams:n,user:r,client:i,ticketAuth:s}=e,o=be(t,{type:me.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id});if(Qe(t,t.env.data.logs.create(i.tenant.id,o)),Qe(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})),s){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const v=Xw(),f=Re(12),_=await t.env.data.codes.create(i.tenant.id,{code_id:Re(),code_type:"ticket",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Ly).toISOString(),code_verifier:[f,v].join("|")});return t.json({login_ticket:_.code_id,co_verifier:v,co_id:f})}let c=e.refreshToken,l=e.sessionId;if(!l){const v=await Bg(t,{user:r,client:i,scope:n.scope,audience:n.audience});l=v.id,c=(m=v.refresh_token)==null?void 0:m.id}if(e.authParams.response_mode===Jt.SAML_POST)return Zw(t,e.client,e.authParams,r,l);console.log("Create auth tokens");const u=await Xl(t,{authParams:n,user:r,client:i,session_id:l,refresh_token:c}),p=new Headers({"set-cookie":Eg(i.tenant.id,l)});if(n.response_mode===Jt.WEB_MESSAGE)return t.json(u,{headers:p});if((n.response_type||_n.CODE)===_n.CODE){if(!e.loginSession)throw new z(500,{message:"Login session not found"});const v=await t.env.data.codes.create(i.tenant.id,{code_id:Re(),user_id:r.user_id,code_type:"authorization_code",login_id:e.loginSession.login_id,expires_at:new Date(Date.now()+Py*1e3).toISOString()});p.set("location",`${n.redirect_uri}?state=${e.authParams.state}&code=${v.code_id}`)}return new Response("Redirecting",{status:302,headers:p})}function eb(t){return async(e,n)=>{if(!n.email||!n.email_verified)return t.users.create(e,n);const r=await Ys({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 tb(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 nb(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 rb(t,e){return async(n,r)=>{let i=await eb(e)(n,r);return await tb(t,e)(n,i),i}}async function Pg(t,e,n,r){if(e.disable_sign_ups&&!await Ys({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 nb(t,n)(t.var.tenant_id||"",r)}function ib(t,e){return{...e,users:{...e.users,create:rb(t,e)}}}async function sb(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,...Tn(t.req)}));const c=await Sg(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()+Ry*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Ip(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 Ho(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(!Fo(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 Sg(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 v=await yn({userAdapter:r.data.users,tenant_id:o.tenant.id,email:m,provider:c.name});if(!v){try{await Pg(t,o,t.env.data,m)}catch(_){const w=_;throw new z(500,{message:`Failed to run preUserSignupHook: ${w.message}`})}v=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",v.user_id)}return on(t,{client:o,authParams:s.authParams,loginSession:s,user:v})}async function Cp(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}`});Qe(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return By(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 ob=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 Cp(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ip(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 Cp(t,e,r,i,s,o);if(!n)throw new z(400,{message:"Code is required"});return Ip(t,{code:n,state:e})}),ab=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(!Fo(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=Hs(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":zv(r.tenant.id),location:s}})}),Np=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()}),cb=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Np}},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(Np.parse({...e,sub:e.user_id}))}),lb=new a.OpenAPIHono().openapi(a.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:of}},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 Hl(r.cert).publicKey.export(),o=await crypto.subtle.exportKey("jwk",s);return Qc.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:ka}},description:"List of tenants"}}}),async t=>{const e=ka.parse({issuer:fv(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 ub(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 Xl(t,{authParams:r,client:n});return t.json(i)}const db=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 pb(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 Cv(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),on(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Jt.WEB_MESSAGE}})}const fb=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 hb(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 on(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 zp=a.z.object({client_id:a.z.string().optional(),client_secret:a.z.string().optional()}),gb=a.z.union([Rg.extend(zp.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(),...zp.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 mb(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 _b=new a.OpenAPIHono().openapi(a.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:gb}}}},responses:{200:{content:{"application/json":{schema:pf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=mb(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 pb(t,db.parse(r));case jr.ClientCredential:return ub(t,Rg.parse(r));case jr.RefreshToken:return hb(t,fb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var Ql={exports:{}};const eu=[{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=eu,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};Ql.exports={passwordStrength:Lg,defaultOptions:eu};var yb=Ql.exports.passwordStrength=Lg;Ql.exports.defaultOptions=eu;function tu(t){return yb(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 Wo(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 Wo(t,{to:e,subject:"Reset your password",html:`Click here to reset your password: ${At(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:de("password_reset_title",o),resetPasswordEmailClickToReset:de("reset_password_email_click_to_reset",o),resetPasswordEmailReset:de("reset_password_email_reset",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}})}async function 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 Wo(t,{to:e,subject:de("code_email_subject",i),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",magicLink:`${Ne(t.env)}passwordless/verify_redirect?ticket=${n}`,buttonColor:r.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",i),linkEmailClickToLogin:de("link_email_click_to_login",i),linkEmailLogin:de("link_email_login",i),linkEmailOrEnterCode:de("link_email_or_enter_code",i),codeValid30Mins:de("code_valid_30_minutes",i),supportInfo:de("support_info",i),contactUs:de("contact_us",i),copyright:de("copyright",i)}});const s=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(r.id,s))}async function nu(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("verification_code",n),s.searchParams.set("connection","email"),s.searchParams.set("client_id",r.client_id),s.searchParams.set("redirect_uri",r.redirect_uri),s.searchParams.set("email",e),r.response_type&&s.searchParams.set("response_type",r.response_type),r.scope&&s.searchParams.set("scope",r.scope),r.state&&s.searchParams.set("state",r.state),r.nonce&&s.searchParams.set("nonce",r.nonce),r.code_challenge&&s.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&s.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&s.searchParams.set("audience",r.audience);const o={vendorName:i.name,code:n,lng:i.language||"en"};await Wo(t,{to:e,subject:de("code_email_subject",o),html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:s.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:de("welcome_to_your_account",o),linkEmailClickToLogin:de("link_email_click_to_login",o),linkEmailLogin:de("link_email_login",o),linkEmailOrEnterCode:de("link_email_or_enter_code",o),codeValid30Mins:de("code_valid_30_minutes",o),supportInfo:de("support_info",o),contactUs:de("contact_us",o),copyright:de("copyright",o)}});const c=be(t,{type:me.CODE_LINK_SENT,description:e});Qe(t,t.env.data.logs.create(i.id,c))}async function ru(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 Wo(t,{to:e.email,subject:"Validate your email address",html:`Click here to validate your email: ${At(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${At(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:de("welcome_to_your_account",r),verifyEmailVerify:de("verify_email_verify",r),supportInfo:de("support_info",r),contactUs:de("contact_us",r),copyright:de("copyright",r)}})}const vb=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),!tu(n))throw new z(400,{message:"Password does not meet the requirements"});if(await yn({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 ru(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 Gn({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,...Tn(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 or(){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 iu(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=Tn(t.req);if(l.ip!==u.ip)return t.redirect(`${At(t.env)}invalid-session?state=${l.login_id}`);if(n.redirect_uri&&!Fo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});let p=await yn({userAdapter:o.data.users,tenant_id:e.tenant.id,email:r,provider:"email"});if(!p){if(e.disable_sign_ups)throw new z(400,{message:"User not found"});p=await o.data.users.create(e.tenant.id,{email:r,email_verified:!0,connection:"email",provider:"email",is_social:!1,user_id:`email|${Re()}`})}return await o.data.codes.used(e.tenant.id,i),on(t,{user:p,client:e,loginSession:l,authParams:n,ticketAuth:s})}const wb=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:Xc.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()+Dc).toISOString(),...Tn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:or(),code_type:"otp",login_id:l.login_id,expires_at:new Date(Date.now()+Dc).toISOString()});return s==="link"?await nu(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(_n),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 Ho(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),iu(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 su(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 Gn({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:o,provider:"auth2"});if(!c){const f=be(t,{type:me.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw Qe(t,t.env.data.logs.create(e.tenant.id,f)),new 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 Qe(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 Qe(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 ru(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 v=be(t,{type:me.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return Qe(t,t.env.data.logs.create(e.tenant.id,v)),on(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function bb(t,e,n,r){let i=await yn({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n,provider:"auth2"});if(!i){if(!(await tl(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()+Vy).toISOString(),authParams:{client_id:e.id,username:n},...Tn(t.req)});let o=or(),c=await t.env.data.codes.get(e.tenant.id,o,"password_reset");for(;c;)o=or(),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()+Uy).toISOString()});await Ug(t,n,l.code_id,r)}const kb=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 iu(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},...Tn(t.req)});return su(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=da(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=da(o))==null?void 0:i.host)??null:c=((s=da("https://"+o))==null?void 0:s.host)??null,n===c)return!0}return!1}function da(t){try{return new URL(t)}catch{return null}}async function Sb({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,...Tn(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 on(t,{client:n,loginSession:o,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=or();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 nu(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 Ab(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Eb(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=Ab(i);let p=await yn({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 on(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:h.id,user:p,client:l})}async function $p(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&&y("div",{className:"absolute left-0 top-0 flex h-full w-full items-center justify-center",children:y(s1,{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 y(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||"",y("div",{className:Et("text-left text-black dark:text-white sm:text-base",{"hidden sm:inline short:hidden":r}),children:e})]})},o1=({...t})=>y("svg",{width:"45",height:"45",viewBox:"0 0 45 45",xmlns:"http://www.w3.org/2000/svg",...t,children:[y("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"}),y("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"}),y("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"}),y("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"})]}),Pn=({children:t,className:e})=>y(lu,{children:[y(ni,{className:e,id:"initial-btn",children:t}),y(ni,{className:Et(e,"hidden"),isLoading:!0,id:"loading-btn",disabled:!0,children:" "})]}),Rn=({children:t,className:e})=>y("form",{id:"form",method:"post",className:e,children:t}),a1=({...t})=>y("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:[y("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"}),y("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`})]}),Up=({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 y(zt,{title:U.t("welcome"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("welcome")}),y("div",{className:"mb-8 text-gray-300",children:U.t("login_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"mb-7",children:[y("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&&y("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&&y(br,{children:t}),y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("continue")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})]}),h&&y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("continue_social_login")})]}),y("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&&y(Pi,{connection:"facebook",text:U.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:y(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&&y(Pi,{connection:"google-oauth2",text:U.t("continue_with",{provider:"Google"}),canResize:!0,icon:y(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}),u&&y(Pi,{connection:"apple",text:U.t("continue_with",{provider:"Apple"}),canResize:!0,icon:y(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&&y(Pi,{connection:"vipps",text:U.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:y(a1,{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})]})]})]})},c1=["Auth0.swift"];function l1(t){if(!t)return"link";const e=atob(t),n=JSON.parse(e);return c1.includes(n.name)?"code":"link"}const u1=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 Fe(t,e);return t.html(y(Up,{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 Fe(t,n);t.set("client_id",i.id);const c=r.username,l=await Ys({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 v=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,v),t.html(y(Up,{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 Jb(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=or(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=or(),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()+Dc).toISOString()});return l1(s.auth0Client)==="link"&&!r.username.includes("online.no")?Qe(t,nu(t,r.username,h.code_id,s.authParams)):Qe(t,Vg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),Qt=t=>y("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",d1={Change:"Input",DoubleClick:"DblClick"},p1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Gc=new WeakMap,cr=void 0,f1=()=>cr,$t=t=>"t"in t,ha={onClick:["click",!1]},Vp=t=>{if(!t.startsWith("on"))return;if(ha[t])return ha[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return ha[t]=[(d1[n]||n).toLowerCase(),!!r]}},Mp=(t,e)=>cr&&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,h1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Ks(i);const o=Vp(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),Gc.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=Mp(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=Ks(i);const o=Vp(i);o?t.removeEventListener(o[0],s,o[1]):i==="ref"?(r=Gc.get(t))==null||r():t.removeAttribute(Mp(t,i))}}},g1=(t,e)=>{e[Se][0]=0,ii.push([t,e]);const n=e.tag[ou]||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($t(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)})},m1=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;$t(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=Gc.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)},qp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Dp=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=qp(o,m1(t.nN));p!==void 0?(l=o[p],c=p):c=qp(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 v;if(m.s&&m.e)v=m.e,m.s=!1;else{const f=n||!m.e;$t(m)?(m.e&&m.d&&(m.e.textContent=m.t),m.d=!1,v=m.e||(m.e=document.createTextNode(m.t))):(v=m.e||(m.e=m.n?document.createElementNS(m.n,m.tag):document.createElement(m.tag)),h1(v,m.props,m.pP),tm(m,v,f))}m.tag===ri?c--:n?v.parentNode||e.appendChild(v):o[c]!==v&&o[c-1]!==v&&(o[c+1]===v?e.appendChild(o[c]):e.insertBefore(v,l||o[c]||null))}if(t.pP&&delete t.pP,s.length){const p=[],h=[];s.forEach(([,m,,v,f])=>{m&&p.push(m),v&&h.push(v),f==null||f()}),p.forEach(m=>m()),h.length&&requestAnimationFrame(()=>{h.forEach(m=>m())})}},Ji=new WeakMap,Jc=(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"?g1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Kc]&&(i=n[0][Kc],t[5].push([t,i,e]));const h=r?[...e.pC]:e.vC?[...e.vC]:void 0,m=[];let v;for(let f=0;f<n.length;f++){Array.isArray(n[f])&&n.splice(f,1,...n[f].flat());let _=_1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Dg]&&(ar.length>0&&(_[Se][2]=ar.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($t(_)?N=>$t(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($t(_))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)[Ob])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!$t(_)&&cr){const S=wr(cr);S&&(_.n=S)}if(!$t(_)&&!_.s&&(Jc(t,_),delete _.f),m.push(_),v&&!v.s&&!_.s)for(let S=v;S&&!$t(S);S=(u=S.vC)==null?void 0:u.at(-1))S.nN=_;v=_}}e.vR=r?[...e.vC,...h||[]]:h||[],e.vC=m,r&&delete e.pC}catch(h){if(e.f=!0,h===Dp){if(i)return;throw h}const[m,v,f]=((p=e[Se])==null?void 0:p[3])||[];if(v){const _=()=>Zi([0,!1,t[2]],f),w=Ji.get(f)||[];w.push(_),Ji.set(f,w);const S=v(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(Jc(t,f,[S]),(v.length===1||t!==m)&&f.c){em(f,f.c,!1);return}throw Dp}}throw h}finally{i&&t[5].pop()}},_1=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=p1[t.tag];e&&(cr||(cr=Fg("")),t.props.children=[{tag:cr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Hp=(t,e)=>{var n,r;(n=e[Se][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Jc(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,Fp=[],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=>{Hp(s,e)}).then(()=>r(e)):(Hp(t,e),r(e))}]),Fp.length)Fp.at(-1).add(e);else{await Promise.resolve();const s=zr.get(e);s&&(zr.delete(e),s[1]())}return i},y1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),ga=0,nm=1,ma=2,_a=3,ya=new WeakMap,rm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),v1=void 0,Kp=[],w1=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])[ga]||(o[ga]=[]),s=r[Se][0]++;return i[s]||(i[s]=[e(),c=>{const l=v1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Kp.length){const[p,h]=Kp.at(-1);Promise.all([p===3?r:Zi([p,!1,l],r),h]).then(([m])=>{if(!m||!(p===2||p===3))return;const v=m.vC;requestAnimationFrame(()=>{setTimeout(()=>{v===m.vC&&Zi([p===3?1:0,!1,l],m)})})})}else Zi([0,!1,l],r)}])},uu=(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]:t=i[s][0],t},b1=t=>{const e=ya.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ya.set(t,[n]),n=>ya.set(t,[void 0,n])),t},k1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Se][1])[_a]||(c[_a]=[]),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}),Wp=new Set,S1=t=>{Wp.add(t),t.finally(()=>Wp.delete(t))},du=(t,e)=>k1(()=>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]),Mn=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 v=Ki[t];let f;if(v.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=v.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 v)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 _=uu(N=>{if(v.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=du(e.ref,N=>{var te;const B=v[0];if(n===2&&(N.innerHTML=""),(m||f)&&_(N),!c&&!o)return;let R=Mn[te=N.getAttribute(B)]||(Mn[te]=new Promise((fe,le)=>{N.addEventListener("load",fe),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=Mn[B]||(Mn[B]=new Promise((te,fe)=>{_(h),h.addEventListener("load",te),h.addEventListener("error",fe)}));b1(R)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),y1(S,s)},A1=t=>{const e=f1(),n=e&&wr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Ci("title",t,void 0,!1,!1)},E1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Ci("script",t,1,!1,!0),I1=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)),C1=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),N1=t=>Ci("meta",t,void 0,!1,!1),im=Symbol(),z1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=w1([null,!1]),s=uu(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&&(S1(m),await m),i([null,!0])},[]),o=du(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=uu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[im]:e}}))},[]);n.ref=du(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},$1=t=>sm("input",t),j1=t=>sm("button",t);Object.assign(Wc,{title:A1,script:E1,style:I1,link:C1,meta:N1,form:z1,input:$1,button:j1});new TextEncoder;const om=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(Gb(r[m],{},p)),c=s.lastIndex}return c<i.length&&o.push(i.substring(c)),y(lu,{children:o})},Gp=6,Jp=({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 y(zt,{title:U.t("verify_your_email"),vendorSettings:e,children:[y("div",{className:"mb-4 text-2xl font-medium",children:U.t("verify_your_email")}),y("div",{className:"mb-8 text-gray-300",children:y(om,{i18nKey:"we_sent_a_code_to",components:[y("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"pt-2",children:[y("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:Gp,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:Gp,required:!0,id:"code-input"}),t&&y(br,{children:t}),y("div",{className:"text-center sm:mt-2",children:y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("login")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),l&&y("div",{className:"text-center mb-12",children:[y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),y(ni,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${o.toString()}`,variant:"secondary",className:"block",children:U.t("enter_your_password_btn")})]})]}),y(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 Fe(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await yn({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(Jp,{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 Fe(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 iu(t,i,r.authParams,r.authParams.username,n)}catch(o){const c=o,l=await yn({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(Jp,{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 y(zt,{title:U.t("unverified_email"),vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("p",{className:"mb-8 text-gray-300 text-lg",children:U.t("unverified_email")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),y(Qt,{state:n})]}),y(Qt,{state:n})]})},va=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return y(zt,{title:U.t("enter_password"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("enter_password")}),y("div",{className:"mb-6 text-gray-300",children:U.t("enter_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"mb-7",children:[y("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}),y("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&&y(br,{children:e}),y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("login")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})]}),y("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:U.t("forgot_password_link")}),y("div",{className:"text-center mb-12",children:[y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),y("form",{method:"post",action:`/u/enter-email?${s.toString()}`,children:[y("input",{type:"hidden",name:"login_selection",value:"code"}),y("input",{type:"hidden",name:"username",value:r}),y(ni,{variant:"secondary",className:"block",children:U.t("enter_a_code_btn")})]})]}),y(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 Fe(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(va,{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 Fe(t,e),{username:c}=o.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await su(t,s,{...o.authParams,password:r},o)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(y(va,{vendorSettings:i,email:c,error:U.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(y(B1,{vendorSettings:i,state:e}),400):t.html(y(va,{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 y(zt,{title:U.t("create_account_title"),vendorSettings:r,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("create_account_title")}),y("div",{className:"mb-6 text-gray-300",children:U.t("create_account_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{children:[y("input",{type:"hidden",name:"code",value:s}),y("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}),y("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"}),y("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&&y(br,{children:n}),y(Pn,{className:"text-base sm:mt-2 md:text-base",children:U.t("continue")})]}),y(Qt,{state:e})]})]})},am=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return y(zt,{title:"Login",vendorSettings:n,children:[r?y("div",{className:"mb-6 text-gray-300",children:r}):"",y("div",{className:"flex flex-1 flex-col justify-center",children:e}),i?y(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 Fe(t,e),{username:s}=i.authParams;if(!s)throw new z(400,{message:"Username required"});return n?t.html(y(Cr,{state:e,vendorSettings:r,email:s,code:n})):t.html(y(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 Fe(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(y(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_passwords_didnt_match"),email:o.authParams.username}),400);if(!tu(n.password))return t.html(y(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 Gn({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,v=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 Gn({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 su(t,s,{...o.authParams,password:n.password},o):(await ru(t,v),t.html(y(am,{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),v=h;return t.html(y(Cr,{state:e,vendorSettings:m,error:v.message,email:l}),400)}}),Nr=t=>{const{error:e,vendorSettings:n,email:r}=t;return y(zt,{title:U.t("reset_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("reset_password_title")}),y("div",{className:"mb-6 text-gray-300",children:`${U.t("reset_password_description")} ${r}`}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(Rn,{children:[y("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"}),y("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&&y(br,{children:e}),y(Pn,{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 Fe(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(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 Fe(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(y(Nr,{error:U.t("create_account_passwords_didnt_match"),vendorSettings:o,email:l.authParams.username}),400);if(!tu(r))return t.html(y(Nr,{error:U.t("create_account_weak_password"),vendorSettings:o,email:l.authParams.username}),400);const u=await Gn({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(y(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(y(Nr,{error:"The password could not be reset",vendorSettings:o,email:l.authParams.username}),400)}return t.html(y(am,{message:U.t("password_has_been_reset"),vendorSettings:o,state:e}))}),L1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return y(zt,{title:U.t("forgot_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("forgot_password_title")}),y("div",{className:"mb-6 text-gray-300",children:U.t("forgot_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"pt-2",children:[y("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&&y(br,{children:e}),y(Pn,{className:"sm:mt-4",children:U.t("forgot_password_cta")})]}),y(Qt,{state:i})]})]})},U1=t=>{const{vendorSettings:e,state:n}=t;return y(zt,{title:"Login",vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{children:U.t("forgot_password_email_sent")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]})]}),y(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 Fe(t,e);return t.html(y(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 Fe(t,e);return await bb(t,r,i.authParams.username,i.login_id),t.html(y(U1,{vendorSettings:n,state:e}))}),M1=({vendorSettings:t,state:e,user:n})=>y(zt,{title:de("check_email_title"),vendorSettings:t,children:y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{className:"mb-8 text-gray-700 dark:text-gray-300",children:[y(om,{i18nKey:"currently_logged_in_as",components:[y("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:n.email}}),y("br",{}),de("continue_with_sso_provider_headline")]}),y("div",{className:"space-y-6",children:[y(Rn,{children:y(Pn,{className:"w-full text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center justify-center space-x-2",children:y("span",{children:U.t("yes_continue_with_existing_account")})})})}),y("a",{className:"block text-center text-primary hover:text-primaryHover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-900",href:`/u/enter-email?state=${encodeURIComponent(e)}`,children:U.t("no_use_another")})]})]})}),q1=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{env:e}=t,{state:n}=t.req.valid("query"),{vendorSettings:r,client:i}=await Fe(t,n),s=Hs(i.tenant.id,t.req.header("cookie")),o=s?await e.data.sessions.get(i.tenant.id,s):null;if(!o)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,o.user_id);return c?t.html(y(M1,{vendorSettings:r,state:n,user:c})):t.redirect(`/u/enter-email?state=${n}`)}).openapi(a.createRoute({tags:["login"],method:"post",path:"/check-account",request:{query:a.z.object({state:a.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{302:{description:"Redirect"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{session:r,client:i}=await Fe(t,n),s=Hs(i.tenant.id,t.req.header("cookie")),o=s?await e.data.sessions.get(i.tenant.id,s):null;if(!o)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,o.user_id);return c?on(t,{user:c,authParams:r.authParams,client:i}):t.redirect(`/u/enter-email?state=${n}`)});function D1(){const e=new a.OpenAPIHono().route("/check-account",q1).route("/enter-email",u1).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 H1="Account detected",F1="We have detected that you have already created an account through",K1="By signing in, you agree to our",W1="and",G1="Callback URL mismatch",J1="The provided redirect_uri is not in the list of allowed callback URLs.",Z1="continue with user",Y1="Please click the button to create a new password account.",X1="Enter the code at {{vendorName}} to complete the login",Q1="Welcome to {{vendorName}}! {{code}} is the login code",ek="Welcome to {{vendorName}}! {{code}} is the login code",tk="The code is valid for 30 minutes",nk="Confirm password",rk="Need Help?",ik="Contact us",sk="or continue with social account",ok="Continue with {{provider}}",ak="Would you like to continue with your existing account?",ck="Copyright © 2023 SESAMY. All rights reserved.",lk="©2023 Sesamy",uk="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",dk="Please enter a valid email address.",pk="The passwords didn't match. Try again.",fk="Choose password",hk="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",gk="Create new account",mk="Sign up with password",_k="You are currently logged in as <0>{{email}}</0>",yk="Email",vk="Email address",wk="Your email address has been validated",bk="Now enter your password to login again",kk="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.",xk="Email verification sent",Sk="Enter a code",Ak="We'll send you a verification link to ensure you own this email address.",Ek="Enter new password",Ik="Enter password",Ck="Enter your email address and password to login.",Nk="Enter your password",zk="The magic link has expired. Please click on the button below to receive a new link in your inbox.",$k="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",jk="Send password reset email",Ok="Click the button below and we’ll send instructions on how to reset your password.",Bk="Password reset email sent",Tk="Forgot password?",Pk="Forgot password?",Rk="Go back",Lk="Invalid password",Uk=`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`})]}),Up=({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 y(zt,{title:U.t("welcome"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("welcome")}),y("div",{className:"mb-8 text-gray-300",children:U.t("login_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"mb-7",children:[y("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&&y("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&&y(br,{children:t}),y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("continue")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})]}),h&&y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("continue_social_login")})]}),y("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&&y(Pi,{connection:"facebook",text:U.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:y(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&&y(Pi,{connection:"google-oauth2",text:U.t("continue_with",{provider:"Google"}),canResize:!0,icon:y(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}),u&&y(Pi,{connection:"apple",text:U.t("continue_with",{provider:"Apple"}),canResize:!0,icon:y(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&&y(Pi,{connection:"vipps",text:U.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:y(a1,{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})]})]})]})},c1=["Auth0.swift"];function l1(t){if(!t)return"link";const e=atob(t),n=JSON.parse(e);return c1.includes(n.name)?"code":"link"}const u1=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 Fe(t,e);return t.html(y(Up,{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 Fe(t,n);t.set("client_id",i.id);const c=r.username,l=await Ys({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 v=be(t,{type:me.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,v),t.html(y(Up,{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 Jb(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=or(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=or(),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()+Dc).toISOString()});return l1(s.auth0Client)==="link"&&!r.username.includes("online.no")?Qe(t,nu(t,r.username,h.code_id,s.authParams)):Qe(t,Vg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),Qt=t=>y("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",d1={Change:"Input",DoubleClick:"DblClick"},p1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Gc=new WeakMap,cr=void 0,f1=()=>cr,$t=t=>"t"in t,ha={onClick:["click",!1]},Vp=t=>{if(!t.startsWith("on"))return;if(ha[t])return ha[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return ha[t]=[(d1[n]||n).toLowerCase(),!!r]}},Mp=(t,e)=>cr&&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,h1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Ks(i);const o=Vp(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),Gc.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=Mp(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=Ks(i);const o=Vp(i);o?t.removeEventListener(o[0],s,o[1]):i==="ref"?(r=Gc.get(t))==null||r():t.removeAttribute(Mp(t,i))}}},g1=(t,e)=>{e[Se][0]=0,ii.push([t,e]);const n=e.tag[ou]||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($t(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)})},m1=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;$t(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=Gc.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)},qp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Dp=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=qp(o,m1(t.nN));p!==void 0?(l=o[p],c=p):c=qp(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 v;if(m.s&&m.e)v=m.e,m.s=!1;else{const f=n||!m.e;$t(m)?(m.e&&m.d&&(m.e.textContent=m.t),m.d=!1,v=m.e||(m.e=document.createTextNode(m.t))):(v=m.e||(m.e=m.n?document.createElementNS(m.n,m.tag):document.createElement(m.tag)),h1(v,m.props,m.pP),tm(m,v,f))}m.tag===ri?c--:n?v.parentNode||e.appendChild(v):o[c]!==v&&o[c-1]!==v&&(o[c+1]===v?e.appendChild(o[c]):e.insertBefore(v,l||o[c]||null))}if(t.pP&&delete t.pP,s.length){const p=[],h=[];s.forEach(([,m,,v,f])=>{m&&p.push(m),v&&h.push(v),f==null||f()}),p.forEach(m=>m()),h.length&&requestAnimationFrame(()=>{h.forEach(m=>m())})}},Ji=new WeakMap,Jc=(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"?g1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Kc]&&(i=n[0][Kc],t[5].push([t,i,e]));const h=r?[...e.pC]:e.vC?[...e.vC]:void 0,m=[];let v;for(let f=0;f<n.length;f++){Array.isArray(n[f])&&n.splice(f,1,...n[f].flat());let _=_1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Dg]&&(ar.length>0&&(_[Se][2]=ar.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($t(_)?N=>$t(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($t(_))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)[Ob])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!$t(_)&&cr){const S=wr(cr);S&&(_.n=S)}if(!$t(_)&&!_.s&&(Jc(t,_),delete _.f),m.push(_),v&&!v.s&&!_.s)for(let S=v;S&&!$t(S);S=(u=S.vC)==null?void 0:u.at(-1))S.nN=_;v=_}}e.vR=r?[...e.vC,...h||[]]:h||[],e.vC=m,r&&delete e.pC}catch(h){if(e.f=!0,h===Dp){if(i)return;throw h}const[m,v,f]=((p=e[Se])==null?void 0:p[3])||[];if(v){const _=()=>Zi([0,!1,t[2]],f),w=Ji.get(f)||[];w.push(_),Ji.set(f,w);const S=v(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(Jc(t,f,[S]),(v.length===1||t!==m)&&f.c){em(f,f.c,!1);return}throw Dp}}throw h}finally{i&&t[5].pop()}},_1=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=p1[t.tag];e&&(cr||(cr=Fg("")),t.props.children=[{tag:cr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Hp=(t,e)=>{var n,r;(n=e[Se][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Jc(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,Fp=[],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=>{Hp(s,e)}).then(()=>r(e)):(Hp(t,e),r(e))}]),Fp.length)Fp.at(-1).add(e);else{await Promise.resolve();const s=zr.get(e);s&&(zr.delete(e),s[1]())}return i},y1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),ga=0,nm=1,ma=2,_a=3,ya=new WeakMap,rm=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),v1=void 0,Kp=[],w1=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])[ga]||(o[ga]=[]),s=r[Se][0]++;return i[s]||(i[s]=[e(),c=>{const l=v1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Kp.length){const[p,h]=Kp.at(-1);Promise.all([p===3?r:Zi([p,!1,l],r),h]).then(([m])=>{if(!m||!(p===2||p===3))return;const v=m.vC;requestAnimationFrame(()=>{setTimeout(()=>{v===m.vC&&Zi([p===3?1:0,!1,l],m)})})})}else Zi([0,!1,l],r)}])},uu=(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]:t=i[s][0],t},b1=t=>{const e=ya.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ya.set(t,[n]),n=>ya.set(t,[void 0,n])),t},k1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Se][1])[_a]||(c[_a]=[]),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}),Wp=new Set,S1=t=>{Wp.add(t),t.finally(()=>Wp.delete(t))},du=(t,e)=>k1(()=>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]),Mn=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 v=Ki[t];let f;if(v.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=v.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 v)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 _=uu(N=>{if(v.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=du(e.ref,N=>{var te;const B=v[0];if(n===2&&(N.innerHTML=""),(m||f)&&_(N),!c&&!o)return;let R=Mn[te=N.getAttribute(B)]||(Mn[te]=new Promise((fe,le)=>{N.addEventListener("load",fe),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=Mn[B]||(Mn[B]=new Promise((te,fe)=>{_(h),h.addEventListener("load",te),h.addEventListener("error",fe)}));b1(R)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),y1(S,s)},A1=t=>{const e=f1(),n=e&&wr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:Ci("title",t,void 0,!1,!1)},E1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:Ci("script",t,1,!1,!0),I1=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)),C1=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),N1=t=>Ci("meta",t,void 0,!1,!1),im=Symbol(),z1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=w1([null,!1]),s=uu(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&&(S1(m),await m),i([null,!0])},[]),o=du(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=uu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[im]:e}}))},[]);n.ref=du(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},$1=t=>sm("input",t),j1=t=>sm("button",t);Object.assign(Wc,{title:A1,script:E1,style:I1,link:C1,meta:N1,form:z1,input:$1,button:j1});new TextEncoder;const om=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(Gb(r[m],{},p)),c=s.lastIndex}return c<i.length&&o.push(i.substring(c)),y(lu,{children:o})},Gp=6,Jp=({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 y(zt,{title:U.t("verify_your_email"),vendorSettings:e,children:[y("div",{className:"mb-4 text-2xl font-medium",children:U.t("verify_your_email")}),y("div",{className:"mb-8 text-gray-300",children:y(om,{i18nKey:"we_sent_a_code_to",components:[y("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"pt-2",children:[y("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:Gp,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:Gp,required:!0,id:"code-input"}),t&&y(br,{children:t}),y("div",{className:"text-center sm:mt-2",children:y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("login")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),l&&y("div",{className:"text-center mb-12",children:[y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),y(ni,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${o.toString()}`,variant:"secondary",className:"block",children:U.t("enter_your_password_btn")})]})]}),y(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 Fe(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await yn({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(Jp,{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 Fe(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 iu(t,i,r.authParams,r.authParams.username,n)}catch(o){const c=o,l=await yn({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(Jp,{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 y(zt,{title:U.t("unverified_email"),vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("p",{className:"mb-8 text-gray-300 text-lg",children:U.t("unverified_email")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]}),y(Qt,{state:n})]}),y(Qt,{state:n})]})},va=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return y(zt,{title:U.t("enter_password"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("enter_password")}),y("div",{className:"mb-6 text-gray-300",children:U.t("enter_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"mb-7",children:[y("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}),y("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&&y(br,{children:e}),y(Pn,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:U.t("login")}),y(gt,{className:"text-xs",name:"arrow-right"})]})})]}),y("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:U.t("forgot_password_link")}),y("div",{className:"text-center mb-12",children:[y("div",{className:"relative mb-5 block text-center text-gray-300 dark:text-gray-300",children:[y("div",{className:"absolute left-0 right-0 top-1/2 border-b border-gray-200 dark:border-gray-600"}),y("div",{className:"relative inline-block bg-white px-2 dark:bg-gray-800",children:U.t("or")})]}),y("form",{method:"post",action:`/u/enter-email?${s.toString()}`,children:[y("input",{type:"hidden",name:"login_selection",value:"code"}),y("input",{type:"hidden",name:"username",value:r}),y(ni,{variant:"secondary",className:"block",children:U.t("enter_a_code_btn")})]})]}),y(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 Fe(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(va,{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 Fe(t,e),{username:c}=o.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await su(t,s,{...o.authParams,password:r},o)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(y(va,{vendorSettings:i,email:c,error:U.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(y(B1,{vendorSettings:i,state:e}),400):t.html(y(va,{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 y(zt,{title:U.t("create_account_title"),vendorSettings:r,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("create_account_title")}),y("div",{className:"mb-6 text-gray-300",children:U.t("create_account_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{children:[y("input",{type:"hidden",name:"code",value:s}),y("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}),y("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"}),y("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&&y(br,{children:n}),y(Pn,{className:"text-base sm:mt-2 md:text-base",children:U.t("continue")})]}),y(Qt,{state:e})]})]})},am=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return y(zt,{title:"Login",vendorSettings:n,children:[r?y("div",{className:"mb-6 text-gray-300",children:r}):"",y("div",{className:"flex flex-1 flex-col justify-center",children:e}),i?y(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 Fe(t,e),{username:s}=i.authParams;if(!s)throw new z(400,{message:"Username required"});return n?t.html(y(Cr,{state:e,vendorSettings:r,email:s,code:n})):t.html(y(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 Fe(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(y(Cr,{state:e,code:n.code,vendorSettings:i,error:U.t("create_account_passwords_didnt_match"),email:o.authParams.username}),400);if(!tu(n.password))return t.html(y(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 Gn({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,v=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 Gn({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 su(t,s,{...o.authParams,password:n.password},o):(await ru(t,v),t.html(y(am,{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),v=h;return t.html(y(Cr,{state:e,vendorSettings:m,error:v.message,email:l}),400)}}),Nr=t=>{const{error:e,vendorSettings:n,email:r}=t;return y(zt,{title:U.t("reset_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("reset_password_title")}),y("div",{className:"mb-6 text-gray-300",children:`${U.t("reset_password_description")} ${r}`}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(Rn,{children:[y("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"}),y("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&&y(br,{children:e}),y(Pn,{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 Fe(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(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 Fe(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(y(Nr,{error:U.t("create_account_passwords_didnt_match"),vendorSettings:o,email:l.authParams.username}),400);if(!tu(r))return t.html(y(Nr,{error:U.t("create_account_weak_password"),vendorSettings:o,email:l.authParams.username}),400);const u=await Gn({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(y(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(y(Nr,{error:"The password could not be reset",vendorSettings:o,email:l.authParams.username}),400)}return t.html(y(am,{message:U.t("password_has_been_reset"),vendorSettings:o,state:e}))}),L1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return y(zt,{title:U.t("forgot_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:U.t("forgot_password_title")}),y("div",{className:"mb-6 text-gray-300",children:U.t("forgot_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(Rn,{className:"pt-2",children:[y("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&&y(br,{children:e}),y(Pn,{className:"sm:mt-4",children:U.t("forgot_password_cta")})]}),y(Qt,{state:i})]})]})},U1=t=>{const{vendorSettings:e,state:n}=t;return y(zt,{title:"Login",vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{children:U.t("forgot_password_email_sent")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(gt,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:U.t("sent_code_spam")})]})]}),y(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 Fe(t,e);return t.html(y(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 Fe(t,e);return await bb(t,r,i.authParams.username,i.login_id),t.html(y(U1,{vendorSettings:n,state:e}))}),M1=({vendorSettings:t,state:e,user:n})=>y(zt,{title:de("check_email_title"),vendorSettings:t,children:y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{className:"mb-8 text-gray-700 dark:text-gray-300",children:[y(om,{i18nKey:"currently_logged_in_as",components:[y("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:n.email}}),y("br",{}),de("continue_with_sso_provider_headline")]}),y("div",{className:"space-y-6",children:[y(Rn,{children:y(Pn,{className:"w-full text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center justify-center space-x-2",children:y("span",{children:U.t("yes_continue_with_existing_account")})})})}),y("a",{className:"block text-center text-primary hover:text-primaryHover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 dark:focus:ring-offset-gray-900",href:`/u/enter-email?state=${encodeURIComponent(e)}`,children:U.t("no_use_another")})]})]})}),q1=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{env:e}=t,{state:n}=t.req.valid("query"),{vendorSettings:r,client:i}=await Fe(t,n),s=Hs(i.tenant.id,t.req.header("cookie")),o=s?await e.data.sessions.get(i.tenant.id,s):null;if(!o)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,o.user_id);return c?t.html(y(M1,{vendorSettings:r,state:n,user:c})):t.redirect(`/u/enter-email?state=${n}`)}).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:{302:{description:"Redirect"}}}),async t=>{const{env:e}=t,{state:n}=t.req.valid("query"),{session:r,client:i}=await Fe(t,n),s=Hs(i.tenant.id,t.req.header("cookie")),o=s?await e.data.sessions.get(i.tenant.id,s):null;if(!o)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,o.user_id);return c?on(t,{user:c,authParams:r.authParams,client:i,loginSession:r}):t.redirect(`/u/enter-email?state=${n}`)});function D1(){const e=new a.OpenAPIHono().route("/check-account",q1).route("/enter-email",u1).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 H1="Account detected",F1="We have detected that you have already created an account through",K1="By signing in, you agree to our",W1="and",G1="Callback URL mismatch",J1="The provided redirect_uri is not in the list of allowed callback URLs.",Z1="continue with user",Y1="Please click the button to create a new password account.",X1="Enter the code at {{vendorName}} to complete the login",Q1="Welcome to {{vendorName}}! {{code}} is the login code",ek="Welcome to {{vendorName}}! {{code}} is the login code",tk="The code is valid for 30 minutes",nk="Confirm password",rk="Need Help?",ik="Contact us",sk="or continue with social account",ok="Continue with {{provider}}",ak="Would you like to continue with your existing account?",ck="Copyright © 2023 SESAMY. All rights reserved.",lk="©2023 Sesamy",uk="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",dk="Please enter a valid email address.",pk="The passwords didn't match. Try again.",fk="Choose password",hk="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",gk="Create new account",mk="Sign up with password",_k="You are currently logged in as <0>{{email}}</0>",yk="Email",vk="Email address",wk="Your email address has been validated",bk="Now enter your password to login again",kk="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.",xk="Email verification sent",Sk="Enter a code",Ak="We'll send you a verification link to ensure you own this email address.",Ek="Enter new password",Ik="Enter password",Ck="Enter your email address and password to login.",Nk="Enter your password",zk="The magic link has expired. Please click on the button below to receive a new link in your inbox.",$k="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",jk="Send password reset email",Ok="Click the button below and we’ll send instructions on how to reset your password.",Bk="Password reset email sent",Tk="Forgot password?",Pk="Forgot password?",Rk="Go back",Lk="Invalid password",Uk=`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
|
|
package/dist/authhero.d.ts
CHANGED
package/dist/authhero.mjs
CHANGED
|
@@ -17705,47 +17705,47 @@ async function _g(t, e) {
|
|
|
17705
17705
|
return { ...o, refresh_token: a };
|
|
17706
17706
|
}
|
|
17707
17707
|
async function sn(t, e) {
|
|
17708
|
-
var
|
|
17709
|
-
const { authParams: n, user: r, client: i } = e,
|
|
17708
|
+
var m;
|
|
17709
|
+
const { authParams: n, user: r, client: i, ticketAuth: s } = e, o = xe(t, {
|
|
17710
17710
|
type: ve.SUCCESS_LOGIN,
|
|
17711
17711
|
description: `Successful login for ${r.user_id}`,
|
|
17712
17712
|
userId: r.user_id
|
|
17713
17713
|
});
|
|
17714
|
-
if (tt(t, t.env.data.logs.create(i.tenant.id,
|
|
17714
|
+
if (tt(t, t.env.data.logs.create(i.tenant.id, o)), tt(
|
|
17715
17715
|
t,
|
|
17716
17716
|
t.env.data.users.update(i.tenant.id, r.user_id, {
|
|
17717
17717
|
last_login: (/* @__PURE__ */ new Date()).toISOString(),
|
|
17718
17718
|
last_ip: t.req.header("x-real-ip") || "",
|
|
17719
17719
|
login_count: r.login_count + 1
|
|
17720
17720
|
})
|
|
17721
|
-
),
|
|
17721
|
+
), s) {
|
|
17722
17722
|
if (!e.loginSession)
|
|
17723
17723
|
throw new $(500, {
|
|
17724
17724
|
message: "Login session not found"
|
|
17725
17725
|
});
|
|
17726
|
-
const
|
|
17726
|
+
const v = Kw(), f = Ve(12), _ = await t.env.data.codes.create(i.tenant.id, {
|
|
17727
17727
|
code_id: Ve(),
|
|
17728
17728
|
code_type: "ticket",
|
|
17729
17729
|
login_id: e.loginSession.login_id,
|
|
17730
17730
|
expires_at: new Date(Date.now() + Oy).toISOString(),
|
|
17731
17731
|
// Concat the co_id and co_verifier
|
|
17732
|
-
code_verifier: [
|
|
17732
|
+
code_verifier: [f, v].join("|")
|
|
17733
17733
|
});
|
|
17734
17734
|
return t.json({
|
|
17735
|
-
login_ticket:
|
|
17736
|
-
co_verifier:
|
|
17737
|
-
co_id:
|
|
17735
|
+
login_ticket: _.code_id,
|
|
17736
|
+
co_verifier: v,
|
|
17737
|
+
co_id: f
|
|
17738
17738
|
});
|
|
17739
17739
|
}
|
|
17740
|
-
let
|
|
17741
|
-
if (!
|
|
17742
|
-
const
|
|
17740
|
+
let a = e.refreshToken, l = e.sessionId;
|
|
17741
|
+
if (!l) {
|
|
17742
|
+
const v = await _g(t, {
|
|
17743
17743
|
user: r,
|
|
17744
17744
|
client: i,
|
|
17745
17745
|
scope: n.scope,
|
|
17746
17746
|
audience: n.audience
|
|
17747
17747
|
});
|
|
17748
|
-
|
|
17748
|
+
l = v.id, a = (m = v.refresh_token) == null ? void 0 : m.id;
|
|
17749
17749
|
}
|
|
17750
17750
|
if (e.authParams.response_mode === gn.SAML_POST)
|
|
17751
17751
|
return Fw(
|
|
@@ -17753,27 +17753,28 @@ async function sn(t, e) {
|
|
|
17753
17753
|
e.client,
|
|
17754
17754
|
e.authParams,
|
|
17755
17755
|
r,
|
|
17756
|
-
|
|
17756
|
+
l
|
|
17757
17757
|
);
|
|
17758
|
-
|
|
17758
|
+
console.log("Create auth tokens");
|
|
17759
|
+
const u = await Wl(t, {
|
|
17759
17760
|
authParams: n,
|
|
17760
17761
|
user: r,
|
|
17761
17762
|
client: i,
|
|
17762
|
-
session_id:
|
|
17763
|
-
refresh_token:
|
|
17764
|
-
}),
|
|
17765
|
-
"set-cookie": lg(i.tenant.id,
|
|
17763
|
+
session_id: l,
|
|
17764
|
+
refresh_token: a
|
|
17765
|
+
}), p = new Headers({
|
|
17766
|
+
"set-cookie": lg(i.tenant.id, l)
|
|
17766
17767
|
});
|
|
17767
17768
|
if (n.response_mode === gn.WEB_MESSAGE)
|
|
17768
|
-
return t.json(
|
|
17769
|
-
headers:
|
|
17769
|
+
return t.json(u, {
|
|
17770
|
+
headers: p
|
|
17770
17771
|
});
|
|
17771
17772
|
if ((n.response_type || Wn.CODE) === Wn.CODE) {
|
|
17772
17773
|
if (!e.loginSession)
|
|
17773
17774
|
throw new $(500, {
|
|
17774
17775
|
message: "Login session not found"
|
|
17775
17776
|
});
|
|
17776
|
-
const
|
|
17777
|
+
const v = await t.env.data.codes.create(i.tenant.id, {
|
|
17777
17778
|
code_id: Ve(),
|
|
17778
17779
|
user_id: r.user_id,
|
|
17779
17780
|
code_type: "authorization_code",
|
|
@@ -17782,14 +17783,14 @@ async function sn(t, e) {
|
|
|
17782
17783
|
Date.now() + $y * 1e3
|
|
17783
17784
|
).toISOString()
|
|
17784
17785
|
});
|
|
17785
|
-
|
|
17786
|
+
p.set(
|
|
17786
17787
|
"location",
|
|
17787
|
-
`${n.redirect_uri}?state=${e.authParams.state}&code=${
|
|
17788
|
+
`${n.redirect_uri}?state=${e.authParams.state}&code=${v.code_id}`
|
|
17788
17789
|
);
|
|
17789
17790
|
}
|
|
17790
17791
|
return new Response("Redirecting", {
|
|
17791
17792
|
status: 302,
|
|
17792
|
-
headers:
|
|
17793
|
+
headers: p
|
|
17793
17794
|
});
|
|
17794
17795
|
}
|
|
17795
17796
|
function Gw(t) {
|
|
@@ -22516,7 +22517,7 @@ const Dg = (t) => {
|
|
|
22516
22517
|
D({
|
|
22517
22518
|
tags: ["login"],
|
|
22518
22519
|
method: "post",
|
|
22519
|
-
path: "/
|
|
22520
|
+
path: "/",
|
|
22520
22521
|
request: {
|
|
22521
22522
|
query: c.object({
|
|
22522
22523
|
state: c.string().openapi({
|
|
@@ -22544,7 +22545,8 @@ const Dg = (t) => {
|
|
|
22544
22545
|
return a ? sn(t, {
|
|
22545
22546
|
user: a,
|
|
22546
22547
|
authParams: r.authParams,
|
|
22547
|
-
client: i
|
|
22548
|
+
client: i,
|
|
22549
|
+
loginSession: r
|
|
22548
22550
|
}) : t.redirect(`/u/enter-email?state=${n}`);
|
|
22549
22551
|
}
|
|
22550
22552
|
);
|