Repository navigation
Expand file tree
/
Copy pathdigest.ts
More file actions
85 lines (77 loc) · 3.26 KB
/
Copy pathdigest.ts
File metadata and controls
85 lines (77 loc) · 3.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import * as stream from 'stream';
import * as url from 'url';
import { md5 } from '../misc';
import got = require('got');
const uuidv4 = require('uuid/v4');
export function digest(user: string, pass: string): got.AfterResponseHook<got.GotBodyOptions<null>, string | Buffer | stream.Readable> {
return (response, retryWithMergedOptions) => {
if (response.statusCode === 401
&& response.headers['www-authenticate']
&& response.headers['www-authenticate'].split(' ')[0].toLowerCase() === 'digest') {
const authHeader = response.headers['www-authenticate'];
const method = (response as any).request.gotOptions.method;
const path = url.parse(response.url).path;
const challenge = {
qop: '',
algorithm: '',
realm: '',
nonce: '',
opaque: ''
};
const re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi;
/* Copy from https://github.com/request/request/blob/master/lib/auth.js */
while (true) {
const match = re.exec(authHeader);
if (!match) {
break;
}
challenge[match[1]] = match[2] || match[3];
}
const ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
const ha1 = md5(user + ':' + realm + ':' + pass);
if (algorithm?.toLowerCase() === 'md5-sess') {
return md5(ha1 + ':' + nonce + ':' + cnonce);
} else {
return ha1;
}
};
const qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth';
const nc = qop && '00000001';
const cnonce = qop && uuidv4().replace(/-/g, '');
const ha1 = ha1Compute(challenge.algorithm, user, challenge.realm, pass, challenge.nonce, cnonce);
const ha2 = md5(method + ':' + path);
const digestResponse = qop
? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
: md5(ha1 + ':' + challenge.nonce + ':' + ha2);
const authValues = {
username: user,
realm: challenge.realm,
nonce: challenge.nonce,
uri: path,
qop: qop,
response: digestResponse,
nc: nc,
cnonce: cnonce,
algorithm: challenge.algorithm,
opaque: challenge.opaque
};
const authParams: string[] = [];
for (const [key, value] of Object.entries(authValues)) {
if (authValues[key]) {
if (key === 'qop' || key === 'nc' || key === 'algorithm') {
authParams.push(key + '=' + value);
} else {
authParams.push(key + '="' + value + '"');
}
}
}
const updatedOptions = {
headers: {
authorization: 'Digest ' + authParams.join(', ')
}
};
return retryWithMergedOptions(updatedOptions);
}
return response;
};
}