UNPKG

identi-recognition

Version:

identiRecognition

67 lines (63 loc) 2.3 kB
const crypto = require('crypto') const url = require('url') const axios = require('axios') const http = require('http') const keepAliveAgent = new http.Agent({ keepAlive: true }) class AxiosDigestAuth { constructor({ axios: axiosInst, password, username }) { if (!axiosInst) { this.axios = axios.create({ httpAgent: keepAliveAgent, headers: { Connection: 'close' } }) } else { this.axios = axiosInst } this.count = 0 this.password = password this.username = username } async request(opts) { var _a, _b try { return await this.axios(opts) } catch (resp1) { if ( resp1.response === undefined || resp1.response.status !== 401 || !((_a = resp1.response.headers['www-authenticate']) === null || _a === void 0 ? void 0 : _a.includes('nonce')) ) { throw resp1 } const authDetails = resp1.response.headers['www-authenticate'].split(',').map((v) => v.split('=')) ++this.count const nonceCount = ('00000000' + this.count).slice(-8) const cnonce = crypto.randomBytes(24).toString('hex') const realm = authDetails.find((el) => el[0].toLowerCase().indexOf('realm') > -1)[1].replace(/"/g, '') const nonce = authDetails.find((el) => el[0].toLowerCase().indexOf('nonce') > -1)[1].replace(/"/g, '') const ha1 = crypto.createHash('md5').update(`${this.username}:${realm}:${this.password}`).digest('hex') const path = url.parse(opts.url).pathname const ha2 = crypto .createHash('md5') .update(`${(_b = opts.method) !== null && _b !== void 0 ? _b : 'GET'}:${path}`) .digest('hex') const response = crypto .createHash('md5') .update(`${ha1}:${nonce}:${nonceCount}:${cnonce}:auth:${ha2}`) .digest('hex') const authorization = `Digest username="${this.username}",realm="${realm}",` + `nonce="${nonce}",uri="${path}",qop="auth",algorithm="MD5",` + `response="${response}",nc="${nonceCount}",cnonce="${cnonce}"` if (opts.headers) { opts.headers['authorization'] = authorization } else { opts.headers = { authorization } } return this.axios(opts) } } } exports.default = AxiosDigestAuth