@whook/oauth2 8.4.2 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +21 -7
  2. package/dist/handlers/getOAuth2Authorize.d.ts +5 -3
  3. package/dist/handlers/getOAuth2Authorize.js +6 -13
  4. package/dist/handlers/getOAuth2Authorize.js.map +1 -1
  5. package/dist/handlers/getOAuth2Authorize.mjs +3 -12
  6. package/dist/handlers/getOAuth2Authorize.mjs.map +1 -1
  7. package/dist/handlers/getOAuth2Authorize.test.js.map +1 -1
  8. package/dist/handlers/getOAuth2Authorize.test.mjs.map +1 -1
  9. package/dist/handlers/postAuthLogin.d.ts +2 -2
  10. package/dist/handlers/postAuthLogin.js +2 -1
  11. package/dist/handlers/postAuthLogin.js.map +1 -1
  12. package/dist/handlers/postAuthLogin.mjs +1 -0
  13. package/dist/handlers/postAuthLogin.mjs.map +1 -1
  14. package/dist/handlers/postAuthLogin.test.js.map +1 -1
  15. package/dist/handlers/postAuthLogin.test.mjs.map +1 -1
  16. package/dist/handlers/postAuthLogout.js +1 -1
  17. package/dist/handlers/postAuthLogout.js.map +1 -1
  18. package/dist/handlers/postAuthLogout.mjs.map +1 -1
  19. package/dist/handlers/postAuthLogout.test.js.map +1 -1
  20. package/dist/handlers/postAuthLogout.test.mjs.map +1 -1
  21. package/dist/handlers/postAuthRefresh.d.ts +3 -3
  22. package/dist/handlers/postAuthRefresh.js +5 -4
  23. package/dist/handlers/postAuthRefresh.js.map +1 -1
  24. package/dist/handlers/postAuthRefresh.mjs +3 -3
  25. package/dist/handlers/postAuthRefresh.mjs.map +1 -1
  26. package/dist/handlers/postAuthRefresh.test.js.map +1 -1
  27. package/dist/handlers/postAuthRefresh.test.mjs.map +1 -1
  28. package/dist/handlers/postOAuth2Acknowledge.d.ts +10 -7
  29. package/dist/handlers/postOAuth2Acknowledge.js +3 -3
  30. package/dist/handlers/postOAuth2Acknowledge.js.map +1 -1
  31. package/dist/handlers/postOAuth2Acknowledge.mjs +2 -2
  32. package/dist/handlers/postOAuth2Acknowledge.mjs.map +1 -1
  33. package/dist/handlers/postOAuth2Acknowledge.test.js.map +1 -1
  34. package/dist/handlers/postOAuth2Acknowledge.test.mjs.map +1 -1
  35. package/dist/handlers/postOAuth2Token.d.ts +3 -3
  36. package/dist/handlers/postOAuth2Token.js +6 -18
  37. package/dist/handlers/postOAuth2Token.js.map +1 -1
  38. package/dist/handlers/postOAuth2Token.mjs +6 -17
  39. package/dist/handlers/postOAuth2Token.mjs.map +1 -1
  40. package/dist/handlers/postOAuth2Token.test.js.map +1 -1
  41. package/dist/handlers/postOAuth2Token.test.mjs.map +1 -1
  42. package/dist/index.js +62 -62
  43. package/dist/index.js.map +1 -1
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/index.test.js +6 -7
  46. package/dist/index.test.js.map +1 -1
  47. package/dist/index.test.mjs +6 -7
  48. package/dist/index.test.mjs.map +1 -1
  49. package/dist/services/authCookies.js.map +1 -1
  50. package/dist/services/authCookies.mjs.map +1 -1
  51. package/dist/services/authCookies.test.js.map +1 -1
  52. package/dist/services/authCookies.test.mjs.map +1 -1
  53. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -1
  54. package/dist/services/oAuth2ClientCredentialsGranter.mjs.map +1 -1
  55. package/dist/services/oAuth2CodeGranter.js.map +1 -1
  56. package/dist/services/oAuth2CodeGranter.mjs.map +1 -1
  57. package/dist/services/oAuth2CodeGranter.test.js +8 -6
  58. package/dist/services/oAuth2CodeGranter.test.js.map +1 -1
  59. package/dist/services/oAuth2CodeGranter.test.mjs +8 -6
  60. package/dist/services/oAuth2CodeGranter.test.mjs.map +1 -1
  61. package/dist/services/oAuth2Granters.d.ts +22 -19
  62. package/dist/services/oAuth2Granters.js.map +1 -1
  63. package/dist/services/oAuth2Granters.mjs.map +1 -1
  64. package/dist/services/oAuth2PasswordGranter.js.map +1 -1
  65. package/dist/services/oAuth2PasswordGranter.mjs.map +1 -1
  66. package/dist/services/oAuth2RefreshTokenGranter.js +1 -1
  67. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -1
  68. package/dist/services/oAuth2RefreshTokenGranter.mjs +1 -1
  69. package/dist/services/oAuth2RefreshTokenGranter.mjs.map +1 -1
  70. package/dist/services/oAuth2TokenGranter.js.map +1 -1
  71. package/dist/services/oAuth2TokenGranter.mjs.map +1 -1
  72. package/package.json +35 -35
  73. package/src/handlers/getOAuth2Authorize.ts +21 -29
  74. package/src/handlers/postAuthLogin.ts +4 -3
  75. package/src/handlers/postAuthRefresh.ts +6 -8
  76. package/src/handlers/postOAuth2Acknowledge.ts +34 -26
  77. package/src/handlers/postOAuth2Token.test.ts +2 -2
  78. package/src/handlers/postOAuth2Token.ts +11 -22
  79. package/src/index.test.ts +8 -9
  80. package/src/services/oAuth2ClientCredentialsGranter.ts +25 -21
  81. package/src/services/oAuth2CodeGranter.test.ts +15 -14
  82. package/src/services/oAuth2CodeGranter.ts +66 -60
  83. package/src/services/oAuth2Granters.ts +59 -29
  84. package/src/services/oAuth2PasswordGranter.ts +23 -22
  85. package/src/services/oAuth2RefreshTokenGranter.ts +28 -24
  86. package/src/services/oAuth2TokenGranter.ts +44 -42
