@whook/oauth2 25.2.0 → 26.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 (173) hide show
  1. package/README.md +147 -98
  2. package/dist/index.d.ts +30 -11
  3. package/dist/index.js +15 -8
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.test.js +1258 -399
  6. package/dist/index.test.js.map +1 -1
  7. package/dist/libs/clients.d.ts +2 -0
  8. package/dist/libs/clients.js +13 -0
  9. package/dist/libs/clients.js.map +1 -0
  10. package/dist/libs/errors.d.ts +113 -0
  11. package/dist/libs/errors.js +178 -0
  12. package/dist/libs/errors.js.map +1 -0
  13. package/dist/libs/grants.d.ts +2 -0
  14. package/dist/libs/grants.js +10 -0
  15. package/dist/libs/grants.js.map +1 -0
  16. package/dist/libs/redirectURI.d.ts +7 -0
  17. package/dist/libs/redirectURI.js +78 -0
  18. package/dist/libs/redirectURI.js.map +1 -0
  19. package/dist/libs/schemas.d.ts +23 -0
  20. package/dist/libs/schemas.js +25 -0
  21. package/dist/libs/schemas.js.map +1 -0
  22. package/dist/libs/scopes.d.ts +16 -0
  23. package/dist/libs/scopes.js +37 -0
  24. package/dist/libs/scopes.js.map +1 -1
  25. package/dist/libs/utils.d.ts +2 -0
  26. package/dist/libs/utils.js +17 -0
  27. package/dist/libs/utils.js.map +1 -0
  28. package/dist/libs/verifier.d.ts +7 -0
  29. package/dist/libs/verifier.js +37 -0
  30. package/dist/libs/verifier.js.map +1 -0
  31. package/dist/libs/verifier.test.js +21 -0
  32. package/dist/libs/verifier.test.js.map +1 -0
  33. package/dist/routes/getOAuth2Authorize.d.ts +13 -50
  34. package/dist/routes/getOAuth2Authorize.js +60 -86
  35. package/dist/routes/getOAuth2Authorize.js.map +1 -1
  36. package/dist/routes/getOAuth2Authorize.test.js +147 -68
  37. package/dist/routes/getOAuth2Authorize.test.js.map +1 -1
  38. package/dist/routes/getOAuth2WellKnownMetadata.d.ts +8 -8
  39. package/dist/routes/getOAuth2WellKnownMetadata.js +20 -9
  40. package/dist/routes/getOAuth2WellKnownMetadata.js.map +1 -1
  41. package/dist/routes/getOAuth2WellKnownMetadata.test.js +38 -37
  42. package/dist/routes/getOAuth2WellKnownMetadata.test.js.map +1 -1
  43. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.d.ts +3 -6
  44. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.js +3 -6
  45. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.js.map +1 -1
  46. package/dist/routes/postAuthLogin.d.ts +14 -9
  47. package/dist/routes/postAuthLogin.js +10 -5
  48. package/dist/routes/postAuthLogin.js.map +1 -1
  49. package/dist/routes/postAuthLogin.test.js +79 -55
  50. package/dist/routes/postAuthLogin.test.js.map +1 -1
  51. package/dist/routes/postAuthLogout.d.ts +5 -2
  52. package/dist/routes/postAuthLogout.js +12 -7
  53. package/dist/routes/postAuthLogout.js.map +1 -1
  54. package/dist/routes/postAuthLogout.test.js +35 -17
  55. package/dist/routes/postAuthLogout.test.js.map +1 -1
  56. package/dist/routes/postAuthRefresh.d.ts +14 -9
  57. package/dist/routes/postAuthRefresh.js +10 -6
  58. package/dist/routes/postAuthRefresh.js.map +1 -1
  59. package/dist/routes/postAuthRefresh.test.js +90 -59
  60. package/dist/routes/postAuthRefresh.test.js.map +1 -1
  61. package/dist/routes/postOAuth2Acknowledge.d.ts +20 -10
  62. package/dist/routes/postOAuth2Acknowledge.js +54 -38
  63. package/dist/routes/postOAuth2Acknowledge.js.map +1 -1
  64. package/dist/routes/postOAuth2Acknowledge.test.js +137 -72
  65. package/dist/routes/postOAuth2Acknowledge.test.js.map +1 -1
  66. package/dist/routes/postOAuth2Revoke.d.ts +99 -0
  67. package/dist/routes/postOAuth2Revoke.js +102 -0
  68. package/dist/routes/postOAuth2Revoke.js.map +1 -0
  69. package/dist/routes/postOAuth2Revoke.test.d.ts +1 -0
  70. package/dist/routes/postOAuth2Revoke.test.js +161 -0
  71. package/dist/routes/postOAuth2Revoke.test.js.map +1 -0
  72. package/dist/routes/postOAuth2Token.d.ts +35 -108
  73. package/dist/routes/postOAuth2Token.js +53 -114
  74. package/dist/routes/postOAuth2Token.js.map +1 -1
  75. package/dist/routes/postOAuth2Token.test.js +493 -61
  76. package/dist/routes/postOAuth2Token.test.js.map +1 -1
  77. package/dist/services/authCookies.d.ts +9 -13
  78. package/dist/services/authCookies.js +1 -1
  79. package/dist/services/authCookies.js.map +1 -1
  80. package/dist/services/authCookies.test.js.map +1 -1
  81. package/dist/services/oAuth2AuthorizationCodeGranter.d.ts +129 -0
  82. package/dist/services/oAuth2AuthorizationCodeGranter.js +221 -0
  83. package/dist/services/oAuth2AuthorizationCodeGranter.js.map +1 -0
  84. package/dist/services/oAuth2AuthorizationCodeGranter.test.d.ts +1 -0
  85. package/dist/services/oAuth2AuthorizationCodeGranter.test.js +474 -0
  86. package/dist/services/oAuth2AuthorizationCodeGranter.test.js.map +1 -0
  87. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +28 -12
  88. package/dist/services/oAuth2ClientCredentialsGranter.js +39 -21
  89. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -1
  90. package/dist/services/oAuth2ClientCredentialsGranter.test.d.ts +1 -0
  91. package/dist/services/oAuth2ClientCredentialsGranter.test.js +265 -0
  92. package/dist/services/oAuth2ClientCredentialsGranter.test.js.map +1 -0
  93. package/dist/services/oAuth2Granters.d.ts +81 -86
  94. package/dist/services/oAuth2Granters.js +2 -67
  95. package/dist/services/oAuth2Granters.js.map +1 -1
  96. package/dist/services/oAuth2ImplicitGranter.d.ts +38 -0
  97. package/dist/services/oAuth2ImplicitGranter.js +72 -0
  98. package/dist/services/oAuth2ImplicitGranter.js.map +1 -0
  99. package/dist/services/oAuth2ImplicitGranter.test.d.ts +1 -0
  100. package/dist/services/oAuth2ImplicitGranter.test.js +727 -0
  101. package/dist/services/oAuth2ImplicitGranter.test.js.map +1 -0
  102. package/dist/services/oAuth2PasswordGranter.d.ts +43 -10
  103. package/dist/services/oAuth2PasswordGranter.js +53 -18
  104. package/dist/services/oAuth2PasswordGranter.js.map +1 -1
  105. package/dist/services/oAuth2PasswordGranter.test.d.ts +1 -0
  106. package/dist/services/oAuth2PasswordGranter.test.js +455 -0
  107. package/dist/services/oAuth2PasswordGranter.test.js.map +1 -0
  108. package/dist/services/oAuth2RefreshTokenGranter.d.ts +42 -9
  109. package/dist/services/oAuth2RefreshTokenGranter.js +60 -21
  110. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -1
  111. package/dist/services/oAuth2RefreshTokenGranter.test.d.ts +1 -0
  112. package/dist/services/oAuth2RefreshTokenGranter.test.js +403 -0
  113. package/dist/services/oAuth2RefreshTokenGranter.test.js.map +1 -0
  114. package/package.json +11 -11
  115. package/src/index.test.ts +1314 -404
  116. package/src/index.ts +46 -53
  117. package/src/libs/clients.ts +22 -0
  118. package/src/libs/errors.ts +325 -0
  119. package/src/libs/grants.ts +15 -0
  120. package/src/libs/redirectURI.ts +120 -0
  121. package/src/libs/schemas.ts +27 -0
  122. package/src/libs/scopes.ts +49 -0
  123. package/src/libs/utils.ts +24 -0
  124. package/src/libs/verifier.test.ts +37 -0
  125. package/src/libs/verifier.ts +57 -0
  126. package/src/routes/getOAuth2Authorize.test.ts +179 -96
  127. package/src/routes/getOAuth2Authorize.ts +97 -124
  128. package/src/routes/getOAuth2WellKnownMetadata.test.ts +58 -60
  129. package/src/routes/getOAuth2WellKnownMetadata.ts +26 -11
  130. package/src/routes/getOAuth2WellKnownProtectedResourceMetadata.ts +4 -6
  131. package/src/routes/postAuthLogin.test.ts +86 -57
  132. package/src/routes/postAuthLogin.ts +24 -14
  133. package/src/routes/postAuthLogout.test.ts +42 -18
  134. package/src/routes/postAuthLogout.ts +22 -8
  135. package/src/routes/postAuthRefresh.test.ts +98 -61
  136. package/src/routes/postAuthRefresh.ts +25 -13
  137. package/src/routes/postOAuth2Acknowledge.test.ts +169 -110
  138. package/src/routes/postOAuth2Acknowledge.ts +101 -61
  139. package/src/routes/postOAuth2Revoke.test.ts +179 -0
  140. package/src/routes/postOAuth2Revoke.ts +156 -0
  141. package/src/routes/postOAuth2Token.test.ts +570 -108
  142. package/src/routes/postOAuth2Token.ts +92 -136
  143. package/src/services/authCookies.test.ts +5 -5
  144. package/src/services/authCookies.ts +16 -18
  145. package/src/services/oAuth2AuthorizationCodeGranter.test.ts +564 -0
  146. package/src/services/oAuth2AuthorizationCodeGranter.ts +388 -0
  147. package/src/services/oAuth2ClientCredentialsGranter.test.ts +303 -0
  148. package/src/services/oAuth2ClientCredentialsGranter.ts +68 -43
  149. package/src/services/oAuth2Granters.ts +101 -195
  150. package/src/services/oAuth2ImplicitGranter.test.ts +811 -0
  151. package/src/services/oAuth2ImplicitGranter.ts +163 -0
  152. package/src/services/oAuth2PasswordGranter.test.ts +493 -0
  153. package/src/services/oAuth2PasswordGranter.ts +116 -40
  154. package/src/services/oAuth2RefreshTokenGranter.test.ts +441 -0
  155. package/src/services/oAuth2RefreshTokenGranter.ts +118 -51
  156. package/src/types.d.ts +1 -0
  157. package/dist/services/oAuth2CodeGranter.d.ts +0 -41
  158. package/dist/services/oAuth2CodeGranter.js +0 -105
  159. package/dist/services/oAuth2CodeGranter.js.map +0 -1
  160. package/dist/services/oAuth2CodeGranter.test.js +0 -123
  161. package/dist/services/oAuth2CodeGranter.test.js.map +0 -1
  162. package/dist/services/oAuth2TokenGranter.d.ts +0 -22
  163. package/dist/services/oAuth2TokenGranter.js +0 -64
  164. package/dist/services/oAuth2TokenGranter.js.map +0 -1
  165. package/src/__snapshots__/index.test.ts.snap +0 -401
  166. package/src/routes/__snapshots__/getOAuth2Authorize.test.ts.snap +0 -37
  167. package/src/routes/__snapshots__/postOAuth2Acknowledge.test.ts.snap +0 -61
  168. package/src/routes/__snapshots__/postOAuth2Token.test.ts.snap +0 -52
  169. package/src/services/__snapshots__/oAuth2CodeGranter.test.ts.snap +0 -52
  170. package/src/services/oAuth2CodeGranter.test.ts +0 -176
  171. package/src/services/oAuth2CodeGranter.ts +0 -210
  172. package/src/services/oAuth2TokenGranter.ts +0 -119
  173. /package/dist/{services/oAuth2CodeGranter.test.d.ts → libs/verifier.test.d.ts} +0 -0
