@whook/oauth2 27.0.2 → 27.1.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 (121) hide show
  1. package/README.md +44 -25
  2. package/dist/index.d.ts +11 -7
  3. package/dist/index.js +9 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.test.js +131 -15
  6. package/dist/index.test.js.map +1 -1
  7. package/dist/libs/clients.d.ts +17 -1
  8. package/dist/libs/clients.js +39 -6
  9. package/dist/libs/clients.js.map +1 -1
  10. package/dist/libs/clients.test.d.ts +1 -0
  11. package/dist/libs/clients.test.js +32 -0
  12. package/dist/libs/clients.test.js.map +1 -0
  13. package/dist/libs/errors.d.ts +24 -0
  14. package/dist/libs/errors.js +42 -0
  15. package/dist/libs/errors.js.map +1 -1
  16. package/dist/libs/verifier.d.ts +3 -3
  17. package/dist/libs/verifier.js +4 -3
  18. package/dist/libs/verifier.js.map +1 -1
  19. package/dist/routes/getOAuth2Authorize.d.ts +19 -6
  20. package/dist/routes/getOAuth2Authorize.js +29 -14
  21. package/dist/routes/getOAuth2Authorize.js.map +1 -1
  22. package/dist/routes/getOAuth2WellKnownMetadata.d.ts +3 -4
  23. package/dist/routes/getOAuth2WellKnownMetadata.js +19 -7
  24. package/dist/routes/getOAuth2WellKnownMetadata.js.map +1 -1
  25. package/dist/routes/getOAuth2WellKnownMetadata.test.js +81 -0
  26. package/dist/routes/getOAuth2WellKnownMetadata.test.js.map +1 -1
  27. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.d.ts +0 -2
  28. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.js +1 -2
  29. package/dist/routes/getOAuth2WellKnownProtectedResourceMetadata.js.map +1 -1
  30. package/dist/routes/postAuthLogin.d.ts +1 -1
  31. package/dist/routes/postAuthLogin.js +1 -1
  32. package/dist/routes/postAuthLogin.js.map +1 -1
  33. package/dist/routes/postAuthRefresh.d.ts +1 -1
  34. package/dist/routes/postAuthRefresh.js +1 -1
  35. package/dist/routes/postAuthRefresh.js.map +1 -1
  36. package/dist/routes/postOAuth2Acknowledge.d.ts +0 -3
  37. package/dist/routes/postOAuth2Acknowledge.js +1 -3
  38. package/dist/routes/postOAuth2Acknowledge.js.map +1 -1
  39. package/dist/routes/postOAuth2DeviceAcknowledge.d.ts +64 -0
  40. package/dist/routes/postOAuth2DeviceAcknowledge.js +84 -0
  41. package/dist/routes/postOAuth2DeviceAcknowledge.js.map +1 -0
  42. package/dist/routes/postOAuth2DeviceAcknowledge.test.d.ts +1 -0
  43. package/dist/routes/postOAuth2DeviceAcknowledge.test.js +369 -0
  44. package/dist/routes/postOAuth2DeviceAcknowledge.test.js.map +1 -0
  45. package/dist/routes/postOAuth2DeviceAuthorization.d.ts +133 -0
  46. package/dist/routes/postOAuth2DeviceAuthorization.js +177 -0
  47. package/dist/routes/postOAuth2DeviceAuthorization.js.map +1 -0
  48. package/dist/routes/postOAuth2DeviceAuthorization.test.d.ts +1 -0
  49. package/dist/routes/postOAuth2DeviceAuthorization.test.js +174 -0
  50. package/dist/routes/postOAuth2DeviceAuthorization.test.js.map +1 -0
  51. package/dist/routes/postOAuth2PushedAuthorizationRequest.d.ts +1 -6
  52. package/dist/routes/postOAuth2PushedAuthorizationRequest.js +11 -14
  53. package/dist/routes/postOAuth2PushedAuthorizationRequest.js.map +1 -1
  54. package/dist/routes/postOAuth2PushedAuthorizationRequest.test.js +47 -0
  55. package/dist/routes/postOAuth2PushedAuthorizationRequest.test.js.map +1 -1
  56. package/dist/routes/postOAuth2Token.d.ts +2 -7
  57. package/dist/routes/postOAuth2Token.js +2 -6
  58. package/dist/routes/postOAuth2Token.js.map +1 -1
  59. package/dist/routes/postOAuth2Token.test.js +107 -0
  60. package/dist/routes/postOAuth2Token.test.js.map +1 -1
  61. package/dist/routes/schemas.d.ts +178 -0
  62. package/dist/routes/schemas.js +188 -0
  63. package/dist/routes/schemas.js.map +1 -0
  64. package/dist/services/oAuth2AuthorizationCodeGranter.d.ts +0 -70
  65. package/dist/services/oAuth2AuthorizationCodeGranter.js +7 -84
  66. package/dist/services/oAuth2AuthorizationCodeGranter.js.map +1 -1
  67. package/dist/services/oAuth2AuthorizationRequests.js +4 -5
  68. package/dist/services/oAuth2AuthorizationRequests.js.map +1 -1
  69. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +1 -16
  70. package/dist/services/oAuth2ClientCredentialsGranter.js +7 -25
  71. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -1
  72. package/dist/services/oAuth2DeviceAuthorizationCodeGranter.test.d.ts +1 -0
  73. package/dist/services/oAuth2DeviceAuthorizationCodeGranter.test.js +332 -0
  74. package/dist/services/oAuth2DeviceAuthorizationCodeGranter.test.js.map +1 -0
  75. package/dist/services/oAuth2DeviceAuthorizationGranter.d.ts +54 -0
  76. package/dist/services/oAuth2DeviceAuthorizationGranter.js +67 -0
  77. package/dist/services/oAuth2DeviceAuthorizationGranter.js.map +1 -0
  78. package/dist/services/oAuth2Granters.js +0 -2
  79. package/dist/services/oAuth2Granters.js.map +1 -1
  80. package/dist/services/oAuth2PasswordGranter.d.ts +1 -22
  81. package/dist/services/oAuth2PasswordGranter.js +5 -30
  82. package/dist/services/oAuth2PasswordGranter.js.map +1 -1
  83. package/dist/services/oAuth2RefreshTokenGranter.d.ts +1 -19
  84. package/dist/services/oAuth2RefreshTokenGranter.js +5 -28
  85. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -1
  86. package/package.json +4 -4
  87. package/src/index.test.ts +169 -26
  88. package/src/index.ts +21 -26
  89. package/src/libs/clients.test.ts +47 -0
  90. package/src/libs/clients.ts +60 -10
  91. package/src/libs/errors.ts +72 -0
  92. package/src/libs/verifier.ts +11 -3
  93. package/src/routes/__snapshots__/postOAuth2DeviceAcknowledge.test.ts.snap +5 -0
  94. package/src/routes/getOAuth2Authorize.ts +41 -26
  95. package/src/routes/getOAuth2WellKnownMetadata.test.ts +96 -0
  96. package/src/routes/getOAuth2WellKnownMetadata.ts +24 -10
  97. package/src/routes/getOAuth2WellKnownProtectedResourceMetadata.ts +1 -3
  98. package/src/routes/postAuthLogin.ts +1 -1
  99. package/src/routes/postAuthRefresh.ts +1 -1
  100. package/src/routes/postOAuth2Acknowledge.ts +2 -4
  101. package/src/routes/postOAuth2DeviceAcknowledge.test.ts +408 -0
  102. package/src/routes/postOAuth2DeviceAcknowledge.ts +157 -0
  103. package/src/routes/postOAuth2DeviceAuthorization.test.ts +192 -0
  104. package/src/routes/postOAuth2DeviceAuthorization.ts +261 -0
  105. package/src/routes/postOAuth2PushedAuthorizationRequest.test.ts +59 -0
  106. package/src/routes/postOAuth2PushedAuthorizationRequest.ts +16 -22
  107. package/src/routes/postOAuth2Token.test.ts +119 -0
  108. package/src/routes/postOAuth2Token.ts +6 -16
  109. package/src/routes/schemas.ts +210 -0
  110. package/src/services/oAuth2AuthorizationCodeGranter.ts +11 -94
  111. package/src/services/oAuth2AuthorizationRequests.ts +5 -5
  112. package/src/services/oAuth2ClientCredentialsGranter.ts +8 -27
  113. package/src/services/oAuth2DeviceAuthorizationCodeGranter.test.ts +372 -0
  114. package/src/services/oAuth2DeviceAuthorizationGranter.ts +194 -0
  115. package/src/services/oAuth2Granters.ts +0 -2
  116. package/src/services/oAuth2PasswordGranter.ts +7 -33
  117. package/src/services/oAuth2RefreshTokenGranter.ts +6 -31
  118. package/dist/libs/schemas.d.ts +0 -31
  119. package/dist/libs/schemas.js +0 -33
  120. package/dist/libs/schemas.js.map +0 -1
  121. package/src/libs/schemas.ts +0 -37