@@ -1,6 +1,7 @@
1
1
  import { autoHandler } from 'knifecycle';
2
2
  import camelCase from 'camelcase';
3
3
  import YError from 'yerror';
4
+ import { refersTo } from '@whook/whook';
4
5
  import type {
5
6
  WhookAPIHandlerDefinition,
6
7
  WhookAPIParameterDefinition,
@@ -89,21 +90,11 @@ export const definition: WhookAPIHandlerDefinition = {
89
90
  as defined per the OAuth2 RFC.`,
90
91
  tags: ['oauth2'],
91
92
  parameters: [
92
- {
93
- $ref: `#/components/parameters/${responseTypeParameter.name}`,
94
- },
95
- {
96
- $ref: `#/components/parameters/${clientIdParameter.name}`,
97
- },
98
- {
99
- $ref: `#/components/parameters/${redirectURIParameter.name}`,
100
- },
101
- {
102
- $ref: `#/components/parameters/${scopeParameter.name}`,
103
- },
104
- {
105
- $ref: `#/components/parameters/${stateParameter.name}`,
106
- },
93
+ refersTo(responseTypeParameter),
94
+ refersTo(clientIdParameter),
95
+ refersTo(redirectURIParameter),
96
+ refersTo(scopeParameter),
97
+ refersTo(stateParameter),
107
98
  ],