@@ -0,0 +1,388 @@
1
+ import { autoService, location } from 'knifecycle';
2
+ import {
3
+ noop,
4
+ refersTo,
5
+ type WhookAPIParameterDefinition,
6
+ type WhookAPISchemaDefinition,
7
+ } from '@whook/whook';
8
+ import { YError } from 'yerror';
9
+ import { type LogService } from 'common-services';
10
+ import {
11
+ type WhookOAuth2GranterService,
12
+ type WhookOAuth2ReadClientGrantsService,
13
+ type WhookOAuth2Options,
14
+ type WhookOAuth2GranterDefinitions,
15
+ type WhookOAuth2ClientId,
16
+ } from './oAuth2Granters.js';
17
+ import {
18
+ type WhookAuthenticationScope,
19
+ type WhookAuthenticationData,
20
+ } from '@whook/authorization';
21
+ import { checkGrantType } from '../libs/grants.js';
22
+ import { filterScopes } from '../libs/scopes.js';
23
+ import { checkRedirectURI } from '../libs/redirectURI.js';
24
+ import {
25
+ checkCodeChallenge,
26
+ CODE_CHALLENGE_METHODS,
27
+ PLAIN_CODE_CHALLENGE_METHOD,
28
+ type CodeChallengeMethod,
29
+ } from '../libs/verifier.js';
30
+ import { toUsableClientId } from '../libs/clients.js';
31
+
32
+ export const AUTHORIZATION_CODE_GRANT_TYPE = 'authorization_code';
33
+ export const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code';
34
+
35
+ export const codeVerifierSchema = {
36
+ name: 'CodeVerifier',
37
+ schema: {
38
+ type: 'string',
39
+ minLength: 43,
40
+ maxLength: 128,
41
+ pattern: '^[A-Za-z0-9._~-]+$',
42
+ },
43
+ } as const satisfies WhookAPISchemaDefinition;
44
+
45
+ export const authorizationCodeTokenRequestBodySchema = {
46
+ name: 'AuthorizationCodeRequestBody',
47
+ schema: {
48
+ description:
49
+ 'Implements the [Token Endpoint](https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-15.html#section-3.2) as defined per the OAuth2.1 RFC.',
50
+ type: 'object',
51
+ required: ['grant_type', 'code'],
52
+ properties: {
53
+ grant_type: {
54
+ type: 'string',
55
+ const: AUTHORIZATION_CODE_GRANT_TYPE,
56
+ },
57
+ code: {
58
+ type: 'string',
59
+ },
60
+ client_id: {
61
+ type: 'string',
62
+ },
63
+ redirect_uri: {
64
+ type: 'string',
65
+ pattern: '^https?://',
66
+ format: 'uri',
67
+ },
68
+ code_verifier: refersTo(codeVerifierSchema),
69
+ },
70
+ },
71
+ } as const satisfies WhookAPISchemaDefinition;
72
+
73
+ export const codeChallengeSchema = {
74
+ name: 'CodeChallenge',
75
+ schema: {
76
+ type: 'string',
77
+ minLength: 43,
78
+ maxLength: 128,
79
+ pattern: '^[A-Za-z0-9\\-._~]{43,128}$',
80
+ },
81
+ } as const satisfies WhookAPISchemaDefinition;
82
+ export const codeChallengeParameter = {
83
+ name: 'code_challenge',
84
+ parameter: {
85
+ in: 'query',
86
+ name: 'code_challenge',
87
+ required: false,
88
+ schema: refersTo(codeChallengeSchema),
89
+ },
90
+ } as const satisfies WhookAPIParameterDefinition;
91
+ export const codeChallengeMethodSchema = {
92
+ name: 'CodeChallengeMethod',
93
+ schema: {
94
+ type: 'string',
95
+ enum: CODE_CHALLENGE_METHODS.concat(),
96
+ },
97
+ } as const satisfies WhookAPISchemaDefinition;
98
+ export const codeChallengeMethodParameter = {
99
+ name: 'code_challenge_method',
100
+ parameter: {
101
+ in: 'query',
102
+ name: 'code_challenge_method',
103
+ required: false,
104
+ schema: refersTo(codeChallengeMethodSchema),
105
+ },
106
+ } as const satisfies WhookAPIParameterDefinition;
107
+
108
+ /**
109
+ * Utility code for providing your own code type
110
+ */
111
+ export type WhookOAuth2AuthorizationCode = string;
112
+ /**
113
+ * Context passed to the code creation function to
114
+ * be stored and provided as is in the code check one
115
+ */
116
+ export interface WhookOAuth2AuthorizationCodeContext {
117
+ readonly demandedRedirectURI: string;
118
+ readonly demandedScopes: WhookAuthenticationScope[];
119
+ readonly filteredScopes: WhookAuthenticationScope[];
120
+ readonly codeChallenge?: string | undefined;
121
+ readonly codeChallengeMethod?: CodeChallengeMethod | undefined;
122
+ }
123
+
124
+ export interface WhookOAuth2AuthorizationCodeService {
125
+ create: (
126
+ userAuthenticationData: WhookAuthenticationData,
127
+ context: WhookOAuth2AuthorizationCodeContext,
128
+ ) => Promise<WhookOAuth2AuthorizationCode>;
129
+ check: (
130
+ clientAuthenticationData: WhookAuthenticationData,
131
+ code: WhookOAuth2AuthorizationCode,
132
+ ) => Promise<{
133
+ codeAuthenticationData: WhookAuthenticationData;
134
+ context: WhookOAuth2AuthorizationCodeContext;
135
+ }>;
136
+ }
137
+
138
+ export interface WhookOAuth2AuthorizationCodeGranterDependencies {
139
+ OAUTH2: WhookOAuth2Options;
140
+ oAuth2AuthorizationCode: WhookOAuth2AuthorizationCodeService;
141
+ readClientGrants: WhookOAuth2ReadClientGrantsService;
142
+ log?: LogService;
143
+ }
144
+
145
+ export interface WhookOAuth2AuthorizationCodeGranterDefinitions extends WhookOAuth2GranterDefinitions {
146
+ grantType: typeof AUTHORIZATION_CODE_GRANT_TYPE;
147
+ responseType: typeof AUTHORIZATION_CODE_RESPONSE_TYPE;
148
+ authorizeParameters: {
149
+ codeChallenge: string;
150
+ codeChallengeMethod: CodeChallengeMethod;
151
+ };
152
+ acknowledgeParameters: {
153
+ codeChallenge: string;
154
+ codeChallengeMethod: CodeChallengeMethod;
155
+ };
156
+ acknowledgedData: {
157
+ code: WhookOAuth2AuthorizationCode;
158
+ codeChallenge?: string;
159
+ codeChallengeMethod?: CodeChallengeMethod;
160
+ };
161
+ authenticateParameters: {
162
+ code: WhookOAuth2AuthorizationCode;
163
+ redirectURI?: string;
164
+ clientId?: WhookOAuth2ClientId;
165
+ codeVerifier?: string;
166
+ };
167
+ }
168
+
169
+ export type WhookOAuth2AuthorizationCodeGranterService =
170
+ WhookOAuth2GranterService<WhookOAuth2AuthorizationCodeGranterDefinitions>;
171
+
172
+ // Authorization Code Grant
173
+ // https://tools.ietf.org/html/rfc6749#section-4.1
174
+ async function initOAuth2AuthorizationCodeGranter({
175
+ OAUTH2,
176
+ oAuth2AuthorizationCode,
177
+ readClientGrants,
178
+ log = noop,
179
+ }: WhookOAuth2AuthorizationCodeGranterDependencies): Promise<WhookOAuth2AuthorizationCodeGranterService> {
180
+ const authorizeWithCode: NonNullable<
181
+ WhookOAuth2AuthorizationCodeGranterService['authorize']
182
+ > = async ({ clientId, demandedRedirectURI, demandedScopes }) => {
183
+ const grants = await readClientGrants(clientId);
184
+
185
+ if (clientId !== grants.authenticationData.clientId) {
186
+ throw new YError('E_OAUTH2_CLIENT_GRANTS_MISMATCH', [
187
+ clientId,
188
+ grants.authenticationData.clientId,
189
+ ]);
190
+ }
191
+
192
+ checkGrantType(grants.allowedGrantTypes, AUTHORIZATION_CODE_GRANT_TYPE);
193
+
194
+ const filteredScopes = filterScopes(
195
+ demandedScopes,
196
+ grants.allowedScopes,
197
+ !!OAUTH2.strictScopesChecks,
198
+ );
199
+
200
+ if (demandedRedirectURI) {
201
+ checkRedirectURI(grants.allowedRedirectURIS, demandedRedirectURI);
202
+ } else {
203
+ demandedRedirectURI = grants.allowedRedirectURIS[0];
204
+ }
205
+
206
+ return {
207
+ clientId,
208
+ redirectURI: demandedRedirectURI,
209
+ scopes: filteredScopes,
210
+ };
211
+ };
212
+
213
+ // Authorization Code Response:
214
+ // https://tools.ietf.org/html/rfc6749#section-4.1.2
215
+ const acknowledgeWithCode: NonNullable<
216
+ WhookOAuth2AuthorizationCodeGranterService['acknowledge']
217
+ > = async (
218
+ userAuthenticationData,
219
+ { clientId, demandedRedirectURI, demandedScopes },
220
+ { codeChallenge, codeChallengeMethod },
221
+ ) => {
222
+ const grants = await readClientGrants(clientId);
223
+
224
+ if (grants.isPublicClient) {
225
+ if (!codeChallenge) {
226
+ throw new YError('E_OAUTH2_AUTHORIZATION_CODE_CHALLENGE_REQUIRED');
227
+ }
228
+ }
229
+ if (!userAuthenticationData) {
230
+ throw new YError('E_UNAUTHORIZED');
231
+ }
232
+
233
+ checkGrantType(grants.allowedGrantTypes, AUTHORIZATION_CODE_GRANT_TYPE);
234
+ checkRedirectURI(grants.allowedRedirectURIS, demandedRedirectURI);
235
+
236
+ const filteredScopes = filterScopes(
237
+ demandedScopes,
238
+ grants.allowedScopes,
239
+ !!OAUTH2.strictScopesChecks,
240
+ );
241
+
242
+ const code = await oAuth2AuthorizationCode.create(
243
+ {
244
+ ...userAuthenticationData,
245
+ clientId,
246
+ scopes: filteredScopes,
247
+ },
248
+ {
249
+ demandedRedirectURI,
250
+ demandedScopes,
251
+ filteredScopes,
252
+ ...(codeChallenge
253
+ ? {
254
+ codeChallenge,
255
+ codeChallengeMethod:
256
+ codeChallengeMethod || PLAIN_CODE_CHALLENGE_METHOD,
257
+ }
258
+ : {}),
259
+ },
260
+ );
261
+
262
+ return {
263
+ acknowledgedAuthenticationData: {
264
+ ...userAuthenticationData,
265
+ clientId,
266
+ scopes: filteredScopes,
267
+ },
268
+ acknowledgedScopes: filteredScopes,
269
+ acknowledgedRedirectURI: demandedRedirectURI,
270
+ acknowledgedData: {
271
+ code,
272
+ ...(codeChallenge
273
+ ? {
274
+ codeChallenge,
275
+ codeChallengeMethod,
276
+ }
277
+ : {}),
278
+ },
279
+ };
280
+ };
281
+
282
+ const authenticateWithCode: NonNullable<
283
+ WhookOAuth2AuthorizationCodeGranterService['authenticate']
284
+ > = async (
285
+ { code, clientId, redirectURI, codeVerifier },
286
+ optionalAuthenticationData,
287
+ ) => {
288
+ const usableClientId = toUsableClientId([
289
+ optionalAuthenticationData?.clientId,
290
+ clientId,
291
+ ]);
292
+ const grants = await readClientGrants(usableClientId);
293
+
294
+ if (usableClientId !== grants.authenticationData.clientId) {
295
+ throw new YError('E_OAUTH2_CLIENT_GRANTS_MISMATCH', [
296
+ usableClientId,
297
+ grants.authenticationData.clientId,
298
+ ]);
299
+ }
300
+
301
+ if (!grants.isPublicClient) {
302
+ if (!optionalAuthenticationData) {
303
+ throw new YError('E_OAUTH2_AUTHENTICATION_REQUIRED', [
304
+ grants.authenticationData.clientId,
305
+ ]);
306
+ }
307
+ }
308
+
309
+ if (grants.isPublicClient) {
310
+ if (!codeVerifier) {
311
+ throw new YError('E_OAUTH2_AUTHORIZATION_CODE_VERIFIER_REQUIRED');
312
+ }
313
+ }
314
+
315
+ checkGrantType(grants.allowedGrantTypes, AUTHORIZATION_CODE_GRANT_TYPE);
316
+
317
+ const { codeAuthenticationData, context } =
318
+ await oAuth2AuthorizationCode.check(
319
+ optionalAuthenticationData || grants.authenticationData,
320
+ code,
321
+ );
322
+
323
+ if (redirectURI && redirectURI !== context.demandedRedirectURI) {
324
+ throw new YError('E_OAUTH2_BAD_REDIRECT_URI', [
325
+ redirectURI,
326
+ [context.demandedRedirectURI],
327
+ ]);
328
+ }
329
+
330
+ if (usableClientId !== codeAuthenticationData.clientId) {
331
+ throw new YError('E_OAUTH2_CLIENT_MISMATCH', [
332
+ usableClientId,
333
+ codeAuthenticationData.clientId,
334
+ ]);
335
+ }
336
+
337
+ if (codeVerifier) {
338
+ if (!context.codeChallenge || !context.codeChallengeMethod) {
339
+ throw new YError(
340
+ 'E_OAUTH2_BAD_AUTHORIZATION_CODE_VERIFIER_CONTEXT',
341
+ [],
342
+ );
343
+ }
344
+
345
+ checkCodeChallenge(
346
+ context.codeChallengeMethod,
347
+ context.codeChallenge,
348
+ codeVerifier,
349
+ );
350
+ } else if (context.codeChallenge || context.codeChallengeMethod) {
351
+ throw new YError('E_OAUTH2_AUTHORIZATION_CODE_VERIFIER_EXPECTED', [
352
+ context.codeChallenge,
353
+ context.codeChallengeMethod,
354
+ ]);
355
+ }
356
+
357
+ const filteredScopes = filterScopes(
358
+ filterScopes(
359
+ context.filteredScopes,
360
+ codeAuthenticationData.scopes,
361
+ !!OAUTH2.strictScopesChecks,
362
+ ),
363
+ grants.allowedScopes,
364
+ !!OAUTH2.strictScopesChecks,
365
+ );
366
+
367
+ return {
368
+ ...codeAuthenticationData,
369
+ scopes: filteredScopes,
370
+ };
371
+ };
372
+
373
+ log('debug', '👫 - OAuth2AuthorizationCodeGranter Service Initialized!');
374
+
375
+ return {
376
+ grantType: AUTHORIZATION_CODE_GRANT_TYPE,
377
+ responseType: AUTHORIZATION_CODE_RESPONSE_TYPE,
378
+ issuesRefreshToken: true,
379
+ authorize: authorizeWithCode,
380
+ acknowledge: acknowledgeWithCode,
381
+ authenticate: authenticateWithCode,
382
+ };
383
+ }
384
+
385
+ export default location(
386
+ autoService(initOAuth2AuthorizationCodeGranter),
387
+ import.meta.url,
388
+ );
@@ -0,0 +1,303 @@
1
+ import { describe, test, beforeEach, jest, expect } from '@jest/globals';
2
+ import {
3
+ type WhookOAuth2Options,
4
+ type WhookOAuth2ReadClientGrantsService,
5
+ } from './oAuth2Granters.js';
6
+ import initOAuth2ClientCredentialsGranter from './oAuth2ClientCredentialsGranter.js';
7
+ import { YError } from 'yerror';
8
+
9
+ describe('OAuth2ClientCredentialsGranter', () => {
10
+ const OAUTH2: WhookOAuth2Options = {
11
+ rootClientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
12
+ authenticateURL: 'https://auth.example.com/sign_in',
13
+ allowedScopes: ['user', 'admin', 'root'],
14
+ };
15
+ const readClientGrants = jest.fn<WhookOAuth2ReadClientGrantsService>();
16
+ const log = jest.fn();
17
+
18
+ beforeEach(() => {
19
+ readClientGrants.mockReset();
20
+ log.mockReset();
21
+ });
22
+
23
+ test('should work with a complete valid flow', async () => {
24
+ const oAuth2ClientCredentialsGranter =
25
+ await initOAuth2ClientCredentialsGranter({
26
+ OAUTH2,
27
+ readClientGrants,
28
+ log,
29
+ });
30
+
31
+ readClientGrants.mockResolvedValue({
32
+ allowedRedirectURIS: ['https://www.example.com'],
33
+ allowedGrantTypes: ['client_credentials', 'authorization_code'],
34
+ allowedScopes: ['user', 'admin'],
35
+ authenticationData: {
36
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
37
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
38
+ scopes: [],
39
+ },
40
+ isPublicClient: false,
41
+ });
42
+
43
+ const authenticatorResult =
44
+ await oAuth2ClientCredentialsGranter.authenticate?.(
45
+ {
46
+ demandedScopes: ['user', 'root'],
47
+ },
48
+ {
49
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
50
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
51
+ scopes: ['user'],
52
+ },
53
+ );
54
+
55
+ expect({
56
+ authenticatorResult,
57
+ readClientGrantsCalls: readClientGrants.mock.calls,
58
+ logCalls: log.mock.calls,
59
+ }).toMatchInlineSnapshot(`
60
+ {
61
+ "authenticatorResult": {
62
+ "clientId": "abbacaca-abba-caca-abba-cacaabbacaca",
63
+ "scopes": [
64
+ "user",
65
+ ],
66
+ "userId": "abbacaca-abba-caca-abba-cacaabbab0b0",
67
+ },
68
+ "logCalls": [
69
+ [
70
+ "debug",
71
+ "👫 - OAuth2ClientCredentialsGranter Service Initialized!",
72
+ ],
73
+ ],
74
+ "readClientGrantsCalls": [
75
+ [
76
+ "abbacaca-abba-caca-abba-cacaabbacaca",
77
+ ],
78
+ ],
79
+ }
80
+ `);
81
+ });
82
+
83
+ test('should work with a complete valid flow and filter scopes', async () => {
84
+ const oAuth2ClientCredentialsGranter =
85
+ await initOAuth2ClientCredentialsGranter({
86
+ OAUTH2,
87
+ readClientGrants,
88
+ log,
89
+ });
90
+
91
+ readClientGrants.mockResolvedValue({
92
+ allowedRedirectURIS: ['https://www.example.com'],
93
+ allowedGrantTypes: ['client_credentials', 'authorization_code'],
94
+ allowedScopes: ['user', 'admin'],
95
+ authenticationData: {
96
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
97
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
98
+ scopes: [],
99
+ },
100
+ isPublicClient: false,
101
+ });
102
+
103
+ const authenticatorResult =
104
+ await oAuth2ClientCredentialsGranter.authenticate?.(
105
+ {
106
+ demandedScopes: ['user', 'admin', 'oauth2', 'a_scope'],
107
+ },
108
+ {
109
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
110
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
111
+ scopes: ['user'],
112
+ },
113
+ );
114
+
115
+ expect({
116
+ authenticatorResult,
117
+ readClientGrantsCalls: readClientGrants.mock.calls,
118
+ logCalls: log.mock.calls,
119
+ }).toMatchInlineSnapshot(`
120
+ {
121
+ "authenticatorResult": {
122
+ "clientId": "abbacaca-abba-caca-abba-cacaabbacaca",
123
+ "scopes": [
124
+ "user",
125
+ "admin",
126
+ ],
127
+ "userId": "abbacaca-abba-caca-abba-cacaabbab0b0",
128
+ },
129
+ "logCalls": [
130
+ [
131
+ "debug",
132
+ "👫 - OAuth2ClientCredentialsGranter Service Initialized!",
133
+ ],
134
+ ],
135
+ "readClientGrantsCalls": [
136
+ [
137
+ "abbacaca-abba-caca-abba-cacaabbacaca",
138
+ ],
139
+ ],
140
+ }
141
+ `);
142
+ });
143
+
144
+ test('should fail with no authentication', async () => {
145
+ const oAuth2ClientCredentialsGranter =
146
+ await initOAuth2ClientCredentialsGranter({
147
+ OAUTH2,
148
+ readClientGrants,
149
+ log,
150
+ });
151
+
152
+ readClientGrants.mockResolvedValue({
153
+ allowedRedirectURIS: ['https://www.example.com'],
154
+ allowedGrantTypes: ['client_credentials', 'authorization_code'],
155
+ allowedScopes: ['user', 'admin'],
156
+ authenticationData: {
157
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
158
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
159
+ scopes: [],
160
+ },
161
+ isPublicClient: false,
162
+ });
163
+
164
+ try {
165
+ await oAuth2ClientCredentialsGranter.authenticate?.({
166
+ demandedScopes: ['user'],
167
+ });
168
+ throw new YError('E_UNEXPECTED_SUCCESS');
169
+ } catch (err) {
170
+ expect({
171
+ err,
172
+ readClientGrantsCalls: readClientGrants.mock.calls,
173
+ logCalls: log.mock.calls,
174
+ }).toMatchInlineSnapshot(`
175
+ {
176
+ "err": [YError: E_UNAUTHORIZED ([]): E_UNAUTHORIZED],
177
+ "logCalls": [
178
+ [
179
+ "debug",
180
+ "👫 - OAuth2ClientCredentialsGranter Service Initialized!",
181
+ ],
182
+ ],
183
+ "readClientGrantsCalls": [],
184
+ }
185
+ `);
186
+ }
187
+ });
188
+
189
+ test('should fail with a client with not client_credentials grant', async () => {
190
+ const oAuth2ClientCredentialsGranter =
191
+ await initOAuth2ClientCredentialsGranter({
192
+ OAUTH2,
193
+ readClientGrants,
194
+ log,
195
+ });
196
+
197
+ readClientGrants.mockResolvedValue({
198
+ allowedRedirectURIS: ['https://www.example.com'],
199
+ allowedGrantTypes: ['authorization_code'],
200
+ allowedScopes: ['user', 'admin'],
201
+ authenticationData: {
202
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
203
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
204
+ scopes: [],
205
+ },
206
+ isPublicClient: false,
207
+ });
208
+
209
+ try {
210
+ await oAuth2ClientCredentialsGranter.authenticate?.(
211
+ {
212
+ demandedScopes: ['user'],
213
+ },
214
+ {
215
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
216
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
217
+ scopes: ['user'],
218
+ },
219
+ );
220
+ throw new YError('E_UNEXPECTED_SUCCESS');
221
+ } catch (err) {
222
+ expect({
223
+ err,
224
+ readClientGrantsCalls: readClientGrants.mock.calls,
225
+ logCalls: log.mock.calls,
226
+ }).toMatchInlineSnapshot(`
227
+ {
228
+ "err": [YError: E_OAUTH2_GRANT_TYPE_NOT_ALLOWED (["client_credentials",["authorization_code"]]): E_OAUTH2_GRANT_TYPE_NOT_ALLOWED],
229
+ "logCalls": [
230
+ [
231
+ "debug",
232
+ "👫 - OAuth2ClientCredentialsGranter Service Initialized!",
233
+ ],
234
+ ],
235
+ "readClientGrantsCalls": [
236
+ [
237
+ "abbacaca-abba-caca-abba-cacaabbacaca",
238
+ ],
239
+ ],
240
+ }
241
+ `);
242
+ }
243
+ });
244
+
245
+ test('should fail with a client with a bad scope for the client', async () => {
246
+ const oAuth2ClientCredentialsGranter =
247
+ await initOAuth2ClientCredentialsGranter({
248
+ OAUTH2: {
249
+ ...OAUTH2,
250
+ strictScopesChecks: true,
251
+ },
252
+ readClientGrants,
253
+ log,
254
+ });
255
+
256
+ readClientGrants.mockResolvedValue({
257
+ allowedRedirectURIS: ['https://www.example.com'],
258
+ allowedGrantTypes: ['client_credentials'],
259
+ allowedScopes: ['user'],
260
+ authenticationData: {
261
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
262
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
263
+ scopes: [],
264
+ },
265
+ isPublicClient: false,
266
+ });
267
+
268
+ try {
269
+ await oAuth2ClientCredentialsGranter.authenticate?.(
270
+ {
271
+ demandedScopes: ['user', 'admin'],
272
+ },
273
+ {
274
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
275
+ userId: 'abbacaca-abba-caca-abba-cacaabbab0b0',
276
+ scopes: ['user'],
277
+ },
278
+ );
279
+ throw new YError('E_UNEXPECTED_SUCCESS');
280
+ } catch (err) {
281
+ expect({
282
+ err,
283
+ readClientGrantsCalls: readClientGrants.mock.calls,
284
+ logCalls: log.mock.calls,
285
+ }).toMatchInlineSnapshot(`
286
+ {
287
+ "err": [YError: E_OAUTH2_BAD_SCOPE (["admin"]): E_OAUTH2_BAD_SCOPE],
288
+ "logCalls": [
289
+ [
290
+ "debug",
291
+ "👫 - OAuth2ClientCredentialsGranter Service Initialized!",
292
+ ],
293
+ ],
294
+ "readClientGrantsCalls": [
295
+ [
296
+ "abbacaca-abba-caca-abba-cacaabbacaca",
297
+ ],
298
+ ],
299
+ }
300
+ `);
301
+ }
302
+ });
303
+ });