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