108
99
  responses: {
109
100
  '302': {
@@ -141,7 +132,7 @@ async function getOAuth2Authorize(
141
132
  scope?: string;
142
133
  state: string;
143
134
  } & Record<string, unknown>,
144
- ): Promise<WhookResponse> {
135
+ ): Promise<WhookResponse<302, { location: string }>> {
145
136
  const url = new URL(OAUTH2.authenticateURL);
146
137
 
147
138
  try {
@@ -154,29 +145,30 @@ async function getOAuth2Authorize(
154
145
  throw new YError('E_UNKNOWN_AUTHORIZER_TYPE', responseType);
155
146
  }
156
147
 
157
- const { applicationId, redirectURI, scope } =
158
- await granter.authorizer.authorize(
159
- {
160
- clientId,
161
- redirectURI: demandedRedirectURI,
162
- scope: demandedScope,
163
- },
164
- camelCaseObjectProperties(authorizeParameters),
165
- );
148
+ const { applicationId, redirectURI, scope } = await (
149
+ granter.authorizer as NonNullable<OAuth2GranterService['authorizer']>
150
+ ).authorize(
151
+ {
152
+ clientId,
153
+ redirectURI: demandedRedirectURI,
154
+ scope: demandedScope,
155
+ },
156
+ camelCaseObjectProperties(authorizeParameters),
157
+ );
166
158
 
167
159
  url.searchParams.set('type', responseType);
168
160
  url.searchParams.set('redirect_uri', redirectURI);
169
161
  url.searchParams.set('scope', scope);
170
162
  url.searchParams.set('client_id', applicationId);
171
163
  } catch (err) {
172
- log('debug', '👫 - OAuth2 initialization error', err.code);
173
- log('debug-stack', err.stack);
164
+ log('debug', '👫 - OAuth2 initialization error', (err as YError).code);
165
+ log('debug-stack', (err as Error).stack || 'no_stack_trace');
174
166
 
175
167
  url.searchParams.set('redirect_uri', demandedRedirectURI);
176
168
  setURLError(
177
169
  url,
178
- err,
179
- ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2,
170
+ err as YError,
171
+ ERRORS_DESCRIPTORS[(err as YError).code] || ERRORS_DESCRIPTORS.E_OAUTH2,
180
172
  );
181
173
  }
182
174
 
@@ -111,11 +111,12 @@ async function postAuthLogin<
111
111
  },
112
112
  };
