authhero 0.118.0 → 0.120.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 +1 -1
- package/dist/authhero.mjs +27 -12
- 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 $v(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 Ca(await Pf(s))}const Ov=1e3*60*60*24,Pv=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 I(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()+Ov).toISOString()});const n=await Zc({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 I(404,{message:"Key not found"});const r=await Zc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),Tv=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(il)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await ml(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),Bv=an.extend({clients:o.z.array(mn)}),Rv=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Bv,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:hr(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 I(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 I(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(is.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 I(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(is.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||ke(),client_secret:n.client_secret||ke()},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()});Ys.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 Lv=an.extend({tenants:o.z.array(Jn)}),Uv=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:tn},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Jn),Lv])}},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:hr(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:Jn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new I(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(os.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(os.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Jn}},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})}),Vv=an.extend({logs:o.z.array(cs)}),qv=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(cs),Vv])}},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:hr(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:cs}},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 I(404);return t.json(r)}),Mv=an.extend({hooks:o.z.array(Kn)}),Hv=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Kn),Mv])}},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:hr(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(as.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Kn}},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(as.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Kn.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 I(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:Kn}},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 I(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 I(404,{message:"Hook not found"});return t.text("OK")}),Dv=an.extend({connections:o.z.array(Jt)}),Fv=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Jt),Dv])}},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:hr(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:Jt}},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 I(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 I(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(ss.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:Jt}},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 I(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new I(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(ss.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Jt}},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})}),Kv=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:Ui}},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(Ui.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(Ui.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 Cp=!1;function Vg(t){t.use(async(e,n)=>(Cp||(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"}}}}),Cp=!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 Wv(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 I(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function Gv(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 Wv(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 Jv(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 qg(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")||"",[d,p]=l.split(" ");if((d==null?void 0:d.toLowerCase())!=="bearer"||!p)throw new I(401,{message:"Missing bearer token"});const f=Jv(p);if(!f||!await Gv(e,f))throw new I(403,{message:"Invalid JWT signature"});e.set("user_id",f.payload.sub),e.set("user",f.payload);const m=f.payload.permissions||[],w=((a=f.payload.scope)==null?void 0:a.split(" "))||[];if(c.length&&!(c.some(h=>m.includes(h))||c.some(h=>w.includes(h))))throw new I(403,{message:"Unauthorized"})}return await n()}}const Zv=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:Vi}},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 I(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(Vi.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(Vi.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")}),Yv=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:Qs}},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 I(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 I(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 I(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Xv=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:cl}},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 I(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 I(404,{message:"Session not found"});return t.text("OK")}),Qv=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Gt)}},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:Gt}},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 I(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 I(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(Gt.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:Gt}},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 I(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new I(404);return t.json(s)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(ol.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Gt}},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:Gt}},description:"The custom domain"}}}),async()=>{throw new I(501,{message:"Not implemented"})});async function od(t,e){const n=t.req.header("x-forwarded-host");if(n){const i=await t.env.data.customDomains.getByDomain(n);if(i)return t.set("tenant_id",i.tenant_id),t.set("custom_domain",n),await e()}const r=t.req.header("host");if(r){const i=r.split(".");if(i.length>1&&typeof i[0]=="string"){const s=i[0];await t.env.data.tenants.get(s)&&t.set("tenant_id",s)}}return await e()}function eb(t){const e=new o.OpenAPIHono;e.use(df({origin:r=>{var i;return r&&(i=t.allowedOrigins)!=null&&i.includes(r)?r:""},allowHeaders:["Tenant-Id","Content-Type","Content-Range","Auth0-Client","Authorization","Range","Upgrade-Insecure-Requests"],allowMethods:["POST","PUT","GET","DELETE","PATCH","OPTIONS"],exposeHeaders:["Content-Length","Content-Range"],maxAge:600,credentials:!0})),Vg(e),e.use(async(r,i)=>(r.env.data=io(r,t.dataAdapter),i())),e.use(od).use(qg(e));const n=e.route("/branding",E0).route("/custom-domains",Qv).route("/email/providers",Zv).route("/users",By).route("/keys",Pv).route("/users-by-email",Tv).route("/clients",Rv).route("/tenants",Uv).route("/logs",qv).route("/hooks",Hv).route("/connections",Fv).route("/prompts",Kv).route("/sessions",Yv).route("/refresh_tokens",Xv);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function tb(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Np;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Np||(Np={}));var jp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(jp||(jp={}));function nb(t){return Hg(t,rb,ti.Include)}function Mg(t){return Hg(t,ib,ti.None)}function Hg(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===ti.Include&&(r+="=")}return r}const rb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ib="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ti;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ti||(ti={}));var $p;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})($p||($p={}));class sb{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 Op=new sb;function kt(t,e){return(t<<32-e|t>>>e)>>>0}function ob(t){const e=new ab;return e.update(t),e.digest()}class ab{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),Op.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Op.putUint32(e,this.H[n],n*4);return e}process(){for(let d=0;d<16;d++)this.w[d]=(this.blocks[d*4]<<24|this.blocks[d*4+1]<<16|this.blocks[d*4+2]<<8|this.blocks[d*4+3])>>>0;for(let d=16;d<64;d++){const p=(kt(this.w[d-2],17)^kt(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(kt(this.w[d-15],7)^kt(this.w[d-15],18)^this.w[d-15]>>>3)>>>0;this.w[d]=p+this.w[d-7]+f+this.w[d-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 d=0;d<64;d++){const p=(kt(s,6)^kt(s,11)^kt(s,25))>>>0,f=(s&a^~s&c)>>>0,m=l+p+f+cb[d]+this.w[d]|0,w=(kt(e,2)^kt(e,13)^kt(e,22))>>>0,h=(e&n^e&r^n&r)>>>0,_=w+h|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 cb=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 lb{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 db(t){const e=ob(new TextEncoder().encode(t));return Mg(e)}function ub(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Mg(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 ma(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return nb(n)}async function Ks(t){let e;try{e=await fetch(t)}catch(n){throw new Fg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Fi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Dg(n)}catch{throw new Xn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Fi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);return new lb(n)}throw e.body!==null&&await e.body.cancel(),new Fi(e.status)}async function pb(t){let e;try{e=await fetch(t)}catch(n){throw new Fg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Xn(e.status,null)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Dg(n)}catch{throw new Xn(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 Fi(e.status)}function Dg(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 fb(e,n,r,i)}class Fg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class fb 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 Fi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class Xn extends Error{constructor(n,r){super("Unexpected error response body");te(this,"status");te(this,"data");this.status=n,this.data=r}}class ad{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===ni.S256){const c=db(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ni.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=ma(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ks(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=ma(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ks(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=ma(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await pb(i)}}var ni;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ni||(ni={}));var Pp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Pp||(Pp={}));var Tp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Tp||(Tp={}));function Vr(t){return hb(t,gb,Ws.None)}function hb(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===Ws.Include&&(r+="=")}return r}const gb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Ws;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ws||(Ws={}));var Bp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Bp||(Bp={}));function mb(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function _b(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const yb="https://appleid.apple.com/auth/authorize",wb="https://appleid.apple.com/auth/token";class Kg{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(yb);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(wb,n);return await Ks(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,_b(r,i)));return mb(r,i,s)}}const vb="https://www.facebook.com/v16.0/dialog/oauth",bb="https://graph.facebook.com/v16.0/oauth/access_token";class Wg{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(vb);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(bb,n);return await Ks(r)}}const xb="https://accounts.google.com/o/oauth2/v2/auth",Rp="https://oauth2.googleapis.com/token",kb="https://oauth2.googleapis.com/revoke";let Gg=class{constructor(e,n,r){te(this,"client");this.client=new ad(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(xb,e,ni.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Rp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Rp,e,[])}async revokeToken(e){await this.client.revokeToken(kb,e)}};const Yo=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();Yo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Sb(t){return t.ISSUER}function at(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Jg(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 Ab(t,e){var l,d;const{options:n,keyArray:r}=Jg(e),i=new Kg(n.client_id,n.team_id,n.kid,r,`${je(t.env)}callback`),s=ke(),a=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((d=n.scope)==null?void 0:d.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&a.searchParams.set("response_mode","form_post"),{redirectUrl:a.href,code:s}}async function zb(t,e,n){const{options:r,keyArray:i}=Jg(e),a=await new Kg(r.client_id,r.team_id,r.kid,i,`${je(t.env)}callback`).validateAuthorizationCode(n),c=dl(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Yo.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 Eb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Ab,validateAuthorizationCodeAndGetUser:zb},Symbol.toStringTag,{value:"Module"}));async function Ib(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 Wg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke();return{redirectUrl:r.createAuthorizationURL(i,((a=n.scope)==null?void 0:a.split(" "))||["email"]).href,code:i}}async function Cb(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 Wg(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 Nb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Ib,validateAuthorizationCodeAndGetUser:Cb},Symbol.toStringTag,{value:"Module"}));async function jb(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 Gg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),s=ub();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function $b(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 Gg(i.client_id,i.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n,r),c=dl(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Yo.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 Ob=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:jb,validateAuthorizationCodeAndGetUser:$b},Symbol.toStringTag,{value:"Module"}));async function Pb(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 ad(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),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 Tb(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 ad(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=dl(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Yo.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 I(400,{message:"Failed to get user from vipps"});return await l.json()}const Bb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Pb,validateAuthorizationCodeAndGetUser:Tb},Symbol.toStringTag,{value:"Module"}));function Zg(t,e){const n=t.env.STRATEGIES||{},i={apple:Eb,facebook:Nb,"google-oauth2":Ob,vipps:Bb,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Ai(t,e){const n=await t.data.clients.get(e);if(!n)throw new I(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(f=>f.name===c.name);if(!(l!=null&&l.options))return c;const d=Jt.parse({...l||{},...c});return d.options=sl.passthrough().parse({...l.options||{},...c.options}),d}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${at(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${at(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}async function Rb(t,e,n,r){if(!r.state)throw new I(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i){t.set("client_id",e.id);const l=we(t,{type:ge.FAILED_LOGIN,description:"Connection not found"});throw await t.env.data.logs.create(e.tenant.id,l),new I(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()+Qn*1e3).toISOString(),authParams:r,csrf_token:ke(),...Ht(t.req)}));const c=await Zg(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()+X0*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Lp(t,{code:e,state:n}){var h;const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new I(403,{message:"State not found"});const s=await r.data.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new I(403,{message:"Session not found"});const a=await Ai(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 _=we(t,{type:ge.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=we(t,{type:ge.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Redirect URI not defined"})}const d=await Zg(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...f}=d;t.set("user_id",p);const m=((h=d.email)==null?void 0:h.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const w=await oo(t,{client:a,username:m,provider:c.strategy,connection:c.name,userId:p,profileData:f,isSocial:!0,ip:t.req.header("x-real-ip")});return ln(t,{client:a,authParams:s.authParams,loginSession:s,user:w})}async function Up(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 I(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.login_id);if(!c)throw new I(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new I(400,{message:"Redirect uri not found"});const d=we(t,{type:ge.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});zt(t,t.env.data.logs.create(t.var.tenant_id,d));const p=new URL(l);return tb(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${at(t.env)}login/identifier?state=${c.id}&error=${n}`)}const Lb=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 Up(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Lp(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 Up(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Lp(t,{code:n,state:e})});function Yg(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return Ub(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function Ub(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}const Vb=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(!Yg(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new I(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const l=ds(r.tenant.id,a);if(l){const d=await t.env.data.sessions.get(r.tenant.id,l);if(d){const p=await t.env.data.users.get(r.tenant.id,d.user_id);p&&(t.set("user_id",p.user_id),t.set("connection",p.connection));const f=await t.env.data.refreshTokens.list(r.tenant.id,{q:`session_id=${l}`,page:0,per_page:100,include_totals:!1});await Promise.all(f.refresh_tokens.map(m=>t.env.data.refreshTokens.remove(r.tenant.id,m.id))),await t.env.data.sessions.update(r.tenant.id,l,{revoked_at:new Date().toISOString()})}}}const c=we(t,{type:ge.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":r_(r.tenant.id,t.req.header("host")),location:s}})}),Vp=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()}),qb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Vp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new I(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 I(404,{message:"User not found"});return t.json(Vp.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:wf}},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 sd(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return al.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=${Oi}, stale-while-revalidate=${Oi*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:Sb(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=${Oi}, stale-while-revalidate=${Oi*2}, stale-if-error=86400`}})});function Ki(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 Xg=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 Hb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(403,{message:"Invalid client credentials"});if(n.client_secret&&!Ki(n.client_secret,e.client_secret))throw new I(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await ro(t,{authParams:r,client:n});return t.json(i)}const Db=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 Fb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(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 I(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new I(403,{message:"Code expired"});if(r.used_at)throw new I(403,{message:"Code already used"});const i=await t.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new I(403,{message:"Invalid login"});if("client_secret"in e){const a=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Ki(n.client_secret,e.client_secret)&&!Ki(a==null?void 0:a.client_secret,e.client_secret))throw new I(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 G0(e.code_verifier,i.authParams.code_challenge_method);if(!Ki(a,i.authParams.code_challenge||""))throw new I(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new I(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new I(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),ln(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Rt.WEB_MESSAGE}})}const Kb=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 Wb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(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 I(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new I(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 I(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 ln(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:Rt.WEB_MESSAGE}})}function cd(t){return t.includes("@")?"email":"sms"}const Gb=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),otp:o.z.string(),authParams:Mr.optional()});async function Qg(t,{client_id:e,username:n,otp:r,authParams:i}){const s=await t.env.data.clients.get(e);if(!s)throw new I(403,{message:"Client not found"});return ld(t,s,i||{client_id:e,response_type:It.TOKEN_ID_TOKEN,response_mode:Rt.WEB_MESSAGE},n,r)}async function ld(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 I(400,{message:"Code not found or expired"});if(l.expires_at<new Date().toISOString())throw new I(400,{message:"Code expired"});if(l.used_at)throw new I(400,{message:"Code already used"});const d=cd(r),p=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!p||p.authParams.username!==r)throw new I(400,{message:"Code not found or expired"});const f=Ht(t.req);if(a&&p.ip!==f.ip)return t.redirect(`${at(t.env)}invalid-session?state=${p.id}`);const m=await oo(t,{client:e,username:r,provider:d,connection:d,isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),ln(t,{user:m,client:e,loginSession:p,authParams:n,ticketAuth:s})}const qp=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Jb=o.z.union([Xg.extend(qp.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(),...qp.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()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function Zb(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 Yb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Jb}}}},responses:{200:{content:{"application/json":{schema:Af}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=Zb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new I(400,{message:"client_id is required"});switch(t.set("client_id",r.client_id),e.grant_type){case Wn.AuthorizationCode:return Fb(t,Db.parse(r));case Wn.ClientCredential:return Hb(t,Xg.parse(r));case Wn.RefreshToken:return Wb(t,Kb.parse(r));case Wn.OTP:return Qg(t,Gb.parse(r));default:throw new I(400,{message:"Not implemented"})}});var dd={exports:{}};const ud=[{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}],em=(t,e=ud,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};dd.exports={passwordStrength:em,defaultOptions:ud};var Xb=dd.exports.passwordStrength=em;dd.exports.defaultOptions=ud;function pd(t){return Xb(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 zi(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 I(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function Qb(t,e){var a,c;if(!t.var.client_id)throw new I(500,{message:"Client not found"});const n=await Ai(t.env,t.var.client_id),r=n.connections.find(l=>l.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=((a=r.options)==null?void 0:a.provider)||"twilio",s=(c=t.env.smsProviders)==null?void 0:c[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:e.to,text:e.text,template:"auth-code",data:{code:e.code,tenantName:n.tenant.name,tenantId:n.tenant.id}})}async function tm(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const s=`${at(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await zi(t,{to:e,subject:re("reset_password_title",a),html:`Click here to reset your password: ${at(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:re("password_reset_title",a),resetPasswordEmailClickToReset:re("reset_password_email_click_to_reset",a),resetPasswordEmailReset:re("reset_password_email_reset",a),supportInfo:re("support_info",a),contactUs:re("contact_us",a),copyright:re("copyright",a),tenantName:i.name,tenantId:i.id}})}async function nm(t,{to:e,code:n}){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});const i=cd(e),s=new URL(at(t.env)),a={vendorName:r.name,vendorId:r.id,loginDomain:s.hostname,code:n,lng:r.language||"en"};i==="email"?await zi(t,{to:e,subject:re("code_email_subject",a),html:`Click here to validate your email: ${at(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:re("welcome_to_your_account",a),linkEmailClickToLogin:re("link_email_click_to_login",a),linkEmailLogin:re("link_email_login",a),linkEmailOrEnterCode:re("link_email_or_enter_code",a),codeValid30Mins:re("code_valid_30_minutes",a),supportInfo:re("support_info",a),contactUs:re("contact_us",a),copyright:re("copyright",a)}}):i==="sms"&&await Qb(t,{to:e,text:re("sms_code_text",a),code:n});const c=we(t,{type:ge.CODE_LINK_SENT,description:e});zt(t,t.env.data.logs.create(r.id,c))}async function fd(t,{to:e,code:n,authParams:r}){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const s=cd(e),a=new URL(je(t.env));a.pathname="passwordless/verify_redirect",a.searchParams.set("verification_code",n),a.searchParams.set("connection",s),a.searchParams.set("client_id",r.client_id),a.searchParams.set("redirect_uri",r.redirect_uri),a.searchParams.set("email",e),r.response_type&&a.searchParams.set("response_type",r.response_type),r.scope&&a.searchParams.set("scope",r.scope),r.state&&a.searchParams.set("state",r.state),r.nonce&&a.searchParams.set("nonce",r.nonce),r.code_challenge&&a.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&a.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&a.searchParams.set("audience",r.audience);const c={vendorName:i.name,code:n,lng:i.language||"en"};if(s!=="email")throw new I(400,{message:"Only email connections are supported for magic links"});await zi(t,{to:e,subject:re("code_email_subject",c),html:`Click here to validate your email: ${at(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:a.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:re("welcome_to_your_account",c),linkEmailClickToLogin:re("link_email_click_to_login",c),linkEmailLogin:re("link_email_login",c),linkEmailOrEnterCode:re("link_email_or_enter_code",c),codeValid30Mins:re("code_valid_30_minutes",c),supportInfo:re("support_info",c),contactUs:re("contact_us",c),copyright:re("copyright",c)}});const l=we(t,{type:ge.CODE_LINK_SENT,description:e});zt(t,t.env.data.logs.create(i.id,l))}async function hd(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});if(!e.email)throw new I(400,{message:"User has no email"});const r={vendorName:n.name,lng:n.language||"en"};await zi(t,{to:e.email,subject:re("welcome_to_your_account",r),html:`Click here to validate your email: ${at(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${at(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:re("welcome_to_your_account",r),verifyEmailVerify:re("verify_email_verify",r),supportInfo:re("support_info",r),contactUs:re("contact_us",r),copyright:re("copyright",r)}})}async function e1(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const s={vendorName:i.name,lng:i.language||"en"},a=`${at(t.env)}signup?state=${r}&code=${n}`;await zi(t,{to:e,subject:re("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:re("set_password",s),registerPasswordAccount:re("register_password_account",s),clickToSignUpDescription:re("click_to_sign_up_description",s),supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",welcomeToYourAccount:re("welcome_to_your_account",s),verifyEmailVerify:re("verify_email_verify",s),supportInfo:re("support_info",s),contactUs:re("contact_us",s),copyright:re("copyright",s)}})}const t1=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().optional(),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 I(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!pd(n))throw new I(400,{message:"Password does not meet the requirements"});if(await us({userAdapter:t.env.data.users,tenant_id:i.tenant.id,username:e,provider:"auth2"}))throw new I(400,{message:"Invalid sign up"});const a=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${eo()}`,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 oi.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:a.user_id,password:c,algorithm:"bcrypt"}),await hd(t,a);const l=we(t,{type:ge.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 I(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await fr({userAdapter:t.env.data.users,tenant_id:r.tenant.id,username: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()+Qn*1e3).toISOString(),authParams:s,csrf_token:ke(),...Ht(t.req)});return await tm(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()}const n1=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Mr.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Mr.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,send:i,authParams:s,connection:a}=e,c=await t.env.data.clients.get(r);if(!c)throw new I(400,{message:"Client not found"});t.set("client_id",c.id),t.set("tenant_id",c.tenant.id);const l=a==="email"?e.email:e.phone_number,d=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Na).toISOString(),csrf_token:ke(),...Ht(t.req)}),p=await n.data.codes.create(c.tenant.id,{code_id:Tn(),code_type:"otp",login_id:d.id,expires_at:new Date(Date.now()+Na).toISOString()});return i==="link"?await fd(t,{to:l,code:p.code_id,authParams:{...s,client_id:r}}):await nm(t,{to:l,code:p.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(It),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:d,nonce:p}=t.req.valid("query"),f=await Ai(e,n);return t.set("client_id",f.id),t.set("tenant_id",f.tenant.id),t.set("connection","email"),ld(t,f,{client_id:n,redirect_uri:s,state:a,nonce:p,scope:c,audience:l,response_type:d},r,i,!1,!0)});class jr extends I{constructor(n,r){super(n,r);te(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function gd(t,e,n,r,i){const{env:s}=t,{username:a}=n;if(t.set("username",a),!a)throw new I(400,{message:"Username is required"});const c=await fr({userAdapter:t.env.data.users,tenant_id:e.tenant.id,username:a,provider:"auth2"});if(!c){const h=we(t,{type:ge.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(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 jr(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const d=await s.data.passwords.get(e.tenant.id,c.user_id);if(!(d&&await oi.compare(n.password,d.password))){const h=we(t,{type:ge.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(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(h=>h.type===ge.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(h.date)>new Date(Date.now()-1e3*60*5)).length>=3){const h=we(t,{type:ge.FAILED_LOGIN,description:"Too many failed login attempts"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await hd(t,c);const h=we(t,{type:ge.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,h),new jr(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const w=we(t,{type:ge.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return zt(t,t.env.data.logs.create(e.tenant.id,w)),ln(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function r1(t,e,n,r){await oo(t,{client:e,username: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()+t_).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:ke(),...Ht(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()+e_).toISOString()});await tm(t,n,c.code_id,r)}const i1=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 I(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 ld(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()+Qn*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:ke(),...Ht(t.req)});return gd(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new I(400,{message:"Code or password required"})});function s1(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=_a(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=_a(a))==null?void 0:i.host)??null:c=((s=_a("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function _a(t){try{return new URL(t)}catch{return null}}async function o1({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()+Qn*1e3).toISOString(),authParams:r,csrf_token:ke(),authorization_url:t.req.url,...Ht(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 ln(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()+Qn*1e3).toISOString()}),await fd(t,{code:c,to:s,authParams:r}),t.redirect(`/u/enter-code?state=${a.id}`)}return e?t.redirect(`/u/check-account?state=${a.id}`):t.redirect(`/u/login/identifier?state=${a.id}`)}function a1(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new I(403,{message:"Invalid realm"})}async function c1(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 I(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.login_id);if(!c||!c.authParams.username)throw new I(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new I(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const d=a1(i);let p=await oo(t,{username:c.authParams.username,provider:d,client:l,connection:d==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email||p.phone_number),t.set("user_id",p.user_id);const f=await Gf(t,{user:p,client:l,loginSession:c});return ln(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:f.id,user:p,client:l})}async function Mp(t,e){return`<!DOCTYPE html>
|
|
149
|
+
`,r}async function $v(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 Ca(await Pf(s))}const Ov=1e3*60*60*24,Pv=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 I(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()+Ov).toISOString()});const n=await Zc({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 I(404,{message:"Key not found"});const r=await Zc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),Tv=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(il)}},description:"List of users"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),{email:n}=t.req.valid("query"),i=(await ml(t.env.data.users,e,n)).filter(s=>!s.linked_to);return t.json(i)}),Bv=an.extend({clients:o.z.array(mn)}),Rv=new o.OpenAPIHono().openapi(o.createRoute({tags:["clients"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([Bv,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:hr(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 I(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 I(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(is.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 I(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(is.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||ke(),client_secret:n.client_secret||ke()},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()});Ys.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 Lv=an.extend({tenants:o.z.array(Jn)}),Uv=new o.OpenAPIHono().openapi(o.createRoute({tags:["tenants"],method:"get",path:"/",request:{query:tn},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"tenant/json":{schema:o.z.union([o.z.array(Jn),Lv])}},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:hr(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:Jn}},description:"A tenant"}}}),async t=>{const{id:e}=t.req.valid("param"),n=await t.env.data.tenants.get(e);if(!n)throw new I(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(os.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(os.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"tenant/json":{schema:Jn}},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})}),Vv=an.extend({logs:o.z.array(cs)}),qv=new o.OpenAPIHono().openapi(o.createRoute({tags:["logs"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(cs),Vv])}},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:hr(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:cs}},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 I(404);return t.json(r)}),Mv=an.extend({hooks:o.z.array(Kn)}),Hv=new o.OpenAPIHono().openapi(o.createRoute({tags:["hooks"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Kn),Mv])}},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:hr(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(as.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Kn}},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(as.shape).omit({hook_id:!0}).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema:Kn.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 I(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:Kn}},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 I(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 I(404,{message:"Hook not found"});return t.text("OK")}),Dv=an.extend({connections:o.z.array(Jt)}),Fv=new o.OpenAPIHono().openapi(o.createRoute({tags:["connections"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.union([o.z.array(Jt),Dv])}},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:hr(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:Jt}},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 I(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 I(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(ss.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:Jt}},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 I(404,{message:"Connection not found"});const s=await t.env.data.connections.get(e,n);if(!s)throw new I(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(ss.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Jt}},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})}),Kv=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:Ui}},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(Ui.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(Ui.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 Cp=!1;function Vg(t){t.use(async(e,n)=>(Cp||(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"}}}}),Cp=!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 Wv(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 I(500,{message:`Failed to fetch jwks: ${e.message}`})}}async function Gv(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 Wv(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 Jv(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 qg(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")||"",[d,p]=l.split(" ");if((d==null?void 0:d.toLowerCase())!=="bearer"||!p)throw new I(401,{message:"Missing bearer token"});const f=Jv(p);if(!f||!await Gv(e,f))throw new I(403,{message:"Invalid JWT signature"});e.set("user_id",f.payload.sub),e.set("user",f.payload);const m=f.payload.permissions||[],w=((a=f.payload.scope)==null?void 0:a.split(" "))||[];if(c.length&&!(c.some(h=>m.includes(h))||c.some(h=>w.includes(h))))throw new I(403,{message:"Unauthorized"})}return await n()}}const Zv=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:Vi}},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 I(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(Vi.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(Vi.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")}),Yv=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:Qs}},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 I(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 I(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 I(404,{message:"Session not found"});return t.text("Session deletion request accepted.",{status:202})}),Xv=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:cl}},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 I(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 I(404,{message:"Session not found"});return t.text("OK")}),Qv=new o.OpenAPIHono().openapi(o.createRoute({tags:["custom-domains"],method:"get",path:"/",request:{query:tn,headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:o.z.array(Gt)}},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:Gt}},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 I(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 I(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(Gt.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:Gt}},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 I(404);const s=await t.env.data.customDomains.get(e,n);if(!s)throw new I(404);return t.json(s)}).openapi(o.createRoute({tags:["custom-domains"],method:"post",path:"/",request:{body:{content:{"application/json":{schema:o.z.object(ol.shape)}}},headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{201:{content:{"application/json":{schema:Gt}},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:Gt}},description:"The custom domain"}}}),async()=>{throw new I(501,{message:"Not implemented"})});async function od(t,e){const n=t.req.header("x-forwarded-host");if(n){const i=await t.env.data.customDomains.getByDomain(n);if(i)return t.set("tenant_id",i.tenant_id),t.set("custom_domain",n),await e()}const r=t.req.header("host");if(r){const i=r.split(".");if(i.length>1&&typeof i[0]=="string"){const s=i[0];await t.env.data.tenants.get(s)&&t.set("tenant_id",s)}}return await e()}function eb(t){const e=new o.OpenAPIHono;e.use(df({origin:r=>{var i;return r&&(i=t.allowedOrigins)!=null&&i.includes(r)?r:""},allowHeaders:["Tenant-Id","Content-Type","Content-Range","Auth0-Client","Authorization","Range","Upgrade-Insecure-Requests"],allowMethods:["POST","PUT","GET","DELETE","PATCH","OPTIONS"],exposeHeaders:["Content-Length","Content-Range"],maxAge:600,credentials:!0})),Vg(e),e.use(async(r,i)=>(r.env.data=io(r,t.dataAdapter),i())),e.use(od).use(qg(e));const n=e.route("/branding",E0).route("/custom-domains",Qv).route("/email/providers",Zv).route("/users",By).route("/keys",Pv).route("/users-by-email",Tv).route("/clients",Rv).route("/tenants",Uv).route("/logs",qv).route("/hooks",Hv).route("/connections",Fv).route("/prompts",Kv).route("/sessions",Yv).route("/refresh_tokens",Xv);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function tb(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Np;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Np||(Np={}));var jp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(jp||(jp={}));function nb(t){return Hg(t,rb,ti.Include)}function Mg(t){return Hg(t,ib,ti.None)}function Hg(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===ti.Include&&(r+="=")}return r}const rb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ib="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ti;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ti||(ti={}));var $p;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})($p||($p={}));class sb{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 Op=new sb;function kt(t,e){return(t<<32-e|t>>>e)>>>0}function ob(t){const e=new ab;return e.update(t),e.digest()}class ab{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),Op.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)Op.putUint32(e,this.H[n],n*4);return e}process(){for(let d=0;d<16;d++)this.w[d]=(this.blocks[d*4]<<24|this.blocks[d*4+1]<<16|this.blocks[d*4+2]<<8|this.blocks[d*4+3])>>>0;for(let d=16;d<64;d++){const p=(kt(this.w[d-2],17)^kt(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(kt(this.w[d-15],7)^kt(this.w[d-15],18)^this.w[d-15]>>>3)>>>0;this.w[d]=p+this.w[d-7]+f+this.w[d-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 d=0;d<64;d++){const p=(kt(s,6)^kt(s,11)^kt(s,25))>>>0,f=(s&a^~s&c)>>>0,m=l+p+f+cb[d]+this.w[d]|0,w=(kt(e,2)^kt(e,13)^kt(e,22))>>>0,h=(e&n^e&r^n&r)>>>0,_=w+h|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 cb=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 lb{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 db(t){const e=ob(new TextEncoder().encode(t));return Mg(e)}function ub(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Mg(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 ma(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return nb(n)}async function Ks(t){let e;try{e=await fetch(t)}catch(n){throw new Fg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Fi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Dg(n)}catch{throw new Xn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Fi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);return new lb(n)}throw e.body!==null&&await e.body.cancel(),new Fi(e.status)}async function pb(t){let e;try{e=await fetch(t)}catch(n){throw new Fg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Xn(e.status,null)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Dg(n)}catch{throw new Xn(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 Fi(e.status)}function Dg(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 fb(e,n,r,i)}class Fg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class fb 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 Fi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class Xn extends Error{constructor(n,r){super("Unexpected error response body");te(this,"status");te(this,"data");this.status=n,this.data=r}}class ad{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===ni.S256){const c=db(i);a.searchParams.set("code_challenge_method","S256"),a.searchParams.set("code_challenge",c)}else r===ni.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=ma(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ks(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=ma(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Ks(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=ma(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await pb(i)}}var ni;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ni||(ni={}));var Pp;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Pp||(Pp={}));var Tp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Tp||(Tp={}));function Vr(t){return hb(t,gb,Ws.None)}function hb(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===Ws.Include&&(r+="=")}return r}const gb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Ws;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ws||(Ws={}));var Bp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Bp||(Bp={}));function mb(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function _b(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const yb="https://appleid.apple.com/auth/authorize",wb="https://appleid.apple.com/auth/token";class Kg{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(yb);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(wb,n);return await Ks(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,_b(r,i)));return mb(r,i,s)}}const vb="https://www.facebook.com/v16.0/dialog/oauth",bb="https://graph.facebook.com/v16.0/oauth/access_token";class Wg{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(vb);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(bb,n);return await Ks(r)}}const xb="https://accounts.google.com/o/oauth2/v2/auth",Rp="https://oauth2.googleapis.com/token",kb="https://oauth2.googleapis.com/revoke";let Gg=class{constructor(e,n,r){te(this,"client");this.client=new ad(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(xb,e,ni.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Rp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Rp,e,[])}async revokeToken(e){await this.client.revokeToken(kb,e)}};const Yo=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();Yo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function Sb(t){return t.ISSUER}function at(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Jg(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 Ab(t,e){var l,d;const{options:n,keyArray:r}=Jg(e),i=new Kg(n.client_id,n.team_id,n.kid,r,`${je(t.env)}callback`),s=ke(),a=await i.createAuthorizationURL(s,((l=n.scope)==null?void 0:l.split(" "))||["name","email"]);return(((d=n.scope)==null?void 0:d.split(" "))||["name","email"]).some(p=>["email","name"].includes(p))&&a.searchParams.set("response_mode","form_post"),{redirectUrl:a.href,code:s}}async function zb(t,e,n){const{options:r,keyArray:i}=Jg(e),a=await new Kg(r.client_id,r.team_id,r.kid,i,`${je(t.env)}callback`).validateAuthorizationCode(n),c=dl(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Yo.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 Eb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Ab,validateAuthorizationCodeAndGetUser:zb},Symbol.toStringTag,{value:"Module"}));async function Ib(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 Wg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke();return{redirectUrl:r.createAuthorizationURL(i,((a=n.scope)==null?void 0:a.split(" "))||["email"]).href,code:i}}async function Cb(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 Wg(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 Nb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Ib,validateAuthorizationCodeAndGetUser:Cb},Symbol.toStringTag,{value:"Module"}));async function jb(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 Gg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),s=ub();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function $b(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 Gg(i.client_id,i.client_secret,`${je(t.env)}callback`).validateAuthorizationCode(n,r),c=dl(a.idToken());if(!c)throw new Error("Invalid ID token");const l=Yo.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 Ob=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:jb,validateAuthorizationCodeAndGetUser:$b},Symbol.toStringTag,{value:"Module"}));async function Pb(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 ad(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),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 Tb(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 ad(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=dl(s.idToken());if(!a)throw new Error("Invalid ID token");const c=Yo.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 I(400,{message:"Failed to get user from vipps"});return await l.json()}const Bb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Pb,validateAuthorizationCodeAndGetUser:Tb},Symbol.toStringTag,{value:"Module"}));function Zg(t,e){const n=t.env.STRATEGIES||{},i={apple:Eb,facebook:Nb,"google-oauth2":Ob,vipps:Bb,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Ai(t,e){const n=await t.data.clients.get(e);if(!n)throw new I(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(f=>f.name===c.name);if(!(l!=null&&l.options))return c;const d=Jt.parse({...l||{},...c});return d.options=sl.passthrough().parse({...l.options||{},...c.options}),d}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${at(t)}login`],allowed_logout_urls:[...(r==null?void 0:r.allowed_logout_urls)||[],...n.allowed_logout_urls||[],t.ISSUER],callbacks:[...(r==null?void 0:r.callbacks)||[],...n.callbacks||[],`${at(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}async function Rb(t,e,n,r){if(!r.state)throw new I(400,{message:"State not found"});const i=e.connections.find(l=>l.name===n);if(!i){t.set("client_id",e.id);const l=we(t,{type:ge.FAILED_LOGIN,description:"Connection not found"});throw await t.env.data.logs.create(e.tenant.id,l),new I(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()+Qn*1e3).toISOString(),authParams:r,csrf_token:ke(),...Ht(t.req)}));const c=await Zg(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()+X0*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Lp(t,{code:e,state:n}){var h;const{env:r}=t,i=await r.data.codes.get(t.var.tenant_id||"",n,"oauth2_state");if(!i||!i.connection_id)throw new I(403,{message:"State not found"});const s=await r.data.loginSessions.get(t.var.tenant_id||"",i.login_id);if(!s)throw new I(403,{message:"Session not found"});if(s.authorization_url){const _=new URL(s.authorization_url).hostname,v=t.var.custom_domain||t.req.header("host")||"";if(_!==v&&_){const S=new URL(`https://${_}/callback`);return S.searchParams.set("state",n),S.searchParams.set("code",e),new Response("Redirecting",{status:307,headers:{location:S.toString()}})}}const a=await Ai(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 _=we(t,{type:ge.FAILED_LOGIN,description:"Connection not found"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Connection not found"})}if(t.set("connection",c.name),!s.authParams.redirect_uri){const _=we(t,{type:ge.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Redirect URI not defined"})}const d=await Zg(t,c.strategy).validateAuthorizationCodeAndGetUser(t,c,e,i.code_verifier),{sub:p,...f}=d;t.set("user_id",p);const m=((h=d.email)==null?void 0:h.toLocaleLowerCase())||`${c.name}.${p}@${new URL(t.env.ISSUER).hostname}`;t.set("username",m);const w=await oo(t,{client:a,username:m,provider:c.strategy,connection:c.name,userId:p,profileData:f,isSocial:!0,ip:t.req.header("x-real-ip")});return ln(t,{client:a,authParams:s.authParams,loginSession:s,user:w})}async function Up(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 I(400,{message:"State not found"});const c=await t.env.data.loginSessions.get(t.var.tenant_id,a.login_id);if(!c)throw new I(400,{message:"Login not found"});const{redirect_uri:l}=c.authParams;if(!l)throw new I(400,{message:"Redirect uri not found"});const d=we(t,{type:ge.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});zt(t,t.env.data.logs.create(t.var.tenant_id,d));const p=new URL(l);return tb(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${at(t.env)}login/identifier?state=${c.id}&error=${n}`)}const Lb=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 Up(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Lp(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 Up(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Lp(t,{code:n,state:e})});function Yg(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return Ub(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function Ub(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}const Vb=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(!Yg(s,[...r.allowed_logout_urls||[],...(i==null?void 0:i.allowed_logout_urls)||[]],{allowPathWildcards:!0}))throw new I(400,{message:"Invalid redirect uri"});const a=t.req.header("cookie");if(a){const l=ds(r.tenant.id,a);if(l){const d=await t.env.data.sessions.get(r.tenant.id,l);if(d){const p=await t.env.data.users.get(r.tenant.id,d.user_id);p&&(t.set("user_id",p.user_id),t.set("connection",p.connection));const f=await t.env.data.refreshTokens.list(r.tenant.id,{q:`session_id=${l}`,page:0,per_page:100,include_totals:!1});await Promise.all(f.refresh_tokens.map(m=>t.env.data.refreshTokens.remove(r.tenant.id,m.id))),await t.env.data.sessions.update(r.tenant.id,l,{revoked_at:new Date().toISOString()})}}}const c=we(t,{type:ge.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":r_(r.tenant.id,t.req.header("host")),location:s}})}),Vp=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()}),qb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Vp}},description:"Userinfo"}}}),async t=>{if(!t.var.user)throw new I(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 I(404,{message:"User not found"});return t.json(Vp.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:wf}},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 sd(r.cert).publicKey.export(),a=await crypto.subtle.exportKey("jwk",s);return al.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=${Oi}, stale-while-revalidate=${Oi*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:Sb(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=${Oi}, stale-while-revalidate=${Oi*2}, stale-if-error=86400`}})});function Ki(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 Xg=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 Hb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(403,{message:"Invalid client credentials"});if(n.client_secret&&!Ki(n.client_secret,e.client_secret))throw new I(403,{message:"Invalid client credentials"});const r={client_id:n.id,scope:e.scope,audience:e.audience},i=await ro(t,{authParams:r,client:n});return t.json(i)}const Db=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 Fb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(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 I(403,{message:"Invalid client credentials"});if(new Date(r.expires_at)<new Date)throw new I(403,{message:"Code expired"});if(r.used_at)throw new I(403,{message:"Code already used"});const i=await t.env.data.loginSessions.get(n.tenant.id,r.login_id);if(!i)throw new I(403,{message:"Invalid login"});if("client_secret"in e){const a=await t.env.data.clients.get("DEFAULT_CLIENT");if(!Ki(n.client_secret,e.client_secret)&&!Ki(a==null?void 0:a.client_secret,e.client_secret))throw new I(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 G0(e.code_verifier,i.authParams.code_challenge_method);if(!Ki(a,i.authParams.code_challenge||""))throw new I(403,{message:"Invalid client credentials"})}if(i.authParams.redirect_uri&&i.authParams.redirect_uri!==e.redirect_uri)throw new I(403,{message:"Invalid redirect uri"});const s=await t.env.data.users.get(n.tenant.id,r.user_id);if(!s)throw new I(403,{message:"User not found"});return await t.env.data.codes.used(n.tenant.id,e.code),ln(t,{user:s,client:n,loginSession:i,authParams:{...i.authParams,response_mode:Rt.WEB_MESSAGE}})}const Kb=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 Wb(t,e){const n=await t.env.data.clients.get(e.client_id);if(!n)throw new I(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 I(403,{message:JSON.stringify({error:"invalid_grant",error_description:"Refresh token has expired"})})}else throw new I(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 I(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 ln(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:Rt.WEB_MESSAGE}})}function cd(t){return t.includes("@")?"email":"sms"}const Gb=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),otp:o.z.string(),authParams:Mr.optional()});async function Qg(t,{client_id:e,username:n,otp:r,authParams:i}){const s=await t.env.data.clients.get(e);if(!s)throw new I(403,{message:"Client not found"});return ld(t,s,i||{client_id:e,response_type:It.TOKEN_ID_TOKEN,response_mode:Rt.WEB_MESSAGE},n,r)}async function ld(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 I(400,{message:"Code not found or expired"});if(l.expires_at<new Date().toISOString())throw new I(400,{message:"Code expired"});if(l.used_at)throw new I(400,{message:"Code already used"});const d=cd(r),p=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!p||p.authParams.username!==r)throw new I(400,{message:"Code not found or expired"});const f=Ht(t.req);if(a&&p.ip!==f.ip)return t.redirect(`${at(t.env)}invalid-session?state=${p.id}`);const m=await oo(t,{client:e,username:r,provider:d,connection:d,isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),ln(t,{user:m,client:e,loginSession:p,authParams:n,ticketAuth:s})}const qp=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Jb=o.z.union([Xg.extend(qp.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(),...qp.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()}),o.z.object({grant_type:o.z.literal("http://auth0.com/oauth/grant-type/passwordless/otp"),client_id:o.z.string(),username:o.z.string(),otp:o.z.string(),realm:o.z.enum(["email","sms"])})]);function Zb(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 Yb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Jb}}}},responses:{200:{content:{"application/json":{schema:Af}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=Zb(t.req.header("Authorization")),r={...e,...n};if(!r.client_id)throw new I(400,{message:"client_id is required"});switch(t.set("client_id",r.client_id),e.grant_type){case Wn.AuthorizationCode:return Fb(t,Db.parse(r));case Wn.ClientCredential:return Hb(t,Xg.parse(r));case Wn.RefreshToken:return Wb(t,Kb.parse(r));case Wn.OTP:return Qg(t,Gb.parse(r));default:throw new I(400,{message:"Not implemented"})}});var dd={exports:{}};const ud=[{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}],em=(t,e=ud,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};dd.exports={passwordStrength:em,defaultOptions:ud};var Xb=dd.exports.passwordStrength=em;dd.exports.defaultOptions=ud;function pd(t){return Xb(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 zi(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 I(500,{message:"Email provider not found"});const r=(i=t.env.emailProviders)==null?void 0:i[n.name];if(!r)throw new I(500,{message:"Email provider not found"});await r({emailProvider:n,...e,from:n.default_from_address||`login@${t.env.ISSUER}`})}async function Qb(t,e){var a,c;if(!t.var.client_id)throw new I(500,{message:"Client not found"});const n=await Ai(t.env,t.var.client_id),r=n.connections.find(l=>l.strategy==="sms");if(!r)throw new I(500,{message:"SMS provider not found"});const i=((a=r.options)==null?void 0:a.provider)||"twilio",s=(c=t.env.smsProviders)==null?void 0:c[i];if(!s)throw new I(500,{message:"SMS provider not found"});await s({options:r.options,to:e.to,text:e.text,template:"auth-code",data:{code:e.code,tenantName:n.tenant.name,tenantId:n.tenant.id}})}async function tm(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const s=`${at(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await zi(t,{to:e,subject:re("reset_password_title",a),html:`Click here to reset your password: ${at(t.env)}reset-password?state=${r}&code=${n}`,template:"auth-password-reset",data:{vendorName:i.name,logo:i.logo||"",passwordResetUrl:s,supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",passwordResetTitle:re("password_reset_title",a),resetPasswordEmailClickToReset:re("reset_password_email_click_to_reset",a),resetPasswordEmailReset:re("reset_password_email_reset",a),supportInfo:re("support_info",a),contactUs:re("contact_us",a),copyright:re("copyright",a),tenantName:i.name,tenantId:i.id}})}async function nm(t,{to:e,code:n}){const r=await t.env.data.tenants.get(t.var.tenant_id);if(!r)throw new I(500,{message:"Tenant not found"});const i=cd(e),s=new URL(at(t.env)),a={vendorName:r.name,vendorId:r.id,loginDomain:s.hostname,code:n,lng:r.language||"en"};i==="email"?await zi(t,{to:e,subject:re("code_email_subject",a),html:`Click here to validate your email: ${at(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:re("welcome_to_your_account",a),linkEmailClickToLogin:re("link_email_click_to_login",a),linkEmailLogin:re("link_email_login",a),linkEmailOrEnterCode:re("link_email_or_enter_code",a),codeValid30Mins:re("code_valid_30_minutes",a),supportInfo:re("support_info",a),contactUs:re("contact_us",a),copyright:re("copyright",a)}}):i==="sms"&&await Qb(t,{to:e,text:re("sms_code_text",a),code:n});const c=we(t,{type:ge.CODE_LINK_SENT,description:e});zt(t,t.env.data.logs.create(r.id,c))}async function fd(t,{to:e,code:n,authParams:r}){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const s=cd(e),a=new URL(je(t.env));a.pathname="passwordless/verify_redirect",a.searchParams.set("verification_code",n),a.searchParams.set("connection",s),a.searchParams.set("client_id",r.client_id),a.searchParams.set("redirect_uri",r.redirect_uri),a.searchParams.set("email",e),r.response_type&&a.searchParams.set("response_type",r.response_type),r.scope&&a.searchParams.set("scope",r.scope),r.state&&a.searchParams.set("state",r.state),r.nonce&&a.searchParams.set("nonce",r.nonce),r.code_challenge&&a.searchParams.set("code_challenge",r.code_challenge),r.code_challenge_method&&a.searchParams.set("code_challenge_method",r.code_challenge_method),r.audience&&a.searchParams.set("audience",r.audience);const c={vendorName:i.name,code:n,lng:i.language||"en"};if(s!=="email")throw new I(400,{message:"Only email connections are supported for magic links"});await zi(t,{to:e,subject:re("code_email_subject",c),html:`Click here to validate your email: ${at(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",magicLink:a.toString(),buttonColor:i.primary_color||"",welcomeToYourAccount:re("welcome_to_your_account",c),linkEmailClickToLogin:re("link_email_click_to_login",c),linkEmailLogin:re("link_email_login",c),linkEmailOrEnterCode:re("link_email_or_enter_code",c),codeValid30Mins:re("code_valid_30_minutes",c),supportInfo:re("support_info",c),contactUs:re("contact_us",c),copyright:re("copyright",c)}});const l=we(t,{type:ge.CODE_LINK_SENT,description:e});zt(t,t.env.data.logs.create(i.id,l))}async function hd(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});if(!e.email)throw new I(400,{message:"User has no email"});const r={vendorName:n.name,lng:n.language||"en"};await zi(t,{to:e.email,subject:re("welcome_to_your_account",r),html:`Click here to validate your email: ${at(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${at(t.env)}validate-email`,supportUrl:n.support_url||"https://support.sesamy.com",buttonColor:n.primary_color||"#7d68f4",welcomeToYourAccount:re("welcome_to_your_account",r),verifyEmailVerify:re("verify_email_verify",r),supportInfo:re("support_info",r),contactUs:re("contact_us",r),copyright:re("copyright",r)}})}async function e1(t,e,n,r){const i=await t.env.data.tenants.get(t.var.tenant_id);if(!i)throw new I(500,{message:"Tenant not found"});const s={vendorName:i.name,lng:i.language||"en"},a=`${at(t.env)}signup?state=${r}&code=${n}`;await zi(t,{to:e,subject:re("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:re("set_password",s),registerPasswordAccount:re("register_password_account",s),clickToSignUpDescription:re("click_to_sign_up_description",s),supportUrl:i.support_url||"https://support.sesamy.com",buttonColor:i.primary_color||"#7d68f4",welcomeToYourAccount:re("welcome_to_your_account",s),verifyEmailVerify:re("verify_email_verify",s),supportInfo:re("support_info",s),contactUs:re("contact_us",s),copyright:re("copyright",s)}})}const t1=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().optional(),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 I(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!pd(n))throw new I(400,{message:"Password does not meet the requirements"});if(await us({userAdapter:t.env.data.users,tenant_id:i.tenant.id,username:e,provider:"auth2"}))throw new I(400,{message:"Invalid sign up"});const a=await t.env.data.users.create(i.tenant.id,{user_id:`auth2|${eo()}`,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 oi.hash(n,10);await t.env.data.passwords.create(i.tenant.id,{user_id:a.user_id,password:c,algorithm:"bcrypt"}),await hd(t,a);const l=we(t,{type:ge.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 I(400,{message:"Client not found"});if(t.set("client_id",r.id),t.set("tenant_id",r.tenant.id),!await fr({userAdapter:t.env.data.users,tenant_id:r.tenant.id,username: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()+Qn*1e3).toISOString(),authParams:s,csrf_token:ke(),...Ht(t.req)});return await tm(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()}const n1=new o.OpenAPIHono().openapi(o.createRoute({tags:["passwordless"],method:"post",path:"/start",request:{body:{content:{"application/json":{schema:o.z.union([o.z.object({connection:o.z.literal("email"),client_id:o.z.string(),email:o.z.string().transform(t=>t.toLowerCase()),send:o.z.enum(["link","code"]),authParams:Mr.omit({client_id:!0})}),o.z.object({client_id:o.z.string(),connection:o.z.literal("sms"),phone_number:o.z.string(),send:o.z.enum(["link","code"]),authParams:Mr.omit({client_id:!0})})])}}}},responses:{200:{description:"Status"}}}),async t=>{const e=t.req.valid("json"),{env:n}=t,{client_id:r,send:i,authParams:s,connection:a}=e,c=await t.env.data.clients.get(r);if(!c)throw new I(400,{message:"Client not found"});t.set("client_id",c.id),t.set("tenant_id",c.tenant.id);const l=a==="email"?e.email:e.phone_number,d=await n.data.loginSessions.create(c.tenant.id,{authParams:{...s,client_id:r,username:l},expires_at:new Date(Date.now()+Na).toISOString(),csrf_token:ke(),...Ht(t.req)}),p=await n.data.codes.create(c.tenant.id,{code_id:Tn(),code_type:"otp",login_id:d.id,expires_at:new Date(Date.now()+Na).toISOString()});return i==="link"?await fd(t,{to:l,code:p.code_id,authParams:{...s,client_id:r}}):await nm(t,{to:l,code:p.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(It),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:d,nonce:p}=t.req.valid("query"),f=await Ai(e,n);return t.set("client_id",f.id),t.set("tenant_id",f.tenant.id),t.set("connection","email"),ld(t,f,{client_id:n,redirect_uri:s,state:a,nonce:p,scope:c,audience:l,response_type:d},r,i,!1,!0)});class jr extends I{constructor(n,r){super(n,r);te(this,"_code");this._code=r==null?void 0:r.code}get code(){return this._code}}async function gd(t,e,n,r,i){const{env:s}=t,{username:a}=n;if(t.set("username",a),!a)throw new I(400,{message:"Username is required"});const c=await fr({userAdapter:t.env.data.users,tenant_id:e.tenant.id,username:a,provider:"auth2"});if(!c){const h=we(t,{type:ge.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(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 jr(403,{message:"User not found",code:"USER_NOT_FOUND"});t.set("connection",c.connection),t.set("user_id",l.user_id);const d=await s.data.passwords.get(e.tenant.id,c.user_id);if(!(d&&await oi.compare(n.password,d.password))){const h=we(t,{type:ge.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(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(h=>h.type===ge.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(h.date)>new Date(Date.now()-1e3*60*5)).length>=3){const h=we(t,{type:ge.FAILED_LOGIN,description:"Too many failed login attempts"});throw zt(t,t.env.data.logs.create(e.tenant.id,h)),new jr(403,{message:"Too many failed login attempts",code:"TOO_MANY_FAILED_LOGINS"})}if(!c.email_verified&&e.email_validation==="enforced"){await hd(t,c);const h=we(t,{type:ge.FAILED_LOGIN,description:"Email not verified"});throw await t.env.data.logs.create(e.tenant.id,h),new jr(403,{message:"Email not verified",code:"EMAIL_NOT_VERIFIED"})}const w=we(t,{type:ge.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return zt(t,t.env.data.logs.create(e.tenant.id,w)),ln(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function r1(t,e,n,r){await oo(t,{client:e,username: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()+t_).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:ke(),...Ht(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()+e_).toISOString()});await tm(t,n,c.code_id,r)}const i1=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 I(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 ld(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()+Qn*1e3).toISOString(),authParams:{client_id:n,username:s},csrf_token:ke(),...Ht(t.req)});return gd(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new I(400,{message:"Code or password required"})});function s1(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=_a(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=_a(a))==null?void 0:i.host)??null:c=((s=_a("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function _a(t){try{return new URL(t)}catch{return null}}async function o1({ctx:t,session:e,client:n,authParams:r,connection:i,login_hint:s}){const a=new URL(t.req.url);t.var.custom_domain&&(a.hostname=t.var.custom_domain);const c=await t.env.data.loginSessions.create(n.tenant.id,{expires_at:new Date(Date.now()+Qn*1e3).toISOString(),authParams:r,csrf_token:ke(),authorization_url:a.toString(),...Ht(t.req)});if(e&&s){const l=await t.env.data.users.get(n.tenant.id,e.user_id);if((l==null?void 0:l.email)===s)return ln(t,{client:n,loginSession:c,authParams:r,user:l,sessionId:e.id})}if(i==="email"&&s){const l=Tn();return await t.env.data.codes.create(n.tenant.id,{code_id:l,code_type:"otp",login_id:c.id,expires_at:new Date(Date.now()+Qn*1e3).toISOString()}),await fd(t,{code:l,to:s,authParams:r}),t.redirect(`/u/enter-code?state=${c.id}`)}return e?t.redirect(`/u/check-account?state=${c.id}`):t.redirect(`/u/login/identifier?state=${c.id}`)}function a1(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new I(403,{message:"Invalid realm"})}async function c1(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 I(403,{message:"Ticket not found"});const c=await s.data.loginSessions.get(e,a.login_id);if(!c||!c.authParams.username)throw new I(403,{message:"Session not found"});const l=await s.data.clients.get(c.authParams.client_id);if(!l)throw new I(403,{message:"Client not found"});t.set("client_id",c.authParams.client_id),await s.data.codes.used(e,n);const d=a1(i);let p=await oo(t,{username:c.authParams.username,provider:d,client:l,connection:d==="auth2"?"Username-Password-Authentication":"email",isSocial:!1,ip:t.req.header("x-real-ip")});t.set("username",p.email||p.phone_number),t.set("user_id",p.user_id);const f=await Gf(t,{user:p,client:l,loginSession:c});return ln(t,{authParams:{scope:(m=c.authParams)==null?void 0:m.scope,...r},loginSession:c,sessionId:f.id,user:p,client:l})}async function Mp(t,e){return`<!DOCTYPE html>
|
|
150
150
|
<html>
|
|
151
151
|
|
|
152
152
|
<head>
|
package/dist/authhero.mjs
CHANGED
|
@@ -18400,6 +18400,19 @@ async function Op(t, { code: e, state: n }) {
|
|
|
18400
18400
|
);
|
|
18401
18401
|
if (!s)
|
|
18402
18402
|
throw new C(403, { message: "Session not found" });
|
|
18403
|
+
if (s.authorization_url) {
|
|
18404
|
+
const _ = new URL(s.authorization_url).hostname, v = t.var.custom_domain || t.req.header("host") || "";
|
|
18405
|
+
if (_ !== v && _) {
|
|
18406
|
+
const S = new URL(`https://${_}/callback`);
|
|
18407
|
+
return S.searchParams.set("state", n), S.searchParams.set("code", e), new Response("Redirecting", {
|
|
18408
|
+
status: 307,
|
|
18409
|
+
// Temporary Redirect - preserves the HTTP method
|
|
18410
|
+
headers: {
|
|
18411
|
+
location: S.toString()
|
|
18412
|
+
}
|
|
18413
|
+
});
|
|
18414
|
+
}
|
|
18415
|
+
}
|
|
18403
18416
|
const o = await Ai(
|
|
18404
18417
|
r,
|
|
18405
18418
|
s.authParams.client_id
|
|
@@ -20022,7 +20035,9 @@ async function Vb({
|
|
|
20022
20035
|
connection: i,
|
|
20023
20036
|
login_hint: s
|
|
20024
20037
|
}) {
|
|
20025
|
-
const o =
|
|
20038
|
+
const o = new URL(t.req.url);
|
|
20039
|
+
t.var.custom_domain && (o.hostname = t.var.custom_domain);
|
|
20040
|
+
const c = await t.env.data.loginSessions.create(
|
|
20026
20041
|
n.tenant.id,
|
|
20027
20042
|
{
|
|
20028
20043
|
expires_at: new Date(
|
|
@@ -20030,40 +20045,40 @@ async function Vb({
|
|
|
20030
20045
|
).toISOString(),
|
|
20031
20046
|
authParams: r,
|
|
20032
20047
|
csrf_token: Ae(),
|
|
20033
|
-
authorization_url:
|
|
20048
|
+
authorization_url: o.toString(),
|
|
20034
20049
|
...Ft(t.req)
|
|
20035
20050
|
}
|
|
20036
20051
|
);
|
|
20037
20052
|
if (e && s) {
|
|
20038
|
-
const
|
|
20053
|
+
const l = await t.env.data.users.get(
|
|
20039
20054
|
n.tenant.id,
|
|
20040
20055
|
e.user_id
|
|
20041
20056
|
);
|
|
20042
|
-
if ((
|
|
20057
|
+
if ((l == null ? void 0 : l.email) === s)
|
|
20043
20058
|
return an(t, {
|
|
20044
20059
|
client: n,
|
|
20045
|
-
loginSession:
|
|
20060
|
+
loginSession: c,
|
|
20046
20061
|
authParams: r,
|
|
20047
|
-
user:
|
|
20062
|
+
user: l,
|
|
20048
20063
|
sessionId: e.id
|
|
20049
20064
|
});
|
|
20050
20065
|
}
|
|
20051
20066
|
if (i === "email" && s) {
|
|
20052
|
-
const
|
|
20067
|
+
const l = Bn();
|
|
20053
20068
|
return await t.env.data.codes.create(n.tenant.id, {
|
|
20054
|
-
code_id:
|
|
20069
|
+
code_id: l,
|
|
20055
20070
|
code_type: "otp",
|
|
20056
|
-
login_id:
|
|
20071
|
+
login_id: c.id,
|
|
20057
20072
|
expires_at: new Date(
|
|
20058
20073
|
Date.now() + Jn * 1e3
|
|
20059
20074
|
).toISOString()
|
|
20060
20075
|
}), await rd(t, {
|
|
20061
|
-
code:
|
|
20076
|
+
code: l,
|
|
20062
20077
|
to: s,
|
|
20063
20078
|
authParams: r
|
|
20064
|
-
}), t.redirect(`/u/enter-code?state=${
|
|
20079
|
+
}), t.redirect(`/u/enter-code?state=${c.id}`);
|
|
20065
20080
|
}
|
|
20066
|
-
return e ? t.redirect(`/u/check-account?state=${
|
|
20081
|
+
return e ? t.redirect(`/u/check-account?state=${c.id}`) : t.redirect(`/u/login/identifier?state=${c.id}`);
|
|
20067
20082
|
}
|
|
20068
20083
|
function zb(t) {
|
|
20069
20084
|
if (t === "Username-Password-Authentication")
|