authhero 0.111.0 → 0.112.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 +1 -1
- 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 Av(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 ja(await Nf(s))}const zv=1e3*60*60*24,Ev=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(Na)}},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:Na}},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()+zv).toISOString()});const n=await Xc({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 Xc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),Iv=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(sl)}},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)}),Cv=on.extend({clients:o.z.array(mn)}),Nv=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([Cv,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(rs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema: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(rs.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()});Zs.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 jv=on.extend({tenants:o.z.array(Jn)}),$v=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),jv])}},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(ss.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(ss.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})}),Ov=on.extend({logs:o.z.array(as)}),Tv=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(as),Ov])}},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:as}},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)}),Pv=on.extend({hooks:o.z.array(Kn)}),Bv=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),Pv])}},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(os.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(os.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")}),Rv=on.extend({connections:o.z.array(Jt)}),Lv=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),Rv])}},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(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: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(is.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})}),Uv=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Li.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let Ep=!1;function Bg(t){t.use(async(e,n)=>(Ep||(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"}}}}),Ep=!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 Vv(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 qv(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 Vv(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 Mv(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 Rg(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=Mv(p);if(!f||!await qv(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 Dv=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ui}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new 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(Ui.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),Hv=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:Xs}},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})}),Fv=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")}),Kv=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 Wv(t){const e=new o.OpenAPIHono;e.use(of({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})),Bg(e),e.use(async(r,i)=>(r.env.data=ro(r,t.dataAdapter),i())),e.use(od).use(Rg(e));const n=e.route("/branding",v0).route("/custom-domains",Kv).route("/email/providers",Dv).route("/users",Cy).route("/keys",Ev).route("/users-by-email",Iv).route("/clients",Nv).route("/tenants",$v).route("/logs",Tv).route("/hooks",Bv).route("/connections",Lv).route("/prompts",Uv).route("/sessions",Hv).route("/refresh_tokens",Fv);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function Gv(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Ip;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ip||(Ip={}));var Cp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Cp||(Cp={}));function Jv(t){return Ug(t,Zv,ti.Include)}function Lg(t){return Ug(t,Yv,ti.None)}function Ug(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 Zv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Yv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ti;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ti||(ti={}));var Np;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Np||(Np={}));class Xv{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 jp=new Xv;function St(t,e){return(t<<32-e|t>>>e)>>>0}function Qv(t){const e=new eb;return e.update(t),e.digest()}class eb{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),jp.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)jp.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=(St(this.w[d-2],17)^St(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(St(this.w[d-15],7)^St(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=(St(s,6)^St(s,11)^St(s,25))>>>0,f=(s&a^~s&c)>>>0,m=l+p+f+tb[d]+this.w[d]|0,w=(St(e,2)^St(e,13)^St(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 tb=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 nb{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 rb(t){const e=Qv(new TextEncoder().encode(t));return Lg(e)}function ib(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Lg(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 ya(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Jv(n)}async function Fs(t){let e;try{e=await fetch(t)}catch(n){throw new qg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Vg(n)}catch{throw new Xn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);return new nb(n)}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}async function sb(t){let e;try{e=await fetch(t)}catch(n){throw new qg(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=Vg(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 Hi(e.status)}function Vg(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 ob(e,n,r,i)}class qg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class ob extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);te(this,"code");te(this,"description");te(this,"uri");te(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Hi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class 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=rb(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=ya(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Fs(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=ya(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Fs(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=ya(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await sb(i)}}var ni;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ni||(ni={}));var $p;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})($p||($p={}));var Op;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Op||(Op={}));function Vr(t){return ab(t,cb,Ks.None)}function ab(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===Ks.Include&&(r+="=")}return r}const cb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Ks;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ks||(Ks={}));var Tp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Tp||(Tp={}));function lb(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function db(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const ub="https://appleid.apple.com/auth/authorize",pb="https://appleid.apple.com/auth/token";class Mg{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(ub);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(pb,n);return await Fs(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,db(r,i)));return lb(r,i,s)}}const fb="https://www.facebook.com/v16.0/dialog/oauth",hb="https://graph.facebook.com/v16.0/oauth/access_token";class Dg{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(fb);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(hb,n);return await Fs(r)}}const gb="https://accounts.google.com/o/oauth2/v2/auth",Pp="https://oauth2.googleapis.com/token",mb="https://oauth2.googleapis.com/revoke";let Hg=class{constructor(e,n,r){te(this,"client");this.client=new ad(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(gb,e,ni.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Pp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Pp,e,[])}async revokeToken(e){await this.client.revokeToken(mb,e)}};const Zo=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();Zo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function _b(t){return t.ISSUER}function ct(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Fg(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 yb(t,e){var l,d;const{options:n,keyArray:r}=Fg(e),i=new Mg(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 wb(t,e,n){const{options:r,keyArray:i}=Fg(e),a=await new Mg(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=Zo.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 vb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:yb,validateAuthorizationCodeAndGetUser:wb},Symbol.toStringTag,{value:"Module"}));async function bb(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 Dg(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 xb(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 Dg(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 kb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:bb,validateAuthorizationCodeAndGetUser:xb},Symbol.toStringTag,{value:"Module"}));async function Sb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Hg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),s=ib();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function Ab(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 Hg(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=Zo.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 zb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Sb,validateAuthorizationCodeAndGetUser:Ab},Symbol.toStringTag,{value:"Module"}));async function Eb(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 Ib(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=Zo.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 Cb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Eb,validateAuthorizationCodeAndGetUser:Ib},Symbol.toStringTag,{value:"Module"}));function Kg(t,e){const n=t.env.STRATEGIES||{},i={apple:vb,facebook:kb,"google-oauth2":zb,vipps:Cb,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Yo(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);return l!=null&&l.options?Jt.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${ct(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||[],`${ct(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Xo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return Nb(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function Nb(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function jb(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:he.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(),...cn(t.req)}));const c=await Kg(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+F0*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Bp(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 Yo(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:he.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:he.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Redirect URI not defined"})}if(!Xo(s.authParams.redirect_uri,a.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,v=we(t,{type:he.FAILED_LOGIN,description:_});throw await r.data.logs.create(a.tenant.id,v),new I(403,{message:_})}const d=await Kg(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 so(t,{client:a,email: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 Rp(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:he.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});rt(t,t.env.data.logs.create(t.var.tenant_id,d));const p=new URL(l);return Gv(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${ct(t.env)}enter-email?state=${c.id}&error=${n}`)}const $b=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 Rp(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("form");if(r)return Rp(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}),Ob=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(!Xo(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=ls(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:he.SUCCESS_LOGOUT,description:"User successfully logged out"});return await t.env.data.logs.create(r.tenant.id,c),new Response("Redirecting",{status:302,headers:{"set-cookie":Z0(r.tenant.id,t.req.header("host")),location:s}})}),Lp=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()}),Tb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Lp}},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(Lp.parse({...e,sub:e.user_id}))}),Pb=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:gf}},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=${$i}, stale-while-revalidate=${$i*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ca}},description:"List of tenants"}}}),async t=>{const e=Ca.parse({issuer:_b(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=${$i}, stale-while-revalidate=${$i*2}, stale-if-error=86400`}})});function Fi(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const Wg=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 Bb(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&&!Fi(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 no(t,{authParams:r,client:n});return t.json(i)}const Rb=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 Lb(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(!Fi(n.client_secret,e.client_secret)&&!Fi(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 q0(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(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 Ub=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 Vb(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}})}const qb=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),realm:o.z.enum(["email","sms"]),otp:o.z.string(),authParams:Mr.optional()});async function Mb(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 Qo(t,s,i||{client_id:e,response_type:It.TOKEN_ID_TOKEN,response_mode:Rt.WEB_MESSAGE},n,r)}async function Qo(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=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!d||d.authParams.username!==r)throw new I(400,{message:"Code not found or expired"});const p=cn(t.req);if(a&&d.ip!==p.ip)return t.redirect(`${ct(t.env)}invalid-session?state=${d.id}`);if(n.redirect_uri&&!Xo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const f=await so(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),ln(t,{user:f,client:e,loginSession:d,authParams:n,ticketAuth:s})}const Up=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Db=o.z.union([Wg.extend(Up.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(),...Up.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 Hb(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 Fb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Db}}}},responses:{200:{content:{"application/json":{schema:bf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=Hb(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 Lb(t,Rb.parse(r));case Wn.ClientCredential:return Bb(t,Wg.parse(r));case Wn.RefreshToken:return Vb(t,Ub.parse(r));case Wn.OTP:return Mb(t,qb.parse(r));default:throw new I(400,{message:"Not implemented"})}});var cd={exports:{}};const ld=[{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}],Gg=(t,e=ld,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};cd.exports={passwordStrength:Gg,defaultOptions:ld};var Kb=cd.exports.passwordStrength=Gg;cd.exports.defaultOptions=ld;function dd(t){return Kb(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 Ai(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 Wb(t,e){var a,c;const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});const r=(await t.env.data.connections.list(t.var.tenant_id)).connections.find(l=>l.strategy==="sms")||(t.env.DEFAULT_TENANT_ID?(await t.env.data.connections.list(t.env.DEFAULT_TENANT_ID)).connections.find(l=>l.strategy==="sms"):null);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.name,tenantId:n.id}})}async function Jg(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=`${ct(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await Ai(t,{to:e,subject:re("reset_password_title",a),html:`Click here to reset your password: ${ct(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 Zg(t,{to:e,code:n,connection: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=new URL(ct(t.env)),a={vendorName:i.name,vendorId:i.id,loginDomain:s.hostname,code:n,lng:i.language||"en"};r==="email"?await Ai(t,{to:e,subject:re("code_email_subject",a),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",buttonColor:i.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)}}):r==="sms"&&await Wb(t,{to:e,text:re("sms_code_text",a),code:n});const c=we(t,{type:he.CODE_LINK_SENT,description:e});rt(t,t.env.data.logs.create(i.id,c))}async function ud(t,{to:e,code:n,authParams:r,connection:i}){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const a=new URL(je(t.env));a.pathname="passwordless/verify_redirect",a.searchParams.set("verification_code",n),a.searchParams.set("connection",i),a.searchParams.set("client_id",r.client_id),a.searchParams.set("redirect_uri",r.redirect_uri),a.searchParams.set("username",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:s.name,code:n,lng:s.language||"en"};if(i!=="email")throw new I(400,{message:"Only email connections are supported for magic links"});await Ai(t,{to:e,subject:re("code_email_subject",c),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.name,logo:s.logo||"",supportUrl:s.support_url||"",magicLink:a.toString(),buttonColor:s.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:he.CODE_LINK_SENT,description:e});rt(t,t.env.data.logs.create(s.id,l))}async function pd(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Ai(t,{to:e.email,subject:re("welcome_to_your_account",r),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${ct(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 Gb(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=`${ct(t.env)}signup?state=${r}&code=${n}`;await Ai(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 Jb=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.clients.get(r);if(!i)throw new I(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!dd(n))throw new I(400,{message:"Password does not meet the requirements"});if(await ds({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email: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|${Qs()}`,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 pd(t,a);const l=we(t,{type:he.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:a.user_id,email:a.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.clients.get(n);if(!r)throw new 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,email:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+Qn*1e3).toISOString(),authParams:s,csrf_token:ke(),...cn(t.req)});return await Jg(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 Pn(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}const Zb=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()+$a).toISOString(),csrf_token:ke(),...cn(t.req)}),p=await n.data.codes.create(c.tenant.id,{code_id:Pn(),code_type:"otp",login_id:d.id,expires_at:new Date(Date.now()+$a).toISOString()});return i==="link"?await ud(t,{to:l,code:p.code_id,authParams:{...s,client_id:r},connection:a}):await Zg(t,{to:l,code:p.code_id,connection:a}),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 Yo(e,n);return t.set("client_id",f.id),t.set("tenant_id",f.tenant.id),t.set("connection","email"),Qo(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 fd(t,e,n,r,i){const{env:s}=t,a=n.username;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,email:a,provider:"auth2"});if(!c){const h=we(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw rt(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:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw rt(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===he.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(h.date)>new Date(Date.now()-1e3*60*5)).length>=3){const h=we(t,{type:he.FAILED_LOGIN,description:"Too many failed login attempts"});throw rt(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 pd(t,c);const h=we(t,{type:he.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:he.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return rt(t,t.env.data.logs.create(e.tenant.id,w)),ln(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Yb(t,e,n,r){await so(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=Pn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Pn(),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()+G0).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:ke(),...cn(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()+W0).toISOString()});await Jg(t,n,c.code_id,r)}const Xb=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 Qo(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(),...cn(t.req)});return fd(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new I(400,{message:"Code or password required"})});function Qb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=wa(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=wa(a))==null?void 0:i.host)??null:c=((s=wa("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function wa(t){try{return new URL(t)}catch{return null}}async function e1({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,...cn(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=Pn();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 ud(t,{connection:i,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/enter-email?state=${a.id}`)}function t1(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new I(403,{message:"Invalid realm"})}async function n1(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=t1(i);let p=await so(t,{email: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),t.set("user_id",p.user_id);const f=await Hf(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 Vp(t,e){return`<!DOCTYPE html>
|
|
149
|
+
`,r}async function Av(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 ja(await Nf(s))}const zv=1e3*60*60*24,Ev=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(Na)}},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:Na}},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()+zv).toISOString()});const n=await Xc({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 Xc({name:`CN=${t.env.ORGANIZATION_NAME}`});return await t.env.data.keys.create(r),t.text("OK")}),Iv=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(sl)}},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)}),Cv=on.extend({clients:o.z.array(mn)}),Nv=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([Cv,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(rs.shape).partial()}}},params:o.z.object({id:o.z.string()}),headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:write"]}],responses:{200:{content:{"application/json":{schema: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(rs.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()});Zs.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 jv=on.extend({tenants:o.z.array(Jn)}),$v=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),jv])}},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(ss.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(ss.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})}),Ov=on.extend({logs:o.z.array(as)}),Tv=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(as),Ov])}},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:as}},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)}),Pv=on.extend({hooks:o.z.array(Kn)}),Bv=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),Pv])}},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(os.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(os.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")}),Rv=on.extend({connections:o.z.array(Jt)}),Lv=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),Rv])}},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(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: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(is.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})}),Uv=new o.OpenAPIHono().openapi(o.createRoute({tags:["prompts"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Li}},description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.promptSettings.get(e);return n?t.json(n):t.json(Li.parse({}))}).openapi(o.createRoute({tags:["prompts"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Li.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Prompts settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json"),r=await t.env.data.promptSettings.get(e);return Object.assign(r,n),await t.env.data.promptSettings.set(e,r),t.json(r)});let Ep=!1;function Bg(t){t.use(async(e,n)=>(Ep||(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"}}}}),Ep=!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 Vv(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 qv(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 Vv(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 Mv(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 Rg(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=Mv(p);if(!f||!await qv(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 Dv=new o.OpenAPIHono().openapi(o.createRoute({tags:["emails"],method:"get",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()})},security:[{Bearer:["auth:read"]}],responses:{200:{content:{"application/json":{schema:Ui}},description:"Email provider"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=await t.env.data.emailProviders.get(e);if(!n)throw new 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(Ui.shape)}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.create(e,n),t.text("OK",{status:201})}).openapi(o.createRoute({tags:["emails"],method:"patch",path:"/",request:{headers:o.z.object({"tenant-id":o.z.string()}),body:{content:{"application/json":{schema:o.z.object(Ui.shape).partial()}}}},security:[{Bearer:["auth:write"]}],responses:{200:{description:"Branding settings"}}}),async t=>{const{"tenant-id":e}=t.req.valid("header"),n=t.req.valid("json");return await t.env.data.emailProviders.update(e,n),t.text("OK")}),Hv=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:Xs}},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})}),Fv=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")}),Kv=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 Wv(t){const e=new o.OpenAPIHono;e.use(of({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})),Bg(e),e.use(async(r,i)=>(r.env.data=ro(r,t.dataAdapter),i())),e.use(od).use(Rg(e));const n=e.route("/branding",v0).route("/custom-domains",Kv).route("/email/providers",Dv).route("/users",Cy).route("/keys",Ev).route("/users-by-email",Iv).route("/clients",Nv).route("/tenants",$v).route("/logs",Tv).route("/hooks",Bv).route("/connections",Lv).route("/prompts",Uv).route("/sessions",Hv).route("/refresh_tokens",Fv);return n.doc("/spec",{openapi:"3.0.0",info:{version:"1.0.0",title:"Management api"},security:[{oauth2:["openid","email","profile"]}]}),n}function Gv(t,e){Object.keys(e).forEach(n=>{const r=e[n];r!=null&&r.length&&t.searchParams.set(n,r)})}var Ip;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ip||(Ip={}));var Cp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Cp||(Cp={}));function Jv(t){return Ug(t,Zv,ti.Include)}function Lg(t){return Ug(t,Yv,ti.None)}function Ug(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 Zv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Yv="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var ti;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(ti||(ti={}));var Np;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Np||(Np={}));class Xv{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 jp=new Xv;function St(t,e){return(t<<32-e|t>>>e)>>>0}function Qv(t){const e=new eb;return e.update(t),e.digest()}class eb{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),jp.putUint64(this.blocks,this.l,this.blockSize-8),this.process();const e=new Uint8Array(32);for(let n=0;n<8;n++)jp.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=(St(this.w[d-2],17)^St(this.w[d-2],19)^this.w[d-2]>>>10)>>>0,f=(St(this.w[d-15],7)^St(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=(St(s,6)^St(s,11)^St(s,25))>>>0,f=(s&a^~s&c)>>>0,m=l+p+f+tb[d]+this.w[d]|0,w=(St(e,2)^St(e,13)^St(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 tb=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 nb{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 rb(t){const e=Qv(new TextEncoder().encode(t));return Lg(e)}function ib(){const t=new Uint8Array(32);return crypto.getRandomValues(t),Lg(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 ya(t,e){const n=new TextEncoder().encode(`${t}:${e}`);return Jv(n)}async function Fs(t){let e;try{e=await fetch(t)}catch(n){throw new qg(n)}if(e.status===400||e.status===401){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);let r;try{r=Vg(n)}catch{throw new Xn(e.status,n)}throw r}if(e.status===200){let n;try{n=await e.json()}catch{throw new Hi(e.status)}if(typeof n!="object"||n===null)throw new Xn(e.status,n);return new nb(n)}throw e.body!==null&&await e.body.cancel(),new Hi(e.status)}async function sb(t){let e;try{e=await fetch(t)}catch(n){throw new qg(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=Vg(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 Hi(e.status)}function Vg(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 ob(e,n,r,i)}class qg extends Error{constructor(e){super("Failed to send request",{cause:e})}}class ob extends Error{constructor(n,r,i,s){super(`OAuth request error: ${n}`);te(this,"code");te(this,"description");te(this,"uri");te(this,"state");this.code=n,this.description=r,this.uri=i,this.state=s}}class Hi extends Error{constructor(n){super("Unexpected error response");te(this,"status");this.status=n}}class 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=rb(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=ya(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Fs(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=ya(this.clientId,this.clientPassword);s.headers.set("Authorization",`Basic ${c}`)}return await Fs(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=ya(this.clientId,this.clientPassword);i.headers.set("Authorization",`Basic ${s}`)}await sb(i)}}var ni;(function(t){t[t.S256=0]="S256",t[t.Plain=1]="Plain"})(ni||(ni={}));var $p;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})($p||($p={}));var Op;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Op||(Op={}));function Vr(t){return ab(t,cb,Ks.None)}function ab(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===Ks.Include&&(r+="=")}return r}const cb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";var Ks;(function(t){t[t.Include=0]="Include",t[t.None=1]="None"})(Ks||(Ks={}));var Tp;(function(t){t[t.Required=0]="Required",t[t.Ignore=1]="Ignore"})(Tp||(Tp={}));function lb(t,e,n){const r=Vr(new TextEncoder().encode(t)),i=Vr(new TextEncoder().encode(e)),s=Vr(n);return r+"."+i+"."+s}function db(t,e){const n=Vr(new TextEncoder().encode(t)),r=Vr(new TextEncoder().encode(e)),i=n+"."+r;return new TextEncoder().encode(i)}const ub="https://appleid.apple.com/auth/authorize",pb="https://appleid.apple.com/auth/token";class Mg{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(ub);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(pb,n);return await Fs(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,db(r,i)));return lb(r,i,s)}}const fb="https://www.facebook.com/v16.0/dialog/oauth",hb="https://graph.facebook.com/v16.0/oauth/access_token";class Dg{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(fb);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(hb,n);return await Fs(r)}}const gb="https://accounts.google.com/o/oauth2/v2/auth",Pp="https://oauth2.googleapis.com/token",mb="https://oauth2.googleapis.com/revoke";let Hg=class{constructor(e,n,r){te(this,"client");this.client=new ad(e,n,r)}createAuthorizationURL(e,n,r){return this.client.createAuthorizationURLWithPKCE(gb,e,ni.S256,n,r)}async validateAuthorizationCode(e,n){return await this.client.validateAuthorizationCode(Pp,e,n)}async refreshAccessToken(e){return await this.client.refreshAccessToken(Pp,e,[])}async revokeToken(e){await this.client.revokeToken(mb,e)}};const Zo=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();Zo.omit({iat:!0,auth_time:!0,nonce:!0,acr:!0,amr:!0,azp:!0,at_hash:!0,c_hash:!0});function _b(t){return t.ISSUER}function ct(t){return t.UNIVERSAL_LOGIN_URL||`${t.ISSUER}u/`}function je(t){return t.OAUTH_API_URL||t.ISSUER}function Fg(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 yb(t,e){var l,d;const{options:n,keyArray:r}=Fg(e),i=new Mg(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 wb(t,e,n){const{options:r,keyArray:i}=Fg(e),a=await new Mg(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=Zo.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 vb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:yb,validateAuthorizationCodeAndGetUser:wb},Symbol.toStringTag,{value:"Module"}));async function bb(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 Dg(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 xb(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 Dg(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 kb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:bb,validateAuthorizationCodeAndGetUser:xb},Symbol.toStringTag,{value:"Module"}));async function Sb(t,e){var c;const{options:n}=e;if(!(n!=null&&n.client_id)||!n.client_secret)throw new Error("Missing required Google authentication parameters");const r=new Hg(n.client_id,n.client_secret,`${je(t.env)}callback`),i=ke(),s=ib();return{redirectUrl:r.createAuthorizationURL(i,s,((c=n.scope)==null?void 0:c.split(" "))??["email","profile"]).href,code:i,codeVerifier:s}}async function Ab(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 Hg(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=Zo.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 zb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Sb,validateAuthorizationCodeAndGetUser:Ab},Symbol.toStringTag,{value:"Module"}));async function Eb(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 Ib(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=Zo.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 Cb=Object.freeze(Object.defineProperty({__proto__:null,getRedirect:Eb,validateAuthorizationCodeAndGetUser:Ib},Symbol.toStringTag,{value:"Module"}));function Kg(t,e){const n=t.env.STRATEGIES||{},i={apple:vb,facebook:kb,"google-oauth2":zb,vipps:Cb,...n}[e];if(!i)throw new Error(`Strategy ${e} not found`);return i}async function Yo(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);return l!=null&&l.options?Jt.parse({...l||{},...c,options:{...l.options||{},...c.options}}):c}).filter(c=>c);return{...n,web_origins:[...(r==null?void 0:r.web_origins)||[],...n.web_origins||[],`${ct(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||[],`${ct(t)}info`],connections:a,tenant:{...(r==null?void 0:r.tenant)||{},...n.tenant}}}function Xo(t,e=[],n={}){try{const r=new URL(t);return e.some(i=>{try{return Nb(r,new URL(i),n.allowPathWildcards)}catch{return!1}})}catch{return!1}}function Nb(t,e,n){if(t.protocol!==e.protocol)return!1;if(n&&e.pathname.includes("*")){const r=e.pathname.replace(/\*/g,".*").replace(/\//g,"\\/");if(!new RegExp(`^${r}$`).test(t.pathname))return!1}else if(t.pathname!==e.pathname)return!1;if(e.hostname.startsWith("*.")&&e.hostname.split(".").length>2&&["http:","https:"].includes(e.protocol)){const r=e.hostname.split(".").slice(1).join(".");return t.hostname.endsWith(r)}return t.hostname===e.hostname}async function jb(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:he.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(),...cn(t.req)}));const c=await Kg(t,i.strategy).getRedirect(t,i);return await t.env.data.codes.create(e.tenant.id,{login_id:s.id,code_id:c.code,code_type:"oauth2_state",connection_id:i.id,code_verifier:c.codeVerifier,expires_at:new Date(Date.now()+F0*1e3).toISOString()}),t.redirect(c.redirectUrl)}async function Bp(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 Yo(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:he.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:he.FAILED_LOGIN,description:"Redirect URI not defined"});throw await r.data.logs.create(a.tenant.id,_),new I(403,{message:"Redirect URI not defined"})}if(!Xo(s.authParams.redirect_uri,a.callbacks||[],{allowPathWildcards:!0})){const _=`Invalid redirect URI - ${s.authParams.redirect_uri}`,v=we(t,{type:he.FAILED_LOGIN,description:_});throw await r.data.logs.create(a.tenant.id,v),new I(403,{message:_})}const d=await Kg(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 so(t,{client:a,email: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 Rp(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:he.FAILED_LOGIN,description:`Failed connection login: ${i} ${n}, ${r}`});rt(t,t.env.data.logs.create(t.var.tenant_id,d));const p=new URL(l);return Gv(p,{error:n,error_description:r,error_reason:s,error_code:i,state:c.authParams.state}),t.redirect(`${ct(t.env)}enter-email?state=${c.id}&error=${n}`)}const $b=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 Rp(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}).openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:o.z.object({state:o.z.string(),code:o.z.string().optional(),scope:o.z.string().optional(),hd:o.z.string().optional(),error:o.z.string().optional(),error_description:o.z.string().optional(),error_code:o.z.string().optional(),error_reason:o.z.string().optional()})}}}},responses:{302:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{state:e,code:n,error:r,error_description:i,error_code:s,error_reason:a}=t.req.valid("form");if(r)return Rp(t,e,r,i,s,a);if(!n)throw new I(400,{message:"Code is required"});return Bp(t,{code:n,state:e})}),Ob=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(!Xo(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=ls(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:he.SUCCESS_LOGOUT,description:"User successfully logged out"});return await t.env.data.logs.create(r.tenant.id,c),new Response("Redirecting",{status:302,headers:{"set-cookie":Z0(r.tenant.id,t.req.header("host")),location:s}})}),Lp=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()}),Tb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"get",path:"/",request:{},security:[{Bearer:["openid"]}],responses:{200:{content:{"application/json":{schema:Lp}},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(Lp.parse({...e,sub:e.user_id}))}),Pb=new o.OpenAPIHono().openapi(o.createRoute({tags:["well known"],method:"get",path:"/jwks.json",request:{},responses:{200:{content:{"application/json":{schema:gf}},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=${$i}, stale-while-revalidate=${$i*2}, stale-if-error=86400`}})}).openapi(o.createRoute({tags:["well known"],method:"get",path:"/openid-configuration",request:{},responses:{200:{content:{"application/json":{schema:Ca}},description:"List of tenants"}}}),async t=>{const e=Ca.parse({issuer:_b(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=${$i}, stale-while-revalidate=${$i*2}, stale-if-error=86400`}})});function Fi(t,e){if(!t||!e||t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}const Wg=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 Bb(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&&!Fi(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 no(t,{authParams:r,client:n});return t.json(i)}const Rb=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 Lb(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(!Fi(n.client_secret,e.client_secret)&&!Fi(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 q0(e.code_verifier,i.authParams.code_challenge_method);if(!Fi(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 Ub=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 Vb(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}})}const qb=o.z.object({client_id:o.z.string(),username:o.z.string().transform(t=>t.toLowerCase()),realm:o.z.enum(["email","sms"]),otp:o.z.string(),authParams:Mr.optional()});async function Mb(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 Qo(t,s,i||{client_id:e,response_type:It.TOKEN_ID_TOKEN,response_mode:Rt.WEB_MESSAGE},n,r)}async function Qo(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=await c.data.loginSessions.get(e.tenant.id,l.login_id);if(!d||d.authParams.username!==r)throw new I(400,{message:"Code not found or expired"});const p=cn(t.req);if(a&&d.ip!==p.ip)return t.redirect(`${ct(t.env)}invalid-session?state=${d.id}`);if(n.redirect_uri&&!Xo(n.redirect_uri,e.callbacks,{allowPathWildcards:!0}))throw new I(400,{message:`Invalid redirect URI - ${n.redirect_uri}`});const f=await so(t,{client:e,email:r,provider:"email",connection:"email",isSocial:!1,ip:t.req.header("x-real-ip")});return await c.data.codes.used(e.tenant.id,i),ln(t,{user:f,client:e,loginSession:d,authParams:n,ticketAuth:s})}const Up=o.z.object({client_id:o.z.string().optional(),client_secret:o.z.string().optional()}),Db=o.z.union([Wg.extend(Up.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(),...Up.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 Hb(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 Fb=new o.OpenAPIHono().openapi(o.createRoute({tags:["oauth2"],method:"post",path:"/",request:{body:{content:{"application/x-www-form-urlencoded":{schema:Db}}}},responses:{200:{content:{"application/json":{schema:bf}},description:"Tokens"}}}),async t=>{const e=t.req.valid("form"),n=Hb(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 Lb(t,Rb.parse(r));case Wn.ClientCredential:return Bb(t,Wg.parse(r));case Wn.RefreshToken:return Vb(t,Ub.parse(r));case Wn.OTP:return Mb(t,qb.parse(r));default:throw new I(400,{message:"Not implemented"})}});var cd={exports:{}};const ld=[{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}],Gg=(t,e=ld,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};cd.exports={passwordStrength:Gg,defaultOptions:ld};var Kb=cd.exports.passwordStrength=Gg;cd.exports.defaultOptions=ld;function dd(t){return Kb(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 Ai(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 Wb(t,e){var a,c;const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});const r=(await t.env.data.connections.list(t.var.tenant_id)).connections.find(l=>l.strategy==="sms")||(t.env.DEFAULT_TENANT_ID?(await t.env.data.connections.list(t.env.DEFAULT_TENANT_ID)).connections.find(l=>l.strategy==="sms"):null);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.name,tenantId:n.id}})}async function Jg(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=`${ct(t.env)}reset-password?state=${r}&code=${n}`,a={vendorName:i.name,lng:i.language||"en"};await Ai(t,{to:e,subject:re("reset_password_title",a),html:`Click here to reset your password: ${ct(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 Zg(t,{to:e,code:n,connection: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=new URL(ct(t.env)),a={vendorName:i.name,vendorId:i.id,loginDomain:s.hostname,code:n,lng:i.language||"en"};r==="email"?await Ai(t,{to:e,subject:re("code_email_subject",a),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-code",data:{code:n,vendorName:i.name,logo:i.logo||"",supportUrl:i.support_url||"",buttonColor:i.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)}}):r==="sms"&&await Wb(t,{to:e,text:re("sms_code_text",a),code:n});const c=we(t,{type:he.CODE_LINK_SENT,description:e});rt(t,t.env.data.logs.create(i.id,c))}async function ud(t,{to:e,code:n,authParams:r,connection:i}){const s=await t.env.data.tenants.get(t.var.tenant_id);if(!s)throw new I(500,{message:"Tenant not found"});if(!r.redirect_uri)throw new I(400,{message:"redirect_uri is required"});const a=new URL(je(t.env));a.pathname="passwordless/verify_redirect",a.searchParams.set("verification_code",n),a.searchParams.set("connection",i),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:s.name,code:n,lng:s.language||"en"};if(i!=="email")throw new I(400,{message:"Only email connections are supported for magic links"});await Ai(t,{to:e,subject:re("code_email_subject",c),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-link",data:{code:n,vendorName:s.name,logo:s.logo||"",supportUrl:s.support_url||"",magicLink:a.toString(),buttonColor:s.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:he.CODE_LINK_SENT,description:e});rt(t,t.env.data.logs.create(s.id,l))}async function pd(t,e){const n=await t.env.data.tenants.get(t.var.tenant_id);if(!n)throw new I(500,{message:"Tenant not found"});const r={vendorName:n.name,lng:n.language||"en"};await Ai(t,{to:e.email,subject:re("welcome_to_your_account",r),html:`Click here to validate your email: ${ct(t.env)}validate-email`,template:"auth-verify-email",data:{vendorName:n.name,logo:n.logo||"",emailValidationUrl:`${ct(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 Gb(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=`${ct(t.env)}signup?state=${r}&code=${n}`;await Ai(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 Jb=new o.OpenAPIHono().openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/signup",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase()),password:o.z.string()})}}}},responses:{200:{content:{"application/json":{schema:o.z.object({_id:o.z.string(),email:o.z.string(),email_verified:o.z.boolean(),app_metadata:o.z.object({}),user_metadata:o.z.object({})})}},description:"Created user"}}}),async t=>{const{email:e,password:n,client_id:r}=t.req.valid("json"),i=await t.env.data.clients.get(r);if(!i)throw new I(400,{message:"Client not found"});if(t.set("client_id",i.id),t.set("tenant_id",i.tenant.id),!dd(n))throw new I(400,{message:"Password does not meet the requirements"});if(await ds({userAdapter:t.env.data.users,tenant_id:i.tenant.id,email: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|${Qs()}`,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 pd(t,a);const l=we(t,{type:he.SUCCESS_SIGNUP,description:"Successful signup"});return await t.env.data.logs.create(i.tenant.id,l),t.json({_id:a.user_id,email:a.email,email_verified:!1,app_metadata:{},user_metadata:{}})}).openapi(o.createRoute({tags:["dbconnections"],method:"post",path:"/change_password",request:{body:{content:{"application/json":{schema:o.z.object({client_id:o.z.string(),connection:o.z.literal("Username-Password-Authentication"),email:o.z.string().transform(t=>t.toLowerCase())})}}}},responses:{200:{description:"Redirect to the client's redirect uri"}}}),async t=>{const{email:e,client_id:n}=t.req.valid("json"),r=await t.env.data.clients.get(n);if(!r)throw new 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,email:e,provider:"auth2"}))return t.html("If an account with that email exists, we've sent instructions to reset your password.");const s={client_id:n,username:e},a=await t.env.data.loginSessions.create(r.tenant.id,{expires_at:new Date(Date.now()+Qn*1e3).toISOString(),authParams:s,csrf_token:ke(),...cn(t.req)});return await Jg(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 Pn(){const t="1234567890";let e="";for(let n=0;n<6;n+=1)e+=t[Math.floor(Math.random()*10)];return e.toString()}const Zb=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()+$a).toISOString(),csrf_token:ke(),...cn(t.req)}),p=await n.data.codes.create(c.tenant.id,{code_id:Pn(),code_type:"otp",login_id:d.id,expires_at:new Date(Date.now()+$a).toISOString()});return i==="link"?await ud(t,{to:l,code:p.code_id,authParams:{...s,client_id:r},connection:a}):await Zg(t,{to:l,code:p.code_id,connection:a}),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 Yo(e,n);return t.set("client_id",f.id),t.set("tenant_id",f.tenant.id),t.set("connection","email"),Qo(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 fd(t,e,n,r,i){const{env:s}=t,a=n.username;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,email:a,provider:"auth2"});if(!c){const h=we(t,{type:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid user"});throw rt(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:he.FAILED_LOGIN_INCORRECT_PASSWORD,description:"Invalid password"});throw rt(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===he.FAILED_LOGIN_INCORRECT_PASSWORD&&new Date(h.date)>new Date(Date.now()-1e3*60*5)).length>=3){const h=we(t,{type:he.FAILED_LOGIN,description:"Too many failed login attempts"});throw rt(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 pd(t,c);const h=we(t,{type:he.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:he.SUCCESS_LOGIN,description:"Successful login",strategy_type:"Username-Password-Authentication",strategy:"Username-Password-Authentication"});return rt(t,t.env.data.logs.create(e.tenant.id,w)),ln(t,{client:e,authParams:n,user:l,ticketAuth:i,loginSession:r})}async function Yb(t,e,n,r){await so(t,{client:e,email:n,provider:"auth2",connection:"Username-Password-Authentication",isSocial:!1,ip:t.req.header("x-real-ip")});let i=Pn(),s=await t.env.data.codes.get(e.tenant.id,i,"password_reset");for(;s;)i=Pn(),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()+G0).toISOString(),authParams:{client_id:e.id,username:n},csrf_token:ke(),...cn(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()+W0).toISOString()});await Jg(t,n,c.code_id,r)}const Xb=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 Qo(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(),...cn(t.req)});return fd(t,i,{username:s,password:e.password,client_id:n},a,!0)}else throw new I(400,{message:"Code or password required"})});function Qb(t,e){var r,i,s;if(!t||e.length===0)return!1;const n=((r=wa(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=wa(a))==null?void 0:i.host)??null:c=((s=wa("https://"+a))==null?void 0:s.host)??null,n===c)return!0}return!1}function wa(t){try{return new URL(t)}catch{return null}}async function e1({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,...cn(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=Pn();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 ud(t,{connection:i,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/enter-email?state=${a.id}`)}function t1(t){if(t==="Username-Password-Authentication")return"auth2";if(t==="email")return"email";throw new I(403,{message:"Invalid realm"})}async function n1(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=t1(i);let p=await so(t,{email: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),t.set("user_id",p.user_id);const f=await Hf(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 Vp(t,e){return`<!DOCTYPE html>
|
|
150
150
|
<html>
|
|
151
151
|
|
|
152
152
|
<head>
|
package/dist/authhero.mjs
CHANGED
|
@@ -19407,7 +19407,7 @@ async function nd(t, { to: e, code: n, authParams: r, connection: i }) {
|
|
|
19407
19407
|
if (!r.redirect_uri)
|
|
19408
19408
|
throw new C(400, { message: "redirect_uri is required" });
|
|
19409
19409
|
const o = new URL(Te(t.env));
|
|
19410
|
-
o.pathname = "passwordless/verify_redirect", o.searchParams.set("verification_code", n), o.searchParams.set("connection", i), o.searchParams.set("client_id", r.client_id), o.searchParams.set("redirect_uri", r.redirect_uri), o.searchParams.set("
|
|
19410
|
+
o.pathname = "passwordless/verify_redirect", o.searchParams.set("verification_code", n), o.searchParams.set("connection", i), o.searchParams.set("client_id", r.client_id), o.searchParams.set("redirect_uri", r.redirect_uri), o.searchParams.set("email", e), r.response_type && o.searchParams.set("response_type", r.response_type), r.scope && o.searchParams.set("scope", r.scope), r.state && o.searchParams.set("state", r.state), r.nonce && o.searchParams.set("nonce", r.nonce), r.code_challenge && o.searchParams.set("code_challenge", r.code_challenge), r.code_challenge_method && o.searchParams.set(
|
|
19411
19411
|
"code_challenge_method",
|
|
19412
19412
|
r.code_challenge_method
|
|
19413
19413
|
), r.audience && o.searchParams.set("audience", r.audience);
|