113
113
  } catch (err) {
114
- const newErr = YHTTPError.wrap(err);
114
+ const newErr = YHTTPError.wrap(err as Error);
115
115
 
116
116
  newErr.headers = {
117
- ...(err.headers || {}),
118
- 'Set-Cookie': authCookies.build(),
117
+ ...((err as YHTTPError).headers || {}),
118
+ // TODO: Allow string[] in YHTTPError
119
+ 'Set-Cookie': authCookies.build() as unknown as string,
119
120
  };
120
121
 
121
122
  throw newErr;
@@ -1,5 +1,6 @@
1
1
  import { autoHandler } from 'knifecycle';
2
2
  import YHTTPError from 'yhttperror';
3
+ import { refersTo } from '@whook/whook';
3
4
  import initPostOauth2Token from './postOAuth2Token';
4
5
  import { AUTH_API_PREFIX } from '../services/authCookies';
5
6
  import type {
@@ -36,11 +37,7 @@ export const definition: WhookAPIHandlerDefinition = {
36
37
  'x-whook': {
37
38
  disabled: true,
38
39
  },
39
- parameters: [
40
- {
41
- $ref: `#/components/parameters/${authCookieHeaderParameter.name}`,
42
- },
43
- ],
40
+ parameters: [refersTo(authCookieHeaderParameter)],
44
41
  requestBody: {
45
42
  required: true,
46
43
  content: {
@@ -134,11 +131,12 @@ async function postAuthRefresh<
134
131
  },
135
132
  };
136
133
  } catch (err) {
137
- const newErr = YHTTPError.wrap(err);
134
+ const newErr = YHTTPError.wrap(err as Error);
138
135
 
139
136
  newErr.headers = {
140
- ...(err.headers || {}),
141
- 'Set-Cookie': authCookies.build(),
137
+ ...((err as YHTTPError).headers || {}),
138
+ // TODO: Allow string[] in YHTTPError
139
+ 'Set-Cookie': authCookies.build() as unknown as string,
142
140
  };
143
141
 
144
142
  throw newErr;
@@ -4,7 +4,6 @@ import { setURLError } from './getOAuth2Authorize';
4
4
  import type {
5
5
  WhookAPIHandlerDefinition,
6
6
  WhookErrorsDescriptors,
7
- WhookAPIOperationConfig,
8
7
  } from '@whook/whook';
9
8
  import type {
10
9
  CheckApplicationService,
@@ -28,7 +27,7 @@ export const definition: WhookAPIHandlerDefinition = {
28
27
  tags: ['oauth2'],
29
28
  'x-whook': {
30
29
  private: true,
31
- } as WhookAPIOperationConfig,
30
+ },
32
31
  requestBody: {
33
32
  required: true,
34
33
  content: {
@@ -96,7 +95,32 @@ export const definition: WhookAPIHandlerDefinition = {
96
95
  },
97
96
  };
98
97
 
99
- export default autoHandler(postOAuth2Acknowledge);
98
+ export type HandlerDependencies = {
99
+ ERRORS_DESCRIPTORS: WhookErrorsDescriptors;
100
+ oAuth2Granters: OAuth2GranterService[];
101
+ checkApplication: CheckApplicationService;
102
+ log: LogService;
103
+ };
104
+ type HandlerParameters<AUTHENTICATION_DATA> = {
105
+ authenticationData: AUTHENTICATION_DATA;
106
+ body: {
107
+ responseType: string;
108
+ clientId: string;
109
+ redirectURI: string;
110
+ scope: string;
111
+ state: string;
112
+ acknowledged: boolean;
113
+ [name: string]: unknown;
114
+ };
115
+ };
116
+
117
+ export default autoHandler(postOAuth2Acknowledge) as unknown as <
118
+ AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
119
+ >(
120
+ dependencies: HandlerDependencies,
121
+ ) => (
122
+ parameters: HandlerParameters<AUTHENTICATION_DATA>,
123
+ ) => ReturnType<typeof postOAuth2Acknowledge>;
100
124
 
101
125
  async function postOAuth2Acknowledge<
102
126
  AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
@@ -106,12 +130,7 @@ async function postOAuth2Acknowledge<
106
130
  oAuth2Granters,
107
131
  checkApplication,
108
132
  log,
109
- }: {
110
- ERRORS_DESCRIPTORS: WhookErrorsDescriptors;
111
- oAuth2Granters: OAuth2GranterService[];
112
- checkApplication: CheckApplicationService;
113
- log: LogService;
114
- },
133
+ }: HandlerDependencies,
115
134
  {
116
135
  authenticationData,
117
136
  body: {
@@ -123,18 +142,7 @@ async function postOAuth2Acknowledge<
123
142
  acknowledged = false,
124
143
  ...additionalParameters
125
144
  },
126
- }: {
127
- authenticationData: AUTHENTICATION_DATA;
128
- body: {
129
- responseType: string;
130
- clientId: string;
131
- redirectURI: string;
132
- scope: string;
133
- state: string;
134
- acknowledged: boolean;
135
- [name: string]: unknown;
136
- };
137
- },
145
+ }: HandlerParameters<AUTHENTICATION_DATA>,
138
146
  ) {
139
147
  if (!authenticationData) {
140
148
  throw new YError('E_UNAUTHORIZED');
@@ -161,7 +169,7 @@ async function postOAuth2Acknowledge<
161
169
  granter.acknowledger.acknowledgmentType === responseType,
162
170
  );
163
171
 
164
- if (!granter) {
172
+ if (!granter || !granter.acknowledger) {
165
173
  throw new YError('E_UNKNOWN_ACKNOWLEDGOR_TYPE', responseType);
166
174
  }
167
175
 
@@ -183,13 +191,13 @@ async function postOAuth2Acknowledge<
183
191
  url.searchParams.set(snakeCase(key), additionalProperties[key] as string),
184
192
  );
185
193
  } catch (err) {
186
- log('debug', '👫 - OAuth2 acknowledge error', err.code);
187
- log('debug-stack', err.stack);
194
+ log('debug', '👫 - OAuth2 acknowledge error', (err as YError).code);
195
+ log('debug-stack', (err as Error).stack || 'no_stack_trace');
188
196
 
189
197
  setURLError(
190
198
  url,
191
- err,
192
- ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2,
199
+ err as YError,
200
+ ERRORS_DESCRIPTORS[(err as YError).code] || ERRORS_DESCRIPTORS.E_OAUTH2,
193
201
  );
194
202
  }
195
203
 
@@ -133,8 +133,8 @@ describe('postOAuth2Token', () => {
133
133
  throw new YError('E_UNEXPECTED_SUCCESS');
134
134
  } catch (err) {
135
135
  expect({
136
- errorCode: err.code,
137
- errorParams: err.params,
136
+ errorCode: (err as YError).code,
137
+ errorParams: (err as YError).params,
138
138
  }).toMatchInlineSnapshot(`
139
139
  Object {
140
140
  "errorCode": "E_UNKNOWN_AUTHENTICATOR_TYPE",
@@ -2,6 +2,7 @@ import { autoHandler } from 'knifecycle';
2
2
  import { camelCaseObjectProperties } from './getOAuth2Authorize';
3
3
  import { noop } from '@whook/whook';
4
4
  import YError from 'yerror';
5
+ import { refersTo } from '@whook/whook';
5
6
  import type { OpenAPIV3 } from 'openapi-types';
6
7
  import type { LogService, TimeService } from 'common-services';
7
8
  import type {
@@ -121,18 +122,10 @@ export const tokenBodySchema: WhookAPISchemaDefinition = {
121
122
  name: 'TokenRequestBody',
122
123
  schema: {
123
124
  oneOf: [
124
- {
125
- $ref: `#/components/schemas/${passwordTokenRequestBodySchema.name}`,
126
- },
127
- {
128
- $ref: `#/components/schemas/${authorizationCodeTokenRequestBodySchema.name}`,
129
- },
130
- {
131
- $ref: `#/components/schemas/${clientCredentialsTokenRequestBodySchema.name}`,
132
- },
133
- {
134
- $ref: `#/components/schemas/${refreshTokenRequestBodySchema.name}`,
135
- },
125
+ refersTo(passwordTokenRequestBodySchema),
126
+ refersTo(authorizationCodeTokenRequestBodySchema),
127
+ refersTo(clientCredentialsTokenRequestBodySchema),
128
+ refersTo(refreshTokenRequestBodySchema),
136
129
  ],
137
130
  } as OpenAPIV3.SchemaObject,
138
131
  };
