Skip to content

Commit 0e3cfe0

Browse files
authored
Merge branch 'master' into development
2 parents 9edfa2d + b5b89c9 commit 0e3cfe0

15 files changed

+735
-47
lines changed

.github/workflows/tests-release.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,6 @@ jobs:
5757
key: ${{ runner.os }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }}
5858
restore-keys: |
5959
${{ runner.os }}-node-${{ matrix.node }}
60-
6160
# for this workflow we also require npm audit to pass
6261
- run: npm i
6362
- run: npm run test:coverage
@@ -110,6 +109,7 @@ jobs:
110109
# in order to test the adapter we need to use the current checkout
111110
# and install it as local dependency
112111
# we just cloned and install it as local dependency
112+
# xxx: added bluebird as explicit dependency
113113
- run: |
114114
cd github/testing/express
115115
npm i

index.d.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -306,7 +306,7 @@ declare namespace OAuth2Server {
306306
*
307307
*/
308308
saveAuthorizationCode(
309-
code: Pick<AuthorizationCode, 'authorizationCode' | 'expiresAt' | 'redirectUri' | 'scope'>,
309+
code: Pick<AuthorizationCode, 'authorizationCode' | 'expiresAt' | 'redirectUri' | 'scope' | 'codeChallenge' | 'codeChallengeMethod'>,
310310
client: Client,
311311
user: User,
312312
callback?: Callback<AuthorizationCode>): Promise<AuthorizationCode | Falsey>;
@@ -322,6 +322,12 @@ declare namespace OAuth2Server {
322322
*
323323
*/
324324
validateScope?(user: User, client: Client, scope: string | string[], callback?: Callback<string | Falsey>): Promise<string | string[] | Falsey>;
325+
326+
/**
327+
* Invoked to check if the provided `redirectUri` is valid for a particular `client`.
328+
*
329+
*/
330+
validateRedirectUri?(redirect_uri: string, client: Client): Promise<boolean>;
325331
}
326332

327333
interface PasswordModel extends BaseModel, RequestAuthenticationModel {
@@ -410,6 +416,8 @@ declare namespace OAuth2Server {
410416
scope?: string | string[] | undefined;
411417
client: Client;
412418
user: User;
419+
codeChallenge?: string;
420+
codeChallengeMethod?: string;
413421
[key: string]: any;
414422
}
415423

lib/grant-types/authorization-code-grant-type.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const promisify = require('promisify-any').use(Promise);
1313
const ServerError = require('../errors/server-error');
1414
const isFormat = require('@node-oauth/formats');
1515
const util = require('util');
16+
const pkce = require('../pkce/pkce');
1617

1718
/**
1819
* Constructor.
@@ -118,6 +119,36 @@ AuthorizationCodeGrantType.prototype.getAuthorizationCode = function(request, cl
118119
throw new InvalidGrantError('Invalid grant: `redirect_uri` is not a valid URI');
119120
}
120121

122+
// optional: PKCE code challenge
123+
124+
if (code.codeChallenge) {
125+
if (!request.body.code_verifier) {
126+
throw new InvalidGrantError('Missing parameter: `code_verifier`');
127+
}
128+
129+
const hash = pkce.getHashForCodeChallenge({
130+
method: code.codeChallengeMethod,
131+
verifier: request.body.code_verifier
132+
});
133+
134+
if (!hash) {
135+
// notice that we assume that codeChallengeMethod is already
136+
// checked at an earlier stage when being read from
137+
// request.body.code_challenge_method
138+
throw new ServerError('Server error: `getAuthorizationCode()` did not return a valid `codeChallengeMethod` property');
139+
}
140+
141+
if (code.codeChallenge !== hash) {
142+
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
143+
}
144+
}
145+
else {
146+
if (request.body.code_verifier) {
147+
// No code challenge but code_verifier was passed in.
148+
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
149+
}
150+
}
151+
121152
return code;
122153
});
123154
};

lib/handlers/authorize-handler.js

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const UnauthorizedClientError = require('../errors/unauthorized-client-error');
2121
const isFormat = require('@node-oauth/formats');
2222
const tokenUtil = require('../utils/token-util');
2323
const url = require('url');
24+
const pkce = require('../pkce/pkce');
2425

2526
/**
2627
* Response types.
@@ -77,10 +78,6 @@ AuthorizeHandler.prototype.handle = function(request, response) {
7778
throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response');
7879
}
7980

80-
if (request.query.allowed === 'false' || request.body.allowed === 'false') {
81-
return Promise.reject(new AccessDeniedError('Access denied: user denied access to application'));
82-
}
83-
8481
const fns = [
8582
this.getAuthorizationCodeLifetime(),
8683
this.getClient(request),
@@ -98,7 +95,7 @@ AuthorizeHandler.prototype.handle = function(request, response) {
9895
return Promise.bind(this)
9996
.then(function() {
10097
state = this.getState(request);
101-
if(request.query.allowed === 'false') {
98+
if (request.query.allowed === 'false' || request.body.allowed === 'false') {
10299
throw new AccessDeniedError('Access denied: user denied access to application');
103100
}
104101
})
@@ -114,8 +111,10 @@ AuthorizeHandler.prototype.handle = function(request, response) {
114111
})
115112
.then(function(authorizationCode) {
116113
ResponseType = this.getResponseType(request);
114+
const codeChallenge = this.getCodeChallenge(request);
115+
const codeChallengeMethod = this.getCodeChallengeMethod(request);
117116

118-
return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user);
117+
return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user, codeChallenge, codeChallengeMethod);
119118
})
120119
.then(function(code) {
121120
const responseType = new ResponseType(code.authorizationCode);
@@ -293,13 +292,20 @@ AuthorizeHandler.prototype.getRedirectUri = function(request, client) {
293292
* Save authorization code.
294293
*/
295294

296-
AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user) {
297-
const code = {
295+
AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user, codeChallenge, codeChallengeMethod) {
296+
let code = {
298297
authorizationCode: authorizationCode,
299298
expiresAt: expiresAt,
300299
redirectUri: redirectUri,
301300
scope: scope
302301
};
302+
303+
if(codeChallenge && codeChallengeMethod){
304+
code = Object.assign({
305+
codeChallenge: codeChallenge,
306+
codeChallengeMethod: codeChallengeMethod
307+
}, code);
308+
}
303309
return promisify(this.model.saveAuthorizationCode, 3).call(this.model, code, client, user);
304310
};
305311

@@ -369,6 +375,27 @@ AuthorizeHandler.prototype.updateResponse = function(response, redirectUri, stat
369375
response.redirect(url.format(redirectUri));
370376
};
371377

378+
AuthorizeHandler.prototype.getCodeChallenge = function(request) {
379+
return request.body.code_challenge;
380+
};
381+
382+
/**
383+
* Get code challenge method from request or defaults to plain.
384+
* https://www.rfc-editor.org/rfc/rfc7636#section-4.3
385+
*
386+
* @throws {InvalidRequestError} if request contains unsupported code_challenge_method
387+
* (see https://www.rfc-editor.org/rfc/rfc7636#section-4.4)
388+
*/
389+
AuthorizeHandler.prototype.getCodeChallengeMethod = function(request) {
390+
const algorithm = request.body.code_challenge_method;
391+
392+
if (algorithm && !pkce.isValidMethod(algorithm)) {
393+
throw new InvalidRequestError(`Invalid request: transform algorithm '${algorithm}' not supported`);
394+
}
395+
396+
return algorithm || 'plain';
397+
};
398+
372399
/**
373400
* Export constructor.
374401
*/

lib/handlers/token-handler.js

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ const TokenModel = require('../models/token-model');
1818
const UnauthorizedClientError = require('../errors/unauthorized-client-error');
1919
const UnsupportedGrantTypeError = require('../errors/unsupported-grant-type-error');
2020
const auth = require('basic-auth');
21+
const pkce = require('../pkce/pkce');
2122
const isFormat = require('@node-oauth/formats');
2223

2324
/**
@@ -114,12 +115,14 @@ TokenHandler.prototype.handle = function(request, response) {
114115
TokenHandler.prototype.getClient = function(request, response) {
115116
const credentials = this.getClientCredentials(request);
116117
const grantType = request.body.grant_type;
118+
const codeVerifier = request.body.code_verifier;
119+
const isPkce = pkce.isPKCERequest({ grantType, codeVerifier });
117120

118121
if (!credentials.clientId) {
119122
throw new InvalidRequestError('Missing parameter: `client_id`');
120123
}
121124

122-
if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret) {
125+
if (this.isClientAuthenticationRequired(grantType) && !credentials.clientSecret && !isPkce) {
123126
throw new InvalidRequestError('Missing parameter: `client_secret`');
124127
}
125128

@@ -174,6 +177,7 @@ TokenHandler.prototype.getClient = function(request, response) {
174177
TokenHandler.prototype.getClientCredentials = function(request) {
175178
const credentials = auth(request);
176179
const grantType = request.body.grant_type;
180+
const codeVerifier = request.body.code_verifier;
177181

178182
if (credentials) {
179183
return { clientId: credentials.name, clientSecret: credentials.pass };
@@ -183,6 +187,12 @@ TokenHandler.prototype.getClientCredentials = function(request) {
183187
return { clientId: request.body.client_id, clientSecret: request.body.client_secret };
184188
}
185189

190+
if (pkce.isPKCERequest({ grantType, codeVerifier })) {
191+
if(request.body.client_id) {
192+
return { clientId: request.body.client_id };
193+
}
194+
}
195+
186196
if (!this.isClientAuthenticationRequired(grantType)) {
187197
if(request.body.client_id) {
188198
return { clientId: request.body.client_id };

lib/pkce/pkce.js

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
'use strict';
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
const { base64URLEncode } = require('../utils/string-util');
7+
const { createHash } = require('../utils/crypto-util');
8+
const codeChallengeRegexp = /^([a-zA-Z0-9.\-_~]){43,128}$/;
9+
/**
10+
* Export `TokenUtil`.
11+
*/
12+
13+
const pkce = {
14+
/**
15+
* Return hash for code-challenge method-type.
16+
*
17+
* @param method {String} the code challenge method
18+
* @param verifier {String} the code_verifier
19+
* @return {String|undefined}
20+
*/
21+
getHashForCodeChallenge: function({ method, verifier }) {
22+
// to prevent undesired side-effects when passing some wird values
23+
// to createHash or base64URLEncode we first check if the values are right
24+
if (pkce.isValidMethod(method) && typeof verifier === 'string' && verifier.length > 0) {
25+
if (method === 'plain') {
26+
return verifier;
27+
}
28+
29+
if (method === 'S256') {
30+
const hash = createHash({ data: verifier });
31+
return base64URLEncode(hash);
32+
}
33+
}
34+
},
35+
36+
/**
37+
* Check if the request is a PCKE request. We assume PKCE if grant type is
38+
* 'authorization_code' and code verifier is present.
39+
*
40+
* @param grantType {String}
41+
* @param codeVerifier {String}
42+
* @return {boolean}
43+
*/
44+
isPKCERequest: function ({ grantType, codeVerifier }) {
45+
return grantType === 'authorization_code' && !!codeVerifier;
46+
},
47+
48+
/**
49+
* Matches a code verifier (or code challenge) against the following criteria:
50+
*
51+
* code-verifier = 43*128unreserved
52+
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
53+
* ALPHA = %x41-5A / %x61-7A
54+
* DIGIT = %x30-39
55+
*
56+
* @see: https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
57+
* @param codeChallenge {String}
58+
* @return {Boolean}
59+
*/
60+
codeChallengeMatchesABNF: function (codeChallenge) {
61+
return typeof codeChallenge === 'string' &&
62+
!!codeChallenge.match(codeChallengeRegexp);
63+
},
64+
65+
/**
66+
* Checks if the code challenge method is one of the supported methods
67+
* 'sha256' or 'plain'
68+
*
69+
* @param method {String}
70+
* @return {boolean}
71+
*/
72+
isValidMethod: function (method) {
73+
return method === 'S256' || method === 'plain';
74+
}
75+
};
76+
77+
module.exports = pkce;

lib/utils/crypto-util.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'use strict';
2+
3+
const crypto = require('crypto');
4+
5+
/**
6+
* Export `StringUtil`.
7+
*/
8+
9+
module.exports = {
10+
/**
11+
*
12+
* @param algorithm {String} the hash algorithm, default is 'sha256'
13+
* @param data {Buffer|String|TypedArray|DataView} the data to hash
14+
* @param encoding {String|undefined} optional, the encoding to calculate the
15+
* digest
16+
* @return {Buffer|String} if {encoding} undefined a {Buffer} is returned, otherwise a {String}
17+
*/
18+
createHash: function({ algorithm = 'sha256', data = undefined, encoding = undefined }) {
19+
return crypto
20+
.createHash(algorithm)
21+
.update(data)
22+
.digest(encoding);
23+
}
24+
};

lib/utils/string-util.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
'use strict';
2+
3+
/**
4+
* Export `StringUtil`.
5+
*/
6+
7+
module.exports = {
8+
/**
9+
*
10+
* @param str
11+
* @return {string}
12+
*/
13+
base64URLEncode: function(str) {
14+
return str.toString('base64')
15+
.replace(/\+/g, '-')
16+
.replace(/\//g, '_')
17+
.replace(/=/g, '');
18+
}
19+
};

lib/utils/token-util.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
* Module dependencies.
55
*/
66

7-
const crypto = require('crypto');
87
const randomBytes = require('bluebird').promisify(require('crypto').randomBytes);
8+
const { createHash } = require('../utils/crypto-util');
99

1010
/**
1111
* Export `TokenUtil`.
@@ -19,10 +19,7 @@ module.exports = {
1919

2020
generateRandomToken: function() {
2121
return randomBytes(256).then(function(buffer) {
22-
return crypto
23-
.createHash('sha256')
24-
.update(buffer)
25-
.digest('hex');
22+
return createHash({ data: buffer, encoding: 'hex' });
2623
});
2724
}
2825

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@node-oauth/oauth2-server",
33
"description": "Complete, framework-agnostic, compliant and well tested module for implementing an OAuth2 Server in node.js",
4-
"version": "4.2.0",
4+
"version": "4.3.0",
55
"keywords": [
66
"oauth",
77
"oauth2"
@@ -40,7 +40,7 @@
4040
},
4141
"license": "MIT",
4242
"engines": {
43-
"node": ">=12.0.0"
43+
"node": ">=14.0.0"
4444
},
4545
"scripts": {
4646
"pretest": "./node_modules/.bin/eslint lib test index.js",

0 commit comments

Comments
 (0)