import{KvService as l}from"../../persistence/kv/services/kv-service.js";import{DEFAULT_AUTHENTICATED_TEAM as T}from"../../../constants/common.js";import{envConfig as s}from"../../config/env-config.js";import{CACHE_CONTROL_NO_STORE_HEADER_VALUE as h,JWT_SECRET_KEY as y}from"../../constants/common.js";import*as m from"../jwt/jwt.js";import{AlgorithmTypes as I}from"../jwt/types.js";const p=60,f=e=>["POST","PUT","DELETE","PATCH"].includes(e),E=e=>["GET"].includes(e);function R({serverOutDir:e,protectReadMethods:t=!0}){return async(r,a)=>await _(r,a,e,t)}const _=async(e,t,r,a=!0)=>{e.header("Cache-Control",h);const n=e.req.method,o=f(n)||E(n)&&a,i=e.req.header("apiKey");if(i)return await w(e,t,i,r);const u=e.req.header("authorization")?.replace("Bearer ","");return u?await C(e,t,u):o?e.json({message:"API key is required"},401):await t()},w=async(e,t,r,a)=>{if(!s.BH_API_URL||!s.ORGANIZATION_ID)return e.json({message:"API key validation service not configured"},500);try{const n=await l.getInstance({baseDbDir:a});let o=await g(n,r);if(o)return e.set("apiKeyTeams",o.teams),await t();const i=new URL(`/api/orgs/${s.ORGANIZATION_ID}/session`,s.BH_API_URL).toString(),c=await fetch(i,{method:"GET",headers:{Authorization:`Bearer ${r}`}});if(!c.ok)return e.json({message:"Invalid API key"},401);const A=(await c.json())?.user?.teams?.[s.ORGANIZATION_ID]??[],d=[T,...A];return e.set("apiKeyTeams",d),await n.set(["api-keys","reunite",r],{valid:!0,teams:d},{ttlInSeconds:p}),await t()}catch{return e.json({message:"API key validation failed"},400)}},C=async(e,t,r)=>{try{const a=await m.verify(r,y,I.HS256),n=m.decode(r).payload.isInternalConnection;return!a||!n?e.json({message:"API key is required"},401):await t()}catch{return e.json({message:"API key validation failed"},400)}},g=async(e,t)=>{try{return await e.get(["api-keys","reunite",t])}catch{return null}};export{R as catalogAuthMiddleware};
