@usebruno/requests
Version:
3 lines (2 loc) • 4.18 kB
JavaScript
import e,{AxiosError as r}from"axios";import t from"qs";const n=require("crypto"),{URL:o}=require("url");function s(e){return e&&""!==e.trim()&&"undefined"!==e.trim()}function a(e){return e.replace(/"/g,"")}function i(e){return n.createHash("md5").update(e).digest("hex")}function c(e,r){const{username:t,password:c}=r.digestConfig;console.debug("Digest Auth Interceptor Initialized"),s(t)&&s(c)?e.interceptors.response.use((e=>e),(s=>{const u=s.config;if(u._retry)return Promise.reject(s);if(u._retry=!0,401===s.response?.status&&function(e){const r=e?.headers?.["www-authenticate"];return!!r&&r.trim().toLowerCase().startsWith("digest")}(s.response)&&!function(e){return Boolean(e.headers.Authorization||e.headers.authorization)}(u)){console.debug("Processing Digest Authentication Challenge"),console.debug(s.response.headers["www-authenticate"]);const l=s.response.headers["www-authenticate"].split(",").map((e=>e.split("=").map((e=>e.trim())).map(a))).reduce(((e,[r,t])=>{const n=r.toLowerCase().replace("digest ","");return n&&void 0!==t&&(e[n]=t),e}),{});if(!l.realm||!l.nonce)return console.warn("Missing required auth details (realm or nonce)"),Promise.reject(s);console.debug("Auth Details: \n",l);const d="00000001",h=n.randomBytes(24).toString("hex");if(l.algorithm&&"MD5"!==l.algorithm.toUpperCase())return console.warn(`Unsupported Digest algorithm: ${l.algorithm}`),Promise.reject(s);l.algorithm="MD5";const p=new o(r.url,r.baseURL||"http://localhost").pathname,g=i(`${t}:${l.realm}:${c}`),m=i(`${r.method}:${p}`),w=i(`${g}:${l.nonce}:${d}:${h}:auth:${m}`),f=[`username="${t}"`,`realm="${l.realm}"`,`nonce="${l.nonce}"`,`uri="${p}"`,'qop="auth"',`algorithm="${l.algorithm}"`,`response="${w}"`,`nc="${d}"`,`cnonce="${h}"`];l.opaque&&f.push(`opaque="${l.opaque}"`);const $=`Digest ${f.join(", ")}`;return u.headers=u.headers||{},u.headers.Authorization=$,console.debug(`Authorization: ${u.headers.Authorization}`),delete u.digestConfig,e(u)}return Promise.reject(s)})):console.warn("Required Digest Auth fields (username/password) are not present")}const u=async(n,o)=>{const{grantType:s,clientId:a,accessTokenUrl:i}=n;if(!s||!i)throw new Error("Missing required OAuth2 parameters: grantType or accessTokenUrl");const c=i,u=a||n.username||"default",l=await o.getToken(c,u);if(l&&l.expires_at&&l.expires_at>Date.now())return l.access_token;try{let a;if("client_credentials"===s)a=await(async r=>{const{accessTokenUrl:n,clientId:o,clientSecret:s,scope:a,credentialsPlacement:i="header"}=r;if(!n||!o)throw new Error("Missing required OAuth2 parameters");const c={grant_type:"client_credentials",scope:a||""},u={headers:{"Content-Type":"application/x-www-form-urlencoded"}};"header"===i?u.headers.Authorization=`Basic ${Buffer.from(`${o}:${s||""}`).toString("base64")}`:(c.client_id=o,s&&(c.client_secret=s));try{return(await e.post(n,t.stringify(c),u)).data}catch(e){throw e instanceof Error&&console.error("CLIENT_CREDENTIALS: Error fetching OAuth2 token:",e.message),e}})(n);else{if("password"!==s)throw new Error(`Unsupported grant type: ${s}`);a=await(async n=>{const{accessTokenUrl:o,clientId:s,clientSecret:a,username:i,password:c,scope:u,credentialsPlacement:l="header"}=n;if(!o||!i||!c)throw new Error("Missing required OAuth2 parameters for password grant");const d={grant_type:"password",username:i,password:c,scope:u||""},h={headers:{"Content-Type":"application/x-www-form-urlencoded"}};"header"===l&&s?h.headers.Authorization=`Basic ${Buffer.from(`${s}:${a||""}`).toString("base64")}`:s&&(d.client_id=s,a&&(d.client_secret=a));try{return(await e.post(o,t.stringify(d),h)).data}catch(e){throw e instanceof r&&e.response?(console.error("PASSWORD_GRANT: Error fetching OAuth2 token:",e.message),console.error("Status:",e.response.status,"Response:",e.response.data)):e instanceof Error&&console.error("PASSWORD_GRANT: Error fetching OAuth2 token:",e.message),e}})(n)}return a.expires_in&&(a.expires_at=Date.now()+1e3*a.expires_in),await o.saveToken(c,u,a),a.access_token}catch(e){return e instanceof Error&&console.error("Failed to get OAuth2 token:",e.message),null}};export{c as addDigestInterceptor,u as getOAuth2Token};
//# sourceMappingURL=index.js.map