UNPKG

@usebruno/requests

Version:

3 lines (2 loc) 5.16 kB
"use strict";var e=require("axios"),r=require("qs"),t=require("node:url"),n=require("node:net");function o(e,r){return r.forEach((function(r){r&&"string"!=typeof r&&!Array.isArray(r)&&Object.keys(r).forEach((function(t){if("default"!==t&&!(t in e)){var n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:function(){return r[t]}})}}))})),Object.freeze(e)}const s=require("crypto"),{URL:a}=require("url");function i(e){return e&&""!==e.trim()&&"undefined"!==e.trim()}function c(e){return e.replace(/"/g,"")}function u(e){return s.createHash("md5").update(e).digest("hex")}const{URL:l}=t,h=n,p=e=>h.isIPv4(e)?(e=>{const r=e.split(".");return 4===r.length&&127===parseInt(r[0],10)})(e):!!h.isIPv6(e)&&(e=>"::1"===e)(e);var d=o({__proto__:null},[{isPotentiallyTrustworthyOrigin:e=>{let r;try{r=new l(e)}catch(e){if(e instanceof TypeError&&"ERR_INVALID_URL"===e.code)return!1;throw e}const t=r.protocol.replace(":","").toLowerCase(),n=(o=r.hostname,o.length>=2&&o.startsWith("[")&&o.endsWith("]")?o.substring(1,o.length-1):o).replace(/\.+$/,"");var o;return"https"===t||"wss"===t||"file"===t||(h.isIP(n)?p(n):(e=>"localhost"===e.toLowerCase()||(e=>e.toLowerCase().endsWith(".localhost"))(e))(n))}}]);exports.addDigestInterceptor=function(e,r){const{username:t,password:n}=r.digestConfig;console.debug("Digest Auth Interceptor Initialized"),i(t)&&i(n)?e.interceptors.response.use((e=>e),(o=>{const i=o.config;if(i._retry)return Promise.reject(o);if(i._retry=!0,401===o.response?.status&&function(e){const r=e?.headers?.["www-authenticate"];return!!r&&r.trim().toLowerCase().startsWith("digest")}(o.response)&&!function(e){return Boolean(e.headers.Authorization||e.headers.authorization)}(i)){console.debug("Processing Digest Authentication Challenge"),console.debug(o.response.headers["www-authenticate"]);const l=o.response.headers["www-authenticate"].split(",").map((e=>e.split("=").map((e=>e.trim())).map(c))).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(o);console.debug("Auth Details: \n",l);const h="00000001",p=s.randomBytes(24).toString("hex");if(l.algorithm&&"MD5"!==l.algorithm.toUpperCase())return console.warn(`Unsupported Digest algorithm: ${l.algorithm}`),Promise.reject(o);l.algorithm="MD5";const d=new a(r.url,r.baseURL||"http://localhost").pathname,g=u(`${t}:${l.realm}:${n}`),f=u(`${r.method}:${d}`),w=u(`${g}:${l.nonce}:${h}:${p}:auth:${f}`),m=[`username="${t}"`,`realm="${l.realm}"`,`nonce="${l.nonce}"`,`uri="${d}"`,'qop="auth"',`algorithm="${l.algorithm}"`,`response="${w}"`,`nc="${h}"`,`cnonce="${p}"`];l.opaque&&m.push(`opaque="${l.opaque}"`);const $=`Digest ${m.join(", ")}`;return i.headers=i.headers||{},i.headers.Authorization=$,console.debug(`Authorization: ${i.headers.Authorization}`),delete i.digestConfig,e(i)}return Promise.reject(o)})):console.warn("Required Digest Auth fields (username/password) are not present")},exports.getOAuth2Token=async(t,n)=>{const{grantType:o,clientId:s,accessTokenUrl:a}=t;if(!o||!a)throw new Error("Missing required OAuth2 parameters: grantType or accessTokenUrl");const i=a,c=s||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 s;if("client_credentials"===o)s=await(async t=>{const{accessTokenUrl:n,clientId:o,clientSecret:s,scope:a,credentialsPlacement:i="header"}=t;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,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"!==o)throw new Error(`Unsupported grant type: ${o}`);s=await(async t=>{const{accessTokenUrl:n,clientId:o,clientSecret:s,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 l={grant_type:"password",username:a,password:i,scope:c||""},h={headers:{"Content-Type":"application/x-www-form-urlencoded"}};"header"===u&&o?h.headers.Authorization=`Basic ${Buffer.from(`${o}:${s||""}`).toString("base64")}`:o&&(l.client_id=o,s&&(l.client_secret=s));try{return(await e.post(n,r.stringify(l),h)).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 s.expires_in&&(s.expires_at=Date.now()+1e3*s.expires_in),await n.saveToken(i,c,s),s.access_token}catch(e){return e instanceof Error&&console.error("Failed to get OAuth2 token:",e.message),null}},exports.utils=d; //# sourceMappingURL=index.js.map