authhero 0.110.0 → 0.111.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/authhero.cjs CHANGED
@@ -26,7 +26,7 @@
26
26
  }};
27
27
  <\/script>
28
28
  </body>
29
- </html>`;return new Response(i,{headers:{"Content-Type":"text/html"}})}async function my(t,e,n,r,i){var m,w,h;if(!n.redirect_uri)throw new I(400,{message:"Missing redirect_uri in authParams"});const[s]=await t.env.data.keys.list();if(!s)throw new I(500,{message:"No signing key found"});if(!((m=e.addons)!=null&&m.samlp))throw new I(400,{message:`SAML Addon is not enabled for client ${e.id}`});const{recipient:a,audience:c}=e.addons.samlp,l=n.state||"";if(!a||!l||!r||!n.state)throw new I(400,{message:"Missing recipient or inResponseTo"});const d=JSON.parse(n.state),p=new URL(n.redirect_uri),f=await _y(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:d.requestId,userId:((h=(w=r.app_metadata)==null?void 0:w.vimeo)==null?void 0:h.user_id)||r.user_id,email:r.email,sessionIndex:i,signature:{privateKeyPem:s.pkcs7,cert:s.cert,kid:s.kid}});return gy(p.toString(),f,d.relayState)}async function _y(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,a=e.responseId||`_${ke()}`,c=e.assertionId||`_${ke()}`,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":a,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let p=new hy.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)}var yy={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},wy=()=>{var n,r;const t=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[i,s]of Object.entries(yy))if(vy(s))return i}return typeof(t==null?void 0:t.EdgeRuntime)=="string"?"edge-light":(t==null?void 0:t.fastly)!==void 0?"fastly":((r=(n=t==null?void 0:t.process)==null?void 0:n.release)==null?void 0:r.name)==="node"?"node":"other"},vy=t=>navigator.userAgent.startsWith(t);function rt(t,e){wy()==="workerd"&&t.executionCtx.waitUntil(e)}function cn(t){var e,n,r;return{auth0Client:(e=t.query("auth0Client"))==null?void 0:e.slice(0,255),ip:(n=t.header("x-real-ip"))==null?void 0:n.slice(0,45),useragent:(r=t.header("user-agent"))==null?void 0:r.slice(0,512)}}const Zd=["sub","iss","aud","exp","nbf","iat","jti"];async function no(t,e){var v,A;const{authParams:n,user:r,client:i,session_id:s}=e,c=(await t.env.data.keys.list()).filter(C=>!C.revoked_at||new Date(C.revoked_at)>new Date),l=c[c.length-1];if(!(l!=null&&l.pkcs7))throw new I(500,{message:"No signing key available"});const d=V0(l.pkcs7),p=t.var.custom_domain?`https://${t.var.custom_domain}/`:t.env.ISSUER,f={aud:n.audience||"default",scope:n.scope||"",sub:(r==null?void 0:r.user_id)||n.client_id,iss:p,tenant_id:t.var.tenant_id,sid:s},m=r&&((v=n.scope)!=null&&v.split(" ").includes("openid"))?{aud:n.client_id,sub:r.user_id,iss:p,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;(A=t.env.hooks)!=null&&A.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({client:i,user:r,request:{ip:t.req.header("x-real-ip")||"",user_agent:t.req.header("user-agent")||"",method:t.req.method,url:t.req.url},scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(C,O)=>{if(Zd.includes(C))throw new Error(`Cannot overwrite reserved claim '${C}'`);f[C]=O}},idToken:{setCustomClaim:(C,O)=>{if(Zd.includes(C))throw new Error(`Cannot overwrite reserved claim '${C}'`);m&&(m[C]=O)}},access:{deny:C=>{throw new I(400,{message:`Access denied: ${C}`})}}});const w={includeIssuedTimestamp:!0,expiresIn:new ll(1,"d"),headers:{kid:l.kid}},h=await Hd("RS256",d,f,w),_=m?await Hd("RS256",d,m,w):void 0;return{access_token:h,refresh_token:e.refresh_token,id_token:_,token_type:"Bearer",expires_in:86400}}async function Df(t,e){return e.loginSession||(e.loginSession=await t.env.data.loginSessions.create(e.client.tenant.id,{expires_at:new Date(Date.now()+Qn*1e3).toISOString(),authParams:e.authParams,authorization_url:t.req.url,csrf_token:ke(),...cn(t.req)})),{code:(await t.env.data.codes.create(e.client.tenant.id,{code_id:ke(),user_id:e.user.user_id,code_type:"authorization_code",login_id:e.loginSession.id,expires_at:new Date(Date.now()+H0*1e3).toISOString()})).code_id,state:e.authParams.state}}async function by(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:ke(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+eo*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 Hf(t,{user:e,client:n,loginSession:r}){const i=await t.env.data.sessions.create(n.tenant.id,{id:ke(),user_id:e.user_id,idle_expires_at:new Date(Date.now()+eo*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:[n.id]});await t.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id});const{scope:s,audience:a}=r.authParams,c=s!=null&&s.split(" ").includes("offline_access")?await by(t,{session_id:i.id,user:e,client:n,scope:s,audience:a}):void 0;return{...i,refresh_token:c}}async function ln(t,e){var w;const{authParams:n,user:r,client:i,ticketAuth:s}=e,a=we(t,{type:he.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id});if(rt(t,t.env.data.logs.create(i.tenant.id,a)),rt(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 I(500,{message:"Login session not found"});const h=U0(),_=ke(12),v=await t.env.data.codes.create(i.tenant.id,{code_id:ke(),code_type:"ticket",login_id:e.loginSession.id,expires_at:new Date(Date.now()+K0).toISOString(),code_verifier:[_,h].join("|")});return t.json({login_ticket:v.code_id,co_verifier:h,co_id:_})}let c=e.refreshToken,l=e.sessionId,d=r;if(!l){if(!e.loginSession)throw new I(500,{message:"Login session not found"});d=await Ay(t,t.env.data)(i.tenant.id,r);const h=await Hf(t,{user:r,client:i,loginSession:e.loginSession});l=h.id,c=(w=h.refresh_token)==null?void 0:w.id}if(e.authParams.response_mode===Rt.SAML_POST)return my(t,e.client,e.authParams,d,l);const p=await no(t,{authParams:n,user:d,client:i,session_id:l,refresh_token:c}),f=new Headers({"set-cookie":Pf(i.tenant.id,l,t.req.header("host"))});if(n.response_mode===Rt.WEB_MESSAGE)return t.json(p,{headers:f});if((n.response_type||It.CODE)===It.CODE){const h=await Df(t,e);if(!n.redirect_uri)throw new I(400,{message:"Redirect uri not found"});const _=new URL(n.redirect_uri);_.searchParams.set("code",h.code),h.state&&_.searchParams.set("state",h.state),f.set("location",_.toString())}return new Response("Redirecting",{status:302,headers:f})}async function xy(t,e,n){const r=await t.env.data.tenants.get(e);if(!r)throw new Error(`Tenant not found: ${e}`);return no(t,{client:{id:t.env.ISSUER,tenant:r,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:t.env.ISSUER,disable_sign_ups:!1,connections:[]},authParams:{client_id:t.env.ISSUER,response_type:It.TOKEN,scope:n}})}async function gl(t,e,n){const r=await xy(t,n.tenant_id,"webhook");for await(const i of e)if(!(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok){const a=we(t,{type:he.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`});await t.env.data.logs.create(n.tenant_id,a)}}function ky(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e);return await gl(t,r,{tenant_id:e,user:n,trigger_id:"post-user-registration"}),n}}function Sy(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-signup",page:0,per_page:100,include_totals:!1});await gl(t,r,{tenant_id:e,email:n,trigger_id:"pre-user-signup"})}}function Ay(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});return await gl(t,i,{tenant_id:n,user:r,trigger_id:"post-user-login"}),r}}function zy(t,e){return async(n,r)=>{var a,c,l;const i={method:t.req.method,ip:t.req.query("x-real-ip")||"",user_agent:t.req.query("user-agent"),url:((a=t.var.loginSession)==null?void 0:a.authorization_url)||t.req.url};if((c=t.env.hooks)!=null&&c.onExecutePreUserRegistration)try{await t.env.hooks.onExecutePreUserRegistration({user:r,request:i},{user:{setUserMetadata:async(d,p)=>{r[d]=p}}})}catch{const p=we(t,{type:he.FAILED_SIGNUP,description:"Pre user registration hook failed"});await e.logs.create(n,p)}let s=await $0(e)(n,r);if((l=t.env.hooks)!=null&&l.onExecutePostUserRegistration)try{await t.env.hooks.onExecutePostUserRegistration({user:r,request:i},{user:{}})}catch{const p=we(t,{type:he.FAILED_SIGNUP,description:"Post user registration hook failed"});await t.env.data.logs.create(n,p)}return await ky(t)(n,s),s}}async function Ey(t,e,n,r){var i,s;if(e.disable_sign_ups&&!(((s=(i=t.var.loginSession)==null?void 0:i.authParams)==null?void 0:s.prompt)==="signup")&&!await io({userAdapter:n.users,tenant_id:e.tenant.id,email:r})){const l=we(t,{type:he.FAILED_SIGNUP,description:"Public signup is disabled"});throw await n.logs.create(e.tenant.id,l),new I(400,{message:"Signups are disabled for this client"})}await Sy(t)(t.var.tenant_id||"",r)}function ro(t,e){return{...e,users:{...e.users,create:zy(t,e)}}}function Ff(t){return ro(t,t.env.data)}async function ml(t,e,n){return(await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function fr({userAdapter:t,tenant_id:e,email:n,provider:r}){const{users:i}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n} provider:${r}`});return i.length>1&&console.error("More than one user found for same email and provider"),i[0]||null}async function io({userAdapter:t,tenant_id:e,email:n}){var c;const{users:r}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`}),i=r.filter(l=>!(l.provider==="auth2"&&!l.email_verified));if(i.length===0)return;const s=i.filter(l=>!l.linked_to);if(s.length>0)return s.length>1&&console.error("More than one primary user found for same email"),s[0];const a=await t.get(e,(c=i[0])==null?void 0:c.linked_to);if(!a)throw new Error("Primary account not found");return a}async function ds({userAdapter:t,tenant_id:e,email:n,provider:r}){const i=await fr({userAdapter:t,tenant_id:e,email:n,provider:r});return i?i.linked_to?t.get(e,i.linked_to):i:null}async function so(t,e){const{email:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:d=""}=e;let p=await ds({userAdapter:t.env.data.users,tenant_id:e.client.tenant.id,email:n,provider:r});if(!p){const f={user_id:`${r}|${a||Qs()}`,email:n,name:n,provider:r,connection:i,email_verified:!0,last_ip:d,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};p=await Ff(t).users.create(s.tenant.id,f),t.set("user_id",p.user_id)}return p}const tn=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function hr(t){if(!t)return;const[e,n]=t.split(":"),r=n==="1"?"asc":"desc";if(!(!e||!r))return{sort_by:e,sort_order:r}}const Yd=on.extend({users:o.z.array(At)}),Iy=on.extend({sessions:o.z.array(Xs)}),Cy=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(At),Yd])}},description:"List of users"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":a}=t.req.valid("header");if(s!=null&&s.includes("identities.profileData.email")){const p=s.split("=")[1],m=(await t.env.data.users.list(a,{page:e,per_page:n,include_totals:r,q:`email:${p}`})).users.filter(_=>_.linked_to),[w]=m;if(!w)return t.json([]);const h=await t.env.data.users.get(a,w.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return t.json([At.parse(h)])}const c=["-_exists_:linked_to"];s&&c.push(s);const l=await t.env.data.users.list(a,{page:e,per_page:n,include_totals:r,sort:hr(i),q:c.join(" ")}),d=l.users.filter(p=>!p.linked_to);return r?t.json(Yd.parse({users:d,length:l.length,start:l.start,limit:l.limit})):t.json(o.z.array(At).parse(d))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:At}},description:"List of users"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{"tenant-id":n}=t.req.valid("header"),r=await t.env.data.users.get(n,e);if(!r)throw new I(404);if(r.linked_to)throw new I(404,{message:"User is linked to another user"});return t.json(r)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{"tenant-id":n}=t.req.valid("header");if(!await t.env.data.users.remove(n,e))throw new I(404);return t.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...ns.shape})}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:At}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");t.set("body",n);const{email:r}=n;if(!r)throw new I(400,{message:"Email is required"});const i=r.toLowerCase(),s=`${n.provider}|${n.user_id||Qs()}`;try{const a=await t.env.data.users.create(e,{email:i,user_id:s,name:n.name||i,provider:n.provider,connection:n.connection,email_verified:n.email_verified||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString()});t.set("user_id",a.user_id);const c=we(t,{type:he.SUCCESS_API_OPERATION,description:"User created"});rt(t,t.env.data.logs.create(e,c));const l={...a,identities:[{connection:a.connection,provider:a.provider,user_id:Md(a.user_id),isSocial:a.is_social}]};return t.json(At.parse(l),{status:201})}catch(a){throw a.message==="User already exists"?new I(409,{message:"User already exists"}):a}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...ns.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{var p;const{data:e}=t.env,{"tenant-id":n}=t.req.valid("header"),r=t.req.valid("json"),{user_id:i}=t.req.valid("param"),{verify_email:s,password:a,...c}=r,l=await e.users.get(n,i);if(!l)throw new I(404);if(c.email&&c.email!==l.email){const f=await ml(t.env.data.users,n,c.email);if(f.length&&f.some(m=>m.user_id!==i))throw new I(409,{message:"Another user with the same email address already exists."})}if(l.linked_to)throw new I(404,{message:"User is linked to another user"});if(await t.env.data.users.update(n,i,c),a){const f=(p=l.identities)==null?void 0:p.find(h=>h.connection==="Username-Password-Authentication");if(!f)throw new I(400,{message:"User does not have a password identity"});const m={user_id:f.user_id,password:await oi.hash(a,10),algorithm:"bcrypt"};await e.passwords.get(n,f.user_id)?await e.passwords.update(n,m):await e.passwords.create(n,m)}const d=await t.env.data.users.get(n,i);if(!d)throw new I(500);return t.json(d)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(o.z.object({connection:o.z.string(),provider:o.z.string(),user_id:o.z.string(),isSocial:o.z.boolean()}))}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),{user_id:r}=t.req.valid("param"),i="link_with"in n?n.link_with:n.user_id,s=await t.env.data.users.get(e,r);if(!s)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await t.env.data.users.update(e,i,{linked_to:r});const a=await t.env.data.users.list(e,{page:0,per_page:10,include_totals:!1,q:`linked_to:${r}`}),c=[s,...a.users].map(l=>({connection:l.connection,provider:l.provider,user_id:Md(l.user_id),isSocial:l.is_social}));return t.json(c,{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(At)}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{user_id:n,provider:r,linked_user_id:i}=t.req.valid("param");await t.env.data.users.unlink(e,n,r,i);const s=await t.env.data.users.get(e,n);if(!s)throw new I(404);return t.json([At.parse(s)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Xs),Iy])}},description:"List of sessions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{include_totals:n}=t.req.valid("query"),{"tenant-id":r}=t.req.valid("header"),i=await t.env.data.sessions.list(r,{page:0,per_page:10,include_totals:!1,q:`user_id:${e}`});return n?t.json(i):t.json(i.sessions)});/*! *****************************************************************************
29
+ </html>`;return new Response(i,{headers:{"Content-Type":"text/html"}})}async function my(t,e,n,r,i){var m,w,h;if(!n.redirect_uri)throw new I(400,{message:"Missing redirect_uri in authParams"});const[s]=await t.env.data.keys.list();if(!s)throw new I(500,{message:"No signing key found"});if(!((m=e.addons)!=null&&m.samlp))throw new I(400,{message:`SAML Addon is not enabled for client ${e.id}`});const{recipient:a,audience:c}=e.addons.samlp,l=n.state||"";if(!a||!l||!r||!n.state)throw new I(400,{message:"Missing recipient or inResponseTo"});const d=JSON.parse(n.state),p=new URL(n.redirect_uri),f=await _y(t,{issuer:t.env.ISSUER,audience:c||n.client_id,destination:p.toString(),inResponseTo:d.requestId,userId:((h=(w=r.app_metadata)==null?void 0:w.vimeo)==null?void 0:h.user_id)||r.user_id,email:r.email,sessionIndex:i,signature:{privateKeyPem:s.pkcs7,cert:s.cert,kid:s.kid}});return gy(p.toString(),f,d.relayState)}async function _y(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,a=e.responseId||`_${ke()}`,c=e.assertionId||`_${ke()}`,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":a,"@_InResponseTo":e.inResponseTo,"@_IssueInstant":i,"@_Version":"2.0"}}];let p=new hy.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)}var yy={deno:"Deno",bun:"Bun",workerd:"Cloudflare-Workers",node:"Node.js"},wy=()=>{var n,r;const t=globalThis;if(typeof navigator<"u"&&typeof navigator.userAgent=="string"){for(const[i,s]of Object.entries(yy))if(vy(s))return i}return typeof(t==null?void 0:t.EdgeRuntime)=="string"?"edge-light":(t==null?void 0:t.fastly)!==void 0?"fastly":((r=(n=t==null?void 0:t.process)==null?void 0:n.release)==null?void 0:r.name)==="node"?"node":"other"},vy=t=>navigator.userAgent.startsWith(t);function rt(t,e){wy()==="workerd"&&t.executionCtx.waitUntil(e)}function cn(t){var e,n,r;return{auth0Client:(e=t.query("auth0Client"))==null?void 0:e.slice(0,255),ip:(n=t.header("x-real-ip"))==null?void 0:n.slice(0,45),useragent:(r=t.header("user-agent"))==null?void 0:r.slice(0,512)}}const Zd=["sub","iss","aud","exp","nbf","iat","jti"];async function no(t,e){var v,A;const{authParams:n,user:r,client:i,session_id:s}=e,c=(await t.env.data.keys.list()).filter(C=>!C.revoked_at||new Date(C.revoked_at)>new Date),l=c[c.length-1];if(!(l!=null&&l.pkcs7))throw new I(500,{message:"No signing key available"});const d=V0(l.pkcs7),p=t.var.custom_domain?`https://${t.var.custom_domain}/`:t.env.ISSUER,f={aud:n.audience||"default",scope:n.scope||"",sub:(r==null?void 0:r.user_id)||n.client_id,iss:p,tenant_id:t.var.tenant_id,sid:s},m=r&&((v=n.scope)!=null&&v.split(" ").includes("openid"))?{aud:n.client_id,sub:r.user_id,iss:p,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;(A=t.env.hooks)!=null&&A.onExecuteCredentialsExchange&&await t.env.hooks.onExecuteCredentialsExchange({client:i,user:r,request:{ip:t.req.header("x-real-ip")||"",user_agent:t.req.header("user-agent")||"",method:t.req.method,url:t.req.url},scope:n.scope||"",grant_type:""},{accessToken:{setCustomClaim:(C,O)=>{if(Zd.includes(C))throw new Error(`Cannot overwrite reserved claim '${C}'`);f[C]=O}},idToken:{setCustomClaim:(C,O)=>{if(Zd.includes(C))throw new Error(`Cannot overwrite reserved claim '${C}'`);m&&(m[C]=O)}},access:{deny:C=>{throw new I(400,{message:`Access denied: ${C}`})}}});const w={includeIssuedTimestamp:!0,expiresIn:new ll(1,"d"),headers:{kid:l.kid}},h=await Hd("RS256",d,f,w),_=m?await Hd("RS256",d,m,w):void 0;return{access_token:h,refresh_token:e.refresh_token,id_token:_,token_type:"Bearer",expires_in:86400}}async function Df(t,e){return e.loginSession||(e.loginSession=await t.env.data.loginSessions.create(e.client.tenant.id,{expires_at:new Date(Date.now()+Qn*1e3).toISOString(),authParams:e.authParams,authorization_url:t.req.url,csrf_token:ke(),...cn(t.req)})),{code:(await t.env.data.codes.create(e.client.tenant.id,{code_id:ke(),user_id:e.user.user_id,code_type:"authorization_code",login_id:e.loginSession.id,expires_at:new Date(Date.now()+H0*1e3).toISOString()})).code_id,state:e.authParams.state}}async function by(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:ke(),session_id:s,client_id:n.id,expires_at:new Date(Date.now()+eo*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 Hf(t,{user:e,client:n,loginSession:r}){const i=await t.env.data.sessions.create(n.tenant.id,{id:ke(),user_id:e.user_id,idle_expires_at:new Date(Date.now()+eo*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:[n.id]});await t.env.data.loginSessions.update(n.tenant.id,r.id,{session_id:i.id});const{scope:s,audience:a}=r.authParams,c=s!=null&&s.split(" ").includes("offline_access")?await by(t,{session_id:i.id,user:e,client:n,scope:s,audience:a}):void 0;return{...i,refresh_token:c}}async function ln(t,e){var w;const{authParams:n,user:r,client:i,ticketAuth:s}=e,a=we(t,{type:he.SUCCESS_LOGIN,description:`Successful login for ${r.user_id}`,userId:r.user_id});if(rt(t,t.env.data.logs.create(i.tenant.id,a)),rt(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 I(500,{message:"Login session not found"});const h=U0(),_=ke(12),v=await t.env.data.codes.create(i.tenant.id,{code_id:ke(),code_type:"ticket",login_id:e.loginSession.id,expires_at:new Date(Date.now()+K0).toISOString(),code_verifier:[_,h].join("|")});return t.json({login_ticket:v.code_id,co_verifier:h,co_id:_})}let c=e.refreshToken,l=e.sessionId,d=r;if(!l){if(!e.loginSession)throw new I(500,{message:"Login session not found"});d=await Ay(t,t.env.data)(i.tenant.id,r);const h=await Hf(t,{user:r,client:i,loginSession:e.loginSession});l=h.id,c=(w=h.refresh_token)==null?void 0:w.id}if(e.authParams.response_mode===Rt.SAML_POST)return my(t,e.client,e.authParams,d,l);const p=await no(t,{authParams:n,user:d,client:i,session_id:l,refresh_token:c}),f=new Headers({"set-cookie":Pf(i.tenant.id,l,t.req.header("host"))});if(n.response_mode===Rt.WEB_MESSAGE)return t.json(p,{headers:f});if((n.response_type||It.CODE)===It.CODE){const h=await Df(t,e);if(!n.redirect_uri)throw new I(400,{message:"Redirect uri not found"});const _=new URL(n.redirect_uri);_.searchParams.set("code",h.code),h.state&&_.searchParams.set("state",h.state),f.set("location",_.toString())}return new Response("Redirecting",{status:302,headers:f})}async function xy(t,e,n){const r=await t.env.data.tenants.get(e);if(!r)throw new Error(`Tenant not found: ${e}`);return no(t,{client:{id:t.env.ISSUER,tenant:r,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),name:t.env.ISSUER,disable_sign_ups:!1,connections:[]},authParams:{client_id:t.env.ISSUER,response_type:It.TOKEN,scope:n}})}async function gl(t,e,n){const r=await xy(t,n.tenant_id,"webhook");for await(const i of e)if(!(await fetch(i.url,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify(n)})).ok){const a=we(t,{type:he.FAILED_HOOK,description:`Failed to invoke hook ${i.hook_id}`});await t.env.data.logs.create(n.tenant_id,a)}}function ky(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e);return await gl(t,r,{tenant_id:e,user:n,trigger_id:"post-user-registration"}),n}}function Sy(t){return async(e,n)=>{const{hooks:r}=await t.env.data.hooks.list(e,{q:"trigger_id:pre-user-signup",page:0,per_page:100,include_totals:!1});await gl(t,r,{tenant_id:e,email:n,trigger_id:"pre-user-signup"})}}function Ay(t,e){return async(n,r)=>{const{hooks:i}=await e.hooks.list(n,{q:"trigger_id:post-user-login",page:0,per_page:100,include_totals:!1});return await gl(t,i,{tenant_id:n,user:r,trigger_id:"post-user-login"}),r}}function zy(t,e){return async(n,r)=>{var a,c,l;const i={method:t.req.method,ip:t.req.query("x-real-ip")||"",user_agent:t.req.query("user-agent"),url:((a=t.var.loginSession)==null?void 0:a.authorization_url)||t.req.url};if((c=t.env.hooks)!=null&&c.onExecutePreUserRegistration)try{await t.env.hooks.onExecutePreUserRegistration({user:r,request:i},{user:{setUserMetadata:async(d,p)=>{r[d]=p}}})}catch{const p=we(t,{type:he.FAILED_SIGNUP,description:"Pre user registration hook failed"});await e.logs.create(n,p)}let s=await $0(e)(n,r);if((l=t.env.hooks)!=null&&l.onExecutePostUserRegistration)try{await t.env.hooks.onExecutePostUserRegistration({user:r,request:i},{user:{}})}catch{const p=we(t,{type:he.FAILED_SIGNUP,description:"Post user registration hook failed"});await t.env.data.logs.create(n,p)}return await ky(t)(n,s),s}}async function Ey(t,e,n,r){var i;if(e.disable_sign_ups){const s=(i=t.var.loginSession)==null?void 0:i.authorization_url;if(!(s&&new URL(s).searchParams.get("screen_hint")==="signup")&&!await io({userAdapter:n.users,tenant_id:e.tenant.id,email:r})){const l=we(t,{type:he.FAILED_SIGNUP,description:"Public signup is disabled"});throw await n.logs.create(e.tenant.id,l),new I(400,{message:"Signups are disabled for this client"})}}await Sy(t)(t.var.tenant_id||"",r)}function ro(t,e){return{...e,users:{...e.users,create:zy(t,e)}}}function Ff(t){return ro(t,t.env.data)}async function ml(t,e,n){return(await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`})).users}async function fr({userAdapter:t,tenant_id:e,email:n,provider:r}){const{users:i}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n} provider:${r}`});return i.length>1&&console.error("More than one user found for same email and provider"),i[0]||null}async function io({userAdapter:t,tenant_id:e,email:n}){var c;const{users:r}=await t.list(e,{page:0,per_page:10,include_totals:!1,q:`email:${n}`}),i=r.filter(l=>!(l.provider==="auth2"&&!l.email_verified));if(i.length===0)return;const s=i.filter(l=>!l.linked_to);if(s.length>0)return s.length>1&&console.error("More than one primary user found for same email"),s[0];const a=await t.get(e,(c=i[0])==null?void 0:c.linked_to);if(!a)throw new Error("Primary account not found");return a}async function ds({userAdapter:t,tenant_id:e,email:n,provider:r}){const i=await fr({userAdapter:t,tenant_id:e,email:n,provider:r});return i?i.linked_to?t.get(e,i.linked_to):i:null}async function so(t,e){const{email:n,provider:r,connection:i,client:s,userId:a,isSocial:c,profileData:l={},ip:d=""}=e;let p=await ds({userAdapter:t.env.data.users,tenant_id:e.client.tenant.id,email:n,provider:r});if(!p){const f={user_id:`${r}|${a||Qs()}`,email:n,name:n,provider:r,connection:i,email_verified:!0,last_ip:d,is_social:c,last_login:new Date().toISOString(),profileData:JSON.stringify(l)};p=await Ff(t).users.create(s.tenant.id,f),t.set("user_id",p.user_id)}return p}const tn=o.z.object({page:o.z.string().min(0).optional().default("0").transform(t=>parseInt(t,10)).openapi({description:"The page number where 0 is the first page"}),per_page:o.z.string().min(1).optional().default("10").transform(t=>parseInt(t,10)).openapi({description:"The number of items per page"}),include_totals:o.z.string().optional().default("false").transform(t=>t==="true").openapi({description:"If the total number of items should be included in the response"}),sort:o.z.string().regex(/^.+:(-1|1)$/).optional().openapi({description:"A property that should have the format 'string:-1' or 'string:1'"}),q:o.z.string().optional().openapi({description:"A lucene query string used to filter the results"})});function hr(t){if(!t)return;const[e,n]=t.split(":"),r=n==="1"?"asc":"desc";if(!(!e||!r))return{sort_by:e,sort_order:r}}const Yd=on.extend({users:o.z.array(At)}),Iy=on.extend({sessions:o.z.array(Xs)}),Cy=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(At),Yd])}},description:"List of users"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":a}=t.req.valid("header");if(s!=null&&s.includes("identities.profileData.email")){const p=s.split("=")[1],m=(await t.env.data.users.list(a,{page:e,per_page:n,include_totals:r,q:`email:${p}`})).users.filter(_=>_.linked_to),[w]=m;if(!w)return t.json([]);const h=await t.env.data.users.get(a,w.linked_to);if(!h)throw new I(500,{message:"Primary account not found"});return t.json([At.parse(h)])}const c=["-_exists_:linked_to"];s&&c.push(s);const l=await t.env.data.users.list(a,{page:e,per_page:n,include_totals:r,sort:hr(i),q:c.join(" ")}),d=l.users.filter(p=>!p.linked_to);return r?t.json(Yd.parse({users:d,length:l.length,start:l.start,limit:l.limit})):t.json(o.z.array(At).parse(d))}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:At}},description:"List of users"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{"tenant-id":n}=t.req.valid("header"),r=await t.env.data.users.get(n,e);if(!r)throw new I(404);if(r.linked_to)throw new I(404,{message:"User is linked to another user"});return t.json(r)}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{"tenant-id":n}=t.req.valid("header");if(!await t.env.data.users.remove(n,e))throw new I(404);return t.text("OK")}).openapi(o.createRoute({tags:["users"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...ns.shape})}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:At}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");t.set("body",n);const{email:r}=n;if(!r)throw new I(400,{message:"Email is required"});const i=r.toLowerCase(),s=`${n.provider}|${n.user_id||Qs()}`;try{const a=await t.env.data.users.create(e,{email:i,user_id:s,name:n.name||i,provider:n.provider,connection:n.connection,email_verified:n.email_verified||!1,last_ip:"",is_social:!1,last_login:new Date().toISOString()});t.set("user_id",a.user_id);const c=we(t,{type:he.SUCCESS_API_OPERATION,description:"User created"});rt(t,t.env.data.logs.create(e,c));const l={...a,identities:[{connection:a.connection,provider:a.provider,user_id:Md(a.user_id),isSocial:a.is_social}]};return t.json(At.parse(l),{status:201})}catch(a){throw a.message==="User already exists"?new I(409,{message:"User already exists"}):a}}).openapi(o.createRoute({tags:["users"],method:"patch",path:"/{user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object({...ns.shape,verify_email:o.z.boolean(),password:o.z.string()}).partial()}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{var p;const{data:e}=t.env,{"tenant-id":n}=t.req.valid("header"),r=t.req.valid("json"),{user_id:i}=t.req.valid("param"),{verify_email:s,password:a,...c}=r,l=await e.users.get(n,i);if(!l)throw new I(404);if(c.email&&c.email!==l.email){const f=await ml(t.env.data.users,n,c.email);if(f.length&&f.some(m=>m.user_id!==i))throw new I(409,{message:"Another user with the same email address already exists."})}if(l.linked_to)throw new I(404,{message:"User is linked to another user"});if(await t.env.data.users.update(n,i,c),a){const f=(p=l.identities)==null?void 0:p.find(h=>h.connection==="Username-Password-Authentication");if(!f)throw new I(400,{message:"User does not have a password identity"});const m={user_id:f.user_id,password:await oi.hash(a,10),algorithm:"bcrypt"};await e.passwords.get(n,f.user_id)?await e.passwords.update(n,m):await e.passwords.create(n,m)}const d=await t.env.data.users.get(n,i);if(!d)throw new I(500);return t.json(d)}).openapi(o.createRoute({tags:["users"],method:"post",path:"/{user_id}/identities",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.union([o.z.object({link_with:o.z.string()}),o.z.object({user_id:o.z.string(),provider:o.z.string(),connection:o.z.string().optional()})])}}},params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(o.z.object({connection:o.z.string(),provider:o.z.string(),user_id:o.z.string(),isSocial:o.z.boolean()}))}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),{user_id:r}=t.req.valid("param"),i="link_with"in n?n.link_with:n.user_id,s=await t.env.data.users.get(e,r);if(!s)throw new I(400,{message:"Linking an inexistent identity is not allowed."});await t.env.data.users.update(e,i,{linked_to:r});const a=await t.env.data.users.list(e,{page:0,per_page:10,include_totals:!1,q:`linked_to:${r}`}),c=[s,...a.users].map(l=>({connection:l.connection,provider:l.provider,user_id:Md(l.user_id),isSocial:l.is_social}));return t.json(c,{status:201})}).openapi(o.createRoute({tags:["users"],method:"delete",path:"/{user_id}/identities/{provider}/{linked_user_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string(),provider:o.z.string(),linked_user_id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:o.z.array(At)}},description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{user_id:n,provider:r,linked_user_id:i}=t.req.valid("param");await t.env.data.users.unlink(e,n,r,i);const s=await t.env.data.users.get(e,n);if(!s)throw new I(404);return t.json([At.parse(s)])}).openapi(o.createRoute({tags:["users"],method:"get",path:"/{user_id}/sessions",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({user_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Xs),Iy])}},description:"List of sessions"}}}),async t=>{const{user_id:e}=t.req.valid("param"),{include_totals:n}=t.req.valid("query"),{"tenant-id":r}=t.req.valid("header"),i=await t.env.data.sessions.list(r,{page:0,per_page:10,include_totals:!1,q:`user_id:${e}`});return n?t.json(i):t.json(i.sessions)});/*! *****************************************************************************
30
30
  Copyright (C) Microsoft. All rights reserved.
