@whook/oauth2 8.3.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 (146) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +384 -0
  3. package/dist/handlers/getOAuth2Authorize.d.ts +26 -0
  4. package/dist/handlers/getOAuth2Authorize.js +192 -0
  5. package/dist/handlers/getOAuth2Authorize.js.map +1 -0
  6. package/dist/handlers/getOAuth2Authorize.mjs +169 -0
  7. package/dist/handlers/getOAuth2Authorize.mjs.map +1 -0
  8. package/dist/handlers/getOAuth2Authorize.test.d.ts +1 -0
  9. package/dist/handlers/getOAuth2Authorize.test.js +122 -0
  10. package/dist/handlers/getOAuth2Authorize.test.js.map +1 -0
  11. package/dist/handlers/getOAuth2Authorize.test.mjs +114 -0
  12. package/dist/handlers/getOAuth2Authorize.test.mjs.map +1 -0
  13. package/dist/handlers/postAuthLogin.d.ts +45 -0
  14. package/dist/handlers/postAuthLogin.js +125 -0
  15. package/dist/handlers/postAuthLogin.js.map +1 -0
  16. package/dist/handlers/postAuthLogin.mjs +108 -0
  17. package/dist/handlers/postAuthLogin.mjs.map +1 -0
  18. package/dist/handlers/postAuthLogin.test.d.ts +1 -0
  19. package/dist/handlers/postAuthLogin.test.js +90 -0
  20. package/dist/handlers/postAuthLogin.test.js.map +1 -0
  21. package/dist/handlers/postAuthLogin.test.mjs +85 -0
  22. package/dist/handlers/postAuthLogin.test.mjs.map +1 -0
  23. package/dist/handlers/postAuthLogout.d.ts +12 -0
  24. package/dist/handlers/postAuthLogout.js +46 -0
  25. package/dist/handlers/postAuthLogout.js.map +1 -0
  26. package/dist/handlers/postAuthLogout.mjs +33 -0
  27. package/dist/handlers/postAuthLogout.mjs.map +1 -0
  28. package/dist/handlers/postAuthLogout.test.d.ts +1 -0
  29. package/dist/handlers/postAuthLogout.test.js +35 -0
  30. package/dist/handlers/postAuthLogout.test.js.map +1 -0
  31. package/dist/handlers/postAuthLogout.test.mjs +30 -0
  32. package/dist/handlers/postAuthLogout.test.mjs.map +1 -0
  33. package/dist/handlers/postAuthRefresh.d.ts +45 -0
  34. package/dist/handlers/postAuthRefresh.js +140 -0
  35. package/dist/handlers/postAuthRefresh.js.map +1 -0
  36. package/dist/handlers/postAuthRefresh.mjs +122 -0
  37. package/dist/handlers/postAuthRefresh.mjs.map +1 -0
  38. package/dist/handlers/postAuthRefresh.test.d.ts +1 -0
  39. package/dist/handlers/postAuthRefresh.test.js +99 -0
  40. package/dist/handlers/postAuthRefresh.test.js.map +1 -0
  41. package/dist/handlers/postAuthRefresh.test.mjs +94 -0
  42. package/dist/handlers/postAuthRefresh.test.mjs.map +1 -0
  43. package/dist/handlers/postOAuth2Acknowledge.d.ts +28 -0
  44. package/dist/handlers/postOAuth2Acknowledge.js +165 -0
  45. package/dist/handlers/postOAuth2Acknowledge.js.map +1 -0
  46. package/dist/handlers/postOAuth2Acknowledge.mjs +150 -0
  47. package/dist/handlers/postOAuth2Acknowledge.mjs.map +1 -0
  48. package/dist/handlers/postOAuth2Acknowledge.test.d.ts +1 -0
  49. package/dist/handlers/postOAuth2Acknowledge.test.js +148 -0
  50. package/dist/handlers/postOAuth2Acknowledge.test.js.map +1 -0
  51. package/dist/handlers/postOAuth2Acknowledge.test.mjs +140 -0
  52. package/dist/handlers/postOAuth2Acknowledge.test.mjs.map +1 -0
  53. package/dist/handlers/postOAuth2Token.d.ts +36 -0
  54. package/dist/handlers/postOAuth2Token.js +263 -0
  55. package/dist/handlers/postOAuth2Token.js.map +1 -0
  56. package/dist/handlers/postOAuth2Token.mjs +242 -0
  57. package/dist/handlers/postOAuth2Token.mjs.map +1 -0
  58. package/dist/handlers/postOAuth2Token.test.d.ts +1 -0
  59. package/dist/handlers/postOAuth2Token.test.js +166 -0
  60. package/dist/handlers/postOAuth2Token.test.js.map +1 -0
  61. package/dist/handlers/postOAuth2Token.test.mjs +160 -0
  62. package/dist/handlers/postOAuth2Token.test.mjs.map +1 -0
  63. package/dist/index.d.ts +17 -0
  64. package/dist/index.js +230 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/index.mjs +15 -0
  67. package/dist/index.mjs.map +1 -0
  68. package/dist/index.test.d.ts +1 -0
  69. package/dist/index.test.js +759 -0
  70. package/dist/index.test.js.map +1 -0
  71. package/dist/index.test.mjs +748 -0
  72. package/dist/index.test.mjs.map +1 -0
  73. package/dist/services/authCookies.d.ts +26 -0
  74. package/dist/services/authCookies.js +74 -0
  75. package/dist/services/authCookies.js.map +1 -0
  76. package/dist/services/authCookies.mjs +58 -0
  77. package/dist/services/authCookies.mjs.map +1 -0
  78. package/dist/services/authCookies.test.d.ts +1 -0
  79. package/dist/services/authCookies.test.js +82 -0
  80. package/dist/services/authCookies.test.js.map +1 -0
  81. package/dist/services/authCookies.test.mjs +77 -0
  82. package/dist/services/authCookies.test.mjs.map +1 -0
  83. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +17 -0
  84. package/dist/services/oAuth2ClientCredentialsGranter.js +56 -0
  85. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -0
  86. package/dist/services/oAuth2ClientCredentialsGranter.mjs +41 -0
  87. package/dist/services/oAuth2ClientCredentialsGranter.mjs.map +1 -0
  88. package/dist/services/oAuth2CodeGranter.d.ts +17 -0
  89. package/dist/services/oAuth2CodeGranter.js +115 -0
  90. package/dist/services/oAuth2CodeGranter.js.map +1 -0
  91. package/dist/services/oAuth2CodeGranter.mjs +98 -0
  92. package/dist/services/oAuth2CodeGranter.mjs.map +1 -0
  93. package/dist/services/oAuth2CodeGranter.test.d.ts +1 -0
  94. package/dist/services/oAuth2CodeGranter.test.js +86 -0
  95. package/dist/services/oAuth2CodeGranter.test.js.map +1 -0
  96. package/dist/services/oAuth2CodeGranter.test.mjs +81 -0
  97. package/dist/services/oAuth2CodeGranter.test.mjs.map +1 -0
  98. package/dist/services/oAuth2Granters.d.ts +79 -0
  99. package/dist/services/oAuth2Granters.js +140 -0
  100. package/dist/services/oAuth2Granters.js.map +1 -0
  101. package/dist/services/oAuth2Granters.mjs +127 -0
  102. package/dist/services/oAuth2Granters.mjs.map +1 -0
  103. package/dist/services/oAuth2PasswordGranter.d.ts +16 -0
  104. package/dist/services/oAuth2PasswordGranter.js +55 -0
  105. package/dist/services/oAuth2PasswordGranter.js.map +1 -0
  106. package/dist/services/oAuth2PasswordGranter.mjs +40 -0
  107. package/dist/services/oAuth2PasswordGranter.mjs.map +1 -0
  108. package/dist/services/oAuth2RefreshTokenGranter.d.ts +15 -0
  109. package/dist/services/oAuth2RefreshTokenGranter.js +62 -0
  110. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -0
  111. package/dist/services/oAuth2RefreshTokenGranter.mjs +47 -0
  112. package/dist/services/oAuth2RefreshTokenGranter.mjs.map +1 -0
  113. package/dist/services/oAuth2TokenGranter.d.ts +15 -0
  114. package/dist/services/oAuth2TokenGranter.js +92 -0
  115. package/dist/services/oAuth2TokenGranter.js.map +1 -0
  116. package/dist/services/oAuth2TokenGranter.mjs +78 -0
  117. package/dist/services/oAuth2TokenGranter.mjs.map +1 -0
  118. package/package.json +205 -0
  119. package/src/__snapshots__/index.test.ts.snap +396 -0
  120. package/src/handlers/__snapshots__/getOAuth2Authorize.test.ts.snap +38 -0
  121. package/src/handlers/__snapshots__/postOAuth2Acknowledge.test.ts.snap +61 -0
  122. package/src/handlers/__snapshots__/postOAuth2Token.test.ts.snap +52 -0
  123. package/src/handlers/getOAuth2Authorize.test.ts +142 -0
  124. package/src/handlers/getOAuth2Authorize.ts +222 -0
  125. package/src/handlers/postAuthLogin.test.ts +88 -0
  126. package/src/handlers/postAuthLogin.ts +123 -0
  127. package/src/handlers/postAuthLogout.test.ts +33 -0
  128. package/src/handlers/postAuthLogout.ts +38 -0
  129. package/src/handlers/postAuthRefresh.test.ts +97 -0
  130. package/src/handlers/postAuthRefresh.ts +146 -0
  131. package/src/handlers/postOAuth2Acknowledge.test.ts +175 -0
  132. package/src/handlers/postOAuth2Acknowledge.ts +209 -0
  133. package/src/handlers/postOAuth2Token.test.ts +153 -0
  134. package/src/handlers/postOAuth2Token.ts +302 -0
  135. package/src/index.test.ts +936 -0
  136. package/src/index.ts +105 -0
  137. package/src/services/__snapshots__/oAuth2CodeGranter.test.ts.snap +49 -0
  138. package/src/services/authCookies.test.ts +93 -0
  139. package/src/services/authCookies.ts +82 -0
  140. package/src/services/oAuth2ClientCredentialsGranter.ts +76 -0
  141. package/src/services/oAuth2CodeGranter.test.ts +94 -0
  142. package/src/services/oAuth2CodeGranter.ts +133 -0
  143. package/src/services/oAuth2Granters.ts +274 -0
  144. package/src/services/oAuth2PasswordGranter.ts +75 -0
  145. package/src/services/oAuth2RefreshTokenGranter.ts +77 -0
  146. package/src/services/oAuth2TokenGranter.ts +105 -0
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ The MIT License (MIT)
2
+ Copyright © 2017 Nicolas Froidure
3
+
4
+ Permission is hereby granted, free of charge, to any person obtaining a copy
5
+ of this software and associated documentation files (the “Software”), to deal
6
+ in the Software without restriction, including without limitation the rights
7
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8
+ copies of the Software, and to permit persons to whom the Software is
9
+ furnished to do so, subject to the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be included in
12
+ all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,384 @@
1
+ [//]: # ( )
2
+ [//]: # (This file is automatically generated by a `metapak`)
3
+ [//]: # (module. Do not change it except between the)
4
+ [//]: # (`content:start/end` flags, your changes would)
5
+ [//]: # (be overridden.)
6
+ [//]: # ( )
7
+ # @whook/oauth2
8
+ > OAuth2 implementation for Whook servers
9
+
10
+ [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/nfroidure/whook/blob/master/packages/whook-oauth2/LICENSE)
11
+ [![NPM version](https://badge.fury.io/js/%40whook%2Foauth2.svg)](https://npmjs.org/package/@whook/oauth2)
12
+
13
+
14
+ [//]: # (::contents:start)
15
+
16
+ This module is aimed to allow you to easily bring OAuth2 to your
17
+ [Whook](https://github.com/nfroidure/whook) server. It must be used with a
18
+ server side rendered frontend that brings the UI that allows users to
19
+ authenticate and allow client applications to act on behalf of them.
20
+
21
+ ![Code Flow Overview](./code_flow_overview.svg)
22
+
23
+ The module provides :
24
+
25
+ - 3 handlers : the 2 OAuth2 standard endpoints (`getOAuth2authorize` and
26
+ `postOAuth2Tokentoken`) plus the `postOAuth2Acknowledge` to be used by the SSR
27
+ frontend,
28
+ - the 5 OAuth2 standard grant types implemented through plug and play services.
29
+ You can create your own granter services to create additional grant types.
30
+
31
+ This module requires you to implement some services it relies on:
32
+
33
+ - `oAuth2AccessToken` that generates and checks the `access_token` and the
34
+ `oAuth2RefreshToken` for the `refresh_token` both have the same interface,
35
+ - `checkApplication` service that is supposed to check whether an application
36
+ can be used or not for a given grant type, a given scope and redirect URI,
37
+ - `oAuth2PasswordService` aimed to check the `password` grant type with your own
38
+ logic (if you use it),
39
+ - `oAuth2ClientCredentialsService` aimed to check the `client_credential` grant
40
+ type with your own logic (if you use it),
41
+ - `OAuth2CodeService` aimed to check the `code` grant type with your own logic
42
+ (if you use it).
43
+
44
+ ## Quick setup
45
+
46
+ Install the module in your project:
47
+
48
+ ```sh
49
+ npm i @whook/oauth2
50
+ ```
51
+
52
+ Declare the plugin into your `index.ts` file:
53
+
54
+ ```diff
55
+ // (...)
56
+
57
+ // Setup your own whook plugins or avoid whook defaults by leaving it empty
58
+ - $.register(constant('WHOOK_PLUGINS', ['@whook/cli', '@whook/whook']));
59
+ + $.register(constant('WHOOK_PLUGINS', ['@whook/oauth2', '@whook/cli', '@whook/whook']));
60
+
61
+ // (...)
62
+ ```
63
+
64
+ Add the OAuth2 configuration to your config files:
65
+
66
+ ```diff
67
+ + import {
68
+ + OAUTH2_ERRORS_DESCRIPTORS,
69
+ + OAuth2Config,
70
+ + } from '@whook/oauth2';
71
+
72
+ // ...
73
+
74
+ export type AppConfigs = WhookConfigs &
75
+ + OAuth2Config &
76
+ APIConfig;
77
+
78
+ const CONFIG: AppConfigs = {
79
+ // ...
80
+ + OAUTH2: {
81
+ + // The SSR frontend
82
+ + authenticateURL: 'https://auth.example.com',
83
+ + }
84
+ - ERRORS_DESCRIPTORS: DEFAULT_ERRORS_DESCRIPTORS,
85
+ + ERRORS_DESCRIPTORS: {
86
+ + ...DEFAULT_ERRORS_DESCRIPTORS,
87
+ + ...OAUTH2_ERRORS_DESCRIPTORS,
88
+ + },
89
+ // ...
90
+ };
91
+
92
+ export default CONFIG;
93
+ ```
94
+
95
+ ## Using your own grant types
96
+
97
+ The `oAuth2Granters` service gather the various granters services you can use in
98
+ your application but you can write your own that uses a subset or a superset of
99
+ these granters.
100
+
101
+ Here, for example an handler that implement a verify token mechanism in order to
102
+ validate a user subscription:
103
+
104
+ ```ts
105
+ import { autoService } from 'knifecycle';
106
+ import { noop } from '@whook/whook';
107
+ import YError from 'yerror';
108
+ import type { LogService } from 'common-services';
109
+ import type { AuthenticationData } from './authentication';
110
+ import type {
111
+ OAuth2GranterService,
112
+ CheckApplicationService,
113
+ } from '@whook/oauth2';
114
+ import type { JWTService } from 'jwt-service';
115
+ import type { PGService } from 'postgresql-service';
116
+
117
+ export type OAuth2VerifyTokenGranterDependencies = {
118
+ checkApplication: CheckApplicationService;
119
+ jwtToken: JWTService<AuthenticationData>;
120
+ pg: Pick<PGService, 'query'>;
121
+ log?: LogService;
122
+ };
123
+ export type OAuth2VerifyTokenGranterParameters = {
124
+ verifyToken: string;
125
+ };
126
+ export type OAuth2VerifyTokenGranterService = OAuth2GranterService<
127
+ unknown,
128
+ unknown,
129
+ OAuth2VerifyTokenGranterParameters,
130
+ AuthenticationData
131
+ >;
132
+
133
+ export default autoService(initOAuth2VerifyTokenGranter);
134
+
135
+ const USER_VERIFY_QUERY = `
136
+ UPDATE users
137
+ SET roles = ARRAY['user'::role]
138
+ WHERE id = $$userId
139
+ `;
140
+
141
+ async function initOAuth2VerifyTokenGranter({
142
+ checkApplication,
143
+ jwtToken,
144
+ pg,
145
+ log = noop,
146
+ }: OAuth2VerifyTokenGranterDependencies): Promise<
147
+ OAuth2VerifyTokenGranterService
148
+ > {
149
+ const authenticateWithVerifyToken: OAuth2VerifyTokenGranterService['authenticator']['authenticate'] = async (
150
+ { verifyToken },
151
+ authenticationData,
152
+ ) => {
153
+ try {
154
+ // The client must be authenticated
155
+ if (!authenticationData) {
156
+ throw new YError('E_UNAUTHORIZED');
157
+ }
158
+
159
+ const newAuthenticationData = await jwtToken.verify(verifyToken);
160
+
161
+ await checkApplication({
162
+ applicationId: authenticationData.applicationId,
163
+ type: 'verify',
164
+ scope: newAuthenticationData.scope,
165
+ });
166
+
167
+ const result = await pg.query(USER_VERIFY_QUERY, {
168
+ userId: newAuthenticationData.userId,
169
+ });
170
+
171
+ if (result.rowCount === 0) {
172
+ throw new YError('E_ALREADY_VERIFIED', authenticationData.userId);
173
+ }
174
+
175
+ return newAuthenticationData;
176
+ } catch (err) {
177
+ if (err.code === 'E_BAD_TOKEN') {
178
+ throw YError.wrap(err, 'E_BAD_REFRESH_TOKEN');
179
+ }
180
+ throw err;
181
+ }
182
+ };
183
+
184
+ log('debug', '👫 - OAuth2VerifyTokenGranter Service Initialized!');
185
+
186
+ return {
187
+ type: 'verify',
188
+ authenticator: {
189
+ grantType: 'verify_token',
190
+ authenticate: authenticateWithVerifyToken,
191
+ },
192
+ };
193
+ }
194
+ ```
195
+
196
+ ## Additional handlers/helpers
197
+
198
+ For internal use, you may prefer use cookies based auth handlers like
199
+ `postLogin`, `postLogout` and `postRefresh`.
200
+
201
+ To do so, configure the `ROOT_AUTHENTICATION_DATA` and `COOKIES` configurations:
202
+ ```diff
203
+ // src/production/config.ts
204
+ + COOKIES: {
205
+ + domain: 'example.org',
206
+ + },
207
+ + ROOT_AUTHENTICATION_DATA: {
208
+ + applicationId: 'abbacaca-abba-caca-caca-abbacacacaca',
209
+ + scope: 'user,admin',
210
+ + },
211
+ ```
212
+
213
+ Than import the `postLogin`, `postLogout` and `postRefresh` handlers like so:
214
+ ```ts
215
+ // src/handlers/postRefresh.ts
216
+ import {
217
+ initPostAuthRefresh,
218
+ postAuthRefreshDefinition,
219
+ authCookieHeaderParameter,
220
+ } from '@whook/oauth2';
221
+ import type { WhookAPIHandlerDefinition } from '@whook/whook';
222
+
223
+ export { authCookieHeaderParameter };
224
+
225
+ export const definition: WhookAPIHandlerDefinition = {
226
+ ...postAuthRefreshDefinition,
227
+ operation: {
228
+ ...postAuthRefreshDefinition.operation,
229
+ 'x-whook': {
230
+ disabled: false,
231
+ },
232
+ },
233
+ };
234
+
235
+ export default initPostAuthRefresh;
236
+ ```
237
+
238
+ Additionnaly, you could create any handler in the `/auth` path in order to receive the auth cookies.
239
+
240
+ ## Customizing handlers
241
+
242
+ The endpoints definitions are designed to support the standard OAuth2
243
+ definitions but can be easily overriden.
244
+
245
+ You will have to protect the `postOAuth2Acknowledge` with your own security
246
+ mechanism :
247
+
248
+ ```ts
249
+ import {
250
+ initPostOAuth2Acknowledge,
251
+ postOAuth2AcknowledgeDefinition,
252
+ } from '@whook/oauth2';
253
+ import type { OpenAPIV3 } from 'openapi-types';
254
+ import type { WhookAPIHandlerDefinition } from '@whook/whook';
255
+
256
+ export default initPostOAuth2Acknowledge;
257
+
258
+ export const definition: WhookAPIHandlerDefinition = {
259
+ ...postOAuth2AcknowledgeDefinition,
260
+ operation: {
261
+ ...postOAuth2AcknowledgeDefinition.operation,
262
+ security: [
263
+ {
264
+ bearerAuth: ['user'],
265
+ },
266
+ ],
267
+ // Optionally you can rewrite the endpoint definition
268
+ // to add more custom parameters to your endpoint
269
+ requestBody: {
270
+ required: true,
271
+ content: {
272
+ 'application/json': {
273
+ schema: {
274
+ ...((postOAuth2AcknowledgeDefinition.operation
275
+ .requestBody as OpenAPIV3.RequestBodyObject).content[
276
+ 'application/json'
277
+ ].schema as OpenAPIV3.NonArraySchemaObject),
278
+ required: [
279
+ 'userId',
280
+ ...((postOAuth2AcknowledgeDefinition.operation
281
+ .requestBody as OpenAPIV3.RequestBodyObject).content[
282
+ 'application/json'
283
+ ].schema as OpenAPIV3.NonArraySchemaObject).required,
284
+ ],
285
+ properties: {
286
+ ...((postOAuth2AcknowledgeDefinition.operation
287
+ .requestBody as OpenAPIV3.RequestBodyObject).content[
288
+ 'application/json'
289
+ ].schema as OpenAPIV3.NonArraySchemaObject).properties,
290
+ userId: {
291
+ type: 'string',
292
+ },
293
+ },
294
+ },
295
+ },
296
+ },
297
+ },
298
+ },
299
+ };
300
+ ```
301
+
302
+ You will probably need to also protect the `postOAuth2Token` endpoint with your
303
+ own security mecanism :
304
+
305
+ ```ts
306
+ // In a `src/handlers/postOAuth2Token.ts` fileimport {
307
+ initPostOAuth2Token,
308
+ postOAuth2TokenDefinition,
309
+ postOAuth2TokenAuthorizationCodeTokenRequestBodySchema,
310
+ postOAuth2TokenPasswordTokenRequestBodySchema,
311
+ postOAuth2TokenClientCredentialsTokenRequestBodySchema,
312
+ postOAuth2TokenRefreshTokenRequestBodySchema,
313
+ postOAuth2TokenTokenBodySchema,
314
+ } from '@whook/oauth2';
315
+ import type { WhookAPIHandlerDefinition } from '@whook/whook';
316
+
317
+ export default initPostOAuth2Token;
318
+
319
+ export const definition: WhookAPIHandlerDefinition = {
320
+ ...postOAuth2TokenDefinition,
321
+ operation: {
322
+ ...postOAuth2TokenDefinition.operation,
323
+ security: [
324
+ {
325
+ basicAuth: ['admin'],
326
+ },
327
+ ],
328
+ },
329
+ };
330
+
331
+ export {
332
+ postOAuth2TokenAuthorizationCodeTokenRequestBodySchema,
333
+ postOAuth2TokenPasswordTokenRequestBodySchema,
334
+ postOAuth2TokenClientCredentialsTokenRequestBodySchema,
335
+ postOAuth2TokenRefreshTokenRequestBodySchema,
336
+ postOAuth2TokenTokenBodySchema,
337
+ };
338
+ ```
339
+
340
+ Or you may want to reduce the OAuth2 grant types supported:
341
+
342
+ ```ts
343
+ // In a `src/handlers/getOAuth2Authorize.ts` file
344
+ import {
345
+ initGetOAuth2Authorize,
346
+ getOAuth2AuthorizeDefinition as definition,
347
+ getOAuth2AuthorizeResponseTypeParameter as baseResponseTypeParameter,
348
+ getOAuth2AuthorizeClientIdParameter as clientIdParameter,
349
+ getOAuth2AuthorizeRedirectURIParameter as redirectURIParameter,
350
+ getOAuth2AuthorizeScopeParameter as scopeParameter,
351
+ getOAuth2AuthorizeStateParameter as stateParameter,
352
+ } from '@whook/oauth2';
353
+
354
+ export default initGetOAuth2Authorize;
355
+
356
+ export {
357
+ definition,
358
+ clientIdParameter,
359
+ redirectURIParameter,
360
+ scopeParameter,
361
+ stateParameter,
362
+ };
363
+
364
+ export const responseTypeParameter = {
365
+ ...baseResponseTypeParameter,
366
+ parameter: {
367
+ ...baseResponseTypeParameter.parameter,
368
+ schema: {
369
+ ...baseResponseTypeParameter.parameter.schema,
370
+ enum: ['code'], // Allow only the 'code' grant type
371
+ },
372
+ },
373
+ };
374
+ ```
375
+
376
+ [//]: # (::contents:end)
377
+
378
+ # API
379
+
380
+ # Authors
381
+ - [Nicolas Froidure](http://insertafter.com/en/index.html)
382
+
383
+ # License
384
+ [MIT](https://github.com/nfroidure/whook/blob/master/packages/whook-oauth2/LICENSE)
@@ -0,0 +1,26 @@
1
+ /// <reference types="node" />
2
+ import YError from 'yerror';
3
+ import type { WhookAPIHandlerDefinition, WhookAPIParameterDefinition, WhookResponse, WhookErrorsDescriptors, WhookErrorDescriptor } from '@whook/whook';
4
+ import type { OAuth2Options, OAuth2GranterService } from '../services/oAuth2Granters';
5
+ import type { LogService } from 'common-services';
6
+ export declare const responseTypeParameter: WhookAPIParameterDefinition;
7
+ export declare const clientIdParameter: WhookAPIParameterDefinition;
8
+ export declare const redirectURIParameter: WhookAPIParameterDefinition;
9
+ export declare const scopeParameter: WhookAPIParameterDefinition;
10
+ export declare const stateParameter: WhookAPIParameterDefinition;
11
+ export declare const definition: WhookAPIHandlerDefinition;
12
+ declare const _default: import("knifecycle").ServiceInitializer<{
13
+ OAUTH2: OAuth2Options;
14
+ ERRORS_DESCRIPTORS: WhookErrorsDescriptors;
15
+ oAuth2Granters: OAuth2GranterService<Record<string, unknown>, Record<string, unknown>, Record<string, unknown>, import("@whook/authorization").BaseAuthenticationData<string, string>>[];
16
+ log: LogService;
17
+ }, (parameters: {
18
+ response_type: string;
19
+ client_id: string;
20
+ redirect_uri?: string;
21
+ scope?: string;
22
+ state: string;
23
+ } & Record<string, unknown>) => Promise<WhookResponse<number, import("@whook/http-transaction").WhookHeaders, import("stream").Readable | import("type-fest").JsonValue>>>;
24
+ export default _default;
25
+ export declare function camelCaseObjectProperties<T>(object: Record<string, T>): Record<string, T>;
26
+ export declare function setURLError(url: URL, err: YError | Error, oAuth2Error: WhookErrorDescriptor): void;
@@ -0,0 +1,192 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.camelCaseObjectProperties = camelCaseObjectProperties;
7
+ exports.setURLError = setURLError;
8
+ exports.default = exports.definition = exports.stateParameter = exports.scopeParameter = exports.redirectURIParameter = exports.clientIdParameter = exports.responseTypeParameter = void 0;
9
+
10
+ var _knifecycle = require("knifecycle");
11
+
12
+ var _camelcase = _interopRequireDefault(require("camelcase"));
13
+
14
+ var _yerror = _interopRequireDefault(require("yerror"));
15
+
16
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
+
18
+ /* Architecture Note #1: OAuth2 authorize
19
+ This endpoint simply redirect the user to the authentication
20
+ server page by first checking the application details are
21
+ fine.
22
+ */
23
+ const responseTypeParameter = {
24
+ name: 'responseType',
25
+ parameter: {
26
+ in: 'query',
27
+ name: 'response_type',
28
+ required: true,
29
+ schema: {
30
+ type: 'string',
31
+ enum: ['code', 'token']
32
+ }
33
+ }
34
+ };
35
+ exports.responseTypeParameter = responseTypeParameter;
36
+ const clientIdParameter = {
37
+ name: 'clientId',
38
+ parameter: {
39
+ in: 'query',
40
+ name: 'client_id',
41
+ required: true,
42
+ schema: {
43
+ type: 'string'
44
+ }
45
+ }
46
+ };
47
+ exports.clientIdParameter = clientIdParameter;
48
+ const redirectURIParameter = {
49
+ name: 'redirectURI',
50
+ parameter: {
51
+ in: 'query',
52
+ name: 'redirect_uri',
53
+ required: false,
54
+ schema: {
55
+ type: 'string',
56
+ pattern: '^https?://',
57
+ format: 'uri'
58
+ }
59
+ }
60
+ };
61
+ exports.redirectURIParameter = redirectURIParameter;
62
+ const scopeParameter = {
63
+ name: 'scope',
64
+ parameter: {
65
+ in: 'query',
66
+ name: 'scope',
67
+ description: 'See https://tools.ietf.org/html/rfc6749#section-3.3',
68
+ required: false,
69
+ schema: {
70
+ type: 'string'
71
+ }
72
+ }
73
+ };
74
+ exports.scopeParameter = scopeParameter;
75
+ const stateParameter = {
76
+ name: 'state',
77
+ parameter: {
78
+ in: 'query',
79
+ name: 'state',
80
+ required: true,
81
+ schema: {
82
+ type: 'string'
83
+ }
84
+ }
85
+ };
86
+ exports.stateParameter = stateParameter;
87
+ const definition = {
88
+ method: 'get',
89
+ path: '/oauth2/authorize',
90
+ operation: {
91
+ operationId: 'getOAuth2Authorize',
92
+ summary: `Implements the [Authorization Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1)
93
+ as defined per the OAuth2 RFC.`,
94
+ tags: ['oauth2'],
95
+ parameters: [{
96
+ $ref: `#/components/parameters/${responseTypeParameter.name}`
97
+ }, {
98
+ $ref: `#/components/parameters/${clientIdParameter.name}`
99
+ }, {
100
+ $ref: `#/components/parameters/${redirectURIParameter.name}`
101
+ }, {
102
+ $ref: `#/components/parameters/${scopeParameter.name}`
103
+ }, {
104
+ $ref: `#/components/parameters/${stateParameter.name}`
105
+ }],
106
+ responses: {
107
+ '302': {
108
+ description: 'Redirects the user to the authorization interface.'
109
+ }
110
+ }
111
+ }
112
+ };
113
+ exports.definition = definition;
114
+
115
+ var _default = (0, _knifecycle.handler)(getOAuth2Authorize, "getOAuth2Authorize", ["OAUTH2", "ERRORS_DESCRIPTORS", "oAuth2Granters", "log"]);
116
+
117
+ exports.default = _default;
118
+
119
+ async function getOAuth2Authorize({
120
+ OAUTH2,
121
+ ERRORS_DESCRIPTORS,
122
+ oAuth2Granters,
123
+ log
124
+ }, {
125
+ response_type: responseType,
126
+ client_id: clientId,
127
+ redirect_uri: demandedRedirectURI = '',
128
+ scope: demandedScope = '',
129
+ state,
130
+ ...authorizeParameters
131
+ }) {
132
+ const url = new URL(OAUTH2.authenticateURL);
133
+
134
+ try {
135
+ const granter = oAuth2Granters.find(granter => granter.authorizer && granter.authorizer.responseType === responseType);
136
+
137
+ if (!granter) {
138
+ throw new _yerror.default('E_UNKNOWN_AUTHORIZER_TYPE', responseType);
139
+ }
140
+
141
+ const {
142
+ applicationId,
143
+ redirectURI,
144
+ scope
145
+ } = await granter.authorizer.authorize({
146
+ clientId,
147
+ redirectURI: demandedRedirectURI,
148
+ scope: demandedScope
149
+ }, camelCaseObjectProperties(authorizeParameters));
150
+ url.searchParams.set('type', responseType);
151
+ url.searchParams.set('redirect_uri', redirectURI);
152
+ url.searchParams.set('scope', scope);
153
+ url.searchParams.set('client_id', applicationId);
154
+ } catch (err) {
155
+ log('debug', '👫 - OAuth2 initialization error', err.code);
156
+ log('debug-stack', err.stack);
157
+ url.searchParams.set('redirect_uri', demandedRedirectURI);
158
+ setURLError(url, err, ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2);
159
+ }
160
+
161
+ if (state) {
162
+ url.searchParams.set('state', state);
163
+ }
164
+
165
+ return {
166
+ status: 302,
167
+ headers: {
168
+ location: url.href
169
+ }
170
+ };
171
+ } // The OAuth2 standard uses snake case names so we are
172
+ // converting them to the project standards asap
173
+
174
+
175
+ function camelCaseObjectProperties(object) {
176
+ return Object.keys(object).reduce((camelCasedObject, key) => {
177
+ const newKey = key === 'redirect_uri' ? 'redirectURI' : (0, _camelcase.default)(key);
178
+ camelCasedObject[newKey] = object[key];
179
+ return camelCasedObject;
180
+ }, {});
181
+ }
182
+
183
+ function setURLError(url, err, oAuth2Error) {
184
+ url.searchParams.set('error', oAuth2Error.code);
185
+
186
+ if (oAuth2Error.description) {
187
+ url.searchParams.set('error_decription', oAuth2Error.description.replace(/\$([0-9]+)/g, (_, paramIndex) => {
188
+ return (err.params || [])[parseInt(paramIndex, 10)];
189
+ }));
190
+ }
191
+ }
192
+ //# sourceMappingURL=getOAuth2Authorize.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/handlers/getOAuth2Authorize.ts"],"names":["responseTypeParameter","name","parameter","in","required","schema","type","enum","clientIdParameter","redirectURIParameter","pattern","format","scopeParameter","description","stateParameter","definition","method","path","operation","operationId","summary","tags","parameters","$ref","responses","getOAuth2Authorize","OAUTH2","ERRORS_DESCRIPTORS","oAuth2Granters","log","response_type","responseType","client_id","clientId","redirect_uri","demandedRedirectURI","scope","demandedScope","state","authorizeParameters","url","URL","authenticateURL","granter","find","authorizer","YError","applicationId","redirectURI","authorize","camelCaseObjectProperties","searchParams","set","err","code","stack","setURLError","E_OAUTH2","status","headers","location","href","object","Object","keys","reduce","camelCasedObject","key","newKey","oAuth2Error","replace","_","paramIndex","params","parseInt"],"mappings":";;;;;;;;;AAAA;;AACA;;AACA;;;;AAcA;AACA;AACA;AACA;AACA;AAEO,MAAMA,qBAAkD,GAAG;AAChEC,EAAAA,IAAI,EAAE,cAD0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{ autoHandler } from 'knifecycle';\nimport camelCase from 'camelcase';\nimport YError from 'yerror';\nimport type {\n WhookAPIHandlerDefinition,\n WhookAPIParameterDefinition,\n WhookResponse,\n WhookErrorsDescriptors,\n WhookErrorDescriptor,\n} from '@whook/whook';\nimport type {\n OAuth2Options,\n OAuth2GranterService,\n} from '../services/oAuth2Granters';\nimport type { LogService } from 'common-services';\n\n/* Architecture Note #1: OAuth2 authorize\nThis endpoint simply redirect the user to the authentication\n server page by first checking the application details are\n fine.\n*/\n\nexport const responseTypeParameter: WhookAPIParameterDefinition = {\n name: 'responseType',\n parameter: {\n in: 'query',\n name: 'response_type',\n required: true,\n schema: {\n type: 'string',\n enum: ['code', 'token'],\n },\n },\n};\nexport const clientIdParameter: WhookAPIParameterDefinition = {\n name: 'clientId',\n parameter: {\n in: 'query',\n name: 'client_id',\n required: true,\n schema: {\n type: 'string',\n },\n },\n};\nexport const redirectURIParameter: WhookAPIParameterDefinition = {\n name: 'redirectURI',\n parameter: {\n in: 'query',\n name: 'redirect_uri',\n required: false,\n schema: {\n type: 'string',\n pattern: '^https?://',\n format: 'uri',\n },\n },\n};\nexport const scopeParameter: WhookAPIParameterDefinition = {\n name: 'scope',\n parameter: {\n in: 'query',\n name: 'scope',\n description: 'See https://tools.ietf.org/html/rfc6749#section-3.3',\n required: false,\n schema: {\n type: 'string',\n },\n },\n};\nexport const stateParameter: WhookAPIParameterDefinition = {\n name: 'state',\n parameter: {\n in: 'query',\n name: 'state',\n required: true,\n schema: {\n type: 'string',\n },\n },\n};\n\nexport const definition: WhookAPIHandlerDefinition = {\n method: 'get',\n path: '/oauth2/authorize',\n operation: {\n operationId: 'getOAuth2Authorize',\n summary: `Implements the [Authorization Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1)\n as defined per the OAuth2 RFC.`,\n tags: ['oauth2'],\n parameters: [\n {\n $ref: `#/components/parameters/${responseTypeParameter.name}`,\n },\n {\n $ref: `#/components/parameters/${clientIdParameter.name}`,\n },\n {\n $ref: `#/components/parameters/${redirectURIParameter.name}`,\n },\n {\n $ref: `#/components/parameters/${scopeParameter.name}`,\n },\n {\n $ref: `#/components/parameters/${stateParameter.name}`,\n },\n ],\n responses: {\n '302': {\n description: 'Redirects the user to the authorization interface.',\n },\n },\n },\n};\n\nexport default autoHandler(getOAuth2Authorize);\n\nasync function getOAuth2Authorize(\n {\n OAUTH2,\n ERRORS_DESCRIPTORS,\n oAuth2Granters,\n log,\n }: {\n OAUTH2: OAuth2Options;\n ERRORS_DESCRIPTORS: WhookErrorsDescriptors;\n oAuth2Granters: OAuth2GranterService[];\n log: LogService;\n },\n {\n response_type: responseType,\n client_id: clientId,\n redirect_uri: demandedRedirectURI = '',\n scope: demandedScope = '',\n state,\n ...authorizeParameters\n }: {\n response_type: string;\n client_id: string;\n redirect_uri?: string;\n scope?: string;\n state: string;\n } & Record<string, unknown>,\n): Promise<WhookResponse> {\n const url = new URL(OAUTH2.authenticateURL);\n\n try {\n const granter = oAuth2Granters.find(\n (granter) =>\n granter.authorizer && granter.authorizer.responseType === responseType,\n );\n\n if (!granter) {\n throw new YError('E_UNKNOWN_AUTHORIZER_TYPE', responseType);\n }\n\n const { applicationId, redirectURI, scope } =\n await granter.authorizer.authorize(\n {\n clientId,\n redirectURI: demandedRedirectURI,\n scope: demandedScope,\n },\n camelCaseObjectProperties(authorizeParameters),\n );\n\n url.searchParams.set('type', responseType);\n url.searchParams.set('redirect_uri', redirectURI);\n url.searchParams.set('scope', scope);\n url.searchParams.set('client_id', applicationId);\n } catch (err) {\n log('debug', '👫 - OAuth2 initialization error', err.code);\n log('debug-stack', err.stack);\n\n url.searchParams.set('redirect_uri', demandedRedirectURI);\n setURLError(\n url,\n err,\n ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2,\n );\n }\n\n if (state) {\n url.searchParams.set('state', state);\n }\n\n return {\n status: 302,\n headers: {\n location: url.href,\n },\n };\n}\n\n// The OAuth2 standard uses snake case names so we are\n// converting them to the project standards asap\nexport function camelCaseObjectProperties<T>(\n object: Record<string, T>,\n): Record<string, T> {\n return Object.keys(object).reduce((camelCasedObject, key) => {\n const newKey = key === 'redirect_uri' ? 'redirectURI' : camelCase(key);\n\n camelCasedObject[newKey] = object[key];\n return camelCasedObject;\n }, {});\n}\n\nexport function setURLError(\n url: URL,\n err: YError | Error,\n oAuth2Error: WhookErrorDescriptor,\n): void {\n url.searchParams.set('error', oAuth2Error.code);\n if (oAuth2Error.description) {\n url.searchParams.set(\n 'error_decription',\n oAuth2Error.description.replace(/\\$([0-9]+)/g, (_, paramIndex) => {\n return ((err as YError).params || [])[parseInt(paramIndex, 10)];\n }),\n );\n }\n}\n"],"file":"getOAuth2Authorize.js"}