authhero 0.95.0 → 0.96.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.mjs +5 -2
- package/package.json +1 -1
package/dist/authhero.cjs
CHANGED
|
@@ -146,7 +146,7 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
146
146
|
`,i=0;for(;i<n.length;)i+64<=n.length?r+=n.substr(i,64)+`\r
|
|
147
147
|
`:r+=n.substr(i)+`\r
|
|
148
148
|
`,i+=64;return r+=`-----END ${t} KEY-----\r
|
|
149
|
-
`,r}async function ow(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return za(await zf(s))}const aw=1e3*60*60*24,cw=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Ia)}},description:"List of keys"}}}),async t=>{const n=(await t.env.data.keys.list()).filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ia}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),r=(await t.env.data.keys.list()).find(i=>i.kid===e);if(!r)throw new z(404,{message:"Key not found"});return t.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const e=await t.env.data.keys.list();for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+aw).toISOString()});const n=await Jc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new z(404,{message:"Key not found"});const r=await Jc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),lw=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(el)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await pl(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),uw=nn.extend({clients:o.z.array(mn)}),dw=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Xt,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([uw,o.z.array(mn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),l=(await t.env.data.applications.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a})).applications;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:mn}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=(await t.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(s=>s.id===n);if(!i)throw new z(404);return t.json(i)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.applications.remove(e,n))throw new z(404,{message:"Application not found"});return t.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(ns.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:mn}},description:"The update application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.applications.update(e,n,i);const s=await t.env.data.applications.get(e,n);if(!s)throw new z(404,{message:"Application not found"});return t.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(ns.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(mn.shape)}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||xe(),client_secret:n.client_secret||xe()},i=await t.env.data.applications.create(e,r);return t.json(i,{status:201})});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});Js.extend({email:o.z.string(),login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any());const pw=nn.extend({tenants:o.z.array(Fn)}),fw=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Xt},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Fn),pw])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:dr(i),q:s});return r?t.json(a):t.json(a.tenants)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Fn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new z(404);return t.json(n)}).openapi(o.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(is.shape).partial()}}},params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(is.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Fn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),hw=nn.extend({logs:o.z.array(os)}),gw=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Xt,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(os),hw])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":a}=t.req.valid("header"),c=await t.env.data.logs.list(a,{page:e,per_page:n,include_totals:r,sort:dr(i),q:s});return r?t.json(c):t.json(c.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:os}},description:"A log entry"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.logs.get(e,n);if(!r)throw new z(404);return t.json(r)}),mw=nn.extend({hooks:o.z.array(Dn)}),_w=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Xt,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(Dn),mw])}},description:"List of hooks"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.hooks.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a});return i?t.json(c):t.json(c.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(ss.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Dn}},description:"The created hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.hooks.create(e,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(ss.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Dn.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=t.req.valid("json");await t.env.data.hooks.update(e,n,r);const i=await t.env.data.hooks.get(e,n);if(!i)throw new z(404,{message:"Hook not found"});return t.json(i)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Dn}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=await t.env.data.hooks.get(e,n);if(!r)throw new z(404,{message:"Hook not found"});return t.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param");if(!await t.env.data.hooks.remove(e,n))throw new z(404,{message:"Hook not found"});return t.text("OK")}),yw=nn.extend({connections:o.z.array(Ft)}),vw=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Xt,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(Ft),yw])}},description:"List of connectionss"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.connections.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a});return i?t.json(c):t.json(c.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.connections.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.connections.remove(e,n))throw new z(404,{message:"Connection not found"});return t.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(rs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"The updated connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.connections.update(e,n,r))throw new z(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new z(404,{message:"Connection not found"});return t.json(s)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(rs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Ft}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.connections.create(e,n);return t.json(r,{status:201})}),ww=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Li.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let Ap=!1;function Bg(t){t.use(async(e,n)=>(Ap||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Ap=!0),await n()))}o.z.object({alg:o.z.literal("RS256"),kty:o.z.literal("RSA"),use:o.z.literal("sig"),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string(),x5c:o.z.array(o.z.string())});async function bw(t){try{const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new z(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function kw(t,e){const r=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),i=new Uint8Array(Array.from(e.signature).map(l=>l.charCodeAt(0))),a=(await bw(t.env)).find(l=>l.kid===e.header.kid);if(!a)return console.log("No matching kid found"),!1;const c=await crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",c,i,r)}function xw(t){const[e,n,r]=t.split(".");if(!e||!n||!r)return null;const i=JSON.parse(atob(e)),s=JSON.parse(atob(n)),a=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return{header:i,payload:s,signature:a,raw:{header:e,payload:n,signature:r}}}function Tg(t){return async(e,n)=>{var i,s,a;const r=t.openAPIRegistry.definitions.find(c=>"route"in c&&c.route.path===e.req.path&&c.route.method.toUpperCase()===e.req.method);if(r&&"route"in r){const c=(s=(i=r.route.security)==null?void 0:i[0])==null?void 0:s.Bearer;if(!(c!=null&&c.length))return await n();const l=e.req.header("authorization")||"",[u,p]=l.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!p)throw new z(401,{message:"Missing bearer token"});const h=xw(p);if(!h||!await kw(e,h))throw new z(403,{message:"Invalid JWT signature"});e.set("user_id",h.payload.sub),e.set("user",h.payload);const m=h.payload.permissions||[],v=((a=h.payload.scope)==null?void 0:a.split(" "))||[];if(c.length&&!(c.some(f=>m.includes(f))||c.some(f=>v.includes(f))))throw new z(403,{message:"Unauthorized"})}return await n()}}const Sw=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ui}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new z(404,{message:"Email provider not found"});return t.json(n)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),Aw=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ys}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.sessions.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.remove(e,n))throw new z(404,{message:"Session not found"});return t.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.update(e,n,{revoked_at:new Date().toDateString()}))throw new z(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Ew=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:il}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.refreshTokens.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(e,n))throw new z(404,{message:"Session not found"});return t.text("OK")}),Iw=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Xt,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(fn)}},description:"List of custom domains"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.customDomains.list(e);return t.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.customDomains.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.customDomains.remove(e,n))throw new z(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(fn.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"The updated custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.customDomains.update(e,n,r))throw new z(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new z(404);return t.json(s)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(nl.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:fn}},description:"The created custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.customDomains.create(e,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"The custom domain"}}}),async()=>{throw new z(501,{message:"Not implemented"})});function zw(t){const e=new o.OpenAPIHono;Bg(e),e.use(async(r,i)=>(r.env.data=no(r,t.dataAdapter),i())),e.use(Tg(e));const n=e.route("/branding",t_).route("/custom-domains",Iw).route("/email/providers",Sw).route("/users",uy).route("/keys",cw).route("/users-by-email",lw).route("/clients",dw).route("/tenants",fw).route("/logs",gw).route("/hooks",_w).route("/connections",vw).route("/prompts",ww).route("/sessions",Aw).route("/refresh_tokens",Ew);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function Nw(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Ep;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ep||(Ep={}));var Ip;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ip||(Ip={}));function Cw(t){return Rg(t,jw,ei.Include)}function Pg(t){return Rg(t,$w,ei.None)}function Rg(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===ei.Include&&(r+="=")}return r}const jw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ei;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ei||(ei={}));var zp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(zp||(zp={}));class Ow{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Np=new Ow;function kt(t,e){return(t<<32-e|t>>>e)>>>0}function Bw(t){const e=new Tw;return e.update(t),e.digest()}class Tw{constructor(){te(this,"blockSize",64);te(this,"size",32);te(this,"blocks",new Uint8Array(64));te(this,"currentBlockSize",0);te(this,"H",new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]));te(this,"l",0n);te(this,"w",new Uint32Array(64))}update(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),Np.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Np.putUint32(e,this.H[n],n*4);return e}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const p=(kt(this.w[u-2],17)^kt(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,h=(kt(this.w[u-15],7)^kt(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=p+this.w[u-7]+h+this.w[u-16]|0}let e=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const p=(kt(s,6)^kt(s,11)^kt(s,25))>>>0,h=(s&a^~s&c)>>>0,m=l+p+h+Pw[u]+this.w[u]|0,v=(kt(e,2)^kt(e,13)^kt(e,22))>>>0,f=(e&n^e&r^n&r)>>>0,_=v+f|0;l=c,c=a,a=s,s=i+m|0,i=r,r=n,n=e,e=m+_|0}this.H[0]=e+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const Pw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class Rw{constructor(e){te(this,"data");this.data=e}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function Lw(t){const e=Bw(new TextEncoder().encode(t));return Pg(e)}function Uw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Pg(t)}function Ur(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function ha(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Cw(n)}async function Hs(t){let e;try{e=await fetch(t)}catch(n){throw new Ug(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);let r;try{r=Lg(n)}catch{throw new Gn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);return new Rw(n)}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}async function Vw(t){let e;try{e=await fetch(t)}catch(n){throw new Ug(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Gn(e.status,null)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);let r;try{r=Lg(n)}catch{throw new Gn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}function Lg(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new qw(e,n,r,i)}class Ug extends Error{constructor(e){super("Failed to send request",{cause:e})}}class qw extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);te(this,"code");te(this,"description");te(this,"uri");te(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Hi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class Gn extends Error{constructor(n,r){super("Unexpected error response body");te(this,"status");te(this,"data");this.status=n,this.data=r}}class nu{constructor(e,n,r){te(this,"clientId");te(this,"clientPassword");te(this,"redirectURI");this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(e,n,r,i,s){const a=new URL(e);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===ti.S256){const c=Lw(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ti.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(e,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Ur(e,i);if(this.clientPassword!==null){const c=ha(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Hs(s)}async refreshAccessToken(e,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Ur(e,i);if(this.clientPassword!==null){const c=ha(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Hs(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Ur(e,r);if(this.clientPassword!==null){const s=ha(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await Vw(i)}}var ti;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ti||(ti={}));var Cp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Cp||(Cp={}));var jp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(jp||(jp={}));function Vr(t){return Mw(t,Dw,Fs.None)}function Mw(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===Fs.Include&&(r+="=")}return r}const Dw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Fs;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Fs||(Fs={}));var $p;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})($p||($p={}));function Hw(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function Fw(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const Kw="https://appleid.apple.com/auth/authorize",Ww="https://appleid.apple.com/auth/token";class Vg{constructor(e,n,r,i,s){te(this,"clientId");te(this,"teamId");te(this,"keyId");te(this,"pkcs8PrivateKey");te(this,"redirectURI");this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(Kw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Ur(Ww,n);return await Hs(i)}async createClientSecret(){const e=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+5*60,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,Fw(r,i)));return Hw(r,i,s)}}const Gw="https://www.facebook.com/v16.0/dialog/oauth",Jw="https://graph.facebook.com/v16.0/oauth/access_token";class qg{constructor(e,n,r){te(this,"clientId");te(this,"clientSecret");te(this,"redirectURI");this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(Gw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Ur(Jw,n);return await Hs(r)}}const Zw="https://accounts.google.com/o/oauth2/v2/auth",Op="https://oauth2.googleapis.com/token",Yw="https://oauth2.googleapis.com/revoke";let Mg=class{constructor(e,n,r){te(this,"client");this.client=new nu(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(Zw,e,ti.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Op,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Op,e,[])}async revokeToken(e){await this.client.revokeToken(Yw,e)}};const Jo=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Jo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Xw(t){return t.ISSUER}function _t(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Dg(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:e,keyArray:i}}async function Qw(t,e){var l,u;const{options:n,keyArray:r}=Dg(e),i=new Vg(n.client_id,n.team_id,n.kid,r,`${je(t.env)}callback`),s=xe(),a=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((u=n.scope)==null?void 0:u.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&a.searchParams.set("response_mode","form_post"),{redirectUrl:a.href,code:s}}async function eb(t,e,n){const{options:r,keyArray:i}=Dg(e),a=await new Vg(r.client_id,r.team_id,r.kid,i,`${je(t.env)}callback`).validateAuthorizationCode(n),c=ol(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Jo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const tb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Qw,validateAuthorizationCodeAndGetUser:eb},Symbol.toStringTag,{value:"Module"}));async function nb(t,e){var a;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new qg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe();return{redirectUrl:r.createAuthorizationURL(i,((a=n.scope)==null?void 0:a.split(" "))||["email"]).href,code:i}}async function rb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new qg(r.client_id,r.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v16.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const ib=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:nb,validateAuthorizationCodeAndGetUser:rb},Symbol.toStringTag,{value:"Module"}));async function sb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Mg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe(),s=Uw();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function ob(t,e,n,r){const{options:i}=e;if(!(i!=null&&i.client_id)||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new Mg(i.client_id,i.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n,r),c=ol(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Jo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const ab=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:sb,validateAuthorizationCodeAndGetUser:ob},Symbol.toStringTag,{value:"Module"}));async function cb(t,e){var a;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new nu(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,((a=n.scope)==null?void 0:a.split(" "))||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function lb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new nu(r.client_id,r.client_secret,`${je(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=ol(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Jo.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new z(400,{message:"Failed to get user from vipps"});return await l.json()}const ub=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:cb,validateAuthorizationCodeAndGetUser:lb},Symbol.toStringTag,{value:"Module"}));function Hg(t,e){const n=t.env.STRATEGIES||{},i={apple:tb,facebook:ib,"google-oauth2":ab,vipps:ub,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Zo(t,e){const n=await t.data.clients.get(e);if(!n)throw new z(403,{message:"Client not found"});const r=t.DEFAULT_CLIENT_ID?await t.data.clients.get(t.DEFAULT_CLIENT_ID):void 0,i=await t.data.connections.list(n.tenant.id),s=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},a=i.connections.map(c=>{var p;const l=(p=s.connections)==null?void 0:p.find(h=>h.name===c.name);return l!=null&&l.options?Ft.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${_t(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${_t(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Yo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return db(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function db(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function pb(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=ve(t,{type:he.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.loginSessions.get(e.tenant.id,r.state);s||(s=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:r,csrf_token:xe(),...sn(t.req)}));const c=await Hg(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+E_*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Bp(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.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new z(403,{message:"Session not found"});const a=await Zo(r,s.authParams.client_id);t.set("client_id",a.id),t.set("tenant_id",a.tenant.id);const c=a.connections.find(_=>_.id===i.connection_id);if(!c){const _=ve(t,{type:he.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(a.tenant.id,_),new z(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=ve(t,{type:he.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new z(403,{message:"Redirect URI not defined"})}if(!Yo(s.authParams.redirect_uri,a.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,w=ve(t,{type:he.FAILED_LOGIN,description:_});throw await r.data.logs.create(a.tenant.id,w),new z(403,{message:_})}const u=await Hg(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...h}=u;t.set("user_id",p);const m=((f=u.email)==null?void 0:f.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const v=await io(t,{client:a,email:m,provider:c.strategy,connection:c.name,userId:p,profileData:h,isSocial:!0,ip:t.req.header("x-real-ip")});return on(t,{client:a,authParams:s.authParams,loginSession:s,user:v})}async function Tp(t,e,n,r,i,s){const a=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!a)throw new z(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.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=ve(t,{type:he.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});nt(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Nw(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${_t(t.env)}enter-email?state=${c.id}&error=${n}`)}const fb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.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:a}=t.req.valid("query");if(r)return Tp(t,e,r,i,s,a);if(!n)throw new z(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.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:a}=t.req.valid("form");if(r)return Tp(t,e,r,i,s,a);if(!n)throw new z(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}),hb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.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(!Yo(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new z(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const l=cs(r.tenant.id,a);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=ve(t,{type:he.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":j_(r.tenant.id,t.req.header("host")),location:s}})}),Pp=o.z.object({sub:o.z.string(),email:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),email_verified:o.z.boolean()}),gb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Pp}},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(Pp.parse({...e,sub:e.user_id}))}),mb=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:ff}},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 tu(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return rl.parse({...a,kid:r.kid})}));return t.json({keys:n},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ji}, stale-while-revalidate=${ji*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ea}},description:"List of tenants"}}}),async t=>{const e=Ea.parse({issuer:Xw(t.env),authorization_endpoint:`${je(t.env)}authorize`,token_endpoint:`${je(t.env)}oauth/token`,device_authorization_endpoint:`${je(t.env)}oauth/device/code`,userinfo_endpoint:`${je(t.env)}userinfo`,mfa_challenge_endpoint:`${je(t.env)}mfa/challenge`,jwks_uri:`${je(t.env)}.well-known/jwks.json`,registration_endpoint:`${je(t.env)}oidc/register`,revocation_endpoint:`${je(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=${ji}, stale-while-revalidate=${ji*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 Fg=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional()});async function _b(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 to(t,{authParams:r,client:n});return t.json(i)}const yb=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.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 vb(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.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new z(403,{message:"Invalid login"});if("client_secret"in e){const a=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Fi(n.client_secret,e.client_secret)&&!Fi(a==null?void 0:a.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 a=await k_(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(a,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:Yt.WEB_MESSAGE}})}const wb=o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),redirect_uri:o.z.string().optional(),refresh_token:o.z.string()});async function bb(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 a=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:a.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:Yt.WEB_MESSAGE}})}const Rp=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),kb=o.z.union([Fg.extend(Rp.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128)}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),...Rp.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional()})]);function xb(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 Sb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:kb}}}},responses:{200:{content:{"application/json":{schema:vf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=xb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new z(400,{message:"client_id is required"});switch(t.set("client_id",r.client_id),e.grant_type){case Br.AuthorizationCode:return vb(t,yb.parse(r));case Br.ClientCredential:return _b(t,Fg.parse(r));case Br.RefreshToken:return bb(t,wb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var ru={exports:{}};const iu=[{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}],Kg=(t,e=iu,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 a=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,a[0]),s};ru.exports={passwordStrength:Kg,defaultOptions:iu};var Ab=ru.exports.passwordStrength=Kg;ru.exports.defaultOptions=iu;function su(t){return Ab(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 Si(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 Wg(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=`${_t(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await Si(t,{to:e,subject:se("reset_password_title",a),html:`Click here to reset your password: ${_t(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:se("password_reset_title",a),resetPasswordEmailClickToReset:se("reset_password_email_click_to_reset",a),resetPasswordEmailReset:se("reset_password_email_reset",a),supportInfo:se("support_info",a),contactUs:se("contact_us",a),copyright:se("copyright",a)}})}async function Gg(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 Si(t,{to:e,subject:se("code_email_subject",i),html:`Click here to validate your email: ${_t(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",buttonColor:r.primary_color||"",welcomeToYourAccount:se("welcome_to_your_account",i),linkEmailClickToLogin:se("link_email_click_to_login",i),linkEmailLogin:se("link_email_login",i),linkEmailOrEnterCode:se("link_email_or_enter_code",i),codeValid30Mins:se("code_valid_30_minutes",i),supportInfo:se("support_info",i),contactUs:se("contact_us",i),copyright:se("copyright",i)}});const s=ve(t,{type:he.CODE_LINK_SENT,description:e});nt(t,t.env.data.logs.create(r.id,s))}async function ou(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(je(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 a={vendorName:i.name,code:n,lng:i.language||"en"};await Si(t,{to:e,subject:se("code_email_subject",a),html:`Click here to validate your email: ${_t(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:se("welcome_to_your_account",a),linkEmailClickToLogin:se("link_email_click_to_login",a),linkEmailLogin:se("link_email_login",a),linkEmailOrEnterCode:se("link_email_or_enter_code",a),codeValid30Mins:se("code_valid_30_minutes",a),supportInfo:se("support_info",a),contactUs:se("contact_us",a),copyright:se("copyright",a)}});const c=ve(t,{type:he.CODE_LINK_SENT,description:e});nt(t,t.env.data.logs.create(i.id,c))}async function au(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 Si(t,{to:e.email,subject:se("welcome_to_your_account",r),html:`Click here to validate your email: ${_t(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${_t(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:se("welcome_to_your_account",r),verifyEmailVerify:se("verify_email_verify",r),supportInfo:se("support_info",r),contactUs:se("contact_us",r),copyright:se("copyright",r)}})}async function Eb(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={vendorName:i.name,lng:i.language||"en"},a=`${_t(t.env)}signup?state=${r}&code=${n}`;await Si(t,{to:e,subject:se("register_password_account",s),html:`Click here to register: ${a}`,template:"auth-pre-signup-verification",data:{vendorName:i.name,logo:i.logo||"",emailValidationUrl:a,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",welcomeToYourAccount:se("welcome_to_your_account",s),verifyEmailVerify:se("verify_email_verify",s),supportInfo:se("support_info",s),contactUs:se("contact_us",s),copyright:se("copyright",s)}})}const Ib=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.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),!su(n))throw new z(400,{message:"Password does not meet the requirements"});if(await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const a=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Xs()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",a.user_id),t.set("username",a.email),t.set("connection",a.connection);const c=await si.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:a.user_id,password:c,algorithm:"bcrypt"}),await au(t,a);const l=ve(t,{type:he.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:a.user_id,email:a.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.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 ur({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},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:s,csrf_token:xe(),...sn(t.req)});return await Wg(t,e,a.id,a.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function Tn(){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 cu(t,e,n,r,i,s,a){const{env:c}=t,l=await c.data.codes.get(e.tenant.id,i,"otp");if(!l)throw new z(400,{message:"Code not found or expired"});if(l.expires_at<new Date().toISOString())throw new z(400,{message:"Code expired"});if(l.used_at)throw new z(400,{message:"Code already used"});const u=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!u||u.authParams.username!==r)throw new z(400,{message:"Code not found or expired"});const p=sn(t.req);if(a&&u.ip!==p.ip)return t.redirect(`${_t(t.env)}invalid-session?state=${u.id}`);if(n.redirect_uri&&!Yo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const h=await io(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),on(t,{user:h,client:e,loginSession:u,authParams:n,ticketAuth:s})}const zb=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:tl.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:a}=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.loginSessions.create(c.tenant.id,{authParams:{...a,client_id:r,username:i},expires_at:new Date(Date.now()+Na).toISOString(),csrf_token:xe(),...sn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:Tn(),code_type:"otp",login_id:l.id,expires_at:new Date(Date.now()+Na).toISOString()});return s==="link"?await ou(t,i,u.code_id,{...a,client_id:r}):await Gg(t,i,u.code_id),t.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(Pt),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),audience:o.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:a,scope:c,audience:l,response_type:u,nonce:p}=t.req.valid("query"),h=await Zo(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),cu(t,h,{client_id:n,redirect_uri:s,state:a,nonce:p,scope:c,audience:l,response_type:u},r,i,!1,!0)});class Nr extends z{constructor(n,r){super(n,r);te(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function lu(t,e,n,r,i){const{env:s}=t,a=n.username;if(t.set("username",a),!a)throw new z(400,{message:"Username is required"});const c=await ur({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:a,provider:"auth2"});if(!c){const f=ve(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(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 Nr(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const u=await s.data.passwords.get(e.tenant.id,c.user_id);if(!(u&&await si.compare(n.password,u.password))){const f=ve(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(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===he.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(f.date)>new Date(Date.now()-1e3*60*5)).length>=3){const f=ve(t,{type:he.FAILED_LOGIN,description:"Too many failed login attempts"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await au(t,c);const f=ve(t,{type:he.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,f),new Nr(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const v=ve(t,{type:he.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return nt(t,t.env.data.logs.create(e.tenant.id,v)),on(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Nb(t,e,n,r){await io(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=Tn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Tn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const a=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+N_).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:xe(),...sn(t.req)}),c=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:a.id,expires_at:new Date(Date.now()+z_).toISOString()});await Wg(t,n,c.code_id,r)}const Cb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.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 cu(t,i,{client_id:n,username:s},s,e.otp,!0);if("password"in e){const a=await t.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:xe(),...sn(t.req)});return lu(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new z(400,{message:"Code or password required"})});function jb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ga(t))==null?void 0:r.host)??null;if(!n)return!1;for(const a of e){let c;if(a.startsWith("http://")||a.startsWith("https://")?c=((i=ga(a))==null?void 0:i.host)??null:c=((s=ga("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function ga(t){try{return new URL(t)}catch{return null}}async function $b({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const a=await t.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:r,csrf_token:xe(),authorization_url:t.req.url,...sn(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:a,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=Tn();return await t.env.data.codes.create(n.tenant.id,{code_id:c,code_type:"otp",login_id:a.id,expires_at:new Date(Date.now()+Jn*1e3).toISOString()}),await ou(t,s,c,r),t.redirect(`/u/enter-code?state=${a.id}`)}return e?t.redirect(`/u/check-account?state=${a.id}`):t.redirect(`/u/enter-email?state=${a.id}`)}function Ob(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Bb(t,e,n,r,i){var m;const{env:s}=t;t.set("connection",i);const a=await s.data.codes.get(e,n,"ticket");if(!a||a.used_at)throw new z(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.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=Ob(i);let p=await io(t,{email:c.authParams.username,provider:u,client:l,connection:u==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email),t.set("user_id",p.user_id);const h=await Mf(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 Lp(t,e){return`<!DOCTYPE html>
|
|
149
|
+
`,r}async function ow(t){const e=await t.publicKey.export(),n=await crypto.subtle.exportKey("jwk",e),r=JSON.stringify(n,Object.keys(n).sort()),s=new TextEncoder().encode(r);return za(await zf(s))}const aw=1e3*60*60*24,cw=new o.OpenAPIHono().openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Ia)}},description:"List of keys"}}}),async t=>{const n=(await t.env.data.keys.list()).filter(r=>"cert"in r).map(r=>r);return t.json(n)}).openapi(o.createRoute({tags:["keys"],method:"get",path:"/signing/{kid}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ia}},description:"The requested key"}}}),async t=>{const{kid:e}=t.req.valid("param"),r=(await t.env.data.keys.list()).find(i=>i.kid===e);if(!r)throw new z(404,{message:"Key not found"});return t.json(r)}).openapi(o.createRoute({tags:["keys"],method:"post",path:"/signing/rotate",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const e=await t.env.data.keys.list();for await(const r of e)await t.env.data.keys.update(r.kid,{revoked_at:new Date(Date.now()+aw).toISOString()});const n=await Jc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["keys"],method:"put",path:"/signing/{kid}/revoke",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({kid:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{description:"Status"}}}),async t=>{const{kid:e}=t.req.valid("param");if(!await t.env.data.keys.update(e,{revoked_at:new Date().toISOString()}))throw new z(404,{message:"Key not found"});const r=await Jc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),lw=new o.OpenAPIHono().openapi(o.createRoute({tags:["users"],method:"get",path:"/",request:{query:o.z.object({email:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.array(el)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await pl(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),uw=nn.extend({clients:o.z.array(mn)}),dw=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:Xt,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([uw,o.z.array(mn)])}},description:"List of clients"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),l=(await t.env.data.applications.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a})).applications;return i?t.json({clients:l,start:0,limit:10,length:l.length}):t.json(l)}).openapi(o.createRoute({tags:["clients"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:mn}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=(await t.env.data.applications.list(e,{page:1,per_page:0,include_totals:!1})).applications.find(s=>s.id===n);if(!i)throw new z(404);return t.json(i)}).openapi(o.createRoute({tags:["clients"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.applications.remove(e,n))throw new z(404,{message:"Application not found"});return t.text("OK")}).openapi(o.createRoute({tags:["clients"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(ns.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:mn}},description:"The update application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),i=t.req.valid("json");await t.env.data.applications.update(e,n,i);const s=await t.env.data.applications.get(e,n);if(!s)throw new z(404,{message:"Application not found"});return t.json(s)}).openapi(o.createRoute({tags:["clients"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(ns.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:o.z.object(mn.shape)}},description:"An application"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r={...n,id:n.id||xe(),client_secret:n.client_secret||xe()},i=await t.env.data.applications.create(e,r);return t.json(i,{status:201})});o.z.object({start:o.z.number(),limit:o.z.number(),length:o.z.number()});Js.extend({email:o.z.string(),login_count:o.z.number(),multifactor:o.z.array(o.z.string()).optional(),last_ip:o.z.string().optional(),last_login:o.z.string().optional(),user_id:o.z.string()}).catchall(o.z.any());const pw=nn.extend({tenants:o.z.array(Fn)}),fw=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:Xt},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Fn),pw])}},description:"List of tenants"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),a=await t.env.data.tenants.list({page:e,per_page:n,include_totals:r,sort:dr(i),q:s});return r?t.json(a):t.json(a.tenants)}).openapi(o.createRoute({tags:["tenants"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:Fn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new z(404);return t.json(n)}).openapi(o.createRoute({tags:["tenants"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param");return await t.env.data.tenants.remove(e),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(is.shape).partial()}}},params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{id:e}=t.req.valid("param"),n=t.req.valid("json");return await t.env.data.tenants.update(e,n),t.text("OK")}).openapi(o.createRoute({tags:["tenants"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(is.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Fn}},description:"An tenant"}}}),async t=>{const e=t.req.valid("json"),n=await t.env.data.tenants.create(e);return t.json(n,{status:201})}),hw=nn.extend({logs:o.z.array(os)}),gw=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:Xt,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(os),hw])}},description:"List of log rows"}}}),async t=>{const{page:e,per_page:n,include_totals:r,sort:i,q:s}=t.req.valid("query"),{"tenant-id":a}=t.req.valid("header"),c=await t.env.data.logs.list(a,{page:e,per_page:n,include_totals:r,sort:dr(i),q:s});return r?t.json(c):t.json(c.logs)}).openapi(o.createRoute({tags:["logs"],method:"get",path:"/{id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:os}},description:"A log entry"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.logs.get(e,n);if(!r)throw new z(404);return t.json(r)}),mw=nn.extend({hooks:o.z.array(Dn)}),_w=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:Xt,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(Dn),mw])}},description:"List of hooks"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.hooks.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a});return i?t.json(c):t.json(c.hooks)}).openapi(o.createRoute({tags:["hooks"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(ss.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Dn}},description:"The created hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.hooks.create(e,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["hooks"],method:"patch",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()}),body:{content:{"application/json":{schema:o.z.object(ss.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Dn.shape}},description:"The updated hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=t.req.valid("json");await t.env.data.hooks.update(e,n,r);const i=await t.env.data.hooks.get(e,n);if(!i)throw new z(404,{message:"Hook not found"});return t.json(i)}).openapi(o.createRoute({tags:["hooks"],method:"get",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Dn}},description:"A hook"},404:{description:"Hook not found"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param"),r=await t.env.data.hooks.get(e,n);if(!r)throw new z(404,{message:"Hook not found"});return t.json(r)}).openapi(o.createRoute({tags:["hooks"],method:"delete",path:"/{hook_id}",request:{headers:o.z.object({"tenant-id":o.z.string()}),params:o.z.object({hook_id:o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{description:"A hook"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{hook_id:n}=t.req.valid("param");if(!await t.env.data.hooks.remove(e,n))throw new z(404,{message:"Hook not found"});return t.text("OK")}),yw=nn.extend({connections:o.z.array(Ft)}),vw=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:Xt,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(Ft),yw])}},description:"List of connectionss"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{page:n,per_page:r,include_totals:i=!1,sort:s,q:a}=t.req.valid("query"),c=await t.env.data.connections.list(e,{page:n,per_page:r,include_totals:i,sort:dr(s),q:a});return i?t.json(c):t.json(c.connections)}).openapi(o.createRoute({tags:["connections"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.connections.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["connections"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.connections.remove(e,n))throw new z(404,{message:"Connection not found"});return t.text("OK")}).openapi(o.createRoute({tags:["connections"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(rs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Ft}},description:"The updated connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.connections.update(e,n,r))throw new z(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new z(404,{message:"Connection not found"});return t.json(s)}).openapi(o.createRoute({tags:["connections"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(rs.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Ft}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.connections.create(e,n);return t.json(r,{status:201})}),ww=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Li.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let Ap=!1;function Bg(t){t.use(async(e,n)=>(Ap||(t.openAPIRegistry.registerComponent("securitySchemes","Bearer",{type:"oauth2",scheme:"bearer",flows:{implicit:{authorizationUrl:`${e.env.AUTH_URL}/authorize`,scopes:{openid:"Basic user information",email:"User email",profile:"User profile information"}}}}),Ap=!0),await n()))}o.z.object({alg:o.z.literal("RS256"),kty:o.z.literal("RSA"),use:o.z.literal("sig"),n:o.z.string(),e:o.z.string(),kid:o.z.string(),x5t:o.z.string(),x5c:o.z.array(o.z.string())});async function bw(t){try{const e=await t.JWKS_SERVICE.fetch(t.JWKS_URL);if(!e.ok)throw new Error("Failed to fetch jwks");return(await e.json()).keys}catch(e){throw new z(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function kw(t,e){const r=new TextEncoder().encode([e.raw.header,e.raw.payload].join(".")),i=new Uint8Array(Array.from(e.signature).map(l=>l.charCodeAt(0))),a=(await bw(t.env)).find(l=>l.kid===e.header.kid);if(!a)return console.log("No matching kid found"),!1;const c=await crypto.subtle.importKey("jwk",a,{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);return crypto.subtle.verify("RSASSA-PKCS1-v1_5",c,i,r)}function xw(t){const[e,n,r]=t.split(".");if(!e||!n||!r)return null;const i=JSON.parse(atob(e)),s=JSON.parse(atob(n)),a=atob(r.replace(/-/g,"+").replace(/_/g,"/"));return{header:i,payload:s,signature:a,raw:{header:e,payload:n,signature:r}}}function Tg(t){return async(e,n)=>{var i,s,a;const r=t.openAPIRegistry.definitions.find(c=>"route"in c&&c.route.path===e.req.path&&c.route.method.toUpperCase()===e.req.method);if(r&&"route"in r){const c=(s=(i=r.route.security)==null?void 0:i[0])==null?void 0:s.Bearer;if(!(c!=null&&c.length))return await n();const l=e.req.header("authorization")||"",[u,p]=l.split(" ");if((u==null?void 0:u.toLowerCase())!=="bearer"||!p)throw new z(401,{message:"Missing bearer token"});const h=xw(p);if(!h||!await kw(e,h))throw new z(403,{message:"Invalid JWT signature"});e.set("user_id",h.payload.sub),e.set("user",h.payload);const m=h.payload.permissions||[],v=((a=h.payload.scope)==null?void 0:a.split(" "))||[];if(c.length&&!(c.some(f=>m.includes(f))||c.some(f=>v.includes(f))))throw new z(403,{message:"Unauthorized"})}return await n()}}const Sw=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ui}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new z(404,{message:"Email provider not found"});return t.json(n)}).openapi(o.createRoute({tags:["emails"],method:"post",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),Aw=new o.OpenAPIHono().openapi(o.createRoute({tags:["sessions"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ys}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.sessions.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["sessions"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.remove(e,n))throw new z(404,{message:"Session not found"});return t.text("OK")}).openapi(o.createRoute({tags:["sessions"],method:"post",path:"/{id}/revoke",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{202:{description:"Sesssion deletion status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.sessions.update(e,n,{revoked_at:new Date().toDateString()}))throw new z(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Ew=new o.OpenAPIHono().openapi(o.createRoute({tags:["refresh_tokens"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:il}},description:"A session"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.refreshTokens.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["refresh_tokens"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.refreshTokens.remove(e,n))throw new z(404,{message:"Session not found"});return t.text("OK")}),Iw=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:Xt,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(fn)}},description:"List of custom domains"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.customDomains.list(e);return t.json(n)}).openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"A connection"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=await t.env.data.customDomains.get(e,n);if(!r)throw new z(404);return t.json(r)}).openapi(o.createRoute({tags:["custom-domains"],method:"delete",path:"/{id}",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Status"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param");if(!await t.env.data.customDomains.remove(e,n))throw new z(404,{message:"Custom domain not found"});return t.text("OK")}).openapi(o.createRoute({tags:["custom-domains"],method:"patch",path:"/{id}",request:{body:{content:{"application/json":{schema:o.z.object(fn.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"The updated custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{id:n}=t.req.valid("param"),r=t.req.valid("json");if(!await t.env.data.customDomains.update(e,n,r))throw new z(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new z(404);return t.json(s)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(nl.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:fn}},description:"The created custom domain"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.customDomains.create(e,n);return t.json(r,{status:201})}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/{id}/verify",request:{params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:fn}},description:"The custom domain"}}}),async()=>{throw new z(501,{message:"Not implemented"})});function zw(t){const e=new o.OpenAPIHono;Bg(e),e.use(async(r,i)=>(r.env.data=no(r,t.dataAdapter),i())),e.use(Tg(e));const n=e.route("/branding",t_).route("/custom-domains",Iw).route("/email/providers",Sw).route("/users",uy).route("/keys",cw).route("/users-by-email",lw).route("/clients",dw).route("/tenants",fw).route("/logs",gw).route("/hooks",_w).route("/connections",vw).route("/prompts",ww).route("/sessions",Aw).route("/refresh_tokens",Ew);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function Nw(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Ep;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ep||(Ep={}));var Ip;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Ip||(Ip={}));function Cw(t){return Rg(t,jw,ei.Include)}function Pg(t){return Rg(t,$w,ei.None)}function Rg(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===ei.Include&&(r+="=")}return r}const jw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",$w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ei;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ei||(ei={}));var zp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(zp||(zp={}));class Ow{uint8(e,n){if(e.byteLength<n+1)throw new TypeError("Insufficient bytes");return e[n]}uint16(e,n){if(e.byteLength<n+2)throw new TypeError("Insufficient bytes");return e[n]<<8|e[n+1]}uint32(e,n){if(e.byteLength<n+4)throw new TypeError("Insufficient bytes");let r=0;for(let i=0;i<4;i++)r|=e[n+i]<<24-i*8;return r}uint64(e,n){if(e.byteLength<n+8)throw new TypeError("Insufficient bytes");let r=0n;for(let i=0;i<8;i++)r|=BigInt(e[n+i])<<BigInt(56-i*8);return r}putUint8(e,n,r){if(e.length<r+1)throw new TypeError("Not enough space");if(n<0||n>255)throw new TypeError("Invalid uint8 value");e[r]=n}putUint16(e,n,r){if(e.length<r+2)throw new TypeError("Not enough space");if(n<0||n>65535)throw new TypeError("Invalid uint16 value");e[r]=n>>8,e[r+1]=n&255}putUint32(e,n,r){if(e.length<r+4)throw new TypeError("Not enough space");if(n<0||n>4294967295)throw new TypeError("Invalid uint32 value");for(let i=0;i<4;i++)e[r+i]=n>>(3-i)*8&255}putUint64(e,n,r){if(e.length<r+8)throw new TypeError("Not enough space");if(n<0||n>18446744073709551615n)throw new TypeError("Invalid uint64 value");for(let i=0;i<8;i++)e[r+i]=Number(n>>BigInt((7-i)*8)&0xffn)}}const Np=new Ow;function kt(t,e){return(t<<32-e|t>>>e)>>>0}function Bw(t){const e=new Tw;return e.update(t),e.digest()}class Tw{constructor(){te(this,"blockSize",64);te(this,"size",32);te(this,"blocks",new Uint8Array(64));te(this,"currentBlockSize",0);te(this,"H",new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]));te(this,"l",0n);te(this,"w",new Uint32Array(64))}update(e){if(this.l+=BigInt(e.byteLength)*8n,this.currentBlockSize+e.byteLength<64){this.blocks.set(e,this.currentBlockSize),this.currentBlockSize+=e.byteLength;return}let n=0;if(this.currentBlockSize>0){const r=e.slice(0,64-this.currentBlockSize);this.blocks.set(r,this.currentBlockSize),this.process(),n+=r.byteLength,this.currentBlockSize=0}for(;n+64<=e.byteLength;){const r=e.slice(n,n+64);this.blocks.set(r),this.process(),n+=64}if(e.byteLength-n>0){const r=e.slice(n);this.blocks.set(r),this.currentBlockSize=r.byteLength}}digest(){this.blocks[this.currentBlockSize]=128,this.currentBlockSize+=1,64-this.currentBlockSize<8&&(this.blocks.fill(0,this.currentBlockSize),this.process(),this.currentBlockSize=0),this.blocks.fill(0,this.currentBlockSize),Np.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Np.putUint32(e,this.H[n],n*4);return e}process(){for(let u=0;u<16;u++)this.w[u]=(this.blocks[u*4]<<24|this.blocks[u*4+1]<<16|this.blocks[u*4+2]<<8|this.blocks[u*4+3])>>>0;for(let u=16;u<64;u++){const p=(kt(this.w[u-2],17)^kt(this.w[u-2],19)^this.w[u-2]>>>10)>>>0,h=(kt(this.w[u-15],7)^kt(this.w[u-15],18)^this.w[u-15]>>>3)>>>0;this.w[u]=p+this.w[u-7]+h+this.w[u-16]|0}let e=this.H[0],n=this.H[1],r=this.H[2],i=this.H[3],s=this.H[4],a=this.H[5],c=this.H[6],l=this.H[7];for(let u=0;u<64;u++){const p=(kt(s,6)^kt(s,11)^kt(s,25))>>>0,h=(s&a^~s&c)>>>0,m=l+p+h+Pw[u]+this.w[u]|0,v=(kt(e,2)^kt(e,13)^kt(e,22))>>>0,f=(e&n^e&r^n&r)>>>0,_=v+f|0;l=c,c=a,a=s,s=i+m|0,i=r,r=n,n=e,e=m+_|0}this.H[0]=e+this.H[0]|0,this.H[1]=n+this.H[1]|0,this.H[2]=r+this.H[2]|0,this.H[3]=i+this.H[3]|0,this.H[4]=s+this.H[4]|0,this.H[5]=a+this.H[5]|0,this.H[6]=c+this.H[6]|0,this.H[7]=l+this.H[7]|0}}const Pw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);new BigUint64Array([0x428a2f98d728ae22n,0x7137449123ef65cdn,0xb5c0fbcfec4d3b2fn,0xe9b5dba58189dbbcn,0x3956c25bf348b538n,0x59f111f1b605d019n,0x923f82a4af194f9bn,0xab1c5ed5da6d8118n,0xd807aa98a3030242n,0x12835b0145706fben,0x243185be4ee4b28cn,0x550c7dc3d5ffb4e2n,0x72be5d74f27b896fn,0x80deb1fe3b1696b1n,0x9bdc06a725c71235n,0xc19bf174cf692694n,0xe49b69c19ef14ad2n,0xefbe4786384f25e3n,0x0fc19dc68b8cd5b5n,0x240ca1cc77ac9c65n,0x2de92c6f592b0275n,0x4a7484aa6ea6e483n,0x5cb0a9dcbd41fbd4n,0x76f988da831153b5n,0x983e5152ee66dfabn,0xa831c66d2db43210n,0xb00327c898fb213fn,0xbf597fc7beef0ee4n,0xc6e00bf33da88fc2n,0xd5a79147930aa725n,0x06ca6351e003826fn,0x142929670a0e6e70n,0x27b70a8546d22ffcn,0x2e1b21385c26c926n,0x4d2c6dfc5ac42aedn,0x53380d139d95b3dfn,0x650a73548baf63den,0x766a0abb3c77b2a8n,0x81c2c92e47edaee6n,0x92722c851482353bn,0xa2bfe8a14cf10364n,0xa81a664bbc423001n,0xc24b8b70d0f89791n,0xc76c51a30654be30n,0xd192e819d6ef5218n,0xd69906245565a910n,0xf40e35855771202an,0x106aa07032bbd1b8n,0x19a4c116b8d2d0c8n,0x1e376c085141ab53n,0x2748774cdf8eeb99n,0x34b0bcb5e19b48a8n,0x391c0cb3c5c95a63n,0x4ed8aa4ae3418acbn,0x5b9cca4f7763e373n,0x682e6ff3d6b2b8a3n,0x748f82ee5defb2fcn,0x78a5636f43172f60n,0x84c87814a1f0ab72n,0x8cc702081a6439ecn,0x90befffa23631e28n,0xa4506cebde82bde9n,0xbef9a3f7b2c67915n,0xc67178f2e372532bn,0xca273eceea26619cn,0xd186b8c721c0c207n,0xeada7dd6cde0eb1en,0xf57d4f7fee6ed178n,0x06f067aa72176fban,0x0a637dc5a2c898a6n,0x113f9804bef90daen,0x1b710b35131c471bn,0x28db77f523047d84n,0x32caab7b40c72493n,0x3c9ebe0a15c9bebcn,0x431d67c49c100d4cn,0x4cc5d4becb3e42b6n,0x597f299cfc657e2an,0x5fcb6fab3ad6faecn,0x6c44198c4a475817n]);class Rw{constructor(e){te(this,"data");this.data=e}tokenType(){if("token_type"in this.data&&typeof this.data.token_type=="string")return this.data.token_type;throw new Error("Missing or invalid 'token_type' field")}accessToken(){if("access_token"in this.data&&typeof this.data.access_token=="string")return this.data.access_token;throw new Error("Missing or invalid 'access_token' field")}accessTokenExpiresInSeconds(){if("expires_in"in this.data&&typeof this.data.expires_in=="number")return this.data.expires_in;throw new Error("Missing or invalid 'expires_in' field")}accessTokenExpiresAt(){return new Date(Date.now()+this.accessTokenExpiresInSeconds()*1e3)}hasRefreshToken(){return"refresh_token"in this.data&&typeof this.data.refresh_token=="string"}refreshToken(){if("refresh_token"in this.data&&typeof this.data.refresh_token=="string")return this.data.refresh_token;throw new Error("Missing or invalid 'refresh_token' field")}hasScopes(){return"scope"in this.data&&typeof this.data.scope=="string"}scopes(){if("scope"in this.data&&typeof this.data.scope=="string")return this.data.scope.split(" ");throw new Error("Missing or invalid 'scope' field")}idToken(){if("id_token"in this.data&&typeof this.data.id_token=="string")return this.data.id_token;throw new Error("Missing or invalid field 'id_token'")}}function Lw(t){const e=Bw(new TextEncoder().encode(t));return Pg(e)}function Uw(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Pg(t)}function Ur(t,e){const n=new TextEncoder().encode(e.toString()),r=new Request(t,{method:"POST",body:n});return r.headers.set("Content-Type","application/x-www-form-urlencoded"),r.headers.set("Accept","application/json"),r.headers.set("User-Agent","arctic"),r.headers.set("Content-Length",n.byteLength.toString()),r}function ha(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Cw(n)}async function Hs(t){let e;try{e=await fetch(t)}catch(n){throw new Ug(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);let r;try{r=Lg(n)}catch{throw new Gn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);return new Rw(n)}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}async function Vw(t){let e;try{e=await fetch(t)}catch(n){throw new Ug(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Gn(e.status,null)}if(typeof n!="object"||n===null)throw new Gn(e.status,n);let r;try{r=Lg(n)}catch{throw new Gn(e.status,n)}throw r}if(e.status===200){e.body!==null&&await e.body.cancel();return}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}function Lg(t){let e;if("error"in t&&typeof t.error=="string")e=t.error;else throw new Error("Invalid error response");let n=null,r=null,i=null;if("error_description"in t){if(typeof t.error_description!="string")throw new Error("Invalid data");n=t.error_description}if("error_uri"in t){if(typeof t.error_uri!="string")throw new Error("Invalid data");r=t.error_uri}if("state"in t){if(typeof t.state!="string")throw new Error("Invalid data");i=t.state}return new qw(e,n,r,i)}class Ug extends Error{constructor(e){super("Failed to send request",{cause:e})}}class qw extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);te(this,"code");te(this,"description");te(this,"uri");te(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Hi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class Gn extends Error{constructor(n,r){super("Unexpected error response body");te(this,"status");te(this,"data");this.status=n,this.data=r}}class nu{constructor(e,n,r){te(this,"clientId");te(this,"clientPassword");te(this,"redirectURI");this.clientId=e,this.clientPassword=n,this.redirectURI=r}createAuthorizationURL(e,n,r){const i=new URL(e);return i.searchParams.set("response_type","code"),i.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&i.searchParams.set("redirect_uri",this.redirectURI),i.searchParams.set("state",n),r.length>0&&i.searchParams.set("scope",r.join(" ")),i}createAuthorizationURLWithPKCE(e,n,r,i,s){const a=new URL(e);if(a.searchParams.set("response_type","code"),a.searchParams.set("client_id",this.clientId),this.redirectURI!==null&&a.searchParams.set("redirect_uri",this.redirectURI),a.searchParams.set("state",n),r===ti.S256){const c=Lw(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ti.Plain&&(a.searchParams.set("code_challenge_method","plain"),a.searchParams.set("code_challenge",i));return s.length>0&&a.searchParams.set("scope",s.join(" ")),a}async validateAuthorizationCode(e,n,r){const i=new URLSearchParams;i.set("grant_type","authorization_code"),i.set("code",n),this.redirectURI!==null&&i.set("redirect_uri",this.redirectURI),r!==null&&i.set("code_verifier",r),this.clientPassword===null&&i.set("client_id",this.clientId);const s=Ur(e,i);if(this.clientPassword!==null){const c=ha(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Hs(s)}async refreshAccessToken(e,n,r){const i=new URLSearchParams;i.set("grant_type","refresh_token"),i.set("refresh_token",n),this.clientPassword===null&&i.set("client_id",this.clientId),r.length>0&&i.set("scope",r.join(" "));const s=Ur(e,i);if(this.clientPassword!==null){const c=ha(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Hs(s)}async revokeToken(e,n){const r=new URLSearchParams;r.set("token",n),this.clientPassword===null&&r.set("client_id",this.clientId);const i=Ur(e,r);if(this.clientPassword!==null){const s=ha(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await Vw(i)}}var ti;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ti||(ti={}));var Cp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Cp||(Cp={}));var jp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(jp||(jp={}));function Vr(t){return Mw(t,Dw,Fs.None)}function Mw(t,e,n){let r="";for(let i=0;i<t.byteLength;i+=3){let s=0,a=0;for(let c=0;c<3&&i+c<t.byteLength;c++)s=s<<8|t[i+c],a+=8;for(let c=0;c<4;c++)a>=6?(r+=e[s>>a-6&63],a-=6):a>0?(r+=e[s<<6-a&63],a=0):n===Fs.Include&&(r+="=")}return r}const Dw="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Fs;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Fs||(Fs={}));var $p;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})($p||($p={}));function Hw(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function Fw(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const Kw="https://appleid.apple.com/auth/authorize",Ww="https://appleid.apple.com/auth/token";class Vg{constructor(e,n,r,i,s){te(this,"clientId");te(this,"teamId");te(this,"keyId");te(this,"pkcs8PrivateKey");te(this,"redirectURI");this.clientId=e,this.teamId=n,this.keyId=r,this.pkcs8PrivateKey=i,this.redirectURI=s}createAuthorizationURL(e,n){const r=new URL(Kw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId);const r=await this.createClientSecret();n.set("client_secret",r);const i=Ur(Ww,n);return await Hs(i)}async createClientSecret(){const e=await crypto.subtle.importKey("pkcs8",this.pkcs8PrivateKey,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]),n=Math.floor(Date.now()/1e3),r=JSON.stringify({typ:"JWT",alg:"ES256",kid:this.keyId}),i=JSON.stringify({iss:this.teamId,exp:n+5*60,aud:["https://appleid.apple.com"],sub:this.clientId,iat:n}),s=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,Fw(r,i)));return Hw(r,i,s)}}const Gw="https://www.facebook.com/v16.0/dialog/oauth",Jw="https://graph.facebook.com/v16.0/oauth/access_token";class qg{constructor(e,n,r){te(this,"clientId");te(this,"clientSecret");te(this,"redirectURI");this.clientId=e,this.clientSecret=n,this.redirectURI=r}createAuthorizationURL(e,n){const r=new URL(Gw);return r.searchParams.set("response_type","code"),r.searchParams.set("client_id",this.clientId),r.searchParams.set("state",e),n.length>0&&r.searchParams.set("scope",n.join(" ")),r.searchParams.set("redirect_uri",this.redirectURI),r}async validateAuthorizationCode(e){const n=new URLSearchParams;n.set("grant_type","authorization_code"),n.set("code",e),n.set("redirect_uri",this.redirectURI),n.set("client_id",this.clientId),n.set("client_secret",this.clientSecret);const r=Ur(Jw,n);return await Hs(r)}}const Zw="https://accounts.google.com/o/oauth2/v2/auth",Op="https://oauth2.googleapis.com/token",Yw="https://oauth2.googleapis.com/revoke";let Mg=class{constructor(e,n,r){te(this,"client");this.client=new nu(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(Zw,e,ti.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Op,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Op,e,[])}async revokeToken(e){await this.client.revokeToken(Yw,e)}};const Jo=o.z.object({iss:o.z.string().url(),sub:o.z.string(),aud:o.z.string(),exp:o.z.number(),email:o.z.string().optional(),given_name:o.z.string().optional(),family_name:o.z.string().optional(),name:o.z.string().optional(),iat:o.z.number(),auth_time:o.z.number().optional(),nonce:o.z.string().optional(),acr:o.z.string().optional(),amr:o.z.array(o.z.string()).optional(),azp:o.z.string().optional(),at_hash:o.z.string().optional(),c_hash:o.z.string().optional()}).passthrough();Jo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Xw(t){return t.ISSUER}function _t(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Dg(t){const{options:e}=t;if(!e||!e.client_id||!e.team_id||!e.kid||!e.app_secret)throw new Error("Missing required Apple authentication parameters");const n=Buffer.from(e.app_secret,"utf-8"),r=n.toString().replace(/-----BEGIN PRIVATE KEY-----|-----END PRIVATE KEY-----|\s/g,""),i=Uint8Array.from(Buffer.from(r,"base64"));return n.fill(0),{options:e,keyArray:i}}async function Qw(t,e){var l,u;const{options:n,keyArray:r}=Dg(e),i=new Vg(n.client_id,n.team_id,n.kid,r,`${je(t.env)}callback`),s=xe(),a=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((u=n.scope)==null?void 0:u.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&a.searchParams.set("response_mode","form_post"),{redirectUrl:a.href,code:s}}async function eb(t,e,n){const{options:r,keyArray:i}=Dg(e),a=await new Vg(r.client_id,r.team_id,r.kid,i,`${je(t.env)}callback`).validateAuthorizationCode(n),c=ol(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Jo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const tb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Qw,validateAuthorizationCodeAndGetUser:eb},Symbol.toStringTag,{value:"Module"}));async function nb(t,e){var a;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new qg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe();return{redirectUrl:r.createAuthorizationURL(i,((a=n.scope)==null?void 0:a.split(" "))||["email"]).href,code:i}}async function rb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new qg(r.client_id,r.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n),a=await fetch("https://graph.facebook.com/v16.0/me?fields=id,email,name",{headers:{Authorization:`Bearer ${s.accessToken()}`}});if(!a.ok)throw new Error("Failed to fetch user info");const c=await a.json();return t.set("log",`Userinfo: ${JSON.stringify(c)}`),{sub:c.id,email:c.email,name:c.name}}const ib=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:nb,validateAuthorizationCodeAndGetUser:rb},Symbol.toStringTag,{value:"Module"}));async function sb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Mg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe(),s=Uw();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function ob(t,e,n,r){const{options:i}=e;if(!(i!=null&&i.client_id)||!i.client_secret||!r)throw new Error("Missing required authentication parameters");const a=await new Mg(i.client_id,i.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n,r),c=ol(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Jo.parse(c.payload);return{sub:l.sub,email:l.email,given_name:l.given_name,family_name:l.family_name,name:l.name,picture:l.picture,locale:l.locale}}const ab=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:sb,validateAuthorizationCodeAndGetUser:ob},Symbol.toStringTag,{value:"Module"}));async function cb(t,e){var a;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required authentication parameters");const r=new nu(n.client_id,n.client_secret,`${je(t.env)}callback`),i=xe(),s=r.createAuthorizationURL("https://api.vipps.no/access-management-1.0/access/oauth2/auth",i,((a=n.scope)==null?void 0:a.split(" "))||["openid","email","phoneNumber","name","address","birthDate"]);return s.searchParams.set("response_type","code"),s.searchParams.set("response_mode","query"),{redirectUrl:s.href,code:i}}async function lb(t,e,n){const{options:r}=e;if(!(r!=null&&r.client_id)||!r.client_secret)throw new Error("Missing required authentication parameters");const s=await new nu(r.client_id,r.client_secret,`${je(t.env)}callback`).validateAuthorizationCode("https://api.vipps.no/access-management-1.0/access/oauth2/token",n,null),a=ol(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Jo.parse(a.payload);if(typeof c.msn!="string")throw new Error("msn not available in id token");const l=await fetch("https://api.vipps.no/vipps-userinfo-api/userinfo",{headers:{Authorization:`Bearer ${s.accessToken()}`,"Merchant-Serial-Number":c.msn}});if(!l.ok)throw new z(400,{message:"Failed to get user from vipps"});return await l.json()}const ub=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:cb,validateAuthorizationCodeAndGetUser:lb},Symbol.toStringTag,{value:"Module"}));function Hg(t,e){const n=t.env.STRATEGIES||{},i={apple:tb,facebook:ib,"google-oauth2":ab,vipps:ub,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Zo(t,e){const n=await t.data.clients.get(e);if(!n)throw new z(403,{message:"Client not found"});const r=t.DEFAULT_CLIENT_ID?await t.data.clients.get(t.DEFAULT_CLIENT_ID):void 0,i=await t.data.connections.list(n.tenant.id),s=t.DEFAULT_TENANT_ID?await t.data.connections.list(t.DEFAULT_TENANT_ID):{connections:[]},a=i.connections.map(c=>{var p;const l=(p=s.connections)==null?void 0:p.find(h=>h.name===c.name);return l!=null&&l.options?Ft.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${_t(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${_t(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Yo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return db(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function db(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function pb(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=ve(t,{type:he.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.loginSessions.get(e.tenant.id,r.state);s||(s=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:r,csrf_token:xe(),...sn(t.req)}));const c=await Hg(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+E_*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Bp(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.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new z(403,{message:"Session not found"});const a=await Zo(r,s.authParams.client_id);t.set("client_id",a.id),t.set("tenant_id",a.tenant.id);const c=a.connections.find(_=>_.id===i.connection_id);if(!c){const _=ve(t,{type:he.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(a.tenant.id,_),new z(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=ve(t,{type:he.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new z(403,{message:"Redirect URI not defined"})}if(!Yo(s.authParams.redirect_uri,a.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,w=ve(t,{type:he.FAILED_LOGIN,description:_});throw await r.data.logs.create(a.tenant.id,w),new z(403,{message:_})}const u=await Hg(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...h}=u;t.set("user_id",p);const m=((f=u.email)==null?void 0:f.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const v=await io(t,{client:a,email:m,provider:c.strategy,connection:c.name,userId:p,profileData:h,isSocial:!0,ip:t.req.header("x-real-ip")});return on(t,{client:a,authParams:s.authParams,loginSession:s,user:v})}async function Tp(t,e,n,r,i,s){const a=await t.env.data.codes.get(t.var.tenant_id||"",e,"oauth2_state");if(!a)throw new z(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.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=ve(t,{type:he.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});nt(t,t.env.data.logs.create(t.var.tenant_id,u));const p=new URL(l);return Nw(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${_t(t.env)}enter-email?state=${c.id}&error=${n}`)}const fb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.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:a}=t.req.valid("query");if(r)return Tp(t,e,r,i,s,a);if(!n)throw new z(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.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:a}=t.req.valid("form");if(r)return Tp(t,e,r,i,s,a);if(!n)throw new z(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}),hb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{query:o.z.object({client_id:o.z.string(),returnTo:o.z.string().optional()}),header:o.z.object({cookie:o.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(!Yo(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new z(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const l=cs(r.tenant.id,a);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=ve(t,{type:he.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":j_(r.tenant.id,t.req.header("host")),location:s}})}),Pp=o.z.object({sub:o.z.string(),email:o.z.string().optional(),family_name:o.z.string().optional(),given_name:o.z.string().optional(),email_verified:o.z.boolean()}),gb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Pp}},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(Pp.parse({...e,sub:e.user_id}))}),mb=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:ff}},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 tu(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return rl.parse({...a,kid:r.kid})}));return t.json({keys:n},{headers:{"access-control-allow-origin":"*","access-control-allow-method":"GET","cache-control":`public, max-age=${ji}, stale-while-revalidate=${ji*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ea}},description:"List of tenants"}}}),async t=>{const e=Ea.parse({issuer:Xw(t.env),authorization_endpoint:`${je(t.env)}authorize`,token_endpoint:`${je(t.env)}oauth/token`,device_authorization_endpoint:`${je(t.env)}oauth/device/code`,userinfo_endpoint:`${je(t.env)}userinfo`,mfa_challenge_endpoint:`${je(t.env)}mfa/challenge`,jwks_uri:`${je(t.env)}.well-known/jwks.json`,registration_endpoint:`${je(t.env)}oidc/register`,revocation_endpoint:`${je(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=${ji}, stale-while-revalidate=${ji*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 Fg=o.z.object({grant_type:o.z.literal("client_credentials"),scope:o.z.string().optional(),client_secret:o.z.string(),client_id:o.z.string(),audience:o.z.string().optional()});async function _b(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 to(t,{authParams:r,client:n});return t.json(i)}const yb=o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string().optional(),client_secret:o.z.string().optional(),code_verifier:o.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 vb(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.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new z(403,{message:"Invalid login"});if("client_secret"in e){const a=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Fi(n.client_secret,e.client_secret)&&!Fi(a==null?void 0:a.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 a=await k_(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(a,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:Yt.WEB_MESSAGE}})}const wb=o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),redirect_uri:o.z.string().optional(),refresh_token:o.z.string()});async function bb(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 a=new Date(Date.now()+2592e6);await t.env.data.refreshTokens.update(n.tenant.id,r.id,{idle_expires_at:a.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:Yt.WEB_MESSAGE}})}const Rp=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),kb=o.z.union([Fg.extend(Rp.shape),o.z.object({grant_type:o.z.literal("authorization_code"),client_id:o.z.string(),code:o.z.string(),redirect_uri:o.z.string(),code_verifier:o.z.string().min(43).max(128)}),o.z.object({grant_type:o.z.literal("authorization_code"),code:o.z.string(),redirect_uri:o.z.string().optional(),...Rp.shape}),o.z.object({grant_type:o.z.literal("refresh_token"),client_id:o.z.string(),refresh_token:o.z.string(),redirect_uri:o.z.string().optional()})]);function xb(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 Sb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:kb}}}},responses:{200:{content:{"application/json":{schema:vf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=xb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new z(400,{message:"client_id is required"});switch(t.set("client_id",r.client_id),e.grant_type){case Br.AuthorizationCode:return vb(t,yb.parse(r));case Br.ClientCredential:return _b(t,Fg.parse(r));case Br.RefreshToken:return bb(t,wb.parse(r));default:throw new z(400,{message:"Not implemented"})}});var ru={exports:{}};const iu=[{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}],Kg=(t,e=iu,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 a=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,a[0]),s};ru.exports={passwordStrength:Kg,defaultOptions:iu};var Ab=ru.exports.passwordStrength=Kg;ru.exports.defaultOptions=iu;function su(t){return Ab(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 Si(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 Wg(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=`${_t(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await Si(t,{to:e,subject:se("reset_password_title",a),html:`Click here to reset your password: ${_t(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:se("password_reset_title",a),resetPasswordEmailClickToReset:se("reset_password_email_click_to_reset",a),resetPasswordEmailReset:se("reset_password_email_reset",a),supportInfo:se("support_info",a),contactUs:se("contact_us",a),copyright:se("copyright",a)}})}async function Gg(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 Si(t,{to:e,subject:se("code_email_subject",i),html:`Click here to validate your email: ${_t(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:r.name,logo:r.logo||"",supportUrl:r.support_url||"",buttonColor:r.primary_color||"",welcomeToYourAccount:se("welcome_to_your_account",i),linkEmailClickToLogin:se("link_email_click_to_login",i),linkEmailLogin:se("link_email_login",i),linkEmailOrEnterCode:se("link_email_or_enter_code",i),codeValid30Mins:se("code_valid_30_minutes",i),supportInfo:se("support_info",i),contactUs:se("contact_us",i),copyright:se("copyright",i)}});const s=ve(t,{type:he.CODE_LINK_SENT,description:e});nt(t,t.env.data.logs.create(r.id,s))}async function ou(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(je(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 a={vendorName:i.name,code:n,lng:i.language||"en"};await Si(t,{to:e,subject:se("code_email_subject",a),html:`Click here to validate your email: ${_t(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:se("welcome_to_your_account",a),linkEmailClickToLogin:se("link_email_click_to_login",a),linkEmailLogin:se("link_email_login",a),linkEmailOrEnterCode:se("link_email_or_enter_code",a),codeValid30Mins:se("code_valid_30_minutes",a),supportInfo:se("support_info",a),contactUs:se("contact_us",a),copyright:se("copyright",a)}});const c=ve(t,{type:he.CODE_LINK_SENT,description:e});nt(t,t.env.data.logs.create(i.id,c))}async function au(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 Si(t,{to:e.email,subject:se("welcome_to_your_account",r),html:`Click here to validate your email: ${_t(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${_t(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:se("welcome_to_your_account",r),verifyEmailVerify:se("verify_email_verify",r),supportInfo:se("support_info",r),contactUs:se("contact_us",r),copyright:se("copyright",r)}})}async function Eb(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={vendorName:i.name,lng:i.language||"en"},a=`${_t(t.env)}signup?state=${r}&code=${n}`;await Si(t,{to:e,subject:se("register_password_account",s),html:`Click here to register: ${a}`,template:"auth-pre-signup-verification",data:{vendorName:i.name,logo:i.logo||"",signupUrl:a,setPassword:se("set_password",s),registerPasswordAccount:se("register_password_account",s),clickToSignUpDescription:se("click_to_sign_up_description",s),supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",welcomeToYourAccount:se("welcome_to_your_account",s),verifyEmailVerify:se("verify_email_verify",s),supportInfo:se("support_info",s),contactUs:se("contact_us",s),copyright:se("copyright",s)}})}const Ib=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.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),!su(n))throw new z(400,{message:"Password does not meet the requirements"});if(await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:e,provider:"auth2"}))throw new z(400,{message:"Invalid sign up"});const a=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${Xs()}`,email:e,email_verified:!1,provider:"auth2",connection:"Username-Password-Authentication",is_social:!1});t.set("user_id",a.user_id),t.set("username",a.email),t.set("connection",a.connection);const c=await si.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:a.user_id,password:c,algorithm:"bcrypt"}),await au(t,a);const l=ve(t,{type:he.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:a.user_id,email:a.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.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 ur({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},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:s,csrf_token:xe(),...sn(t.req)});return await Wg(t,e,a.id,a.authParams.state),t.html("If an account with that email exists, we've sent instructions to reset your password.")});function Tn(){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 cu(t,e,n,r,i,s,a){const{env:c}=t,l=await c.data.codes.get(e.tenant.id,i,"otp");if(!l)throw new z(400,{message:"Code not found or expired"});if(l.expires_at<new Date().toISOString())throw new z(400,{message:"Code expired"});if(l.used_at)throw new z(400,{message:"Code already used"});const u=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!u||u.authParams.username!==r)throw new z(400,{message:"Code not found or expired"});const p=sn(t.req);if(a&&u.ip!==p.ip)return t.redirect(`${_t(t.env)}invalid-session?state=${u.id}`);if(n.redirect_uri&&!Yo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new z(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const h=await io(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),on(t,{user:h,client:e,loginSession:u,authParams:n,ticketAuth:s})}const zb=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:tl.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:a}=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.loginSessions.create(c.tenant.id,{authParams:{...a,client_id:r,username:i},expires_at:new Date(Date.now()+Na).toISOString(),csrf_token:xe(),...sn(t.req)}),u=await n.data.codes.create(c.tenant.id,{code_id:Tn(),code_type:"otp",login_id:l.id,expires_at:new Date(Date.now()+Na).toISOString()});return s==="link"?await ou(t,i,u.code_id,{...a,client_id:r}):await Gg(t,i,u.code_id),t.html("OK")}).openapi(o.createRoute({tags:["passwordless"],method:"get",path:"/verify_redirect",request:{query:o.z.object({scope:o.z.string(),response_type:o.z.nativeEnum(Pt),redirect_uri:o.z.string(),state:o.z.string(),nonce:o.z.string().optional(),verification_code:o.z.string(),connection:o.z.string(),client_id:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),audience:o.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:a,scope:c,audience:l,response_type:u,nonce:p}=t.req.valid("query"),h=await Zo(e,n);return t.set("client_id",h.id),t.set("tenant_id",h.tenant.id),t.set("connection","email"),cu(t,h,{client_id:n,redirect_uri:s,state:a,nonce:p,scope:c,audience:l,response_type:u},r,i,!1,!0)});class Nr extends z{constructor(n,r){super(n,r);te(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function lu(t,e,n,r,i){const{env:s}=t,a=n.username;if(t.set("username",a),!a)throw new z(400,{message:"Username is required"});const c=await ur({userAdapter:t.env.data.users,tenant_id:e.tenant.id,email:a,provider:"auth2"});if(!c){const f=ve(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(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 Nr(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const u=await s.data.passwords.get(e.tenant.id,c.user_id);if(!(u&&await si.compare(n.password,u.password))){const f=ve(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(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===he.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(f.date)>new Date(Date.now()-1e3*60*5)).length>=3){const f=ve(t,{type:he.FAILED_LOGIN,description:"Too many failed login attempts"});throw nt(t,t.env.data.logs.create(e.tenant.id,f)),new Nr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await au(t,c);const f=ve(t,{type:he.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,f),new Nr(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const v=ve(t,{type:he.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return nt(t,t.env.data.logs.create(e.tenant.id,v)),on(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Nb(t,e,n,r){await io(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=Tn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Tn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");const a=await t.env.data.loginSessions.create(e.tenant.id,{expires_at:new Date(Date.now()+N_).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:xe(),...sn(t.req)}),c=await t.env.data.codes.create(e.tenant.id,{code_id:i,code_type:"password_reset",login_id:a.id,expires_at:new Date(Date.now()+z_).toISOString()});await Wg(t,n,c.code_id,r)}const Cb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),otp:o.z.string(),client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),realm:o.z.enum(["email"]),scope:o.z.string().optional()}),o.z.object({credential_type:o.z.literal("http://auth0.com/oauth/grant-type/password-realm"),client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string(),realm:o.z.enum(["Username-Password-Authentication"]),scope:o.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 cu(t,i,{client_id:n,username:s},s,e.otp,!0);if("password"in e){const a=await t.env.data.loginSessions.create(i.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:xe(),...sn(t.req)});return lu(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new z(400,{message:"Code or password required"})});function jb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=ga(t))==null?void 0:r.host)??null;if(!n)return!1;for(const a of e){let c;if(a.startsWith("http://")||a.startsWith("https://")?c=((i=ga(a))==null?void 0:i.host)??null:c=((s=ga("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function ga(t){try{return new URL(t)}catch{return null}}async function $b({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const a=await t.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+Jn*1e3).toISOString(),authParams:r,csrf_token:xe(),authorization_url:t.req.url,...sn(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:a,authParams:r,user:c,sessionId:e.id})}if(i==="email"&&s){const c=Tn();return await t.env.data.codes.create(n.tenant.id,{code_id:c,code_type:"otp",login_id:a.id,expires_at:new Date(Date.now()+Jn*1e3).toISOString()}),await ou(t,s,c,r),t.redirect(`/u/enter-code?state=${a.id}`)}return e?t.redirect(`/u/check-account?state=${a.id}`):t.redirect(`/u/enter-email?state=${a.id}`)}function Ob(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new z(403,{message:"Invalid realm"})}async function Bb(t,e,n,r,i){var m;const{env:s}=t;t.set("connection",i);const a=await s.data.codes.get(e,n,"ticket");if(!a||a.used_at)throw new z(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.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=Ob(i);let p=await io(t,{email:c.authParams.username,provider:u,client:l,connection:u==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email),t.set("user_id",p.user_id);const h=await Mf(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 Lp(t,e){return`<!DOCTYPE html>
|
|
150
150
|
<html>
|
|
151
151
|
|
|
152
152
|
<head>
|
|
@@ -219,7 +219,7 @@ PERFORMANCE OF THIS SOFTWARE.
|
|
|
219
219
|
${a?"invisible h-0":"visible h-auto"}
|
|
220
220
|
`,children:t}),a&&y("div",{className:"absolute left-0 top-0 flex h-full w-full items-center justify-center",children:y(f1,{size:"medium"})})]})},Pi=({connection:t,text:e,icon:n=null,canResize:r=!1,loginSession: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.id);const a=`/authorize?${s.toString()}`;return y(cr,{className:It("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:a,children:[n||"",y("div",{className:It("text-left text-black dark:text-white sm:text-base",{"hidden sm:inline short:hidden":r}),children:e})]})},h1=({...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"})]}),un=({children:t,className:e})=>y(fu,{children:[y(cr,{className:e,id:"initial-btn",children:t}),y(cr,{className:It(e,"hidden"),isLoading:!0,id:"loading-btn",disabled:!0,children:" "})]}),dn=({children:t,className:e})=>y("form",{id:"form",method:"post",className:e,children:t}),g1=({...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`})]}),Kp=({error:t,vendorSettings:e,loginSession:n,email:r,client:i,impersonation:s})=>{const a=i.connections.map(({name:m})=>m),c=a.includes("facebook"),l=a.includes("google-oauth2"),u=a.includes("apple"),p=a.includes("vipps"),h=c||l||u||p;return y(Je,{title:P.t("welcome"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("welcome")}),y("div",{className:"mb-8 text-gray-300",children:P.t("login_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"mb-7",children:[y("input",{type:"email",name:"username",placeholder:P.t("email_placeholder"),className:It("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:It("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(xr,{children:t}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("continue")}),y(Qe,{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:P.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:P.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:y(Qe,{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"}),loginSession:n}),l&&y(Pi,{connection:"google-oauth2",text:P.t("continue_with",{provider:"Google"}),canResize:!0,icon:y(h1,{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"}),loginSession:n}),u&&y(Pi,{connection:"apple",text:P.t("continue_with",{provider:"Apple"}),canResize:!0,icon:y(Qe,{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"}),loginSession:n}),p&&y(Pi,{connection:"vipps",text:P.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:y(g1,{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"}),loginSession:n})]})]})]})},m1=["Auth0.swift"];function _1(t){if(!t)return"code";const e=atob(t),n=JSON.parse(e);return m1.includes(n.name)?"code":"link"}const y1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:o.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,impersonation:n}=t.req.valid("query"),{vendorSettings:r,loginSession:i,client:s}=await Ie(t,e);return t.html(y(Kp,{vendorSettings:r,loginSession:i,client:s,email:i.authParams.username,impersonation:n==="true"}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({username:o.z.string().transform(t=>t.toLowerCase()),act_as:o.z.string().transform(t=>t.toLowerCase()).optional(),login_selection:o.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,loginSession:s,vendorSettings:a}=await Ie(t,n);t.set("client_id",i.id);const c=r.username,l=await ro({userAdapter:e.data.users,tenant_id:i.tenant.id,email:c});if(l&&t.set("user_id",l.user_id),!l)try{await cy(t,i,t.env.data,r.username)}catch{const v=ve(t,{type:he.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,v),t.html(y(Kp,{vendorSettings:a,loginSession:s,error:P.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.loginSessions.update(i.tenant.id,s.id,s),await r1(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=Tn(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=Tn(),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.id,expires_at:new Date(Date.now()+Na).toISOString()});return _1(s.auth0Client)==="link"&&!r.username.includes("online.no")?nt(t,ou(t,r.username,h.code_id,s.authParams)):nt(t,Gg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),zt=t=>y("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/enter-email?state=${t.state}`,children:P.t("go_back")});var ri="_hp",v1={Change:"Input",DoubleClick:"DblClick"},w1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Xc=new WeakMap,lr=void 0,b1=()=>lr,$t=t=>"t"in t,ya={onClick:["click",!1]},Wp=t=>{if(!t.startsWith("on"))return;if(ya[t])return ya[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return ya[t]=[(v1[n]||n).toLowerCase(),!!r]}},Gp=(t,e)=>lr&&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,k1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Ws(i);const a=Wp(i);if(a){if((n==null?void 0:n[i])!==s&&(n&&t.removeEventListener(a[0],n[i],a[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${i}" is not a function`);t.addEventListener(a[0],s,a[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),Xc.set(t,c)}else if(i==="style"){const c=t.style;typeof s=="string"?c.cssText=s:(c.cssText="",s!=null&&nm(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=Gp(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=Ws(i);const a=Wp(i);a?t.removeEventListener(a[0],s,a[1]):i==="ref"?(r=Xc.get(t))==null||r():t.removeAttribute(Gp(t,i))}}},x1=(t,e)=>{e[Ae][0]=0,ii.push([t,e]);const n=e.tag[uu]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{ii.pop()}},sm=(t,e,n,r,i)=>{var s,a;(s=t.vR)!=null&&s.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&((a=t[Ae][1][lm])==null||a.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(sm(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)})},S1=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}},om=t=>{var e,n,r,i,s,a;$t(t)||((n=(e=t[Ae])==null?void 0:e[1][lm])==null||n.forEach(c=>{var l;return(l=c[2])==null?void 0:l.call(c)}),(r=Xc.get(t.e))==null||r(),t.p===2&&((i=t.vC)==null||i.forEach(c=>c.p=2)),(s=t.vC)==null||s.forEach(om)),t.p||((a=t.e)==null||a.remove(),delete t.e),typeof t.tag=="function"&&($r.delete(t),Ji.delete(t),delete t[Ae][3],t.a=!0)},am=(t,e,n)=>{t.c=e,cm(t,e,n)},Jp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Zp=Symbol(),cm=(t,e,n)=>{var u;const r=[],i=[],s=[];sm(t,e,r,i,s),i.forEach(om);const a=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!a.length)c=0;else{const p=Jp(a,S1(t.nN));p!==void 0?(l=a[p],c=p):c=Jp(a,(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)),k1(v,m.props,m.pP),cm(m,v,f))}m.tag===ri?c--:n?v.parentNode||e.appendChild(v):a[c]!==v&&a[c-1]!==v&&(a[c+1]===v?e.appendChild(a[c]):e.insertBefore(v,l||a[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,Qc=(t,e,n)=>{var s,a,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"?x1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Zc]&&(i=n[0][Zc],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 _=A1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Yg]&&(ar.length>0&&(_[Ae][2]=ar.map(S=>[S,S.values.at(-1)])),(a=t[5])!=null&&a.length&&(_[Ae][3]=t[5].at(-1)));let w;if(h&&h.length){const S=h.findIndex($t(_)?C=>$t(C):_.key!==void 0?C=>C.key===_.key&&C.tag===_.tag:C=>C.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[Ae][2]=_[Ae][2]||[],w[Ae][3]=_[Ae][3],!w.f&&((w.o||w)===_.o||(l=(c=w.tag)[qb])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!$t(_)&&lr){const S=kr(lr);S&&(_.n=S)}if(!$t(_)&&!_.s&&(Qc(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===Zp){if(i)return;throw h}const[m,v,f]=((p=e[Ae])==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 C=Ji.get(f);if(C){const B=C.indexOf(_);if(B!==-1)return C.splice(B,1),_()}});if(S){if(t[0]===1)t[1]=!0;else if(Qc(t,f,[S]),(v.length===1||t!==m)&&f.c){am(f,f.c,!1);return}throw Zp}}throw h}finally{i&&t[5].pop()}},A1=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[Ae]=[0,[]];else{const e=w1[t.tag];e&&(lr||(lr=Qg("")),t.props.children=[{tag:lr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Yp=(t,e)=>{var n,r;(n=e[Ae][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Qc(t,e,void 0)}catch{return}if(e.a){delete e.a;return}(r=e[Ae][2])==null||r.forEach(([i])=>{i.values.pop()}),(t[0]!==1||!t[1])&&am(e,e.c,!1)},$r=new WeakMap,Xp=[],Zi=async(t,e)=>{t[5]||(t[5]=[]);const n=$r.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if($r.set(e,[r,()=>{t[2]?t[2](t,e,s=>{Yp(s,e)}).then(()=>r(e)):(Yp(t,e),r(e))}]),Xp.length)Xp.at(-1).add(e);else{await Promise.resolve();const s=$r.get(e);s&&($r.delete(e),s[1]())}return i},E1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),va=0,lm=1,wa=2,ba=3,ka=new WeakMap,um=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),I1=void 0,Qp=[],z1=t=>{var a;const e=()=>typeof t=="function"?t():t,n=ii.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=(a=r[Ae][1])[va]||(a[va]=[]),s=r[Ae][0]++;return i[s]||(i[s]=[e(),c=>{const l=I1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Qp.length){const[p,h]=Qp.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)}])},gu=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t;const[,r]=n,i=(c=r[Ae][1])[wa]||(c[wa]=[]),s=r[Ae][0]++,a=i[s];return um(a==null?void 0:a[1],e)?i[s]=[t,e]:t=i[s][0],t},N1=t=>{const e=ka.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ka.set(t,[n]),n=>ka.set(t,[void 0,n])),t},C1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Ae][1])[ba]||(c[ba]=[]),s=r[Ae][0]++,a=i[s];return um(a==null?void 0:a[1],e)&&(i[s]=[t(),e]),i[s][0]},j1=Qg({pending:!1,data:null,method:null,action:null}),ef=new Set,$1=t=>{ef.add(t),t.finally(()=>ef.delete(t))},mu=(t,e)=>C1(()=>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),zi=(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:a,onError:c,precedence:l,blocking:u,...p}=e,h=null,m=!1;const v=Ki[t];let f;if(v.length>0){const C=s.querySelectorAll(t);e:for(const B of C)for(const L of Ki[t])if(B.getAttribute(L)===e[L]){h=B;break e}if(!h){const B=v.reduce((L,Q)=>e[Q]===void 0?L:`${L}-${Q}-${e[Q]}`,t);m=!Ri[B],h=Ri[B]||(Ri[B]=(()=>{const L=document.createElement(t);for(const Q of v)e[Q]!==void 0&&L.setAttribute(Q,e[Q]),e.rel&&L.setAttribute("rel",e.rel);return L})())}}else f=s.querySelectorAll(t);l=r?l??"":void 0,r&&(p[Wi]=l);const _=gu(C=>{if(v.length>0){let B=!1;for(const L of s.querySelectorAll(t)){if(B&&L.getAttribute(Wi)!==l){s.insertBefore(C,L);return}L.getAttribute(Wi)===l&&(B=!0)}s.appendChild(C)}else if(f){let B=!1;for(const L of f)if(L===C){B=!0;break}B||s.insertBefore(C,s.contains(f[0])?f[0]:s.querySelector(t)),f=void 0}},[l]),w=mu(e.ref,C=>{var Q;const B=v[0];if(n===2&&(C.innerHTML=""),(m||f)&&_(C),!c&&!a)return;let L=Mn[Q=C.getAttribute(B)]||(Mn[Q]=new Promise((ce,le)=>{C.addEventListener("load",ce),C.addEventListener("error",le)}));a&&(L=L.then(a)),c&&(L=L.catch(c)),L.catch(()=>{})});if(i&&u==="render"){const C=Ki[t][0];if(e[C]){const B=e[C],L=Mn[B]||(Mn[B]=new Promise((Q,ce)=>{_(h),h.addEventListener("load",Q),h.addEventListener("error",ce)}));N1(L)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),E1(S,s)},O1=t=>{const e=b1(),n=e&&kr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:zi("title",t,void 0,!1,!1)},B1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:zi("script",t,1,!1,!0),T1=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,zi("style",t,2,!0,!0)),P1=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}:zi("link",t,1,"precedence"in t,!0),R1=t=>zi("meta",t,void 0,!1,!1),dm=Symbol(),L1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=z1([null,!1]),s=gu(async u=>{const p=u.isTrusted?e:u.detail[dm];if(typeof p!="function")return;u.preventDefault();const h=new FormData(u.target);i([h,!0]);const m=p(h);m instanceof Promise&&($1(m),await m),i([null,!0])},[]),a=mu(t.ref,u=>(u.addEventListener("submit",s),()=>{u.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:j1,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:a},type:"form",ref:a}},f:l}},pm=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=gu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[dm]:e}}))},[]);n.ref=mu(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},U1=t=>pm("input",t),V1=t=>pm("button",t);Object.assign(Yc,{title:O1,script:B1,style:T1,link:P1,meta:R1,form:L1,input:U1,button:V1});new TextEncoder;const _u=t=>{const{i18nKey:e,values:n,components:r}=t,i=P.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,a=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,u,p]=l,h=i.substring(c,l.index);h&&a.push(h);const m=parseInt(u,10);a.push(n1(r[m],{},p)),c=s.lastIndex}return c<i.length&&a.push(i.substring(c)),y(fu,{children:a})},tf=6,nf=({error:t,vendorSettings:e,email:n,state:r,client:i,hasPasswordLogin:s})=>{const a=new URLSearchParams({state:r}),l=i.connections.map(({name:u})=>u).includes("auth2");return y(Je,{title:P.t("verify_your_email"),vendorSettings:e,children:[y("div",{className:"mb-4 text-2xl font-medium",children:P.t("verify_your_email")}),y("div",{className:"mb-8 text-gray-300",children:y(_u,{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(dn,{className:"pt-2",children:[y("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:tf,inputMode:"numeric",name:"code",placeholder:"******",className:It("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:tf,required:!0,id:"code-input"}),t&&y(xr,{children:t}),y("div",{className:"text-center sm:mt-2",children:y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("login")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.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:P.t("or")})]}),y(cr,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${a.toString()}`,variant:"secondary",className:"block",children:P.t("enter_your_password_btn")})]})]}),y(zt,{state:r})]})]})},q1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,loginSession:r,client:i}=await Ie(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(nf,{vendorSettings:n,email:r.authParams.username,state:e,client:i,hasPasswordLogin:!!s}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{code:n}=t.req.valid("form"),{loginSession:r,client:i,vendorSettings:s}=await Ie(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 cu(t,i,r.authParams,r.authParams.username,n)}catch(a){const c=a,l=await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(nf,{vendorSettings:s,email:r.authParams.username,state:e,client:i,error:c.message,hasPasswordLogin:!!l}),400)}}),M1=t=>{const{vendorSettings:e,state:n}=t;return y(Je,{title:P.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:P.t("unverified_email")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]}),y(zt,{state:n})]}),y(zt,{state:n})]})},xa=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return y(Je,{title:P.t("enter_password"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("enter_password")}),y("div",{className:"mb-6 text-gray-300",children:P.t("enter_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"mb-7",children:[y("input",{type:"text",name:"username",placeholder:P.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:P.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(xr,{children:e}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("login")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})]}),y("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:P.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:P.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(cr,{variant:"secondary",className:"block",children:P.t("enter_a_code_btn")})]})]}),y(zt,{state:i})]})]})},D1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:i}=await Ie(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(xa,{vendorSettings:n,email:i.authParams.username,state:e,client:r}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.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,loginSession:a}=await Ie(t,e),{username:c}=a.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await lu(t,s,{...a.authParams,password:r},a)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(y(xa,{vendorSettings:i,email:c,error:P.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(y(M1,{vendorSettings:i,state:e}),400):t.html(y(xa,{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(Je,{title:P.t("create_account_title"),vendorSettings:r,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("create_account_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("create_account_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{children:[y("input",{type:"hidden",name:"code",value:s}),y("input",{type:"email",name:"username",placeholder:P.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:P.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:P.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(xr,{children:n}),y(un,{className:"text-base sm:mt-2 md:text-base",children:P.t("continue")})]}),y(zt,{state:e})]})]})},yu=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return y(Je,{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(zt,{state:i}):""]})},H1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.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,loginSession:i}=await Ie(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(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string(),code:o.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,loginSession:a}=await Ie(t,e),c="Username-Password-Authentication";t.set("client_id",s.id),t.set("connection",c);const l=a.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:P.t("create_account_passwords_didnt_match"),email:a.authParams.username}),400);if(!su(n.password))return t.html(y(Cr,{state:e,code:n.code,vendorSettings:i,error:P.t("create_account_weak_password"),email:a.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.loginSessions.get(s.tenant.id,u.login_id):void 0;try{if(await ur({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 Df(t).users.create(s.tenant.id,{user_id:`auth2|${Xs()}`,email:l,email_verified:m,provider:"auth2",connection:c,is_social:!1});return await r.data.passwords.create(s.tenant.id,{user_id:v.user_id,password:await si.hash(n.password,10),algorithm:"bcrypt"}),m?await lu(t,s,{...a.authParams,password:n.password},a):(await au(t,v),t.html(y(yu,{message:P.t("validate_email_body"),pageTitle:P.t("validate_email_title"),vendorSettings:i,state:e})))}catch(h){const m=await hu(r,s.id,a.authParams.vendor_id),v=h;return t.html(y(Cr,{state:e,vendorSettings:m,error:v.message,email:l}),400)}}),jr=t=>{const{error:e,vendorSettings:n,email:r}=t;return y(Je,{title:P.t("reset_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("reset_password_title")}),y("div",{className:"mb-6 text-gray-300",children:`${P.t("reset_password_description")} ${r}`}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(dn,{children:[y("input",{type:"password",name:"password",placeholder:P.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:P.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(xr,{children:e}),y(un,{className:"text-base sm:mt-2 md:text-base",children:P.t("reset_password_cta")})]})})]})},F1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.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,loginSession:r}=await Ie(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(jr,{vendorSettings:n,email:r.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.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:a,client:c,loginSession:l}=await Ie(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(y(jr,{error:P.t("create_account_passwords_didnt_match"),vendorSettings:a,email:l.authParams.username}),400);if(!su(r))return t.html(y(jr,{error:P.t("create_account_weak_password"),vendorSettings:a,email:l.authParams.username}),400);const u=await ur({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(jr,{error:"Code not found or expired",vendorSettings:a,email:l.authParams.username}),400);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(jr,{error:"The password could not be reset",vendorSettings:a,email:l.authParams.username}),400)}return t.html(y(yu,{message:P.t("password_has_been_reset"),vendorSettings:a,state:e}))}),K1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return y(Je,{title:P.t("forgot_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("forgot_password_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("forgot_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"pt-2",children:[y("input",{type:"email",name:"username",placeholder:P.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(xr,{children:e}),y(un,{className:"sm:mt-4",children:P.t("forgot_password_cta")})]}),y(zt,{state:i})]})]})},W1=t=>{const{vendorSettings:e,state:n}=t;return y(Je,{title:"Login",vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{children:P.t("forgot_password_email_sent")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]})]}),y(zt,{state:n})]})},G1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e);return t.html(y(K1,{vendorSettings:n,state:e,email:r.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.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,loginSession:i}=await Ie(t,e);return await Nb(t,r,i.authParams.username,i.id),t.html(y(W1,{vendorSettings:n,state:e}))}),J1=({vendorSettings:t,state:e,user:n})=>y(Je,{title:se("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(_u,{i18nKey:"currently_logged_in_as",components:[y("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:n.email}}),y("br",{}),se("continue_with_sso_provider_headline")]}),y("div",{className:"space-y-6",children:[y(dn,{children:y(un,{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:P.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:P.t("no_use_another")})]})]})}),Z1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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 Ie(t,n),s=cs(i.tenant.id,t.req.header("cookie")),a=s?await e.data.sessions.get(i.tenant.id,s):null;if(!a)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,a.user_id);return c?t.html(y(J1,{vendorSettings:r,state:n,user:c})):t.redirect(`/u/enter-email?state=${n}`)}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.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"),{loginSession:r,client:i}=await Ie(t,n),s=cs(i.tenant.id,t.req.header("cookie")),a=s?await e.data.sessions.get(i.tenant.id,s):null;if(!a)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,a.user_id);return c?on(t,{user:c,authParams:r.authParams,client:i,loginSession:r}):t.redirect(`/u/enter-email?state=${n}`)}),Y1=t=>{const{vendorSettings:e,email:n,state:r}=t;return y(Je,{title:P.t("create_password_account_title"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("create_password_account_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("enter_email_for_verification_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(dn,{className:"pt-2",children:[y("input",{type:"email",name:"username",placeholder:P.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:n,disabled:!0}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:y("span",{children:P.t("send")})})})]})}),y(zt,{state:r})]})},X1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e),{username:i}=r.authParams;if(!i)throw new z(400,{message:"Username required"});return t.html(y(Y1,{state:e,vendorSettings:n,email:i}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{loginSession:n,client:r}=await Ie(t,e),{username:i}=n.authParams;if(!i)throw new z(400,{message:"Username required"});const s=await t.env.data.codes.create(r.tenant.id,{code_id:Tn(),code_type:"email_verification",login_id:n.id,expires_at:new Date(Date.now()+S_).toISOString()});return await Eb(t,i,s.code_id,n.authParams.state||""),t.redirect(`/u/pre-signup-sent?state=${e}`)}),Q1=t=>{const{redirectUrl:e,vendorSettings:n}=t;return y(Je,{title:P.t("invalid_session_title"),vendorSettings:n,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:P.t("invalid_session_body")}),y("div",{className:"flex flex-1 flex-col justify-center",children:e&&y("a",{className:"block text-primary hover:text-primaryHover text-center",href:e,children:P.t("go_back")})})]})},ek=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,loginSession:r}=await Ie(t,e);let i;return r.authParams.redirect_uri&&r.authParams.state&&(i=new URL(r.authParams.redirect_uri),i.searchParams.set("state",r.authParams.state),i.searchParams.set("error","invalid_session"),i.searchParams.set("error_description",r.authParams.username||"")),t.html(y(Q1,{redirectUrl:i==null?void 0:i.href,vendorSettings:n}))}),tk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const e=await hu(t.env),{state:n}=t.req.valid("query");return t.html(y(yu,{message:"Not implemented",pageTitle:"User info",vendorSettings:e,state:n}))}),nk=({vendorSettings:t,state:e})=>{const n=new URLSearchParams({state:e});return y(Je,{title:P.t("email_validated"),vendorSettings:t,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("email_validated")}),y("div",{className:"flex flex-1 flex-col justify-center mb-7",children:y(cr,{Component:"a",href:`/u/enter-password?${n}`,className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("email_validated_cta")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})})]})},rk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{var m;const{state:e,code:n}=t.req.valid("query"),{env:r}=t,{client:i,loginSession:s,vendorSettings:a}=await Ie(t,e),c=s.authParams.username;if(!c)throw new z(400,{message:"Username not found in state"});const l=await ur({userAdapter:r.data.users,tenant_id:i.tenant.id,email:c,provider:"auth2"});if(!l)throw new z(500,{message:"No user found"});if(!await r.data.codes.get(i.tenant.id,n,"email_verification"))throw new z(400,{message:"Code not found or expired"});await r.data.users.update(i.tenant.id,l.user_id,{email_verified:!0});const h=(await pl(r.data.users,i.tenant.id,c)).filter(v=>v.provider!=="auth2");if(h.length>0){const v=h.filter(f=>!f.linked_to);v.length>1&&console.error("More than one primary user found for email",c),v.length===0&&console.error("No primary user found for email",c),v.length===1&&await r.data.users.update(i.tenant.id,l.user_id,{linked_to:(m=v[0])==null?void 0:m.user_id})}return t.html(y(nk,{vendorSettings:a,state:e}))}),ik=t=>{const{vendorSettings:e,email:n,state:r}=t;return y(Je,{title:P.t("email_verification_for_signup_sent_title"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("email_verification_for_signup_sent_title")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{className:"mb-6 text-gray-300",children:y(_u,{i18nKey:"email_verification_for_signup_sent_description",components:[y("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]})]}),y(zt,{state:r})]})},sk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e),{username:i}=r.authParams;if(!i)throw new z(400,{message:"Username required"});return t.html(y(ik,{vendorSettings:n,state:e,email:i}))});function ok(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>(r.env.data=no(r,t.dataAdapter),i()));const n=e.route("/info",tk).route("/check-account",Z1).route("/enter-email",y1).route("/enter-code",q1).route("/enter-password",D1).route("/invalid-session",ek).route("/pre-signup",X1).route("/pre-signup-sent",sk).route("/reset-password",F1).route("/forgot-password",G1).route("/validate-email",rk).route("/signup",H1);return n.doc("/u/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Universal login"}}),n}const ak="Account detected",ck="We have detected that you have already created an account through",lk="By signing in, you agree to our",uk="and",dk="Callback URL mismatch",pk="The provided redirect_uri is not in the list of allowed callback URLs.",fk="continue with user",hk="Please click the button to create a new password account.",gk="Enter the code at {{vendorName}} to complete the login",mk="Welcome to {{vendorName}}! {{code}} is the login code",_k="Welcome to {{vendorName}}! {{code}} is the login code",yk="The code is valid for 30 minutes",vk="Confirm password",wk="Need Help?",bk="Contact us",kk="or continue with social account",xk="Continue with {{provider}}",Sk="Would you like to continue with your existing account?",Ak="Copyright © 2023 SESAMY. All rights reserved.",Ek="©2023 Sesamy",Ik="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",zk="Please enter a valid email address.",Nk="The passwords didn't match. Try again.",Ck="Choose password",jk="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",$k="Create new account",Ok="Sign up with password",Bk="You are currently logged in as <0>{{email}}</0>",Tk="Email",Pk="Email address",Rk="Your email address has been validated",Lk="Now enter your password to login again",Uk="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.",Vk="Email verification sent",qk="Enter a code",Mk="We'll send you a verification link to ensure you own this email address.",Dk="Enter new password",Hk="Enter password",Fk="Enter your email address and password to login.",Kk="Enter your password",Wk="The magic link has expired. Please click on the button below to receive a new link in your inbox.",Gk="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",Jk="Send password reset email",Zk="Click the button below and we’ll send instructions on how to reset your password.",Yk="Password reset email sent",Xk="Forgot password?",Qk="Forgot password?",ex="Go back",tx="Invalid password",nx=`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`})]}),Kp=({error:t,vendorSettings:e,loginSession:n,email:r,client:i,impersonation:s})=>{const a=i.connections.map(({name:m})=>m),c=a.includes("facebook"),l=a.includes("google-oauth2"),u=a.includes("apple"),p=a.includes("vipps"),h=c||l||u||p;return y(Je,{title:P.t("welcome"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("welcome")}),y("div",{className:"mb-8 text-gray-300",children:P.t("login_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"mb-7",children:[y("input",{type:"email",name:"username",placeholder:P.t("email_placeholder"),className:It("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:It("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(xr,{children:t}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("continue")}),y(Qe,{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:P.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:P.t("continue_with",{provider:"Facebook"}),canResize:!0,icon:y(Qe,{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"}),loginSession:n}),l&&y(Pi,{connection:"google-oauth2",text:P.t("continue_with",{provider:"Google"}),canResize:!0,icon:y(h1,{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"}),loginSession:n}),u&&y(Pi,{connection:"apple",text:P.t("continue_with",{provider:"Apple"}),canResize:!0,icon:y(Qe,{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"}),loginSession:n}),p&&y(Pi,{connection:"vipps",text:P.t("continue_with",{provider:"Vipps"}),canResize:!0,icon:y(g1,{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"}),loginSession:n})]})]})]})},m1=["Auth0.swift"];function _1(t){if(!t)return"code";const e=atob(t),n=JSON.parse(e);return m1.includes(n.name)?"code":"link"}const y1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),impersonation:o.z.string().optional()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e,impersonation:n}=t.req.valid("query"),{vendorSettings:r,loginSession:i,client:s}=await Ie(t,e);return t.html(y(Kp,{vendorSettings:r,loginSession:i,client:s,email:i.authParams.username,impersonation:n==="true"}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({username:o.z.string().transform(t=>t.toLowerCase()),act_as:o.z.string().transform(t=>t.toLowerCase()).optional(),login_selection:o.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,loginSession:s,vendorSettings:a}=await Ie(t,n);t.set("client_id",i.id);const c=r.username,l=await ro({userAdapter:e.data.users,tenant_id:i.tenant.id,email:c});if(l&&t.set("user_id",l.user_id),!l)try{await cy(t,i,t.env.data,r.username)}catch{const v=ve(t,{type:he.FAILED_SIGNUP,description:"Public signup is disabled"});return await t.env.data.logs.create(i.tenant.id,v),t.html(y(Kp,{vendorSettings:a,loginSession:s,error:P.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.loginSessions.update(i.tenant.id,s.id,s),await r1(t,i,r.username,r.login_selection))return t.redirect(`/u/enter-password?state=${n}`);let u=Tn(),p=await e.data.codes.get(i.tenant.id,u,"otp");for(;p;)u=Tn(),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.id,expires_at:new Date(Date.now()+Na).toISOString()});return _1(s.auth0Client)==="link"&&!r.username.includes("online.no")?nt(t,ou(t,r.username,h.code_id,s.authParams)):nt(t,Gg(t,r.username,h.code_id)),t.redirect(`/u/enter-code?state=${n}`)}),zt=t=>y("a",{className:"block text-primary hover:text-primaryHover text-center",href:`/u/enter-email?state=${t.state}`,children:P.t("go_back")});var ri="_hp",v1={Change:"Input",DoubleClick:"DblClick"},w1={svg:"2000/svg",math:"1998/Math/MathML"},ii=[],Xc=new WeakMap,lr=void 0,b1=()=>lr,$t=t=>"t"in t,ya={onClick:["click",!1]},Wp=t=>{if(!t.startsWith("on"))return;if(ya[t])return ya[t];const e=t.match(/^on([A-Z][a-zA-Z]+?(?:PointerCapture)?)(Capture)?$/);if(e){const[,n,r]=e;return ya[t]=[(v1[n]||n).toLowerCase(),!!r]}},Gp=(t,e)=>lr&&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,k1=(t,e,n)=>{var r;e||(e={});for(let i in e){const s=e[i];if(i!=="children"&&(!n||n[i]!==s)){i=Ws(i);const a=Wp(i);if(a){if((n==null?void 0:n[i])!==s&&(n&&t.removeEventListener(a[0],n[i],a[1]),s!=null)){if(typeof s!="function")throw new Error(`Event handler for "${i}" is not a function`);t.addEventListener(a[0],s,a[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),Xc.set(t,c)}else if(i==="style"){const c=t.style;typeof s=="string"?c.cssText=s:(c.cssText="",s!=null&&nm(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=Gp(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=Ws(i);const a=Wp(i);a?t.removeEventListener(a[0],s,a[1]):i==="ref"?(r=Xc.get(t))==null||r():t.removeAttribute(Gp(t,i))}}},x1=(t,e)=>{e[Ae][0]=0,ii.push([t,e]);const n=e.tag[uu]||e.tag,r=n.defaultProps?{...n.defaultProps,...e.props}:e.props;try{return[n.call(null,r)]}finally{ii.pop()}},sm=(t,e,n,r,i)=>{var s,a;(s=t.vR)!=null&&s.length&&(r.push(...t.vR),delete t.vR),typeof t.tag=="function"&&((a=t[Ae][1][lm])==null||a.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(sm(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)})},S1=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}},om=t=>{var e,n,r,i,s,a;$t(t)||((n=(e=t[Ae])==null?void 0:e[1][lm])==null||n.forEach(c=>{var l;return(l=c[2])==null?void 0:l.call(c)}),(r=Xc.get(t.e))==null||r(),t.p===2&&((i=t.vC)==null||i.forEach(c=>c.p=2)),(s=t.vC)==null||s.forEach(om)),t.p||((a=t.e)==null||a.remove(),delete t.e),typeof t.tag=="function"&&($r.delete(t),Ji.delete(t),delete t[Ae][3],t.a=!0)},am=(t,e,n)=>{t.c=e,cm(t,e,n)},Jp=(t,e)=>{if(e){for(let n=0,r=t.length;n<r;n++)if(t[n]===e)return n}},Zp=Symbol(),cm=(t,e,n)=>{var u;const r=[],i=[],s=[];sm(t,e,r,i,s),i.forEach(om);const a=n?void 0:e.childNodes;let c,l=null;if(n)c=-1;else if(!a.length)c=0;else{const p=Jp(a,S1(t.nN));p!==void 0?(l=a[p],c=p):c=Jp(a,(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)),k1(v,m.props,m.pP),cm(m,v,f))}m.tag===ri?c--:n?v.parentNode||e.appendChild(v):a[c]!==v&&a[c-1]!==v&&(a[c+1]===v?e.appendChild(a[c]):e.insertBefore(v,l||a[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,Qc=(t,e,n)=>{var s,a,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"?x1(t,e):Ai(e.props.children)),((s=n[0])==null?void 0:s.tag)===""&&n[0][Zc]&&(i=n[0][Zc],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 _=A1(n[f]);if(_){typeof _.tag=="function"&&!_.tag[Yg]&&(ar.length>0&&(_[Ae][2]=ar.map(S=>[S,S.values.at(-1)])),(a=t[5])!=null&&a.length&&(_[Ae][3]=t[5].at(-1)));let w;if(h&&h.length){const S=h.findIndex($t(_)?C=>$t(C):_.key!==void 0?C=>C.key===_.key&&C.tag===_.tag:C=>C.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[Ae][2]=_[Ae][2]||[],w[Ae][3]=_[Ae][3],!w.f&&((w.o||w)===_.o||(l=(c=w.tag)[qb])!=null&&l.call(c,S,w.props))&&(w.s=!0)),_=w}else if(!$t(_)&&lr){const S=kr(lr);S&&(_.n=S)}if(!$t(_)&&!_.s&&(Qc(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===Zp){if(i)return;throw h}const[m,v,f]=((p=e[Ae])==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 C=Ji.get(f);if(C){const B=C.indexOf(_);if(B!==-1)return C.splice(B,1),_()}});if(S){if(t[0]===1)t[1]=!0;else if(Qc(t,f,[S]),(v.length===1||t!==m)&&f.c){am(f,f.c,!1);return}throw Zp}}throw h}finally{i&&t[5].pop()}},A1=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[Ae]=[0,[]];else{const e=w1[t.tag];e&&(lr||(lr=Qg("")),t.props.children=[{tag:lr,props:{value:t.n=`http://www.w3.org/${e}`,children:t.props.children}}])}return t}},Yp=(t,e)=>{var n,r;(n=e[Ae][2])==null||n.forEach(([i,s])=>{i.values.push(s)});try{Qc(t,e,void 0)}catch{return}if(e.a){delete e.a;return}(r=e[Ae][2])==null||r.forEach(([i])=>{i.values.pop()}),(t[0]!==1||!t[1])&&am(e,e.c,!1)},$r=new WeakMap,Xp=[],Zi=async(t,e)=>{t[5]||(t[5]=[]);const n=$r.get(e);n&&n[0](void 0);let r;const i=new Promise(s=>r=s);if($r.set(e,[r,()=>{t[2]?t[2](t,e,s=>{Yp(s,e)}).then(()=>r(e)):(Yp(t,e),r(e))}]),Xp.length)Xp.at(-1).add(e);else{await Promise.resolve();const s=$r.get(e);s&&($r.delete(e),s[1]())}return i},E1=(t,e,n)=>({tag:ri,props:{children:t},key:n,e,p:1}),va=0,lm=1,wa=2,ba=3,ka=new WeakMap,um=(t,e)=>!t||!e||t.length!==e.length||e.some((n,r)=>n!==t[r]),I1=void 0,Qp=[],z1=t=>{var a;const e=()=>typeof t=="function"?t():t,n=ii.at(-1);if(!n)return[e(),()=>{}];const[,r]=n,i=(a=r[Ae][1])[va]||(a[va]=[]),s=r[Ae][0]++;return i[s]||(i[s]=[e(),c=>{const l=I1,u=i[s];if(typeof c=="function"&&(c=c(u[0])),!Object.is(c,u[0]))if(u[0]=c,Qp.length){const[p,h]=Qp.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)}])},gu=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t;const[,r]=n,i=(c=r[Ae][1])[wa]||(c[wa]=[]),s=r[Ae][0]++,a=i[s];return um(a==null?void 0:a[1],e)?i[s]=[t,e]:t=i[s][0],t},N1=t=>{const e=ka.get(t);if(e){if(e.length===2)throw e[1];return e[0]}throw t.then(n=>ka.set(t,[n]),n=>ka.set(t,[void 0,n])),t},C1=(t,e)=>{var c;const n=ii.at(-1);if(!n)return t();const[,r]=n,i=(c=r[Ae][1])[ba]||(c[ba]=[]),s=r[Ae][0]++,a=i[s];return um(a==null?void 0:a[1],e)&&(i[s]=[t(),e]),i[s][0]},j1=Qg({pending:!1,data:null,method:null,action:null}),ef=new Set,$1=t=>{ef.add(t),t.finally(()=>ef.delete(t))},mu=(t,e)=>C1(()=>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),zi=(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:a,onError:c,precedence:l,blocking:u,...p}=e,h=null,m=!1;const v=Ki[t];let f;if(v.length>0){const C=s.querySelectorAll(t);e:for(const B of C)for(const L of Ki[t])if(B.getAttribute(L)===e[L]){h=B;break e}if(!h){const B=v.reduce((L,Q)=>e[Q]===void 0?L:`${L}-${Q}-${e[Q]}`,t);m=!Ri[B],h=Ri[B]||(Ri[B]=(()=>{const L=document.createElement(t);for(const Q of v)e[Q]!==void 0&&L.setAttribute(Q,e[Q]),e.rel&&L.setAttribute("rel",e.rel);return L})())}}else f=s.querySelectorAll(t);l=r?l??"":void 0,r&&(p[Wi]=l);const _=gu(C=>{if(v.length>0){let B=!1;for(const L of s.querySelectorAll(t)){if(B&&L.getAttribute(Wi)!==l){s.insertBefore(C,L);return}L.getAttribute(Wi)===l&&(B=!0)}s.appendChild(C)}else if(f){let B=!1;for(const L of f)if(L===C){B=!0;break}B||s.insertBefore(C,s.contains(f[0])?f[0]:s.querySelector(t)),f=void 0}},[l]),w=mu(e.ref,C=>{var Q;const B=v[0];if(n===2&&(C.innerHTML=""),(m||f)&&_(C),!c&&!a)return;let L=Mn[Q=C.getAttribute(B)]||(Mn[Q]=new Promise((ce,le)=>{C.addEventListener("load",ce),C.addEventListener("error",le)}));a&&(L=L.then(a)),c&&(L=L.catch(c)),L.catch(()=>{})});if(i&&u==="render"){const C=Ki[t][0];if(e[C]){const B=e[C],L=Mn[B]||(Mn[B]=new Promise((Q,ce)=>{_(h),h.addEventListener("load",Q),h.addEventListener("error",ce)}));N1(L)}}const S={tag:t,type:t,props:{...p,ref:w},ref:w};return S.p=n,h&&(S.e=h),E1(S,s)},O1=t=>{const e=b1(),n=e&&kr(e);return n!=null&&n.endsWith("svg")?{tag:"title",props:t,type:"title",ref:t.ref}:zi("title",t,void 0,!1,!1)},B1=t=>!t||["src","async"].some(e=>!t[e])?{tag:"script",props:t,type:"script",ref:t.ref}:zi("script",t,1,!1,!0),T1=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,zi("style",t,2,!0,!0)),P1=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}:zi("link",t,1,"precedence"in t,!0),R1=t=>zi("meta",t,void 0,!1,!1),dm=Symbol(),L1=t=>{const{action:e,...n}=t;typeof e!="function"&&(n.action=e);const[r,i]=z1([null,!1]),s=gu(async u=>{const p=u.isTrusted?e:u.detail[dm];if(typeof p!="function")return;u.preventDefault();const h=new FormData(u.target);i([h,!0]);const m=p(h);m instanceof Promise&&($1(m),await m),i([null,!0])},[]),a=mu(t.ref,u=>(u.addEventListener("submit",s),()=>{u.removeEventListener("submit",s)})),[c,l]=r;return r[1]=!1,{tag:j1,props:{value:{pending:c!==null,data:c,method:c?"post":null,action:c?e:null},children:{tag:"form",props:{...n,ref:a},type:"form",ref:a}},f:l}},pm=(t,{formAction:e,...n})=>{if(typeof e=="function"){const r=gu(i=>{i.preventDefault(),i.currentTarget.form.dispatchEvent(new CustomEvent("submit",{detail:{[dm]:e}}))},[]);n.ref=mu(n.ref,i=>(i.addEventListener("click",r),()=>{i.removeEventListener("click",r)}))}return{tag:t,props:n,type:t,ref:n.ref}},U1=t=>pm("input",t),V1=t=>pm("button",t);Object.assign(Yc,{title:O1,script:B1,style:T1,link:P1,meta:R1,form:L1,input:U1,button:V1});new TextEncoder;const _u=t=>{const{i18nKey:e,values:n,components:r}=t,i=P.t(e,n),s=/<(\d+)>(.*?)<\/\d+>/g,a=[];let c=0,l;for(;(l=s.exec(i))!==null;){const[,u,p]=l,h=i.substring(c,l.index);h&&a.push(h);const m=parseInt(u,10);a.push(n1(r[m],{},p)),c=s.lastIndex}return c<i.length&&a.push(i.substring(c)),y(fu,{children:a})},tf=6,nf=({error:t,vendorSettings:e,email:n,state:r,client:i,hasPasswordLogin:s})=>{const a=new URLSearchParams({state:r}),l=i.connections.map(({name:u})=>u).includes("auth2");return y(Je,{title:P.t("verify_your_email"),vendorSettings:e,children:[y("div",{className:"mb-4 text-2xl font-medium",children:P.t("verify_your_email")}),y("div",{className:"mb-8 text-gray-300",children:y(_u,{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(dn,{className:"pt-2",children:[y("input",{autoFocus:!0,type:"text",pattern:"[0-9]*",maxLength:tf,inputMode:"numeric",name:"code",placeholder:"******",className:It("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:tf,required:!0,id:"code-input"}),t&&y(xr,{children:t}),y("div",{className:"text-center sm:mt-2",children:y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("login")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.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:P.t("or")})]}),y(cr,{Component:"a",href:`/u/${s?"enter-password":"pre-signup"}?${a.toString()}`,variant:"secondary",className:"block",children:P.t("enter_your_password_btn")})]})]}),y(zt,{state:r})]})]})},q1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,loginSession:r,client:i}=await Ie(t,e);if(!r.authParams.username)throw new z(400,{message:"Username not found in state"});const s=await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(nf,{vendorSettings:n,email:r.authParams.username,state:e,client:i,hasPasswordLogin:!!s}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({code:o.z.string()})}}}},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{code:n}=t.req.valid("form"),{loginSession:r,client:i,vendorSettings:s}=await Ie(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 cu(t,i,r.authParams,r.authParams.username,n)}catch(a){const c=a,l=await ls({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email:r.authParams.username,provider:"auth2"});return t.html(y(nf,{vendorSettings:s,email:r.authParams.username,state:e,client:i,error:c.message,hasPasswordLogin:!!l}),400)}}),M1=t=>{const{vendorSettings:e,state:n}=t;return y(Je,{title:P.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:P.t("unverified_email")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]}),y(zt,{state:n})]}),y(zt,{state:n})]})},xa=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t,s=new URLSearchParams({state:i});return y(Je,{title:P.t("enter_password"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("enter_password")}),y("div",{className:"mb-6 text-gray-300",children:P.t("enter_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"mb-7",children:[y("input",{type:"text",name:"username",placeholder:P.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:P.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(xr,{children:e}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("login")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})]}),y("a",{href:`/u/forgot-password?${s.toString()}`,className:"text-primary hover:underline mb-4",children:P.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:P.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(cr,{variant:"secondary",className:"block",children:P.t("enter_a_code_btn")})]})]}),y(zt,{state:i})]})]})},D1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:i}=await Ie(t,e);if(!i.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(xa,{vendorSettings:n,email:i.authParams.username,state:e,client:r}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.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,loginSession:a}=await Ie(t,e),{username:c}=a.authParams;if(!c)throw new z(400,{message:"Username required"});try{return await lu(t,s,{...a.authParams,password:r},a)}catch(l){const u=l;return u.code==="INVALID_PASSWORD"||u.code==="USER_NOT_FOUND"?t.html(y(xa,{vendorSettings:i,email:c,error:P.t("invalid_password"),state:e,client:s}),400):u.code==="EMAIL_NOT_VERIFIED"?t.html(y(M1,{vendorSettings:i,state:e}),400):t.html(y(xa,{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(Je,{title:P.t("create_account_title"),vendorSettings:r,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("create_account_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("create_account_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{children:[y("input",{type:"hidden",name:"code",value:s}),y("input",{type:"email",name:"username",placeholder:P.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:P.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:P.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(xr,{children:n}),y(un,{className:"text-base sm:mt-2 md:text-base",children:P.t("continue")})]}),y(zt,{state:e})]})]})},yu=t=>{const{message:e,vendorSettings:n,pageTitle:r,state:i}=t;return y(Je,{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(zt,{state:i}):""]})},H1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.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,loginSession:i}=await Ie(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(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.z.string(),code:o.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,loginSession:a}=await Ie(t,e),c="Username-Password-Authentication";t.set("client_id",s.id),t.set("connection",c);const l=a.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:P.t("create_account_passwords_didnt_match"),email:a.authParams.username}),400);if(!su(n.password))return t.html(y(Cr,{state:e,code:n.code,vendorSettings:i,error:P.t("create_account_weak_password"),email:a.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.loginSessions.get(s.tenant.id,u.login_id):void 0;try{if(await ur({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 Df(t).users.create(s.tenant.id,{user_id:`auth2|${Xs()}`,email:l,email_verified:m,provider:"auth2",connection:c,is_social:!1});return await r.data.passwords.create(s.tenant.id,{user_id:v.user_id,password:await si.hash(n.password,10),algorithm:"bcrypt"}),m?await lu(t,s,{...a.authParams,password:n.password},a):(await au(t,v),t.html(y(yu,{message:P.t("validate_email_body"),pageTitle:P.t("validate_email_title"),vendorSettings:i,state:e})))}catch(h){const m=await hu(r,s.id,a.authParams.vendor_id),v=h;return t.html(y(Cr,{state:e,vendorSettings:m,error:v.message,email:l}),400)}}),jr=t=>{const{error:e,vendorSettings:n,email:r}=t;return y(Je,{title:P.t("reset_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("reset_password_title")}),y("div",{className:"mb-6 text-gray-300",children:`${P.t("reset_password_description")} ${r}`}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(dn,{children:[y("input",{type:"password",name:"password",placeholder:P.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:P.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(xr,{children:e}),y(un,{className:"text-base sm:mt-2 md:text-base",children:P.t("reset_password_cta")})]})})]})},F1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.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,loginSession:r}=await Ie(t,e);if(!r.authParams.username)throw new z(400,{message:"Username required"});return t.html(y(jr,{vendorSettings:n,email:r.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})}),body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({password:o.z.string(),"re-enter-password":o.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:a,client:c,loginSession:l}=await Ie(t,e);if(!l.authParams.username)throw new z(400,{message:"Username required"});if(r!==i)return t.html(y(jr,{error:P.t("create_account_passwords_didnt_match"),vendorSettings:a,email:l.authParams.username}),400);if(!su(r))return t.html(y(jr,{error:P.t("create_account_weak_password"),vendorSettings:a,email:l.authParams.username}),400);const u=await ur({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(jr,{error:"Code not found or expired",vendorSettings:a,email:l.authParams.username}),400);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(jr,{error:"The password could not be reset",vendorSettings:a,email:l.authParams.username}),400)}return t.html(y(yu,{message:P.t("password_has_been_reset"),vendorSettings:a,state:e}))}),K1=t=>{const{error:e,vendorSettings:n,email:r,state:i}=t;return y(Je,{title:P.t("forgot_password_title"),vendorSettings:n,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("forgot_password_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("forgot_password_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y(dn,{className:"pt-2",children:[y("input",{type:"email",name:"username",placeholder:P.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(xr,{children:e}),y(un,{className:"sm:mt-4",children:P.t("forgot_password_cta")})]}),y(zt,{state:i})]})]})},W1=t=>{const{vendorSettings:e,state:n}=t;return y(Je,{title:"Login",vendorSettings:e,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{children:P.t("forgot_password_email_sent")}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]})]}),y(zt,{state:n})]})},G1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e);return t.html(y(K1,{vendorSettings:n,state:e,email:r.authParams.username}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.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,loginSession:i}=await Ie(t,e);return await Nb(t,r,i.authParams.username,i.id),t.html(y(W1,{vendorSettings:n,state:e}))}),J1=({vendorSettings:t,state:e,user:n})=>y(Je,{title:se("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(_u,{i18nKey:"currently_logged_in_as",components:[y("span",{className:"font-semibold text-gray-900 dark:text-white"},"span")],values:{email:n.email}}),y("br",{}),se("continue_with_sso_provider_headline")]}),y("div",{className:"space-y-6",children:[y(dn,{children:y(un,{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:P.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:P.t("no_use_another")})]})]})}),Z1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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 Ie(t,n),s=cs(i.tenant.id,t.req.header("cookie")),a=s?await e.data.sessions.get(i.tenant.id,s):null;if(!a)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,a.user_id);return c?t.html(y(J1,{vendorSettings:r,state:n,user:c})):t.redirect(`/u/enter-email?state=${n}`)}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.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"),{loginSession:r,client:i}=await Ie(t,n),s=cs(i.tenant.id,t.req.header("cookie")),a=s?await e.data.sessions.get(i.tenant.id,s):null;if(!a)return t.redirect(`/u/enter-email?state=${n}`);const c=await e.data.users.get(i.tenant.id,a.user_id);return c?on(t,{user:c,authParams:r.authParams,client:i,loginSession:r}):t.redirect(`/u/enter-email?state=${n}`)}),Y1=t=>{const{vendorSettings:e,email:n,state:r}=t;return y(Je,{title:P.t("create_password_account_title"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("create_password_account_title")}),y("div",{className:"mb-6 text-gray-300",children:P.t("enter_email_for_verification_description")}),y("div",{className:"flex flex-1 flex-col justify-center",children:y(dn,{className:"pt-2",children:[y("input",{type:"email",name:"username",placeholder:P.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:n,disabled:!0}),y(un,{className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:y("span",{children:P.t("send")})})})]})}),y(zt,{state:r})]})},X1=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e),{username:i}=r.authParams;if(!i)throw new z(400,{message:"Username required"});return t.html(y(Y1,{state:e,vendorSettings:n,email:i}))}).openapi(o.createRoute({tags:["login"],method:"post",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{loginSession:n,client:r}=await Ie(t,e),{username:i}=n.authParams;if(!i)throw new z(400,{message:"Username required"});const s=await t.env.data.codes.create(r.tenant.id,{code_id:Tn(),code_type:"email_verification",login_id:n.id,expires_at:new Date(Date.now()+S_).toISOString()});return await Eb(t,i,s.code_id,n.id),t.redirect(`/u/pre-signup-sent?state=${e}`)}),Q1=t=>{const{redirectUrl:e,vendorSettings:n}=t;return y(Je,{title:P.t("invalid_session_title"),vendorSettings:n,children:[y("div",{className:"flex flex-1 flex-col justify-center",children:P.t("invalid_session_body")}),y("div",{className:"flex flex-1 flex-col justify-center",children:e&&y("a",{className:"block text-primary hover:text-primaryHover text-center",href:e,children:P.t("go_back")})})]})},ek=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string()})},responses:{200:{description:"Response"}}}),async t=>{const{state:e}=t.req.valid("query"),{vendorSettings:n,loginSession:r}=await Ie(t,e);let i;return r.authParams.redirect_uri&&r.authParams.state&&(i=new URL(r.authParams.redirect_uri),i.searchParams.set("state",r.authParams.state),i.searchParams.set("error","invalid_session"),i.searchParams.set("error_description",r.authParams.username||"")),t.html(y(Q1,{redirectUrl:i==null?void 0:i.href,vendorSettings:n}))}),tk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{const e=await hu(t.env),{state:n}=t.req.valid("query");return t.html(y(yu,{message:"Not implemented",pageTitle:"User info",vendorSettings:e,state:n}))}),nk=({vendorSettings:t,state:e})=>{const n=new URLSearchParams({state:e});return y(Je,{title:P.t("email_validated"),vendorSettings:t,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("email_validated")}),y("div",{className:"flex flex-1 flex-col justify-center mb-7",children:y(cr,{Component:"a",href:`/u/enter-password?${n}`,className:"text-base sm:mt-4 md:text-base",children:y("div",{className:"flex items-center space-x-2",children:[y("span",{children:P.t("email_validated_cta")}),y(Qe,{className:"text-xs",name:"arrow-right"})]})})})]})},rk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.z.string().openapi({description:"The state parameter from the authorization request"}),code:o.z.string().openapi({description:"The code parameter from the authorization request"})})},responses:{200:{description:"Response"}}}),async t=>{var m;const{state:e,code:n}=t.req.valid("query"),{env:r}=t,{client:i,loginSession:s,vendorSettings:a}=await Ie(t,e),c=s.authParams.username;if(!c)throw new z(400,{message:"Username not found in state"});const l=await ur({userAdapter:r.data.users,tenant_id:i.tenant.id,email:c,provider:"auth2"});if(!l)throw new z(500,{message:"No user found"});if(!await r.data.codes.get(i.tenant.id,n,"email_verification"))throw new z(400,{message:"Code not found or expired"});await r.data.users.update(i.tenant.id,l.user_id,{email_verified:!0});const h=(await pl(r.data.users,i.tenant.id,c)).filter(v=>v.provider!=="auth2");if(h.length>0){const v=h.filter(f=>!f.linked_to);v.length>1&&console.error("More than one primary user found for email",c),v.length===0&&console.error("No primary user found for email",c),v.length===1&&await r.data.users.update(i.tenant.id,l.user_id,{linked_to:(m=v[0])==null?void 0:m.user_id})}return t.html(y(nk,{vendorSettings:a,state:e}))}),ik=t=>{const{vendorSettings:e,email:n,state:r}=t;return y(Je,{title:P.t("email_verification_for_signup_sent_title"),vendorSettings:e,children:[y("div",{className:"mb-4 text-lg font-medium sm:text-2xl",children:P.t("email_verification_for_signup_sent_title")}),y("div",{className:"flex flex-1 flex-col justify-center",children:[y("div",{className:"mb-6 text-gray-300",children:y(_u,{i18nKey:"email_verification_for_signup_sent_description",components:[y("span",{className:"text-black dark:text-white"},"span")],values:{email:n}})}),y("div",{className:"my-4 flex space-x-2 text-sm text-[#B2B2B2]",children:[y(Qe,{className:"text-base",name:"info-bubble"}),y("div",{className:"text-sm text-gray-300 md:text-sm",children:P.t("sent_code_spam")})]})]}),y(zt,{state:r})]})},sk=new o.OpenAPIHono().openapi(o.createRoute({tags:["login"],method:"get",path:"/",request:{query:o.z.object({state:o.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,loginSession:r}=await Ie(t,e),{username:i}=r.authParams;if(!i)throw new z(400,{message:"Username required"});return t.html(y(ik,{vendorSettings:n,state:e,email:i}))});function ok(t){const e=new o.OpenAPIHono;e.use(async(r,i)=>(r.env.data=no(r,t.dataAdapter),i()));const n=e.route("/info",tk).route("/check-account",Z1).route("/enter-email",y1).route("/enter-code",q1).route("/enter-password",D1).route("/invalid-session",ek).route("/pre-signup",X1).route("/pre-signup-sent",sk).route("/reset-password",F1).route("/forgot-password",G1).route("/validate-email",rk).route("/signup",H1);return n.doc("/u/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Universal login"}}),n}const ak="Account detected",ck="We have detected that you have already created an account through",lk="By signing in, you agree to our",uk="and",dk="Callback URL mismatch",pk="The provided redirect_uri is not in the list of allowed callback URLs.",fk="continue with user",hk="Please click the button to create a new password account.",gk="Enter the code at {{vendorName}} to complete the login",mk="Welcome to {{vendorName}}! {{code}} is the login code",_k="Welcome to {{vendorName}}! {{code}} is the login code",yk="The code is valid for 30 minutes",vk="Confirm password",wk="Need Help?",bk="Contact us",kk="or continue with social account",xk="Continue with {{provider}}",Sk="Would you like to continue with your existing account?",Ak="Copyright © 2023 SESAMY. All rights reserved.",Ek="©2023 Sesamy",Ik="Choose a password with a mix of uppercase and lowercase letters, numbers, and symbols.",zk="Please enter a valid email address.",Nk="The passwords didn't match. Try again.",Ck="Choose password",jk="Password must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one number and one symbol.",$k="Create new account",Ok="Sign up with password",Bk="You are currently logged in as <0>{{email}}</0>",Tk="Email",Pk="Email address",Rk="Your email address has been validated",Lk="Now enter your password to login again",Uk="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.",Vk="Email verification sent",qk="Enter a code",Mk="We'll send you a verification link to ensure you own this email address.",Dk="Enter new password",Hk="Enter password",Fk="Enter your email address and password to login.",Kk="Enter your password",Wk="The magic link has expired. Please click on the button below to receive a new link in your inbox.",Gk="Hey! We updated our login experience. <0>Click here to learn more about it.</0>",Jk="Send password reset email",Zk="Click the button below and we’ll send instructions on how to reset your password.",Yk="Password reset email sent",Xk="Forgot password?",Qk="Forgot password?",ex="Go back",tx="Invalid password",nx=`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.mjs
CHANGED
|
@@ -19237,7 +19237,10 @@ async function bb(t, e, n, r) {
|
|
|
19237
19237
|
data: {
|
|
19238
19238
|
vendorName: i.name,
|
|
19239
19239
|
logo: i.logo || "",
|
|
19240
|
-
|
|
19240
|
+
signupUrl: o,
|
|
19241
|
+
setPassword: oe("set_password", s),
|
|
19242
|
+
registerPasswordAccount: oe("register_password_account", s),
|
|
19243
|
+
clickToSignUpDescription: oe("click_to_sign_up_description", s),
|
|
19241
19244
|
supportUrl: i.support_url || "https://support.sesamy.com",
|
|
19242
19245
|
buttonColor: i.primary_color || "#7d68f4",
|
|
19243
19246
|
welcomeToYourAccount: oe("welcome_to_your_account", s),
|
|
@@ -23055,7 +23058,7 @@ const du = (t) => {
|
|
|
23055
23058
|
t,
|
|
23056
23059
|
i,
|
|
23057
23060
|
s.code_id,
|
|
23058
|
-
n.
|
|
23061
|
+
n.id
|
|
23059
23062
|
), t.redirect(`/u/pre-signup-sent?state=${e}`);
|
|
23060
23063
|
}
|
|
23061
23064
|
), G1 = (t) => {
|