31
31
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
32
32
  this file except in compliance with the License. You may obtain a copy of the
@@ -189,7 +189,7 @@ PERFORMANCE OF THIS SOFTWARE.
189
189
  <\/script>
190
190
  </body>
191
191
 
192
- </html>`}async function r1({ctx:t,client:e,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:d,response_type:p}){const{env:f}=t,m=new URL(r),w=`${m.protocol}//${m.host}`;async function h(ce="Login required"){const le=we(t,{type:he.FAILED_SILENT_AUTH,description:ce});return await t.env.data.logs.create(e.tenant.id,le),t.html(Vp(w,JSON.stringify({error:"login_required",error_description:ce,state:i})))}if(!n||(n==null?void 0:n.expires_at)&&new Date(n.expires_at)<new Date||(n==null?void 0:n.idle_expires_at)&&new Date(n.idle_expires_at)<new Date)return h();t.set("user_id",n.user_id);const v=await f.data.users.get(e.tenant.id,n.user_id);if(!v)return console.error("User not found",n.user_id),h("User not found");t.set("username",v.email),t.set("connection",v.connection);const A={client:e,authParams:{client_id:e.id,audience:l,code_challenge_method:a,code_challenge:c,scope:d,state:i,nonce:s,response_type:p},user:v,session_id:n.id},C=p===It.CODE?await Df(t,A):await no(t,A);await f.data.sessions.update(e.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),device:{...n.device,last_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+eo*1e3).toISOString():void 0});const O=we(t,{type:he.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});await t.env.data.logs.create(e.tenant.id,O);const L=new Headers;L.set("Server-Timing","cf-nel=0; no-cloudflare-insights=1");const Q=Pf(e.tenant.id,n.id,t.req.header("host"));return L.set("set-cookie",Q),t.html(Vp(w,JSON.stringify(C)),{headers:L})}const i1=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string(),scope:o.z.string().optional(),state:o.z.string(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(Rt).optional(),response_type:o.z.nativeEnum(It).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Ys).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),ui_locales:o.z.string().optional()})},responses:{200:{description:"Silent authentication page"},302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{env:e}=t,{client_id:n,vendor_id:r,redirect_uri:i,scope:s,state:a,audience:c,nonce:l,connection:d,response_type:p,response_mode:f,code_challenge:m,code_challenge_method:w,prompt:h,login_ticket:_,realm:v,auth0Client:A,login_hint:C,ui_locales:O,organization:L}=t.req.valid("query");t.set("log","authorize");const Q=await Yo(e,n);t.set("client_id",Q.id),t.set("tenant_id",Q.tenant.id);const ce={redirect_uri:i,scope:s,state:a,client_id:n,vendor_id:r,audience:c,nonce:l,prompt:h,response_type:p,response_mode:f,code_challenge:m,code_challenge_method:w,username:C,ui_locales:O,organization:L},le=t.req.header("origin");if(le&&!Qb(le,Q.web_origins||[]))throw new I(403,{message:`Origin ${le} not allowed`});if(ce.redirect_uri&&!Xo(ce.redirect_uri,Q.callbacks||[],{allowPathWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${ce.redirect_uri}`});const He=ls(Q.tenant.id,t.req.header("cookie")),Ve=He?await e.data.sessions.get(Q.tenant.id,He):void 0,Re=Ve&&!Ve.revoked_at?Ve:void 0;if(h=="none"){if(!p)throw new I(400,{message:"Missing response_type"});return r1({ctx:t,session:Re||void 0,redirect_uri:i,state:a,response_type:p,client:Q,nonce:l,code_challenge_method:w,code_challenge:m,audience:c,scope:s})}return d&&d!=="email"?jb(t,Q,d,ce):_?n1(t,Q.tenant.id,_,ce,v):e1({ctx:t,client:Q,auth0Client:A,authParams:ce,session:Re||void 0,connection:d,login_hint:C})});function s1(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>(r.env.data=ro(r,t.dataAdapter),i())),e.use("/oauth/token",of({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),e.use(od).use(Rg(e));const n=e.route("/v2/logout",Ob).route("/userinfo",Tb).route("/.well-known",Pb).route("/oauth/token",Fb).route("/dbconnections",Jb).route("/passwordless",Zb).route("/co/authenticate",Xb).route("/authorize",i1).route("/callback",$b);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),Bg(n),n}var o1={Stringify:1,BeforeStream:2,Stream:3},_t=(t,e)=>{const n=new String(t);return n.isEscaped=!0,n.callbacks=e,n},a1=/[&<>'"]/,Yg=async(t,e)=>{let n="";e||(e=[]);const r=await Promise.all(t);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&e.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&e.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];en(s,c),n=c[0]}}return _t(n,e)},en=(t,e)=>{const n=t.search(a1);if(n===-1){e[0]+=t;return}let r,i,s=0;for(i=n;i<t.length;i++){switch(t.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(s,i)+r,s=i+1}e[0]+=t.substring(s,i)},Xg=t=>{const e=t.callbacks;if(!(e!=null&&e.length))return t;const n=[t],r={};return e.forEach(i=>i({phase:o1.Stringify,buffer:n,context:r})),n[0]},c1=(t,...e)=>{const n=[""];for(let r=0,i=t.length-1;r<i;r++){n[0]+=t[r];const s=Array.isArray(e[r])?e[r].flat(1/0):[e[r]];for(let a=0,c=s.length;a<c;a++){const l=s[a];if(typeof l=="string")en(l,n);else if(typeof l=="number")n[0]+=l;else{if(typeof l=="boolean"||l===null||l===void 0)continue;if(typeof l=="object"&&l.isEscaped)if(l.callbacks)n.unshift("",l);else{const d=l.toString();d instanceof Promise?n.unshift("",d):n[0]+=d}else l instanceof Promise?n.unshift("",l):en(l.toString(),n)}}}return n[0]+=t[t.length-1],n.length===1?"callbacks"in n?_t(Xg(_t(n[0],n.callbacks))):_t(n[0]):Yg(n,n.callbacks)},hd=Symbol("RENDERER"),Qc=Symbol("ERROR_HANDLER"),Ae=Symbol("STASH"),Qg=Symbol("INTERNAL"),l1=Symbol("MEMO"),Ws=Symbol("PERMALINK"),qp=t=>(t[Qg]=!0,t),em=t=>({value:e,children:n})=>{if(!n)return;const r={children:[{tag:qp(()=>{t.push(e)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:qp(()=>{t.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Qc]=s=>{throw t.pop(),s},i},tm=t=>{const e=[t],n=em(e);return n.values=e,n.Provider=n,ur.push(n),n},ur=[],d1=t=>{const e=[t],n=r=>{e.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new sm("",{},r.children):r.children).toString():""}finally{e.pop()}return i instanceof Promise?i.then(s=>_t(s,s.callbacks)):_t(i)};return n.values=e,n.Provider=n,n[hd]=em(e),ur.push(n),n},Ar=t=>t.values.at(-1),Ki={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},el={},Wi="data-precedence",zi=t=>Array.isArray(t)?t:[t],Mp=new WeakMap,Dp=(t,e,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Mp.get(s)||{};Mp.set(s,a);const c=a[t]||(a[t]=[]);let l=!1;const d=Ki[t];if(d.length>0){e:for(const[,p]of c)for(const f of d)if(((p==null?void 0:p[f])??null)===(n==null?void 0:n[f])){l=!0;break e}}if(l?i[0]=i[0].replaceAll(e,""):d.length>0?c.push([e,n,r]):c.unshift([e,n,r]),i[0].indexOf("</head>")!==-1){let p;if(r===void 0)p=c.map(([f])=>f);else{const f=[];p=c.map(([m,,w])=>{let h=f.indexOf(w);return h===-1&&(f.push(w),h=f.length-1),[m,h]}).sort((m,w)=>m[1]-w[1]).map(([m])=>m)}p.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,p.join(""))}},Ei=(t,e,n)=>_t(new yt(t,n,zi(e??[])).toString()),Ii=(t,e,n,r)=>{if("itemProp"in n)return Ei(t,e,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Wi]=i);const c=new yt(t,a,zi(e||[])).toString();return c instanceof Promise?c.then(l=>_t(c,[...l.callbacks||[],Dp(t,l,a,i)])):_t(c,[Dp(t,c,a,i)])},u1=({children:t,...e})=>{const n=gd();if(n){const r=Ar(n);if(r==="svg"||r==="head")return new yt("title",e,zi(t??[]))}return Ii("title",t,e,!1)},p1=({children:t,...e})=>{const n=gd();return["src","async"].some(r=>!e[r])||n&&Ar(n)==="head"?Ei("script",t,e):Ii("script",t,e,!1)},f1=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ii("style",t,e,!0)):Ei("style",t,e),h1=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ei("link",t,e):Ii("link",t,e,"precedence"in e),g1=({children:t,...e})=>{const n=gd();return n&&Ar(n)==="head"?Ei("meta",t,e):Ii("meta",t,e,!1)},nm=(t,{children:e,...n})=>new yt(t,n,zi(e??[])),m1=t=>(typeof t.action=="function"&&(t.action=Ws in t.action?t.action[Ws]:void 0),nm("form",t)),rm=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=Ws in e.formAction?e.formAction[Ws]:void 0),nm(t,e)),_1=t=>rm("input",t),y1=t=>rm("button",t);const va=Object.freeze(Object.defineProperty({__proto__:null,button:y1,form:m1,input:_1,link:h1,meta:g1,script:p1,style:f1,title:u1},Symbol.toStringTag,{value:"Module"}));var w1=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),Gs=t=>w1.get(t)||t,im=(t,e)=>{for(const[n,r]of Object.entries(t)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);e(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},ri=void 0,gd=()=>ri,v1=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,b1=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],x1=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],md=(t,e)=>{for(let n=0,r=t.length;n<r;n++){const i=t[n];if(typeof i=="string")en(i,e);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof yt?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?e[0]+=i:i instanceof Promise?e.unshift("",i):md(i,e)}}},yt=class{constructor(t,e,n){te(this,"tag");te(this,"props");te(this,"key");te(this,"children");te(this,"isEscaped",!0);te(this,"localContexts");this.tag=t,this.props=e,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){var e,n;const t=[""];(e=this.localContexts)==null||e.forEach(([r,i])=>{r.values.push(i)});try{this.toStringToBuffer(t)}finally{(n=this.localContexts)==null||n.forEach(([r])=>{r.values.pop()})}return t.length===1?"callbacks"in t?Xg(_t(t[0],t.callbacks)).toString():t[0]:Yg(t,t.callbacks)}toStringToBuffer(t){const e=this.tag,n=this.props;let{children:r}=this;t[0]+=`<${e}`;const i=ri&&Ar(ri)==="svg"?s=>v1(Gs(s)):s=>Gs(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";im(a,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),t[0]+=' style="',en(c,t),t[0]+='"'}else if(typeof a=="string")t[0]+=` ${s}="`,en(a,t),t[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)t[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&x1.includes(s))a&&(t[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw"Can only set one of `children` or `props.dangerouslySetInnerHTML`.";r=[_t(a.__html)]}else if(a instanceof Promise)t[0]+=` ${s}="`,t.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on"))throw`Invalid prop '${s}' of type 'function' supplied to '${e}'.`}else t[0]+=` ${s}="`,en(a.toString(),t),t[0]+='"'}if(b1.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",md(r,t),t[0]+=`</${e}>`}},ba=class extends yt{toStringToBuffer(t){const{children:e}=this,n=this.tag.call(null,{...this.props,children:e.length<=1?e[0]:e});if(!(typeof n=="boolean"||n==null))if(n instanceof Promise)if(ur.length===0)t.unshift("",n);else{const r=ur.map(i=>[i,i.values.at(-1)]);t.unshift("",n.then(i=>(i instanceof yt&&(i.localContexts=r),i)))}else n instanceof yt?n.toStringToBuffer(t):typeof n=="number"||n.isEscaped?(t[0]+=n,n.callbacks&&(t.callbacks||(t.callbacks=[]),t.callbacks.push(...n.callbacks))):en(n,t)}},sm=class extends yt{toStringToBuffer(t){md(this.children,t)}},k1=(t,e,...n)=>{e??(e={}),n.length&&(e.children=n.length===1?n[0]:n);const r=e.key;delete e.key;const i=Gi(t,e,n);return i.key=r,i},Hp=!1,Gi=(t,e,n)=>{if(!Hp){for(const r in el)va[r][hd]=el[r];Hp=!0}return typeof t=="function"?new ba(t,e,n):va[t]?new ba(va[t],e,n):t==="svg"||t==="head"?(ri||(ri=d1("")),new yt(t,e,[new ba(ri,{value:t},n)])):new yt(t,e,n)},om=({children:t})=>new sm("",{children:t},Array.isArray(t)?t:t?[t]:[]),S1=(t,e,...n)=>k1(t.tag,{...t.props,...e},...n);function y(t,e,n){let r;if(!e||!("children"in e))r=Gi(t,e,[]);else{const i=e.children;r=Array.isArray(i)?Gi(t,e,i):Gi(t,e,[i])}return r.key=n,r}const Fp={name:"sesamy",logoUrl:"https://assets.sesamy.com/static/images/email/sesamy-logo.png",style:{primaryColor:"#7D68F4",buttonTextColor:"#FFFFFF",primaryHoverColor:"#A091F2"},loginBackgroundImage:"",checkoutHideSocial:!1,supportEmail:"support@sesamy.com",supportUrl:"https://support.sesamy.com",siteUrl:"https://sesamy.com",termsAndConditionsUrl:"https://store.sesamy.com/pages/terms-of-service",manageSubscriptionsUrl:"https://account.sesamy.com/manage-subscriptions"};async function _d(t,e,n){if(!n&&!e)return Fp;const r=n||e;try{const i=await fetch(`${t.API_URL}/profile/vendors/${r}/style`);if(!i.ok)throw new Error("Failed to fetch vendor settings");const s=await i.json();return uf.parse(s)}catch(i){return console.error(i),Fp}}async function Ee(t,e,n=!1){var d;const{env:r}=t,i=await r.data.loginSessions.get(t.var.tenant_id||"",e);if(i)i.session_id;else throw new I(400,{message:"Login session not found"});t.set("loginSession",i);const s=await Yo(r,i.authParams.client_id);t.set("client_id",s.id),t.set("tenant_id",s.tenant.id);const a=await r.data.tenants.get(s.tenant.id);if(a){if(i.session_id&&!n)throw new I(400,{message:"Login session closed"})}else throw new I(400,{message:"Tenant not found"});const c=await _d(r,s.id,i.authParams.vendor_id),l=(d=i.authParams.ui_locales)==null?void 0:d.split(" ").map(p=>p.split("-")[0]).find(p=>{if(Array.isArray(B.options.supportedLngs))return B.options.supportedLngs.includes(p)});return await B.changeLanguage(l||a.language||"sv"),{vendorSettings:{...c,termsAndConditionsUrl:s.id==="fokus-app"?"https://www.fokus.se/kopvillkor-app/":c.termsAndConditionsUrl},client:s,tenant:a,loginSession:i}}async function A1(t,e,n,r){if(r!==void 0)return r==="password";const i=await io({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n});if(i){const a=await t.env.data.logs.list(e.tenant.id,{page:0,per_page:10,include_totals:!1,sort:{sort_by:"date",sort_order:"desc"},q:`type:${he.SUCCESS_LOGIN} user_id:${i.user_id}`}),[c]=a.logs.filter(l=>l.strategy&&["Username-Password-Authentication","passwordless","email"].includes(l.strategy));if(c)return c.strategy==="Username-Password-Authentication"}return(await t.env.data.promptSettings.get(e.tenant.id)).password_first}const am=({vendorSettings:t})=>t!=null&&t.logoUrl?y("div",{className:"flex h-9 items-center",children:y("img",{src:t.logoUrl,className:"max-h-full",alt:"Vendor logo"})}):y(om,{}),cm=({vendorSettings:t})=>{const{termsAndConditionsUrl:e}=t;return y("div",{className:"mt-8",children:e&&y("div",{className:"text-xs text-gray-300",children:[B.t("agree_to")," ",y("a",{href:e,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:B.t("terms")})]})})};var lm={exports:{}};/*!
192
+ </html>`}async function r1({ctx:t,client:e,session:n,redirect_uri:r,state:i,nonce:s,code_challenge_method:a,code_challenge:c,audience:l,scope:d,response_type:p}){const{env:f}=t,m=new URL(r),w=`${m.protocol}//${m.host}`;async function h(ce="Login required"){const le=we(t,{type:he.FAILED_SILENT_AUTH,description:ce});return await t.env.data.logs.create(e.tenant.id,le),t.html(Vp(w,JSON.stringify({error:"login_required",error_description:ce,state:i})))}if(!n||(n==null?void 0:n.expires_at)&&new Date(n.expires_at)<new Date||(n==null?void 0:n.idle_expires_at)&&new Date(n.idle_expires_at)<new Date)return h();t.set("user_id",n.user_id);const v=await f.data.users.get(e.tenant.id,n.user_id);if(!v)return console.error("User not found",n.user_id),h("User not found");t.set("username",v.email),t.set("connection",v.connection);const A={client:e,authParams:{client_id:e.id,audience:l,code_challenge_method:a,code_challenge:c,scope:d,state:i,nonce:s,response_type:p},user:v,session_id:n.id},C=p===It.CODE?await Df(t,A):await no(t,A);await f.data.sessions.update(e.tenant.id,n.id,{used_at:new Date().toISOString(),last_interaction_at:new Date().toISOString(),device:{...n.device,last_ip:t.req.header("x-real-ip")||"",last_user_agent:t.req.header("user-agent")||""},idle_expires_at:n.idle_expires_at?new Date(Date.now()+eo*1e3).toISOString():void 0});const O=we(t,{type:he.SUCCESS_SILENT_AUTH,description:"Successful silent authentication"});await t.env.data.logs.create(e.tenant.id,O);const L=new Headers;L.set("Server-Timing","cf-nel=0; no-cloudflare-insights=1");const Q=Pf(e.tenant.id,n.id,t.req.header("host"));return L.set("set-cookie",Q),t.html(Vp(w,JSON.stringify(C)),{headers:L})}const i1=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),vendor_id:o.z.string().optional(),redirect_uri:o.z.string(),scope:o.z.string().optional(),state:o.z.string(),prompt:o.z.string().optional(),response_mode:o.z.nativeEnum(Rt).optional(),response_type:o.z.nativeEnum(It).optional(),audience:o.z.string().optional(),connection:o.z.string().optional(),nonce:o.z.string().optional(),max_age:o.z.string().optional(),login_ticket:o.z.string().optional(),code_challenge_method:o.z.nativeEnum(Ys).optional(),code_challenge:o.z.string().optional(),realm:o.z.string().optional(),auth0Client:o.z.string().optional(),organization:o.z.string().optional(),login_hint:o.z.string().optional(),screen_hint:o.z.string().openapi({example:"signup",description:'Optional hint for the screen to show, like "signup" or "login".'}).optional(),ui_locales:o.z.string().optional()})},responses:{200:{description:"Silent authentication page"},302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{env:e}=t,{client_id:n,vendor_id:r,redirect_uri:i,scope:s,state:a,audience:c,nonce:l,connection:d,response_type:p,response_mode:f,code_challenge:m,code_challenge_method:w,prompt:h,login_ticket:_,realm:v,auth0Client:A,login_hint:C,ui_locales:O,organization:L}=t.req.valid("query");t.set("log","authorize");const Q=await Yo(e,n);t.set("client_id",Q.id),t.set("tenant_id",Q.tenant.id);const ce={redirect_uri:i,scope:s,state:a,client_id:n,vendor_id:r,audience:c,nonce:l,prompt:h,response_type:p,response_mode:f,code_challenge:m,code_challenge_method:w,username:C,ui_locales:O,organization:L},le=t.req.header("origin");if(le&&!Qb(le,Q.web_origins||[]))throw new I(403,{message:`Origin ${le} not allowed`});if(ce.redirect_uri&&!Xo(ce.redirect_uri,Q.callbacks||[],{allowPathWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${ce.redirect_uri}`});const He=ls(Q.tenant.id,t.req.header("cookie")),Ve=He?await e.data.sessions.get(Q.tenant.id,He):void 0,Re=Ve&&!Ve.revoked_at?Ve:void 0;if(h=="none"){if(!p)throw new I(400,{message:"Missing response_type"});return r1({ctx:t,session:Re||void 0,redirect_uri:i,state:a,response_type:p,client:Q,nonce:l,code_challenge_method:w,code_challenge:m,audience:c,scope:s})}return d&&d!=="email"?jb(t,Q,d,ce):_?n1(t,Q.tenant.id,_,ce,v):e1({ctx:t,client:Q,auth0Client:A,authParams:ce,session:Re||void 0,connection:d,login_hint:C})});function s1(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>(r.env.data=ro(r,t.dataAdapter),i())),e.use("/oauth/token",of({origin:r=>r||"",allowHeaders:["Tenant-Id","Content-Type","Auth0-Client","Upgrade-Insecure-Requests"],allowMethods:["POST"],maxAge:600})),e.use(od).use(Rg(e));const n=e.route("/v2/logout",Ob).route("/userinfo",Tb).route("/.well-known",Pb).route("/oauth/token",Fb).route("/dbconnections",Jb).route("/passwordless",Zb).route("/co/authenticate",Xb).route("/authorize",i1).route("/callback",$b);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Oauth API"},security:[{oauth2:["openid","email","profile"]}]}),Bg(n),n}var o1={Stringify:1,BeforeStream:2,Stream:3},_t=(t,e)=>{const n=new String(t);return n.isEscaped=!0,n.callbacks=e,n},a1=/[&<>'"]/,Yg=async(t,e)=>{let n="";e||(e=[]);const r=await Promise.all(t);for(let i=r.length-1;n+=r[i],i--,!(i<0);i--){let s=r[i];typeof s=="object"&&e.push(...s.callbacks||[]);const a=s.isEscaped;if(s=await(typeof s=="object"?s.toString():s),typeof s=="object"&&e.push(...s.callbacks||[]),s.isEscaped??a)n+=s;else{const c=[n];en(s,c),n=c[0]}}return _t(n,e)},en=(t,e)=>{const n=t.search(a1);if(n===-1){e[0]+=t;return}let r,i,s=0;for(i=n;i<t.length;i++){switch(t.charCodeAt(i)){case 34:r="&quot;";break;case 39:r="&#39;";break;case 38:r="&amp;";break;case 60:r="&lt;";break;case 62:r="&gt;";break;default:continue}e[0]+=t.substring(s,i)+r,s=i+1}e[0]+=t.substring(s,i)},Xg=t=>{const e=t.callbacks;if(!(e!=null&&e.length))return t;const n=[t],r={};return e.forEach(i=>i({phase:o1.Stringify,buffer:n,context:r})),n[0]},c1=(t,...e)=>{const n=[""];for(let r=0,i=t.length-1;r<i;r++){n[0]+=t[r];const s=Array.isArray(e[r])?e[r].flat(1/0):[e[r]];for(let a=0,c=s.length;a<c;a++){const l=s[a];if(typeof l=="string")en(l,n);else if(typeof l=="number")n[0]+=l;else{if(typeof l=="boolean"||l===null||l===void 0)continue;if(typeof l=="object"&&l.isEscaped)if(l.callbacks)n.unshift("",l);else{const d=l.toString();d instanceof Promise?n.unshift("",d):n[0]+=d}else l instanceof Promise?n.unshift("",l):en(l.toString(),n)}}}return n[0]+=t[t.length-1],n.length===1?"callbacks"in n?_t(Xg(_t(n[0],n.callbacks))):_t(n[0]):Yg(n,n.callbacks)},hd=Symbol("RENDERER"),Qc=Symbol("ERROR_HANDLER"),Ae=Symbol("STASH"),Qg=Symbol("INTERNAL"),l1=Symbol("MEMO"),Ws=Symbol("PERMALINK"),qp=t=>(t[Qg]=!0,t),em=t=>({value:e,children:n})=>{if(!n)return;const r={children:[{tag:qp(()=>{t.push(e)}),props:{}}]};Array.isArray(n)?r.children.push(...n.flat()):r.children.push(n),r.children.push({tag:qp(()=>{t.pop()}),props:{}});const i={tag:"",props:r,type:""};return i[Qc]=s=>{throw t.pop(),s},i},tm=t=>{const e=[t],n=em(e);return n.values=e,n.Provider=n,ur.push(n),n},ur=[],d1=t=>{const e=[t],n=r=>{e.push(r.value);let i;try{i=r.children?(Array.isArray(r.children)?new sm("",{},r.children):r.children).toString():""}finally{e.pop()}return i instanceof Promise?i.then(s=>_t(s,s.callbacks)):_t(i)};return n.values=e,n.Provider=n,n[hd]=em(e),ur.push(n),n},Ar=t=>t.values.at(-1),Ki={title:[],script:["src"],style:["data-href"],link:["href"],meta:["name","httpEquiv","charset","itemProp"]},el={},Wi="data-precedence",zi=t=>Array.isArray(t)?t:[t],Mp=new WeakMap,Dp=(t,e,n,r)=>({buffer:i,context:s})=>{if(!i)return;const a=Mp.get(s)||{};Mp.set(s,a);const c=a[t]||(a[t]=[]);let l=!1;const d=Ki[t];if(d.length>0){e:for(const[,p]of c)for(const f of d)if(((p==null?void 0:p[f])??null)===(n==null?void 0:n[f])){l=!0;break e}}if(l?i[0]=i[0].replaceAll(e,""):d.length>0?c.push([e,n,r]):c.unshift([e,n,r]),i[0].indexOf("</head>")!==-1){let p;if(r===void 0)p=c.map(([f])=>f);else{const f=[];p=c.map(([m,,w])=>{let h=f.indexOf(w);return h===-1&&(f.push(w),h=f.length-1),[m,h]}).sort((m,w)=>m[1]-w[1]).map(([m])=>m)}p.forEach(f=>{i[0]=i[0].replaceAll(f,"")}),i[0]=i[0].replace(/(?=<\/head>)/,p.join(""))}},Ei=(t,e,n)=>_t(new yt(t,n,zi(e??[])).toString()),Ii=(t,e,n,r)=>{if("itemProp"in n)return Ei(t,e,n);let{precedence:i,blocking:s,...a}=n;i=r?i??"":void 0,r&&(a[Wi]=i);const c=new yt(t,a,zi(e||[])).toString();return c instanceof Promise?c.then(l=>_t(c,[...l.callbacks||[],Dp(t,l,a,i)])):_t(c,[Dp(t,c,a,i)])},u1=({children:t,...e})=>{const n=gd();if(n){const r=Ar(n);if(r==="svg"||r==="head")return new yt("title",e,zi(t??[]))}return Ii("title",t,e,!1)},p1=({children:t,...e})=>{const n=gd();return["src","async"].some(r=>!e[r])||n&&Ar(n)==="head"?Ei("script",t,e):Ii("script",t,e,!1)},f1=({children:t,...e})=>["href","precedence"].every(n=>n in e)?(e["data-href"]=e.href,delete e.href,Ii("style",t,e,!0)):Ei("style",t,e),h1=({children:t,...e})=>["onLoad","onError"].some(n=>n in e)||e.rel==="stylesheet"&&(!("precedence"in e)||"disabled"in e)?Ei("link",t,e):Ii("link",t,e,"precedence"in e),g1=({children:t,...e})=>{const n=gd();return n&&Ar(n)==="head"?Ei("meta",t,e):Ii("meta",t,e,!1)},nm=(t,{children:e,...n})=>new yt(t,n,zi(e??[])),m1=t=>(typeof t.action=="function"&&(t.action=Ws in t.action?t.action[Ws]:void 0),nm("form",t)),rm=(t,e)=>(typeof e.formAction=="function"&&(e.formAction=Ws in e.formAction?e.formAction[Ws]:void 0),nm(t,e)),_1=t=>rm("input",t),y1=t=>rm("button",t);const va=Object.freeze(Object.defineProperty({__proto__:null,button:y1,form:m1,input:_1,link:h1,meta:g1,script:p1,style:f1,title:u1},Symbol.toStringTag,{value:"Module"}));var w1=new Map([["className","class"],["htmlFor","for"],["crossOrigin","crossorigin"],["httpEquiv","http-equiv"],["itemProp","itemprop"],["fetchPriority","fetchpriority"],["noModule","nomodule"],["formAction","formaction"]]),Gs=t=>w1.get(t)||t,im=(t,e)=>{for(const[n,r]of Object.entries(t)){const i=n[0]==="-"||!/[A-Z]/.test(n)?n:n.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`);e(i,r==null?null:typeof r=="number"?i.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/)?`${r}`:`${r}px`:r)}},ri=void 0,gd=()=>ri,v1=t=>/[A-Z]/.test(t)&&t.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/)?t.replace(/([A-Z])/g,"-$1").toLowerCase():t,b1=["area","base","br","col","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"],x1=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","defer","disabled","download","formnovalidate","hidden","inert","ismap","itemscope","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","selected"],md=(t,e)=>{for(let n=0,r=t.length;n<r;n++){const i=t[n];if(typeof i=="string")en(i,e);else{if(typeof i=="boolean"||i===null||i===void 0)continue;i instanceof yt?i.toStringToBuffer(e):typeof i=="number"||i.isEscaped?e[0]+=i:i instanceof Promise?e.unshift("",i):md(i,e)}}},yt=class{constructor(t,e,n){te(this,"tag");te(this,"props");te(this,"key");te(this,"children");te(this,"isEscaped",!0);te(this,"localContexts");this.tag=t,this.props=e,this.children=n}get type(){return this.tag}get ref(){return this.props.ref||null}toString(){var e,n;const t=[""];(e=this.localContexts)==null||e.forEach(([r,i])=>{r.values.push(i)});try{this.toStringToBuffer(t)}finally{(n=this.localContexts)==null||n.forEach(([r])=>{r.values.pop()})}return t.length===1?"callbacks"in t?Xg(_t(t[0],t.callbacks)).toString():t[0]:Yg(t,t.callbacks)}toStringToBuffer(t){const e=this.tag,n=this.props;let{children:r}=this;t[0]+=`<${e}`;const i=ri&&Ar(ri)==="svg"?s=>v1(Gs(s)):s=>Gs(s);for(let[s,a]of Object.entries(n))if(s=i(s),s!=="children"){if(s==="style"&&typeof a=="object"){let c="";im(a,(l,d)=>{d!=null&&(c+=`${c?";":""}${l}:${d}`)}),t[0]+=' style="',en(c,t),t[0]+='"'}else if(typeof a=="string")t[0]+=` ${s}="`,en(a,t),t[0]+='"';else if(a!=null)if(typeof a=="number"||a.isEscaped)t[0]+=` ${s}="${a}"`;else if(typeof a=="boolean"&&x1.includes(s))a&&(t[0]+=` ${s}=""`);else if(s==="dangerouslySetInnerHTML"){if(r.length>0)throw"Can only set one of `children` or `props.dangerouslySetInnerHTML`.";r=[_t(a.__html)]}else if(a instanceof Promise)t[0]+=` ${s}="`,t.unshift('"',a);else if(typeof a=="function"){if(!s.startsWith("on"))throw`Invalid prop '${s}' of type 'function' supplied to '${e}'.`}else t[0]+=` ${s}="`,en(a.toString(),t),t[0]+='"'}if(b1.includes(e)&&r.length===0){t[0]+="/>";return}t[0]+=">",md(r,t),t[0]+=`</${e}>`}},ba=class extends yt{toStringToBuffer(t){const{children:e}=this,n=this.tag.call(null,{...this.props,children:e.length<=1?e[0]:e});if(!(typeof n=="boolean"||n==null))if(n instanceof Promise)if(ur.length===0)t.unshift("",n);else{const r=ur.map(i=>[i,i.values.at(-1)]);t.unshift("",n.then(i=>(i instanceof yt&&(i.localContexts=r),i)))}else n instanceof yt?n.toStringToBuffer(t):typeof n=="number"||n.isEscaped?(t[0]+=n,n.callbacks&&(t.callbacks||(t.callbacks=[]),t.callbacks.push(...n.callbacks))):en(n,t)}},sm=class extends yt{toStringToBuffer(t){md(this.children,t)}},k1=(t,e,...n)=>{e??(e={}),n.length&&(e.children=n.length===1?n[0]:n);const r=e.key;delete e.key;const i=Gi(t,e,n);return i.key=r,i},Hp=!1,Gi=(t,e,n)=>{if(!Hp){for(const r in el)va[r][hd]=el[r];Hp=!0}return typeof t=="function"?new ba(t,e,n):va[t]?new ba(va[t],e,n):t==="svg"||t==="head"?(ri||(ri=d1("")),new yt(t,e,[new ba(ri,{value:t},n)])):new yt(t,e,n)},om=({children:t})=>new sm("",{children:t},Array.isArray(t)?t:t?[t]:[]),S1=(t,e,...n)=>k1(t.tag,{...t.props,...e},...n);function y(t,e,n){let r;if(!e||!("children"in e))r=Gi(t,e,[]);else{const i=e.children;r=Array.isArray(i)?Gi(t,e,i):Gi(t,e,[i])}return r.key=n,r}const Fp={name:"sesamy",logoUrl:"https://assets.sesamy.com/static/images/email/sesamy-logo.png",style:{primaryColor:"#7D68F4",buttonTextColor:"#FFFFFF",primaryHoverColor:"#A091F2"},loginBackgroundImage:"",checkoutHideSocial:!1,supportEmail:"support@sesamy.com",supportUrl:"https://support.sesamy.com",siteUrl:"https://sesamy.com",termsAndConditionsUrl:"https://store.sesamy.com/pages/terms-of-service",manageSubscriptionsUrl:"https://account.sesamy.com/manage-subscriptions"};async function _d(t,e,n){if(!n&&!e)return Fp;const r=n||e;try{const i=await fetch(`${t.API_URL}/profile/vendors/${r}/style`);if(!i.ok)throw new Error("Failed to fetch vendor settings");const s=await i.json();return uf.parse(s)}catch(i){return console.error(i),Fp}}async function Ee(t,e,n=!1){var d;const{env:r}=t,i=await r.data.loginSessions.get(t.var.tenant_id||"",e);if(i)i.session_id;else throw new I(400,{message:"Login session not found"});t.set("loginSession",i);const s=await Yo(r,i.authParams.client_id);t.set("client_id",s.id),t.set("tenant_id",s.tenant.id);const a=await r.data.tenants.get(s.tenant.id);if(a){if(i.session_id&&!n)throw new I(400,{message:"Login session closed"})}else throw new I(400,{message:"Tenant not found"});const c=await _d(r,s.id,i.authParams.vendor_id),l=(d=i.authParams.ui_locales)==null?void 0:d.split(" ").map(p=>p.split("-")[0]).find(p=>{if(Array.isArray(B.options.supportedLngs))return B.options.supportedLngs.includes(p)});return await B.changeLanguage(l||a.language||"sv"),{vendorSettings:{...c,termsAndConditionsUrl:s.id==="fokus-app"?"https://www.fokus.se/kopvillkor-app/":c.termsAndConditionsUrl},client:s,tenant:a,loginSession:i}}async function A1(t,e,n,r){if(r!==void 0)return r==="password";const i=await io({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:n});if(i){const a=await t.env.data.logs.list(e.tenant.id,{page:0,per_page:10,include_totals:!1,sort:{sort_by:"date",sort_order:"desc"},q:`type:${he.SUCCESS_LOGIN} user_id:${i.user_id}`}),[c]=a.logs.filter(l=>l.strategy&&["Username-Password-Authentication","passwordless","email"].includes(l.strategy));if(c)return c.strategy==="Username-Password-Authentication"}return(await t.env.data.promptSettings.get(e.tenant.id)).password_first}const am=({vendorSettings:t})=>t!=null&&t.logoUrl?y("div",{className:"flex h-9 items-center",children:y("img",{src:t.logoUrl,className:"max-h-full",alt:"Vendor logo"})}):y(om,{}),cm=({vendorSettings:t})=>{const{termsAndConditionsUrl:e}=t;return y("div",{className:"mt-8",children:e&&y("div",{className:"text-xs text-gray-300",children:[B.t("agree_to")," ",y("a",{href:e,className:"text-primary hover:underline",target:"_blank",rel:"noreferrer",children:B.t("terms")})]})})};var lm={exports:{}};/*!
193
193
  Copyright (c) 2018 Jed Watson.
