UNPKG

@usebruno/requests

Version:

3 lines (2 loc) 5.15 kB
import e,{AxiosError as r}from"axios";import t from"qs";import n from"node:url";import o from"node:net";function s(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 a=require("crypto"),{URL:i}=require("url");function c(e){return e&&""!==e.trim()&&"undefined"!==e.trim()}function u(e){return e.replace(/"/g,"")}function l(e){return a.createHash("md5").update(e).digest("hex")}function h(e,r){const{username:t,password:n}=r.digestConfig;console.debug("Digest Auth Interceptor Initialized"),c(t)&&c(n)?e.interceptors.response.use((e=>e),(o=>{const s=o.config;if(s._retry)return Promise.reject(o);if(s._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)}(s)){console.debug("Processing Digest Authentication Challenge"),console.debug(o.response.headers["www-authenticate"]);const c=o.response.headers["www-authenticate"].split(",").map((e=>e.split("=").map((e=>e.trim())).map(u))).reduce(((e,[r,t])=>{const n=r.toLowerCase().replace("digest ","");return n&&void 0!==t&&(e[n]=t),e}),{});if(!c.realm||!c.nonce)return console.warn("Missing required auth details (realm or nonce)"),Promise.reject(o);console.debug("Auth Details: \n",c);const h="00000001",p=a.randomBytes(24).toString("hex");if(c.algorithm&&"MD5"!==c.algorithm.toUpperCase())return console.warn(`Unsupported Digest algorithm: ${c.algorithm}`),Promise.reject(o);c.algorithm="MD5";const d=new i(r.url,r.baseURL||"http://localhost").pathname,g=l(`${t}:${c.realm}:${n}`),f=l(`${r.method}:${d}`),m=l(`${g}:${c.nonce}:${h}:${p}:auth:${f}`),w=[`username="${t}"`,`realm="${c.realm}"`,`nonce="${c.nonce}"`,`uri="${d}"`,'qop="auth"',`algorithm="${c.algorithm}"`,`response="${m}"`,`nc="${h}"`,`cnonce="${p}"`];c.opaque&&w.push(`opaque="${c.opaque}"`);const $=`Digest ${w.join(", ")}`;return s.headers=s.headers||{},s.headers.Authorization=$,console.debug(`Authorization: ${s.headers.Authorization}`),delete s.digestConfig,e(s)}return Promise.reject(o)})):console.warn("Required Digest Auth fields (username/password) are not present")}const p=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 h={grant_type:"password",username:i,password:c,scope:u||""},p={headers:{"Content-Type":"application/x-www-form-urlencoded"}};"header"===l&&s?p.headers.Authorization=`Basic ${Buffer.from(`${s}:${a||""}`).toString("base64")}`:s&&(h.client_id=s,a&&(h.client_secret=a));try{return(await e.post(o,t.stringify(h),p)).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}},{URL:d}=n,g=o,f=e=>g.isIPv4(e)?(e=>{const r=e.split(".");return 4===r.length&&127===parseInt(r[0],10)})(e):!!g.isIPv6(e)&&(e=>"::1"===e)(e);var m=s({__proto__:null},[{isPotentiallyTrustworthyOrigin:e=>{let r;try{r=new d(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||(g.isIP(n)?f(n):(e=>"localhost"===e.toLowerCase()||(e=>e.toLowerCase().endsWith(".localhost"))(e))(n))}}]);export{h as addDigestInterceptor,p as getOAuth2Token,m as utils}; //# sourceMappingURL=index.js.map