Skip to content

Commit 77d00b2

Browse files
committed
fix: improved parsing of requested scopes
1 parent fcb567b commit 77d00b2

File tree

2 files changed

+58
-6
lines changed

2 files changed

+58
-6
lines changed

lib/utils/scope-util.js

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
11
const isFormat = require('@node-oauth/formats');
22
const InvalidScopeError = require('../errors/invalid-scope-error');
3+
const whiteSpace = /\s+/g;
34

45
module.exports = {
56
parseScope: function (requestedScope) {
6-
// XXX: isFormat.nqschar will trat Arrays of strings like String,
7-
// thus we additionally check, whether incoming scopes are Arrays
8-
if (!isFormat.nqschar(requestedScope) || Array.isArray(requestedScope)) {
7+
if (requestedScope == null) {
8+
return undefined;
9+
}
10+
11+
if (typeof requestedScope !== 'string') {
912
throw new InvalidScopeError('Invalid parameter: `scope`');
1013
}
1114

12-
if (requestedScope == null) {
13-
return undefined;
15+
// XXX: this prevents spaced-only strings to become
16+
// treated as valid nqchar by making them empty strings
17+
requestedScope = requestedScope.trim();
18+
19+
if(!isFormat.nqschar(requestedScope)) {
20+
throw new InvalidScopeError('Invalid parameter: `scope`');
1421
}
1522

16-
return requestedScope.split(' ');
23+
return requestedScope.split(whiteSpace);
1724
}
1825
};

test/unit/utils/scope-util_test.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const { parseScope } = require('../../../lib/utils/scope-util');
2+
const should = require('chai').should();
3+
4+
describe(parseScope.name, () => {
5+
it('should return undefined on nullish values', () => {
6+
const values = [undefined, null];
7+
values.forEach(str => {
8+
const compare = parseScope(str) === undefined;
9+
compare.should.equal(true);
10+
});
11+
});
12+
it('should throw on non-string values', () => {
13+
const invalid = [1, -1, true, false, {}, ['foo'], [], () => {}, Symbol('foo')];
14+
invalid.forEach(str => {
15+
try {
16+
parseScope(str);
17+
should.fail();
18+
} catch (e) {
19+
e.message.should.eql('Invalid parameter: `scope`');
20+
}
21+
});
22+
});
23+
it('should throw on empty strings', () => {
24+
const invalid = ['', ' ', ' ', '\n', '\t', '\r'];
25+
invalid.forEach(str => {
26+
try {
27+
parseScope(str);
28+
should.fail();
29+
} catch (e) {
30+
e.message.should.eql('Invalid parameter: `scope`');
31+
}
32+
});
33+
});
34+
it('should split space-delimited strings into arrays', () => {
35+
const values = [
36+
['foo', ['foo']],
37+
['foo bar', ['foo', 'bar']],
38+
['foo bar', ['foo', 'bar']],
39+
];
40+
values.forEach(([str, compare]) => {
41+
const parsed = parseScope(str);
42+
parsed.should.deep.equal(compare);
43+
});
44+
});
45+
});

0 commit comments

Comments
 (0)