@whook/oauth2 25.2.1 → 26.0.2

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