@@ -10,8 +10,7 @@ import {
10
10
  type WhookOAuth2GranterDefinitions,
11
11
  type WhookOAuth2GranterService,
12
12
  } from '../services/oAuth2Granters.js';
13
- import { codeChallengeMethodSchema } from '../services/oAuth2AuthorizationCodeGranter.js';
14
- import { scopeTokenSchema, scopeTokensSchema } from '../libs/schemas.js';
13
+ import { codeChallengeMethodSchema, scopeTokensSchema } from './schemas.js';
15
14
  import { type LogService } from 'common-services';
16
15
  import { type OpenAPI } from 'ya-open-api-types';
17
16
  import { collectScopesFromAPI } from '../libs/scopes.js';
@@ -21,8 +20,6 @@ import {
21
20
  } from '../services/oAuth2AuthorizationRequests.js';
22
21
  import { YError } from 'yerror';
23
22
 
24
- export { scopeTokenSchema, scopeTokensSchema, codeChallengeMethodSchema };
25
-
26
23
  // OAuth Token Endpoint Authentication Methods
27
24
  export const endpointAuthenticationMethodsSchema = {
28
25
  name: 'OAuthTokenEndpointAuthenticationMethods',
@@ -98,6 +95,7 @@ export const oAuth2MetadataSchema = {
98
95
  issuer: refersTo(httpsProtocolURISchema),
99
96
  authorization_endpoint: refersTo(httpsProtocolURISchema),
100
97
  token_endpoint: refersTo(httpsProtocolURISchema),
98
+ device_authorization_endpoint: refersTo(httpsProtocolURISchema),
101
99
  pushed_authorization_request_endpoint: refersTo(httpsProtocolURISchema),
102
100
  jwks_uri: refersTo(httpsProtocolURISchema),
103
101
  registration_endpoint: refersTo(httpsProtocolURISchema),
@@ -135,6 +133,7 @@ export const oAuth2MetadataSchema = {
135
133
  'authorization_code',
136
134
  'implicit',
137
135
  'refresh_token',
136
+ 'urn:ietf:params:oauth:grant-type:device_code',
138
137
  'client_credentials',
139
138
  'password',
140
139
  'urn:ietf:params:oauth:grant-type:jwt-bearer',
@@ -326,6 +325,19 @@ async function initGetOAuth2WellKnownMetadata({
326
325
  throw new YError('E_OAUTH2_MISCONFIGURED');
327
326
  }
328
327
 
328
+ const tokenEndpointPath =
329
+ DEFINITIONS.configs['postOAuth2Token']?.type === 'route'
330
+ ? DEFINITIONS.configs['postOAuth2Token'].path
331
+ : '/oauth2/token';
332
+ const tokenOperation = API.paths?.[tokenEndpointPath]?.post;
333
+ const tokenSecurity = tokenOperation?.security ?? API.security ?? [];
334
+ const allowsUnauthenticatedTokenRequests =
335
+ !!tokenOperation &&
336
+ (tokenSecurity.length === 0 ||
337
+ tokenSecurity.some(
338
+ (requirement) => Object.keys(requirement).length === 0,
339
+ ));
340
+
329
341
  const body = {
330
342
  issuer: `${BASE_URL}`,
331
343
  authorization_endpoint: `${BASE_URL}${
@@ -333,15 +345,11 @@ async function initGetOAuth2WellKnownMetadata({
333
345
  ? DEFINITIONS.configs['getOAuth2Authorize'].path
334
346
  : '/oauth2/authorize'
335
347
  }`,
336
- token_endpoint: `${BASE_URL}${
337
- DEFINITIONS.configs['postOAuth2Token']?.type === 'route'
338
- ? DEFINITIONS.configs['postOAuth2Token'].path
339
- : '/oauth2/token'
340
- }`,
341
- // TODO: Put it behind options (allow none)
348
+ token_endpoint: `${BASE_URL}${tokenEndpointPath}`,
342
349
  token_endpoint_auth_methods_supported: [
343
350
  'client_secret_basic',
344
351
  'client_secret_post',
352
+ ...(allowsUnauthenticatedTokenRequests ? ['none'] : []),
345
353
  ],
346
354
  grant_types_supported: [
347
355
  ...new Set(
@@ -373,6 +381,12 @@ async function initGetOAuth2WellKnownMetadata({
373
381
  require_pushed_authorization_requests: OAUTH2_PAR.mode === 'required',
374
382
  }
375
383
  : {}),
384
+ ...(DEFINITIONS.configs['postOAuth2DeviceAuthorization']?.type ===
385
+ 'route' && DEFINITIONS.configs['postOAuth2DeviceAuthorization']?.path
386
+ ? {
387
+ device_authorization_endpoint: `${BASE_URL}${DEFINITIONS.configs['postOAuth2DeviceAuthorization']?.path}`,
388
+ }
389
+ : {}),
376
390
  };
377
391
 
378
392
  return async () => {
@@ -11,9 +11,7 @@ import {
11
11
  import { type LogService } from 'common-services';
12
12
  import { type OpenAPI } from 'ya-open-api-types';
13
13
  import { collectScopesFromAPI } from '../libs/scopes.js';
14
- import { scopeTokensSchema } from '../libs/schemas.js';
15
-
16
- export { scopeTokensSchema };
14
+ import { scopeTokensSchema } from './schemas.js';
17
15
 
18
16
  export const bearerMethodSchema = {
19
17
  name: 'OAuth2BearerMethod',
@@ -8,7 +8,7 @@ import initPostOAuth2Token from './postOAuth2Token.js';
8
8
  import { AUTH_API_PREFIX } from '../services/authCookies.js';
9
9
  import { refersTo, type WhookRouteDefinition } from '@whook/whook';
10
10
  import { type WhookAuthCookiesService } from '../services/authCookies.js';
11
- import { scopeSchema } from '../libs/schemas.js';
11
+ import { scopeSchema } from './schemas.js';
12
12
  import { PASSWORD_GRANT_TYPE } from '../services/oAuth2PasswordGranter.js';
13
13
 
14
14
  export { scopeSchema };
@@ -12,7 +12,7 @@ import {
12
12
  type WhookOAuth2ReadClientGrantsService,
13
13
  type WhookOAuth2Options,
14
14
  } from '../services/oAuth2Granters.js';
15
- import { scopeSchema } from '../libs/schemas.js';
15
+ import { scopeSchema } from './schemas.js';
16
16
  import { REFRESH_TOKEN_GRANT_TYPE } from '../services/oAuth2RefreshTokenGranter.js';
17
17
 
18
18
  export { scopeSchema };
@@ -19,16 +19,14 @@ import {
19
19
  parseOAuth2Scope,
20
20
  stringifyScopes,
21
21
  } from '../libs/scopes.js';
22
- import { scopeSchema } from '../libs/schemas.js';
23
22
  import {
24
23
  codeChallengeMethodSchema,
25
24
  codeChallengeSchema,
26
- } from '../services/oAuth2AuthorizationCodeGranter.js';
25
+ scopeSchema,
26
+ } from './schemas.js';
27
27
  import { addParamsToURL, buildParamsFromError } from '../libs/redirectURI.js';
28
28
  import { snakeCase } from '../libs/utils.js';
29
29
 
30
- export { scopeSchema, codeChallengeMethodSchema, codeChallengeSchema };
31
-
32
30
  /* Architecture Note #2: OAuth2 acknowledge
33
31
 
34
32
  This endpoint is to be used by the authentication SSR frontend
@@ -0,0 +1,408 @@
1
+ import { describe, test, beforeEach, jest, expect } from '@jest/globals';
2
+ import initPostOAuth2DeviceAcknowledge from './postOAuth2DeviceAcknowledge.js';
3
+ import {
4
+ type WhookOAuth2ReadClientGrantsService,
5
+ type WhookOAuth2Options,
6
+ } from '../services/oAuth2Granters.js';
7
+ import { type WhookOAuth2DeviceAuthorizationCodeService } from '../services/oAuth2DeviceAuthorizationGranter.js';
8
+ import { YError } from 'yerror';
9
+
10
+ describe('postOAuth2DeviceAcknowledge', () => {
11
+ const OAUTH2: WhookOAuth2Options = {
12
+ authenticateURL: 'https://auth.example.com/sign_in',
13
+ allowedScopes: ['user', 'admin'],
14
+ rootClientId: 'root_app_id',
15
+ };
16
+ const readClientGrants = jest.fn<WhookOAuth2ReadClientGrantsService>();
17
+ const oAuth2DeviceAuthorizationCode = {
18
+ acknowledge:
19
+ jest.fn<WhookOAuth2DeviceAuthorizationCodeService['acknowledge']>(),
20
+ };
21
+
22
+ beforeEach(() => {
23
+ readClientGrants.mockReset();
24
+ oAuth2DeviceAuthorizationCode.acknowledge.mockReset();
25
+ });
26
+
27
+ test('should acknowledge a device authorization challenge', async () => {
28
+ oAuth2DeviceAuthorizationCode.acknowledge.mockResolvedValueOnce();
29
+
30
+ const postOAuth2DeviceAcknowledge = await initPostOAuth2DeviceAcknowledge({
31
+ OAUTH2,
32
+ readClientGrants,
33
+ oAuth2DeviceAuthorizationCode,
34
+ });
35
+
36
+ readClientGrants.mockResolvedValueOnce({
37
+ allowedScopes: ['user', 'admin'],
38
+ allowedRedirectURIS: ['https://www.example.com'],
39
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
40
+ authenticationData: {
41
+ clientId: 'root_app_id',
42
+ scopes: ['user', 'admin'],
43
+ userId: 'root_user_id',
44
+ },
45
+ isPublicClient: true,
46
+ canAcknowledge: true,
47
+ });
48
+ readClientGrants.mockResolvedValueOnce({
49
+ allowedScopes: ['user', 'admin'],
50
+ allowedRedirectURIS: ['https://www.example.com'],
51
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
52
+ authenticationData: {
53
+ clientId: 'client_app_id',
54
+ scopes: ['user', 'admin'],
55
+ userId: 'client_user_id',
56
+ },
57
+ isPublicClient: true,
58
+ });
59
+
60
+ const response = await postOAuth2DeviceAcknowledge({
61
+ body: {
62
+ clientId: 'client_app_id',
63
+ userCode: 'a_user_code',
64
+ scope: 'user',
65
+ acknowledged: true,
66
+ },
67
+ authenticationData: {
68
+ clientId: 'root_app_id',
69
+ scopes: ['user', 'admin'],
70
+ userId: 'user_id',
71
+ },
72
+ });
73
+
74
+ expect({
75
+ response,
76
+ readClientGrantsCalls: readClientGrants.mock.calls,
77
+ oAuth2DeviceAuthorizationCodeCreateCalls:
78
+ oAuth2DeviceAuthorizationCode.acknowledge.mock.calls,
79
+ }).toMatchInlineSnapshot(`
80
+ {
81
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [
82
+ [
83
+ true,
84
+ {
85
+ "clientId": "root_app_id",
86
+ "scopes": [
87
+ "user",
88
+ "admin",
89
+ ],
90
+ "userId": "user_id",
91
+ },
92
+ "a_user_code",
93
+ "client_app_id",
94
+ [
95
+ "user",
96
+ ],
97
+ ],
98
+ ],
99
+ "readClientGrantsCalls": [
100
+ [
101
+ "root_app_id",
102
+ ],
103
+ [
104
+ "client_app_id",
105
+ ],
106
+ ],
107
+ "response": {
108
+ "headers": {},
109
+ "status": 204,
110
+ },
111
+ }
112
+ `);
113
+ });
114
+
115
+ test.each([true, false])(
116
+ 'should propagate a stored challenge client mismatch when acknowledged is %p',
117
+ async (acknowledged) => {
118
+ const mismatchError = new YError('E_OAUTH2_CLIENT_MISMATCH', [
119
+ 'client_app_id',
120
+ 'another_client',
121
+ ]);
122
+ oAuth2DeviceAuthorizationCode.acknowledge.mockRejectedValueOnce(
123
+ mismatchError,
124
+ );
125
+ readClientGrants.mockImplementation(async (clientId) => ({
126
+ allowedScopes: ['user'],
127
+ allowedRedirectURIS: [],
128
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
129
+ authenticationData: {
130
+ clientId,
131
+ userId: 'client_user_id',
132
+ scopes: ['user'],
133
+ },
134
+ isPublicClient: true,
135
+ canAcknowledge: clientId === 'root_app_id',
136
+ }));
137
+ const postOAuth2DeviceAcknowledge = await initPostOAuth2DeviceAcknowledge(
138
+ {
139
+ OAUTH2,
140
+ readClientGrants,
141
+ oAuth2DeviceAuthorizationCode,
142
+ },
143
+ );
144
+ const authenticationData = {
145
+ clientId: 'root_app_id',
146
+ userId: 'user_id',
147
+ scopes: ['user'],
148
+ };
149
+
150
+ await expect(
151
+ postOAuth2DeviceAcknowledge({
152
+ body: {
153
+ clientId: 'client_app_id',
154
+ userCode: 'a_user_code',
155
+ scope: 'user admin',
156
+ acknowledged,
157
+ },
158
+ authenticationData,
159
+ }),
160
+ ).rejects.toMatchSnapshot();
161
+ expect(oAuth2DeviceAuthorizationCode.acknowledge).toHaveBeenCalledWith(
162
+ acknowledged,
163
+ authenticationData,
164
+ 'a_user_code',
165
+ 'client_app_id',
166
+ ['user'],
167
+ );
168
+ },
169
+ );
170
+
171
+ test('should fail with a bad client grant setup', async () => {
172
+ const postOAuth2DeviceAcknowledge = await initPostOAuth2DeviceAcknowledge({
173
+ OAUTH2,
174
+ readClientGrants,
175
+ oAuth2DeviceAuthorizationCode,
176
+ });
177
+
178
+ readClientGrants.mockResolvedValueOnce({
179
+ allowedScopes: ['user', 'admin'],
180
+ allowedRedirectURIS: ['https://www.example.com'],
181
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
182
+ authenticationData: {
183
+ clientId: 'root_app_id',
184
+ scopes: ['user', 'admin'],
185
+ userId: 'root_user_id',
186
+ },
187
+ isPublicClient: true,
188
+ canAcknowledge: true,
189
+ });
190
+ readClientGrants.mockResolvedValueOnce({
191
+ allowedScopes: ['user', 'admin'],
192
+ allowedRedirectURIS: ['https://www.example.com'],
193
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
194
+ authenticationData: {
195
+ clientId: 'another_client',
196
+ scopes: ['user', 'admin'],
197
+ userId: 'client_user_id',
198
+ },
199
+ isPublicClient: true,
200
+ });
201
+
202
+ try {
203
+ await postOAuth2DeviceAcknowledge({
204
+ body: {
205
+ clientId: 'client_app_id',
206
+ userCode: 'a_user_code',
207
+ scope: 'user',
208
+ acknowledged: true,
209
+ },
210
+ authenticationData: {
211
+ clientId: 'root_app_id',
212
+ scopes: ['user', 'admin'],
213
+ userId: 'user_id',
214
+ },
215
+ });
216
+ throw new YError('E_UNEXPECTED_SUCCESS');
217
+ } catch (err) {
218
+ expect({
219
+ errorCode: (err as YError).code,
220
+ errorDebug: (err as YError).debug,
221
+ causeErrorCode: ((err as YError).cause as YError)?.code,
222
+ causeErrorDebug: ((err as YError).cause as YError)?.debug,
223
+ readClientGrantsCalls: readClientGrants.mock.calls,
224
+ oAuth2DeviceAuthorizationCodeCreateCalls:
225
+ oAuth2DeviceAuthorizationCode.acknowledge.mock.calls,
226
+ }).toMatchInlineSnapshot(`
227
+ {
228
+ "causeErrorCode": "E_OAUTH2_CLIENT_GRANTS_MISMATCH",
229
+ "causeErrorDebug": [
230
+ "client_app_id",
231
+ "another_client",
232
+ ],
233
+ "errorCode": "E_UNAUTHORIZED",
234
+ "errorDebug": [],
235
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [],
236
+ "readClientGrantsCalls": [
237
+ [
238
+ "root_app_id",
239
+ ],
240
+ [
241
+ "client_app_id",
242
+ ],
243
+ ],
244
+ }
245
+ `);
246
+ }
247
+ });
248
+
249
+ test('should fail with a client without device grant', async () => {
250
+ const postOAuth2DeviceAcknowledge = await initPostOAuth2DeviceAcknowledge({
251
+ OAUTH2,
252
+ readClientGrants,
253
+ oAuth2DeviceAuthorizationCode,
254
+ });
255
+
256
+ readClientGrants.mockResolvedValueOnce({
257
+ allowedScopes: ['user', 'admin'],
258
+ allowedRedirectURIS: ['https://www.example.com'],
259
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
260
+ authenticationData: {
261
+ clientId: 'root_app_id',
262
+ scopes: ['user', 'admin'],
263
+ userId: 'root_user_id',
264
+ },
265
+ isPublicClient: true,
266
+ canAcknowledge: true,
267
+ });
268
+ readClientGrants.mockResolvedValueOnce({
269
+ allowedScopes: ['user', 'admin'],
270
+ allowedRedirectURIS: ['https://www.example.com'],
271
+ allowedGrantTypes: ['client_credentials'],
272
+ authenticationData: {
273
+ clientId: 'client_app_id',
274
+ scopes: ['user', 'admin'],
275
+ userId: 'client_user_id',
276
+ },
277
+ isPublicClient: true,
278
+ });
279
+
280
+ try {
281
+ await postOAuth2DeviceAcknowledge({
282
+ body: {
283
+ clientId: 'client_app_id',
284
+ userCode: 'a_user_code',
285
+ scope: 'user',
286
+ acknowledged: true,
287
+ },
288
+ authenticationData: {
289
+ clientId: 'root_app_id',
290
+ scopes: ['user', 'admin'],
291
+ userId: 'user_id',
292
+ },
293
+ });
294
+ throw new YError('E_UNEXPECTED_SUCCESS');
295
+ } catch (err) {
296
+ expect({
297
+ errorCode: (err as YError).code,
298
+ errorDebug: (err as YError).debug,
299
+ causeErrorCode: ((err as YError).cause as YError)?.code,
300
+ causeErrorDebug: ((err as YError).cause as YError)?.debug,
301
+ readClientGrantsCalls: readClientGrants.mock.calls,
302
+ oAuth2DeviceAuthorizationCodeCreateCalls:
303
+ oAuth2DeviceAuthorizationCode.acknowledge.mock.calls,
304
+ }).toMatchInlineSnapshot(`
305
+ {
306
+ "causeErrorCode": "E_OAUTH2_GRANT_TYPE_NOT_ALLOWED",
307
+ "causeErrorDebug": [
308
+ "urn:ietf:params:oauth:grant-type:device_code",
309
+ [
310
+ "client_credentials",
311
+ ],
312
+ ],
313
+ "errorCode": "E_UNAUTHORIZED",
314
+ "errorDebug": [],
315
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [],
316
+ "readClientGrantsCalls": [
317
+ [
318
+ "root_app_id",
319
+ ],
320
+ [
321
+ "client_app_id",
322
+ ],
323
+ ],
324
+ }
325
+ `);
326
+ }
327
+ });
328
+
329
+ test('should fail with bad scopes', async () => {
330
+ const postOAuth2DeviceAcknowledge = await initPostOAuth2DeviceAcknowledge({
331
+ OAUTH2: {
332
+ ...OAUTH2,
333
+ strictScopesChecks: true,
334
+ },
335
+ readClientGrants,
336
+ oAuth2DeviceAuthorizationCode,
337
+ });
338
+
339
+ readClientGrants.mockResolvedValueOnce({
340
+ allowedScopes: ['user', 'admin'],
341
+ allowedRedirectURIS: ['https://www.example.com'],
342
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
343
+ authenticationData: {
344
+ clientId: 'root_app_id',
345
+ scopes: ['user', 'admin'],
346
+ userId: 'root_user_id',
347
+ },
348
+ isPublicClient: true,
349
+ canAcknowledge: true,
350
+ });
351
+ readClientGrants.mockResolvedValueOnce({
352
+ allowedScopes: ['user', 'admin'],
353
+ allowedRedirectURIS: ['https://www.example.com'],
354
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
355
+ authenticationData: {
356
+ clientId: 'client_app_id',
357
+ scopes: ['user', 'admin'],
358
+ userId: 'client_user_id',
359
+ },
360
+ isPublicClient: true,
361
+ });
362
+
363
+ try {
364
+ await postOAuth2DeviceAcknowledge({
365
+ body: {
366
+ clientId: 'client_app_id',
367
+ userCode: 'a_user_code',
368
+ scope: 'user god',
369
+ acknowledged: true,
370
+ },
371
+ authenticationData: {
372
+ clientId: 'root_app_id',
373
+ scopes: ['user', 'admin'],
374
+ userId: 'user_id',
375
+ },
376
+ });
377
+ throw new YError('E_UNEXPECTED_SUCCESS');
378
+ } catch (err) {
379
+ expect({
380
+ errorCode: (err as YError).code,
381
+ errorDebug: (err as YError).debug,
382
+ causeErrorCode: ((err as YError).cause as YError)?.code,
383
+ causeErrorDebug: ((err as YError).cause as YError)?.debug,
384
+ readClientGrantsCalls: readClientGrants.mock.calls,
385
+ oAuth2DeviceAuthorizationCodeCreateCalls:
386
+ oAuth2DeviceAuthorizationCode.acknowledge.mock.calls,
387
+ }).toMatchInlineSnapshot(`
388
+ {
389
+ "causeErrorCode": "E_OAUTH2_BAD_SCOPE",
390
+ "causeErrorDebug": [
391
+ "god",
392
+ ],
393
+ "errorCode": "E_UNAUTHORIZED",
394
+ "errorDebug": [],
395
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [],
396
+ "readClientGrantsCalls": [
397
+ [
398
+ "root_app_id",
399
+ ],
400
+ [
401
+ "client_app_id",
402
+ ],
403
+ ],
404
+ }
405
+ `);
406
+ }
407
+ });
408
+ });
@@ -0,0 +1,157 @@
1
+ import { autoService, location } from 'knifecycle';
2
+ import {
3
+ refersTo,
4
+ type WhookAPISchemaDefinition,
5
+ type WhookRouteDefinition,
6
+ } from '@whook/whook';
7
+ import {
8
+ type WhookOAuth2Options,
9
+ type WhookOAuth2ReadClientGrantsService,
10
+ type WhookOAuth2ClientId,
11
+ } from '../services/oAuth2Granters.js';
12
+ import {
13
+ DEVICE_AUTHORIZATION_GRANT_TYPE,
14
+ type WhookOAuth2UserCode,
15
+ type WhookOAuth2DeviceAuthorizationCodeService,
16
+ } from '../services/oAuth2DeviceAuthorizationGranter.js';
17
+ import { checkGrants } from '../libs/clients.js';
18
+ import { checkGrantType } from '../libs/grants.js';
19
+ import { filterScopes, parseOAuth2Scope } from '../libs/scopes.js';
20
+ import { clientIdSchema, scopeSchema } from './schemas.js';
21
+ import { type WhookAuthenticationData } from '@whook/authorization';
22
+ import { userCodeSchema } from './postOAuth2DeviceAuthorization.js';
23
+ import { YError } from 'yerror';
24
+
25
+ export const deviceAcknowledgeRequestBodySchema = {
26
+ name: 'DeviceAcknowledgeRequestBody',
27
+ schema: {
28
+ type: 'object',
29
+ description: 'Device acknowledge request',
30
+ required: ['clientId', 'userCode', 'scope', 'acknowledged'],
31
+ properties: {
32
+ clientId: refersTo(clientIdSchema),
33
+ userCode: refersTo(userCodeSchema),
34
+ scope: refersTo(scopeSchema),
35
+ acknowledged: {
36
+ type: 'boolean',
37
+ description: 'Whether the user acknowledged the delegation or not.',
38
+ },
39
+ },
40
+ },
41
+ } as const satisfies WhookAPISchemaDefinition;
42
+
43
+ export const definition = {
44
+ method: 'post',
45
+ path: '/oauth2/device_acknowledge',
46
+ config: {
47
+ environments: [],
48
+ private: true,
49
+ },
50
+ operation: {
51
+ operationId: 'postOAuth2DeviceAcknowledge',
52
+ summary: `Implements the logic that allow the authentication frontend
53
+ to process the [Device Authorization](https://datatracker.ietf.org/doc/html/rfc8628#section-3.1).`,
54
+ tags: ['oauth2'],
55
+ parameters: [],
56
+ requestBody: {
57
+ required: true,
58
+ content: {
59
+ 'application/json': {
60
+ schema: refersTo(deviceAcknowledgeRequestBodySchema),
61
+ },
62
+ },
63
+ },
64
+ responses: {
65
+ '204': {
66
+ description: 'Device authorization acknowledged.',
67
+ },
68
+ },
69
+ },
70
+ } as const satisfies WhookRouteDefinition;
71
+
72
+ async function initPostOAuth2DeviceAcknowledge({
73
+ OAUTH2,
74
+ readClientGrants,
75
+ oAuth2DeviceAuthorizationCode,
76
+ }: {
77
+ OAUTH2: WhookOAuth2Options;
78
+ readClientGrants: WhookOAuth2ReadClientGrantsService;
79
+ oAuth2DeviceAuthorizationCode: Pick<
80
+ WhookOAuth2DeviceAuthorizationCodeService,
81
+ 'acknowledge'
82
+ >;
83
+ }) {
84
+ return async ({
85
+ body: { clientId, userCode, scope: demandedScope, acknowledged },
86
+ authenticationData: userAuthenticationData,
87
+ }: {
88
+ body: {
89
+ clientId: WhookOAuth2ClientId;
90
+ userCode: WhookOAuth2UserCode;
91
+ scope: string;
92
+ acknowledged: boolean;
93
+ };
94
+ authenticationData: WhookAuthenticationData;
95
+ }) => {
96
+ if (!userAuthenticationData) {
97
+ throw new YError('E_UNAUTHORIZED');
98
+ }
99
+
100
+ const acknowledgeClientGrants = await readClientGrants(
101
+ userAuthenticationData.clientId,
102
+ );
103
+
104
+ checkGrants(userAuthenticationData.clientId, acknowledgeClientGrants);
105
+
106
+ if (!acknowledgeClientGrants.canAcknowledge) {
107
+ throw new YError('E_UNAUTHORIZED');
108
+ }
109
+
110
+ try {
111
+ const clientGrants = await readClientGrants(clientId);
112
+
113
+ checkGrants(clientId, clientGrants);
114
+
115
+ checkGrantType(
116
+ clientGrants.allowedGrantTypes,
117
+ DEVICE_AUTHORIZATION_GRANT_TYPE,
118
+ );
119
+
120
+ const filteredScopes = filterScopes(
121
+ filterScopes(
122
+ filterScopes(
123
+ parseOAuth2Scope(demandedScope),
124
+ OAUTH2.allowedScopes,
125
+ !!OAUTH2.strictScopesChecks,
126
+ ),
127
+ clientGrants.allowedScopes,
128
+ !!OAUTH2.strictScopesChecks,
129
+ ),
130
+ userAuthenticationData.scopes,
131
+ !!OAUTH2.strictScopesChecks,
132
+ );
133
+
134
+ await oAuth2DeviceAuthorizationCode.acknowledge(
135
+ acknowledged,
136
+ userAuthenticationData,
137
+ userCode,
138
+ clientId,
139
+ filteredScopes,
140
+ );
141
+
142
+ return {
143
+ status: 204,
144
+ headers: {},
145
+ };
146
+ } catch (err) {
147
+ // Ensure to break device acknoledgement wait when
148
+ // unexpected errors arise
149
+ throw YError.wrap(err as Error, 'E_UNAUTHORIZED');
150
+ }
151
+ };
152
+ }
153
+
154
+ export default location(
155
+ autoService(initPostOAuth2DeviceAcknowledge),
156
+ import.meta.url,
157
+ );