@@ -150,14 +143,10 @@ export const definition: WhookAPIHandlerDefinition = {
150
143
  required: true,
151
144
  content: {
152
145
  'application/x-www-form-urlencoded': {
153
- schema: {
154
- $ref: `#/components/schemas/${tokenBodySchema.name}`,
155
- },
146
+ schema: refersTo(tokenBodySchema),
156
147
  },
157
148
  'application/json': {
158
- schema: {
159
- $ref: `#/components/schemas/${tokenBodySchema.name}`,
160
- },
149
+ schema: refersTo(tokenBodySchema),
161
150
  },
162
151
  },
163
152
  },
@@ -258,7 +247,7 @@ async function postOAuth2Token<
258
247
  granter.authenticator && granter.authenticator.grantType === grantType,
259
248
  );
260
249
 
261
- if (!granter) {
250
+ if (!granter || !granter.authenticator) {
262
251
  throw new YError('E_UNKNOWN_AUTHENTICATOR_TYPE', grantType);
263
252
  }
264
253
 
@@ -294,9 +283,9 @@ async function postOAuth2Token<
294
283
  },
295
284
  };
296
285
  } catch (err) {
297
- log('debug', '👫 - OAuth2 token issuing error', err.code);
298
- log('debug-stack', err.stack);
286
+ log('debug', '👫 - OAuth2 token issuing error', (err as YError).code);
287
+ log('debug-stack', (err as Error).stack || 'no_stack_trace');
299
288
 
300
- throw YError.cast(err, 'E_OAUTH2');
289
+ throw YError.cast(err as Error, 'E_OAUTH2');
301
290
  }
