@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
@@ -0,0 +1,192 @@
1
+ import { describe, test, beforeEach, jest, expect } from '@jest/globals';
2
+ import initPostOAuth2DeviceAuthorization from './postOAuth2DeviceAuthorization.js';
3
+ import {
4
+ type WhookOAuth2ReadClientGrantsService,
5
+ type WhookOAuth2Options,
6
+ } from '../services/oAuth2Granters.js';
7
+ import { type WhookOAuth2DeviceAuthorizationCodeService } from '../services/oAuth2DeviceAuthorizationGranter.js';
8
+ import { type WhookAuthenticationData } from '@whook/authorization';
9
+ import { type LogService, type TimeService } from 'common-services';
10
+ import { YError } from 'yerror';
11
+
12
+ describe('postOAuth2DeviceAuthorization', () => {
13
+ const OAUTH2: WhookOAuth2Options = {
14
+ authenticateURL: 'https://auth.example.com/sign_in',
15
+ allowedScopes: ['user', 'admin'],
16
+ rootClientId: 'root_app_id',
17
+ };
18
+ const OAUTH2_DEVICE_AUTHORIZATION = {
19
+ verificationURI: 'https://auth.example.com/device',
20
+ interval: 8,
21
+ };
22
+ const readClientGrants = jest.fn<WhookOAuth2ReadClientGrantsService>();
23
+ const oAuth2DeviceAuthorizationCode = {
24
+ create: jest.fn<WhookOAuth2DeviceAuthorizationCodeService['create']>(),
25
+ };
26
+ const time = jest.fn<TimeService>();
27
+ const log = jest.fn<LogService>();
28
+
29
+ beforeEach(() => {
30
+ readClientGrants.mockReset();
31
+ oAuth2DeviceAuthorizationCode.create.mockReset();
32
+ time.mockReset();
33
+ log.mockReset();
34
+ readClientGrants.mockResolvedValue({
35
+ allowedScopes: ['user', 'admin'],
36
+ allowedRedirectURIS: ['https://www.example.com'],
37
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
38
+ authenticationData: {
39
+ clientId: 'root_app_id',
40
+ scopes: ['user', 'admin'],
41
+ userId: 'client_user_id',
42
+ },
43
+ isPublicClient: true,
44
+ });
45
+ });
46
+
47
+ test('should create a device authorization challenge', async () => {
48
+ time.mockReturnValue(new Date('2010-03-06T00:00:00Z').getTime());
49
+ oAuth2DeviceAuthorizationCode.create.mockResolvedValueOnce({
50
+ deviceCode: 'a_device_code',
51
+ userCode: 'ABCD-EFGH',
52
+ expiresAt: Date.parse('2010-03-06T00:10:00Z'),
53
+ });
54
+
55
+ const postOAuth2DeviceAuthorization =
56
+ await initPostOAuth2DeviceAuthorization({
57
+ OAUTH2,
58
+ OAUTH2_DEVICE_AUTHORIZATION,
59
+ readClientGrants,
60
+ oAuth2DeviceAuthorizationCode,
61
+ time,
62
+ log,
63
+ });
64
+
65
+ const response = await postOAuth2DeviceAuthorization({
66
+ body: {
67
+ client_id: 'root_app_id',
68
+ scope: 'user',
69
+ },
70
+ });
71
+
72
+ expect({
73
+ response,
74
+ readClientGrantsCalls: readClientGrants.mock.calls,
75
+ oAuth2DeviceAuthorizationCodeCreateCalls:
76
+ oAuth2DeviceAuthorizationCode.create.mock.calls,
77
+ logCalls: log.mock.calls.filter(([type]) => !type.endsWith('stack')),
78
+ }).toMatchInlineSnapshot(`
79
+ {
80
+ "logCalls": [],
81
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [
82
+ [
83
+ {
84
+ "clientId": "root_app_id",
85
+ "scopes": [
86
+ "user",
87
+ "admin",
88
+ ],
89
+ "userId": "client_user_id",
90
+ },
91
+ {
92
+ "demandedScopes": [
93
+ "user",
94
+ ],
95
+ "filteredScopes": [
96
+ "user",
97
+ ],
98
+ },
99
+ ],
100
+ ],
101
+ "readClientGrantsCalls": [
102
+ [
103
+ "root_app_id",
104
+ ],
105
+ ],
106
+ "response": {
107
+ "body": {
108
+ "device_code": "a_device_code",
109
+ "expires_in": 600,
110
+ "interval": 8,
111
+ "scope": "user",
112
+ "user_code": "ABCD-EFGH",
113
+ "verification_uri": "https://auth.example.com/device",
114
+ "verification_uri_complete": "https://auth.example.com/device?userCode=ABCD-EFGH",
115
+ },
116
+ "headers": {
117
+ "Cache-Control": "no-store",
118
+ "Pragma": "no-cache",
119
+ },
120
+ "status": 200,
121
+ },
122
+ }
123
+ `);
124
+ });
125
+
126
+ test('should fail with a bad client grant setup', async () => {
127
+ readClientGrants.mockResolvedValueOnce({
128
+ allowedScopes: ['user', 'admin'],
129
+ allowedRedirectURIS: ['https://www.example.com'],
130
+ allowedGrantTypes: ['urn:ietf:params:oauth:grant-type:device_code'],
131
+ authenticationData: {
132
+ clientId: 'another_client',
133
+ scopes: ['user', 'admin'],
134
+ userId: 'client_user_id',
135
+ },
136
+ isPublicClient: true,
137
+ });
138
+
139
+ const postOAuth2DeviceAuthorization =
140
+ await initPostOAuth2DeviceAuthorization({
141
+ OAUTH2,
142
+ OAUTH2_DEVICE_AUTHORIZATION,
143
+ readClientGrants,
144
+ oAuth2DeviceAuthorizationCode,
145
+ time,
146
+ log,
147
+ });
148
+
149
+ try {
150
+ await postOAuth2DeviceAuthorization({
151
+ body: {
152
+ client_id: 'root_app_id',
153
+ },
154
+ authenticationData: {
155
+ clientId: 'root_app_id',
156
+ scopes: ['user'],
157
+ } as WhookAuthenticationData,
158
+ });
159
+ throw new YError('E_UNEXPECTED_SUCCESS');
160
+ } catch (err) {
161
+ expect({
162
+ errorCode: (err as YError).code,
163
+ errorDebug: (err as YError).debug,
164
+ readClientGrantsCalls: readClientGrants.mock.calls,
165
+ oAuth2DeviceAuthorizationCodeCreateCalls:
166
+ oAuth2DeviceAuthorizationCode.create.mock.calls,
167
+ logCalls: log.mock.calls.filter(([type]) => !type.endsWith('stack')),
168
+ }).toMatchInlineSnapshot(`
169
+ {
170
+ "errorCode": "E_OAUTH2_CLIENT_GRANTS_MISMATCH",
171
+ "errorDebug": [
172
+ "root_app_id",
173
+ "another_client",
174
+ ],
175
+ "logCalls": [
176
+ [
177
+ "debug",
178
+ "👫 - OAuth2 device authorization request error",
179
+ "E_OAUTH2_CLIENT_GRANTS_MISMATCH",
180
+ ],
181
+ ],
182
+ "oAuth2DeviceAuthorizationCodeCreateCalls": [],
183
+ "readClientGrantsCalls": [
184
+ [
185
+ "root_app_id",
186
+ ],
187
+ ],
188
+ }
189
+ `);
190
+ }
191
+ });
192
+ });
@@ -0,0 +1,261 @@
1
+ import { autoService, location } from 'knifecycle';
2
+ import { type LogService, type TimeService } from 'common-services';
3
+ import {
4
+ noop,
5
+ refersTo,
6
+ type WhookAPISchemaDefinition,
7
+ type WhookRouteDefinition,
8
+ } from '@whook/whook';
9
+ import { YError, printStackTrace } from 'yerror';
10
+ import {
11
+ type WhookOAuth2Options,
12
+ type WhookOAuth2ReadClientGrantsService,
13
+ type WhookOAuth2ClientId,
14
+ } from '../services/oAuth2Granters.js';
15
+ import {
16
+ DEFAULT_DEVICE_AUTHORIZATION_INTERVAL,
17
+ DEVICE_AUTHORIZATION_GRANT_TYPE,
18
+ type WhookOAuth2DeviceAuthorizationOptions,
19
+ type WhookOAuth2DeviceAuthorizationCodeService,
20
+ } from '../services/oAuth2DeviceAuthorizationGranter.js';
21
+ import { checkGrants, toUsableClientId } from '../libs/clients.js';
22
+ import { checkGrantType } from '../libs/grants.js';
23
+ import {
24
+ filterScopes,
25
+ parseOAuth2Scope,
26
+ stringifyScopes,
27
+ } from '../libs/scopes.js';
28
+ import { deviceCodeSchema, scopeSchema } from './schemas.js';
29
+ import { type WhookAuthenticationData } from '@whook/authorization';
30
+ import { clientIdSchema } from './schemas.js';
31
+
32
+ export const userCodeSchema = {
33
+ name: 'OAuth2UserCode',
34
+ schema: {
35
+ type: 'string',
36
+ },
37
+ } as const satisfies WhookAPISchemaDefinition;
38
+
39
+ export const deviceAuthorizationRequestBodySchema = {
40
+ name: 'DeviceAuthorizationRequestBody',
41
+ schema: {
42
+ type: 'object',
43
+ description:
44
+ 'Device authorization request, see https://datatracker.ietf.org/doc/html/rfc8628#section-3.1',
45
+ required: [],
46
+ properties: {
47
+ client_id: refersTo(clientIdSchema),
48
+ scope: refersTo(scopeSchema),
49
+ },
50
+ },
51
+ } as const satisfies WhookAPISchemaDefinition;
52
+
53
+ export const definition = {
54
+ method: 'post',
55
+ path: '/oauth2/device_authorization',
56
+ config: {
57
+ environments: [],
58
+ },
59
+ operation: {
60
+ operationId: 'postOAuth2DeviceAuthorization',
61
+ summary: `Implements the [Device Authorization Endpoint](https://datatracker.ietf.org/doc/html/rfc8628#section-3.1).`,
62
+ tags: ['oauth2'],
63
+ parameters: [],
64
+ requestBody: {
65
+ required: false,
66
+ content: {
67
+ 'application/x-www-form-urlencoded': {
68
+ schema: refersTo(deviceAuthorizationRequestBodySchema),
69
+ },
70
+ 'application/json': {
71
+ schema: refersTo(deviceAuthorizationRequestBodySchema),
72
+ },
73
+ },
74
+ },
75
+ responses: {
76
+ '200': {
77
+ description: 'Device authorization request accepted.',
78
+ content: {
79
+ 'application/json': {
80
+ schema: {
81
+ type: 'object',
82
+ required: [
83
+ 'device_code',
84
+ 'user_code',
85
+ 'verification_uri',
86
+ 'expires_in',
87
+ ],
88
+ properties: {
89
+ device_code: refersTo(deviceCodeSchema),
90
+ user_code: refersTo(userCodeSchema),
91
+ verification_uri: {
92
+ type: 'string',
93
+ format: 'uri',
94
+ },
95
+ verification_uri_complete: {
96
+ type: 'string',
97
+ format: 'uri',
98
+ },
99
+ expires_in: {
100
+ type: 'number',
101
+ },
102
+ interval: {
103
+ type: 'number',
104
+ multipleOf: 1,
105
+ minimum: 1,
106
+ },
107
+ scope: refersTo(scopeSchema),
108
+ },
109
+ },
110
+ },
111
+ },
112
+ },
113
+ '400': {
114
+ description:
115
+ 'OAuth2 device authorization error response, see https://datatracker.ietf.org/doc/html/rfc8628#section-3.1.',
116
+ content: {
117
+ 'application/json': {
118
+ schema: {
119
+ type: 'object',
120
+ required: ['error'],
121
+ properties: {
122
+ error: {
123
+ type: 'string',
124
+ enum: [
125
+ 'invalid_request',
126
+ 'invalid_client',
127
+ 'unauthorized_client',
128
+ 'invalid_scope',
129
+ ],
130
+ },
131
+ error_description: { type: 'string' },
132
+ error_uri: { type: 'string' },
133
+ },
134
+ },
135
+ },
136
+ },
137
+ },
138
+ },
139
+ },
140
+ } as const satisfies WhookRouteDefinition;
141
+
142
+ async function initPostOAuth2DeviceAuthorization({
143
+ OAUTH2,
144
+ OAUTH2_DEVICE_AUTHORIZATION,
145
+ readClientGrants,
146
+ oAuth2DeviceAuthorizationCode,
147
+ time = Date.now.bind(Date),
148
+ log = noop,
149
+ }: {
150
+ OAUTH2: WhookOAuth2Options;
151
+ OAUTH2_DEVICE_AUTHORIZATION: WhookOAuth2DeviceAuthorizationOptions;
152
+ readClientGrants: WhookOAuth2ReadClientGrantsService;
153
+ oAuth2DeviceAuthorizationCode: Pick<
154
+ WhookOAuth2DeviceAuthorizationCodeService,
155
+ 'create'
156
+ >;
157
+ time: TimeService;
158
+ log: LogService;
159
+ }) {
160
+ return async ({
161
+ body: { client_id: clientId, scope: demandedScope } = {},
162
+ authenticationData: optionalAuthenticationData,
163
+ }: {
164
+ body: {
165
+ client_id?: WhookOAuth2ClientId;
166
+ scope?: string;
167
+ };
168
+ authenticationData?: WhookAuthenticationData;
169
+ }) => {
170
+ try {
171
+ const usableClientId = toUsableClientId([
172
+ optionalAuthenticationData?.clientId,
173
+ clientId,
174
+ ]);
175
+ const grants = await readClientGrants(usableClientId);
176
+
177
+ checkGrants(usableClientId, grants);
178
+
179
+ if (!grants.isPublicClient) {
180
+ if (!optionalAuthenticationData) {
181
+ throw new YError('E_OAUTH2_AUTHENTICATION_REQUIRED', [
182
+ grants.authenticationData.clientId,
183
+ ]);
184
+ }
185
+ }
186
+
187
+ checkGrantType(grants.allowedGrantTypes, DEVICE_AUTHORIZATION_GRANT_TYPE);
188
+
189
+ const demandedScopes =
190
+ typeof demandedScope === 'string'
191
+ ? filterScopes(
192
+ parseOAuth2Scope(demandedScope),
193
+ OAUTH2.allowedScopes,
194
+ !!OAUTH2.strictScopesChecks,
195
+ )
196
+ : [];
197
+ const filteredScopes = filterScopes(
198
+ typeof demandedScope === 'string'
199
+ ? demandedScopes
200
+ : OAUTH2.defaultToClientScope
201
+ ? filterScopes(
202
+ grants.allowedScopes,
203
+ OAUTH2.allowedScopes,
204
+ !!OAUTH2.strictScopesChecks,
205
+ )
206
+ : [],
207
+ grants.allowedScopes,
208
+ !!OAUTH2.strictScopesChecks,
209
+ );
210
+ const { deviceCode, userCode, expiresAt } =
211
+ await oAuth2DeviceAuthorizationCode.create(
212
+ optionalAuthenticationData || grants.authenticationData,
213
+ {
214
+ demandedScopes,
215
+ filteredScopes,
216
+ },
217
+ );
218
+ const currentTime = time();
219
+ const completeURL = new URL(OAUTH2_DEVICE_AUTHORIZATION.verificationURI);
220
+
221
+ completeURL.searchParams.append('userCode', userCode);
222
+
223
+ return {
224
+ status: 200,
225
+ headers: {
226
+ 'Cache-Control': 'no-store',
227
+ Pragma: 'no-cache',
228
+ },
229
+ body: {
230
+ device_code: deviceCode,
231
+ user_code: userCode,
232
+ verification_uri: OAUTH2_DEVICE_AUTHORIZATION.verificationURI,
233
+ verification_uri_complete: completeURL.toString(),
234
+ expires_in: Math.ceil((expiresAt - currentTime) / 1000),
235
+ interval:
236
+ OAUTH2_DEVICE_AUTHORIZATION.interval ??
237
+ DEFAULT_DEVICE_AUTHORIZATION_INTERVAL,
238
+ ...(filteredScopes.length
239
+ ? {
240
+ scope: stringifyScopes(filteredScopes),
241
+ }
242
+ : {}),
243
+ },
244
+ };
245
+ } catch (err) {
246
+ log(
247
+ 'debug',
248
+ '👫 - OAuth2 device authorization request error',
249
+ (err as YError).code,
250
+ );
251
+ log('error-stack', printStackTrace(err));
252
+
253
+ throw YError.cast(err as Error, 'E_OAUTH2_UNEXPECTED_ERROR');
254
+ }
255
+ };
256
+ }
257
+
258
+ export default location(
259
+ autoService(initPostOAuth2DeviceAuthorization),
260
+ import.meta.url,
261
+ );
@@ -208,6 +208,65 @@ describe('postOAuth2PushedAuthorizationRequest', () => {
208
208
  `);
209
209
  });
210
210
 
211
+ test.each([['enabled'], ['required']] as const)(
212
+ 'should accept PAR mode %s with empty scope requests',
213
+ async (mode) => {
214
+ const clientGrants = {
215
+ allowedGrantTypes: ['code'],
216
+ allowedScopes: ['user'],
217
+ allowedRedirectURIS: ['https://example.com/oauth/cb'],
218
+ isPublicClient: true,
219
+ canAcknowledge: false,
220
+ authenticationData: {
221
+ clientId: 'a_client_id',
222
+ scopes: [],
223
+ userId: '1',
224
+ },
225
+ };
226
+
227
+ readClientGrants.mockResolvedValueOnce(clientGrants);
228
+ codeGranter.authorize.mockResolvedValueOnce({ scopes: [] });
229
+ oAuth2AuthorizationRequests.create.mockResolvedValueOnce({
230
+ requestURI: 'urn:ietf:params:oauth:request_uri:a_request_uri',
231
+ expiresIn: 1000,
232
+ });
233
+
234
+ const postOAuth2PushedAuthorizationRequest =
235
+ await initPostOAuth2PushedAuthorizationRequest({
236
+ OAUTH2: { ...OAUTH2, allowedScopes: ['user', 'other'] },
237
+ OAUTH2_PAR: { ...OAUTH2_PAR, mode },
238
+ oAuth2Granters,
239
+ readClientGrants,
240
+ oAuth2AuthorizationRequests,
241
+ log,
242
+ });
243
+
244
+ const response = await postOAuth2PushedAuthorizationRequest({
245
+ body: {
246
+ response_type: 'code',
247
+ client_id: 'a_client_id',
248
+ redirect_uri: 'https://example.com/oauth/cb',
249
+ },
250
+ });
251
+
252
+ expect(response.status).toBe(201);
253
+ expect(codeGranter.authorize).toHaveBeenLastCalledWith({
254
+ clientId: 'a_client_id',
255
+ clientGrants,
256
+ demandedScopes: [],
257
+ });
258
+ expect(oAuth2AuthorizationRequests.create).toHaveBeenLastCalledWith(
259
+ 'a_client_id',
260
+ {
261
+ response_type: 'code',
262
+ client_id: 'a_client_id',
263
+ redirect_uri: 'https://example.com/oauth/cb',
264
+ scope: '',
265
+ },
266
+ );
267
+ },
268
+ );
269
+
211
270
  test('should reject nested request_uri parameter', async () => {
212
271
  [
213
272
  codeGranter.authorize,
@@ -18,14 +18,15 @@ import {
18
18
  parseOAuth2Scope,
19
19
  stringifyScopes,
20
20
  } from '../libs/scopes.js';
21
+ import { IMPLICIT_RESPONSE_TYPE } from '../services/oAuth2ImplicitGranter.js';
21
22
  import {
22
- AUTHORIZATION_CODE_RESPONSE_TYPE,
23
- codeChallengeMethodSchema,
23
+ scopeSchema,
24
+ requestURISchema,
24
25
  codeChallengeSchema,
25
- } from '../services/oAuth2AuthorizationCodeGranter.js';
26
- import { IMPLICIT_RESPONSE_TYPE } from '../services/oAuth2ImplicitGranter.js';
27
- import { scopeSchema, requestURISchema } from '../libs/schemas.js';
26
+ codeChallengeMethodSchema,
27
+ } from './schemas.js';
28
28
  import {
29
+ AUTHORIZATION_CODE_RESPONSE_TYPE,
29
30
  checkCodeChallengeParameters,
30
31
  PLAIN_CODE_CHALLENGE_METHOD,
31
32
  } from '../libs/verifier.js';
@@ -35,16 +36,10 @@ import {
35
36
  type WhookOAuth2AuthorizationRequestsService,
36
37
  } from '../services/oAuth2AuthorizationRequests.js';
37
38
  import { type WhookAuthenticationData } from '@whook/authorization';
38
- import { toUsableClientId } from '../libs/clients.js';
39
+ import { checkGrants, toUsableClientId } from '../libs/clients.js';
39
40
  import { getUsableRedirectURI } from '../libs/redirectURI.js';
40
41
  import { type WhookOAuth2AuthorizeRequestParameters } from './getOAuth2Authorize.js';
41
-
42
- export {
43
- scopeSchema,
44
- requestURISchema,
45
- codeChallengeSchema,
46
- codeChallengeMethodSchema,
47
- };
42
+ import { clientIdSchema } from './schemas.js';
48
43
 
49
44
  export const pushedAuthorizationRequestBodySchema = {
50
45
  name: 'PushedAuthorizationRequestBody',
@@ -58,9 +53,7 @@ export const pushedAuthorizationRequestBodySchema = {
58
53
  type: 'string',
59
54
  enum: [AUTHORIZATION_CODE_RESPONSE_TYPE, IMPLICIT_RESPONSE_TYPE],
60
55
  },
61
- client_id: {
62
- type: 'string',
63
- },
56
+ client_id: refersTo(clientIdSchema),
64
57
  redirect_uri: {
65
58
  type: 'string',
66
59
  pattern: '^https?://',
@@ -212,12 +205,7 @@ async function initPostOAuth2PushedAuthorizationRequest({
212
205
 
213
206
  const clientGrants = await readClientGrants(usableClientId);
214
207
 
215
- if (usableClientId !== clientGrants.authenticationData.clientId) {
216
- throw new YError('E_OAUTH2_CLIENT_GRANTS_MISMATCH', [
217
- usableClientId,
218
- clientGrants.authenticationData.clientId,
219
- ]);
220
- }
208
+ checkGrants(usableClientId, clientGrants);
221
209
 
222
210
  if (!clientGrants.isPublicClient) {
223
211
  if (!optionalAuthenticationData) {
@@ -239,6 +227,12 @@ async function initPostOAuth2PushedAuthorizationRequest({
239
227
  !!OAUTH2.strictScopesChecks,
240
228
  );
241
229
 
230
+ // When scopes are demanded but filtered to nothing
231
+ // let's error in order to avoid hard to debug situations
232
+ if (demandedScope && demandedScopes.length === 0) {
233
+ throw new YError('E_OAUTH2_BAD_SCOPE', [demandedScope]);
234
+ }
235
+
242
236
  if (requestURI) {
243
237
  throw new YError('E_OAUTH2_REQUEST_URI_NOT_ALLOWED');
244
238
  }