194
194
  Licensed under the MIT License (MIT), see
195
195
  http://jedwatson.github.io/classnames
@@ -7477,6 +7477,7 @@ export declare function init(config: AuthHeroConfig): {
7477
7477
  auth0Client?: string | undefined;
7478
7478
  scope?: string | undefined;
7479
7479
  login_ticket?: string | undefined;
7480
+ screen_hint?: string | undefined;
7480
7481
  code_challenge_method?: CodeChallengeMethod | undefined;
7481
7482
  realm?: string | undefined;
7482
7483
  code_challenge?: string | undefined;
@@ -7505,6 +7506,7 @@ export declare function init(config: AuthHeroConfig): {
7505
7506
  auth0Client?: string | undefined;
7506
7507
  scope?: string | undefined;
7507
7508
  login_ticket?: string | undefined;
7509
+ screen_hint?: string | undefined;
7508
7510
  code_challenge_method?: CodeChallengeMethod | undefined;
7509
7511
  realm?: string | undefined;
7510
7512
  code_challenge?: string | undefined;
package/dist/authhero.mjs CHANGED
@@ -5949,19 +5949,22 @@ function sy(t, e) {
5949
5949
  };
5950
5950
  }
5951
5951
  async function oy(t, e, n, r) {
5952
- var i, s;
5953
- if (e.disable_sign_ups && !(((s = (i = t.var.loginSession) == null ? void 0 : i.authParams) == null ? void 0 : s.prompt) === "signup") && !await Gs({
5954
- userAdapter: n.users,
5955
- tenant_id: e.tenant.id,
5956
- email: r
5957
- })) {
5958
- const l = be(t, {
5959
- type: _e.FAILED_SIGNUP,
5960
- description: "Public signup is disabled"
5961
- });
5962
- throw await n.logs.create(e.tenant.id, l), new C(400, {
5963
- message: "Signups are disabled for this client"
5964
- });
5952
+ var i;
5953
+ if (e.disable_sign_ups) {
5954
+ const s = (i = t.var.loginSession) == null ? void 0 : i.authorization_url;
5955
+ if (!(s && new URL(s).searchParams.get("screen_hint") === "signup") && !await Gs({
5956
+ userAdapter: n.users,
5957
+ tenant_id: e.tenant.id,
5958
+ email: r
5959
+ })) {
5960
+ const l = be(t, {
5961
+ type: _e.FAILED_SIGNUP,
5962
+ description: "Public signup is disabled"
5963
+ });
5964
+ throw await n.logs.create(e.tenant.id, l), new C(400, {
5965
+ message: "Signups are disabled for this client"
5966
+ });
5967
+ }
5965
5968
  }
5966
5969
  await ry(t)(t.var.tenant_id || "", r);
5967
5970
  }
@@ -20277,6 +20280,10 @@ const Lb = new ae().openapi(
20277
20280
  auth0Client: a.string().optional(),
20278
20281
  organization: a.string().optional(),
20279
20282
  login_hint: a.string().optional(),
20283
+ screen_hint: a.string().openapi({
20284
+ example: "signup",
20285
+ description: 'Optional hint for the screen to show, like "signup" or "login".'
20286
+ }).optional(),
20280
20287
  ui_locales: a.string().optional()
20281
20288
  })
20282
20289
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "authhero",
3
- "version": "0.110.0",
3
+ "version": "0.111.0",
4
4
  "files": [
5
5
  "dist"
6
6
  ],