302
291
  }
package/src/index.test.ts CHANGED
@@ -41,7 +41,7 @@ import {
41
41
  postOAuth2TokenRefreshTokenRequestBodySchema,
42
42
  } from '.';
43
43
  import type { OAuth2Options } from '.';
44
- import type { Knifecycle, Dependencies } from 'knifecycle';
44
+ import type { Knifecycle } from 'knifecycle';
45
45
  import type { OpenAPIV3 } from 'openapi-types';
46
46
 
47
47
  describe('OAuth2 server', () => {
@@ -49,10 +49,10 @@ describe('OAuth2 server', () => {
49
49
  const PORT = 4444;
50
50
  const HOST = 'localhost';
51
51
  const logger = {
52
- info: jest.fn(),
52
+ output: jest.fn(),
53
53
  error: jest.fn(),
54
+ debug: jest.fn(),
54
55
  };
55
- const debug = jest.fn();
56
56
  const time = jest.fn();
57
57
  const $autoload = jest.fn();
58
58
 
@@ -167,7 +167,6 @@ describe('OAuth2 server', () => {
167
167
  $.register(constant('MECHANISMS', [BEARER_MECHANISM, BASIC_MECHANISM]));
168
168
  $.register(constant('logger', logger));
169
169
  $.register(constant('time', time));
170
- $.register(constant('debug', debug));
171
170
 
172
171
  // OAuth2 Specifics
173
172
  $.register(constant('OAUTH2', OAUTH2));
@@ -202,8 +201,8 @@ describe('OAuth2 server', () => {
202
201
  $.register(constant('oAuth2Password', oAuth2Password));
203
202
  [
204
203
  initGetOAuth2Authorize,
205
- wrapHandlerWithAuthorization(initPostOAuth2Acknowledge),
206
- wrapHandlerWithAuthorization(initPostOAuth2Token),
204
+ wrapHandlerWithAuthorization(initPostOAuth2Acknowledge as any),
205
+ wrapHandlerWithAuthorization(initPostOAuth2Token as any),
207
206
  initOAuth2Granters,
208
207
  initOAuth2ClientCredentialsGranter,
209
208
  initOAuth2CodeGranter,
@@ -222,7 +221,7 @@ describe('OAuth2 server', () => {
222
221
 
223
222
  beforeAll(async () => {
224
223
  const { $instance: _instance } = await runServer<{
225
- $instance: Knifecycle<Dependencies>;
224
+ $instance: Knifecycle;
226
225
  }>(prepareEnvironment, prepareServer, [
227
226
  '$instance',
228
227
  'httpServer',
@@ -236,9 +235,9 @@ describe('OAuth2 server', () => {
236
235
  });
237
236
 
238
237
  beforeEach(() => {
239
- logger.info.mockReset();
238
+ logger.output.mockReset();
240
239
  logger.error.mockReset();
241
- debug.mockReset();
240
+ logger.debug.mockReset();
242
241
  time.mockReset();
243
242
  $autoload.mockClear();
244
243
  [
@@ -39,30 +39,34 @@ async function initOAuth2ClientCredentialsGranter({
39
39
  checkApplication,
40
40
  log = noop,
41
41
  }: OAuth2ClientCredentialsGranterDependencies): Promise<OAuth2ClientCredentialsGranterService> {
42
- const authenticateWithClientCredentials: OAuth2ClientCredentialsGranterService['authenticator']['authenticate'] =
43
- async ({ scope: demandedScope = '' }, authenticationData) => {
44
- // The client must be authenticated
45
- if (!authenticationData) {
46
- throw new YError('E_UNAUTHORIZED');
47
- }
42
+ const authenticateWithClientCredentials: NonNullable<
43
+ OAuth2ClientCredentialsGranterService['authenticator']
44
+ >['authenticate'] = async (
45
+ { scope: demandedScope = '' },
46
+ authenticationData,
47
+ ) => {
48
+ // The client must be authenticated
49
+ if (!authenticationData) {
50
+ throw new YError('E_UNAUTHORIZED');
51
+ }
48
52
 
49
- // Checking the scope and availability of the demanded
50
- // grant type
51
- await checkApplication({
52
- applicationId: authenticationData.applicationId,
53
- type: 'client_credentials',
54
- scope: demandedScope,
55
- });
53
+ // Checking the scope and availability of the demanded
54
+ // grant type
55
+ await checkApplication({
56
+ applicationId: authenticationData.applicationId,
57
+ type: 'client_credentials',
58
+ scope: demandedScope,
59
+ });
56
60
 
57
- return {
58
- ...authenticationData,
59
- scope: demandedScope
60
- ? demandedScope
61
- : OAUTH2.defaultToClientScope
62
- ? authenticationData.scope
63
- : '',
64
- };
61
+ return {
62
+ ...authenticationData,
63
+ scope: demandedScope
64
+ ? demandedScope
65
+ : OAUTH2.defaultToClientScope
66
+ ? authenticationData.scope
67
+ : '',
65
68
  };
69
+ };
66
70
 
67
71
  log('debug', '👫 - OAuth2ClientCredentialsGranter Service Initialized!');
68
72
 
@@ -31,25 +31,26 @@ describe('OAuth2CodeGranter', () => {
31
31
  scope: 'user',
32
32
  });
33
33
 
34
- const authorizerResult = await oAuth2CodeGranter.authorizer.authorize({
34
+ const authorizerResult = await oAuth2CodeGranter.authorizer?.authorize({
35
35
  clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
36
36
  redirectURI: 'https://www.example.com/oauth2/code',
37
37
  scope: 'user',
38
38
  });
39
- const acknowledgerResult = await oAuth2CodeGranter.acknowledger.acknowledge(
40
- {
41
- applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
42
- scope: 'user, admin',
43
- },
44
- {
45
- clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
46
- redirectURI: 'https://www.example.com/oauth2/code',
47
- scope: 'user',
48
- },
49
- {},
50
- );
39
+ const acknowledgerResult =
40
+ await oAuth2CodeGranter.acknowledger?.acknowledge(
41
+ {
42
+ applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
43
+ scope: 'user, admin',
44
+ },
45
+ {
46
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
47
+ redirectURI: 'https://www.example.com/oauth2/code',
48
+ scope: 'user',
49
+ },
50
+ {},
51
+ );
51
52
  const authenticatorResult =
52
- await oAuth2CodeGranter.authenticator.authenticate(
53
+ await oAuth2CodeGranter.authenticator?.authenticate(
53
54
  {
54
55
  clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
55
56
  redirectURI: 'https://www.example.com/oauth2/code',
@@ -39,79 +39,85 @@ async function initOAuth2CodeGranter({
39
39
  checkApplication,
40
40
  log = noop,
41
41
  }: OAuth2CodeGranterDependencies): Promise<OAuth2CodeGranterService> {
42
- const authorizeWithCode: OAuth2CodeGranterService['authorizer']['authorize'] =
43
- async ({ clientId, redirectURI, scope = '' }) => {
44
- const { redirectURI: finalRedirectURI } = await checkApplication({
45
- applicationId: clientId,
46
- type: CODE_GRANTER_TYPE,
47
- redirectURI,
48
- scope,
49
- });
42
+ const authorizeWithCode: NonNullable<
43
+ OAuth2CodeGranterService['authorizer']
44
+ >['authorize'] = async ({ clientId, redirectURI, scope = '' }) => {
45
+ const { redirectURI: finalRedirectURI } = await checkApplication({
46
+ applicationId: clientId,
47
+ type: CODE_GRANTER_TYPE,
48
+ redirectURI,
49
+ scope,
50
+ });
50
51
 
51
- return {
52
- applicationId: clientId,
53
- redirectURI: finalRedirectURI,
54
- scope,
55
- };
52
+ return {
53
+ applicationId: clientId,
54
+ redirectURI: finalRedirectURI,
55
+ scope,
56
56
  };
57
+ };
57
58
 
58
59
  // Authorization Code Response:
59
60
  // https://tools.ietf.org/html/rfc6749#section-4.1.2
60
- const acknowledgeWithCode: OAuth2CodeGranterService['acknowledger']['acknowledge'] =
61
- async (
62
- authenticationData,
63
- { clientId, redirectURI, scope },
61
+ const acknowledgeWithCode: NonNullable<
62
+ OAuth2CodeGranterService['acknowledger']
63
+ >['acknowledge'] = async (
64
+ authenticationData,
65
+ { clientId, redirectURI, scope },
66
+ additionalParameters,
67
+ ) => {
68
+ const code = await oAuth2Code.create(
69
+ { ...authenticationData, applicationId: clientId, scope },
70
+ redirectURI,
64
71
  additionalParameters,
65
- ) => {
66
- const code = await oAuth2Code.create(
67
- { ...authenticationData, applicationId: clientId, scope },
68
- redirectURI,
69
- additionalParameters,
70
- );
72
+ );
71
73
 
72
- return {
73
- applicationId: clientId,
74
- redirectURI,
75
- scope,
76
- code,
77
- };
74
+ return {
75
+ applicationId: clientId,
76
+ redirectURI,
77
+ scope,
78
+ code,
78
79
  };
80
+ };
79
81
 
80
- const authenticateWithCode: OAuth2CodeGranterService['authenticator']['authenticate'] =
81
- async ({ code, clientId, redirectURI }, authenticationData) => {
82
- // The client must be authenticated (for now, see below)
83
- if (!authenticationData) {
84
- throw new YError('E_UNAUTHORIZED');
85
- }
82
+ const authenticateWithCode: NonNullable<
83
+ OAuth2CodeGranterService['authenticator']
84
+ >['authenticate'] = async (
85
+ { code, clientId, redirectURI },
86
+ authenticationData,
87
+ ) => {
88
+ // The client must be authenticated (for now, see below)
89
+ if (!authenticationData) {
90
+ throw new YError('E_UNAUTHORIZED');
91
+ }
86
92
 
87
- // This check is not really necessary atm but it acts
88
- // as a reminder that this grant type could be used
89
- // without authenticating the client. In this
90
- // scenario, the authenticationData should be deducted
91
- // from the clientId and the code given in parameters
92
- // See https://tools.ietf.org/html/rfc6749#section-4.1.3
93
- if (clientId && clientId !== authenticationData.applicationId) {
94
- throw new YError(
95
- 'E_UNAUTHORIZED',
96
- clientId,
97
- authenticationData.applicationId,
98
- );
99
- }
93
+ // This check is not really necessary atm but it acts
94
+ // as a reminder that this grant type could be used
95
+ // without authenticating the client. In this
96
+ // scenario, the authenticationData should be deducted
97
+ // from the clientId and the code given in parameters
98
+ // See https://tools.ietf.org/html/rfc6749#section-4.1.3
99
+ if (clientId && clientId !== authenticationData.applicationId) {
100
+ throw new YError(
101
+ 'E_UNAUTHORIZED',
102
+ clientId,
103
+ authenticationData.applicationId,
104
+ );
105
+ }
100
106
 
101
- await checkApplication({
102
- applicationId: authenticationData.applicationId,
103
- type: CODE_GRANTER_TYPE,
104
- scope: '',
105
- });
107
+ await checkApplication({
108
+ applicationId: authenticationData.applicationId,
109
+ type: CODE_GRANTER_TYPE,
110
+ scope: '',
111
+ });
106
112
 
107
- const newAuthenticationData = await oAuth2Code.check(
108
- authenticationData,
109
- code,
110
- redirectURI,
111
- );
113
+ const newAuthenticationData = await oAuth2Code.check(
114
+ authenticationData,
115
+ code,
116
+ redirectURI,
117
+ );
112
118
 
113
- return newAuthenticationData;
114
- };
119
+ return newAuthenticationData;
120
+ };
115
121
 
116
122
  log('debug', '👫 - OAuth2CodeGranter Service Initialized!');
117
123