@whook/oauth2 18.1.0 → 19.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 (108) hide show
  1. package/README.md +27 -37
  2. package/dist/index.d.ts +6 -6
  3. package/dist/index.js +6 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.test.js +19 -18
  6. package/dist/index.test.js.map +1 -1
  7. package/dist/routes/getOAuth2Authorize.d.ts +100 -0
  8. package/dist/{handlers → routes}/getOAuth2Authorize.js +38 -35
  9. package/dist/routes/getOAuth2Authorize.js.map +1 -0
  10. package/dist/{handlers → routes}/getOAuth2Authorize.test.js +14 -10
  11. package/dist/routes/getOAuth2Authorize.test.js.map +1 -0
  12. package/dist/routes/postAuthLogin.d.ts +89 -0
  13. package/dist/{handlers → routes}/postAuthLogin.js +40 -39
  14. package/dist/routes/postAuthLogin.js.map +1 -0
  15. package/dist/routes/postAuthLogin.test.js.map +1 -0
  16. package/dist/routes/postAuthLogout.d.ts +28 -0
  17. package/dist/{handlers → routes}/postAuthLogout.js +9 -9
  18. package/dist/routes/postAuthLogout.js.map +1 -0
  19. package/dist/{handlers → routes}/postAuthLogout.test.js +1 -1
  20. package/dist/routes/postAuthLogout.test.js.map +1 -0
  21. package/dist/routes/postAuthRefresh.d.ts +94 -0
  22. package/dist/{handlers → routes}/postAuthRefresh.js +42 -41
  23. package/dist/routes/postAuthRefresh.js.map +1 -0
  24. package/dist/routes/postAuthRefresh.test.js.map +1 -0
  25. package/dist/routes/postOAuth2Acknowledge.d.ts +97 -0
  26. package/dist/{handlers → routes}/postOAuth2Acknowledge.js +46 -44
  27. package/dist/routes/postOAuth2Acknowledge.js.map +1 -0
  28. package/dist/routes/postOAuth2Acknowledge.test.js.map +1 -0
  29. package/dist/routes/postOAuth2Token.d.ts +198 -0
  30. package/dist/{handlers → routes}/postOAuth2Token.js +35 -32
  31. package/dist/routes/postOAuth2Token.js.map +1 -0
  32. package/dist/routes/postOAuth2Token.test.js.map +1 -0
  33. package/dist/services/authCookies.d.ts +3 -3
  34. package/dist/services/authCookies.js.map +1 -1
  35. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +5 -5
  36. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -1
  37. package/dist/services/oAuth2CodeGranter.d.ts +2 -3
  38. package/dist/services/oAuth2CodeGranter.js +2 -0
  39. package/dist/services/oAuth2CodeGranter.js.map +1 -1
  40. package/dist/services/oAuth2CodeGranter.test.js +2 -2
  41. package/dist/services/oAuth2CodeGranter.test.js.map +1 -1
  42. package/dist/services/oAuth2Granters.d.ts +24 -24
  43. package/dist/services/oAuth2Granters.js.map +1 -1
  44. package/dist/services/oAuth2PasswordGranter.d.ts +2 -3
  45. package/dist/services/oAuth2PasswordGranter.js.map +1 -1
  46. package/dist/services/oAuth2RefreshTokenGranter.d.ts +2 -3
  47. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -1
  48. package/dist/services/oAuth2TokenGranter.d.ts +2 -3
  49. package/dist/services/oAuth2TokenGranter.js +4 -0
  50. package/dist/services/oAuth2TokenGranter.js.map +1 -1
  51. package/package.json +9 -8
  52. package/src/__snapshots__/index.test.ts.snap +1 -0
  53. package/src/index.test.ts +31 -42
  54. package/src/index.ts +6 -6
  55. package/src/{handlers → routes}/getOAuth2Authorize.test.ts +14 -10
  56. package/src/{handlers → routes}/getOAuth2Authorize.ts +98 -95
  57. package/src/{handlers → routes}/postAuthLogin.test.ts +2 -1
  58. package/src/routes/postAuthLogin.ts +118 -0
  59. package/src/{handlers → routes}/postAuthLogout.test.ts +1 -1
  60. package/src/{handlers → routes}/postAuthLogout.ts +13 -13
  61. package/src/{handlers → routes}/postAuthRefresh.test.ts +2 -1
  62. package/src/routes/postAuthRefresh.ts +138 -0
  63. package/src/{handlers → routes}/postOAuth2Acknowledge.test.ts +18 -34
  64. package/src/{handlers → routes}/postOAuth2Acknowledge.ts +82 -90
  65. package/src/{handlers → routes}/postOAuth2Token.test.ts +3 -2
  66. package/src/{handlers → routes}/postOAuth2Token.ts +115 -120
  67. package/src/services/authCookies.ts +3 -5
  68. package/src/services/oAuth2ClientCredentialsGranter.ts +5 -10
  69. package/src/services/oAuth2CodeGranter.test.ts +12 -21
  70. package/src/services/oAuth2CodeGranter.ts +4 -6
  71. package/src/services/oAuth2Granters.ts +30 -55
  72. package/src/services/oAuth2PasswordGranter.ts +2 -6
  73. package/src/services/oAuth2RefreshTokenGranter.ts +2 -6
  74. package/src/services/oAuth2TokenGranter.ts +6 -6
  75. package/src/types.d.ts +7 -0
  76. package/dist/handlers/getOAuth2Authorize.d.ts +0 -27
  77. package/dist/handlers/getOAuth2Authorize.js.map +0 -1
  78. package/dist/handlers/getOAuth2Authorize.test.js.map +0 -1
  79. package/dist/handlers/postAuthLogin.d.ts +0 -28
  80. package/dist/handlers/postAuthLogin.js.map +0 -1
  81. package/dist/handlers/postAuthLogin.test.js.map +0 -1
  82. package/dist/handlers/postAuthLogout.d.ts +0 -12
  83. package/dist/handlers/postAuthLogout.js.map +0 -1
  84. package/dist/handlers/postAuthLogout.test.js.map +0 -1
  85. package/dist/handlers/postAuthRefresh.d.ts +0 -28
  86. package/dist/handlers/postAuthRefresh.js.map +0 -1
  87. package/dist/handlers/postAuthRefresh.test.js.map +0 -1
  88. package/dist/handlers/postOAuth2Acknowledge.d.ts +0 -31
  89. package/dist/handlers/postOAuth2Acknowledge.js.map +0 -1
  90. package/dist/handlers/postOAuth2Acknowledge.test.js.map +0 -1
  91. package/dist/handlers/postOAuth2Token.d.ts +0 -36
  92. package/dist/handlers/postOAuth2Token.js.map +0 -1
  93. package/dist/handlers/postOAuth2Token.test.js.map +0 -1
  94. package/src/handlers/postAuthLogin.ts +0 -123
  95. package/src/handlers/postAuthRefresh.ts +0 -143
  96. /package/dist/{handlers → routes}/getOAuth2Authorize.test.d.ts +0 -0
  97. /package/dist/{handlers → routes}/postAuthLogin.test.d.ts +0 -0
  98. /package/dist/{handlers → routes}/postAuthLogin.test.js +0 -0
  99. /package/dist/{handlers → routes}/postAuthLogout.test.d.ts +0 -0
  100. /package/dist/{handlers → routes}/postAuthRefresh.test.d.ts +0 -0
  101. /package/dist/{handlers → routes}/postAuthRefresh.test.js +0 -0
  102. /package/dist/{handlers → routes}/postOAuth2Acknowledge.test.d.ts +0 -0
  103. /package/dist/{handlers → routes}/postOAuth2Acknowledge.test.js +0 -0
  104. /package/dist/{handlers → routes}/postOAuth2Token.test.d.ts +0 -0
  105. /package/dist/{handlers → routes}/postOAuth2Token.test.js +0 -0
  106. /package/src/{handlers → routes}/__snapshots__/getOAuth2Authorize.test.ts.snap +0 -0
  107. /package/src/{handlers → routes}/__snapshots__/postOAuth2Acknowledge.test.ts.snap +0 -0
  108. /package/src/{handlers → routes}/__snapshots__/postOAuth2Token.test.ts.snap +0 -0
@@ -1,11 +1,10 @@
1
- import { autoHandler, location } from 'knifecycle';
1
+ import { autoService, location } from 'knifecycle';
2
2
  import camelCase from 'camelcase';
3
3
  import { YError, printStackTrace } from 'yerror';
4
4
  import {
5
5
  refersTo,
6
- type WhookAPIHandlerDefinition,
6
+ type WhookRouteDefinition,
7
7
  type WhookAPIParameterDefinition,
8
- type WhookResponse,
9
8
  type WhookErrorsDescriptors,
10
9
  type WhookErrorDescriptor,
11
10
  } from '@whook/whook';
@@ -21,7 +20,7 @@ This endpoint simply redirect the user to the authentication
21
20
  fine.
22
21
  */
23
22
 
24
- export const responseTypeParameter: WhookAPIParameterDefinition = {
23
+ export const responseTypeParameter = {
25
24
  name: 'responseType',
26
25
  parameter: {
27
26
  in: 'query',
@@ -32,8 +31,8 @@ export const responseTypeParameter: WhookAPIParameterDefinition = {
32
31
  enum: ['code', 'token'],
33
32
  },
34
33
  },
35
- };
36
- export const clientIdParameter: WhookAPIParameterDefinition = {
34
+ } as const satisfies WhookAPIParameterDefinition;
35
+ export const clientIdParameter = {
37
36
  name: 'clientId',
38
37
  parameter: {
39
38
  in: 'query',
@@ -43,8 +42,8 @@ export const clientIdParameter: WhookAPIParameterDefinition = {
43
42
  type: 'string',
44
43
  },
45
44
  },
46
- };
47
- export const redirectURIParameter: WhookAPIParameterDefinition = {
45
+ } as const satisfies WhookAPIParameterDefinition;
46
+ export const redirectURIParameter = {
48
47
  name: 'redirectURI',
49
48
  parameter: {
50
49
  in: 'query',
@@ -56,8 +55,8 @@ export const redirectURIParameter: WhookAPIParameterDefinition = {
56
55
  format: 'uri',
57
56
  },
58
57
  },
59
- };
60
- export const scopeParameter: WhookAPIParameterDefinition = {
58
+ } as const satisfies WhookAPIParameterDefinition;
59
+ export const scopeParameter = {
61
60
  name: 'scope',
62
61
  parameter: {
63
62
  in: 'query',
@@ -68,8 +67,8 @@ export const scopeParameter: WhookAPIParameterDefinition = {
68
67
  type: 'string',
69
68
  },
70
69
  },
71
- };
72
- export const stateParameter: WhookAPIParameterDefinition = {
70
+ } as const satisfies WhookAPIParameterDefinition;
71
+ export const stateParameter = {
73
72
  name: 'state',
74
73
  parameter: {
75
74
  in: 'query',
@@ -79,9 +78,9 @@ export const stateParameter: WhookAPIParameterDefinition = {
79
78
  type: 'string',
80
79
  },
81
80
  },
82
- };
81
+ } as const satisfies WhookAPIParameterDefinition;
83
82
 
84
- export const definition: WhookAPIHandlerDefinition = {
83
+ export const definition = {
85
84
  method: 'get',
86
85
  path: '/oauth2/authorize',
87
86
  operation: {
@@ -102,87 +101,7 @@ export const definition: WhookAPIHandlerDefinition = {
102
101
  },
103
102
  },
104
103
  },
105
- };
106
-
107
- export default location(autoHandler(getOAuth2Authorize), import.meta.url);
108
-
109
- async function getOAuth2Authorize(
110
- {
111
- OAUTH2,
112
- ERRORS_DESCRIPTORS,
113
- oAuth2Granters,
114
- log,
115
- }: {
116
- OAUTH2: OAuth2Options;
117
- ERRORS_DESCRIPTORS: WhookErrorsDescriptors;
118
- oAuth2Granters: OAuth2GranterService[];
119
- log: LogService;
120
- },
121
- {
122
- response_type: responseType,
123
- client_id: clientId,
124
- redirect_uri: demandedRedirectURI = '',
125
- scope: demandedScope = '',
126
- state,
127
- ...authorizeParameters
128
- }: {
129
- response_type: string;
130
- client_id: string;
131
- redirect_uri?: string;
132
- scope?: string;
133
- state: string;
134
- } & Record<string, unknown>,
135
- ): Promise<WhookResponse<302, { location: string }>> {
136
- const url = new URL(OAUTH2.authenticateURL);
137
-
138
- try {
139
- const granter = oAuth2Granters.find(
140
- (granter) =>
141
- granter.authorizer && granter.authorizer.responseType === responseType,
142
- );
143
-
144
- if (!granter) {
145
- throw new YError('E_UNKNOWN_AUTHORIZER_TYPE', responseType);
146
- }
147
-
148
- const { applicationId, redirectURI, scope } = await (
149
- granter.authorizer as NonNullable<OAuth2GranterService['authorizer']>
150
- ).authorize(
151
- {
152
- clientId,
153
- redirectURI: demandedRedirectURI,
154
- scope: demandedScope,
155
- },
156
- camelCaseObjectProperties(authorizeParameters),
157
- );
158
-
159
- url.searchParams.set('type', responseType);
160
- url.searchParams.set('redirect_uri', redirectURI);
161
- url.searchParams.set('scope', scope);
162
- url.searchParams.set('client_id', applicationId);
163
- } catch (err) {
164
- log('debug', '👫 - OAuth2 initialization error', (err as YError).code);
165
- log('error-stack', printStackTrace(err as Error));
166
-
167
- url.searchParams.set('redirect_uri', demandedRedirectURI);
168
- setURLError(
169
- url,
170
- err as YError,
171
- ERRORS_DESCRIPTORS[(err as YError).code] || ERRORS_DESCRIPTORS.E_OAUTH2,
172
- );
173
- }
174
-
175
- if (state) {
176
- url.searchParams.set('state', state);
177
- }
178
-
179
- return {
180
- status: 302,
181
- headers: {
182
- location: url.href,
183
- },
184
- };
185
- }
104
+ } as const satisfies WhookRouteDefinition;
186
105
 
187
106
  // The OAuth2 standard uses snake case names so we are
188
107
  // converting them to the project standards asap
@@ -212,3 +131,87 @@ export function setURLError(
212
131
  );
213
132
  }
214
133
  }
134
+
135
+ async function initGetOAuth2Authorize({
136
+ OAUTH2,
137
+ ERRORS_DESCRIPTORS,
138
+ oAuth2Granters,
139
+ log,
140
+ }: {
141
+ OAUTH2: OAuth2Options;
142
+ ERRORS_DESCRIPTORS: WhookErrorsDescriptors;
143
+ oAuth2Granters: OAuth2GranterService[];
144
+ log: LogService;
145
+ }) {
146
+ return async ({
147
+ query: {
148
+ response_type: responseType,
149
+ client_id: clientId,
150
+ redirect_uri: demandedRedirectURI = '',
151
+ scope: demandedScope = '',
152
+ state,
153
+ ...authorizeParameters
154
+ },
155
+ }: {
156
+ query: {
157
+ response_type: string;
158
+ client_id: string;
159
+ redirect_uri?: string;
160
+ scope?: string;
161
+ state: string;
162
+ } & Record<string, unknown>;
163
+ }) => {
164
+ const url = new URL(OAUTH2.authenticateURL);
165
+
166
+ try {
167
+ const granter = oAuth2Granters.find(
168
+ (granter) =>
169
+ granter.authorizer &&
170
+ granter.authorizer.responseType === responseType,
171
+ );
172
+
173
+ if (!granter) {
174
+ throw new YError('E_UNKNOWN_AUTHORIZER_TYPE', responseType);
175
+ }
176
+
177
+ const { applicationId, redirectURI, scope } = await (
178
+ granter.authorizer as NonNullable<OAuth2GranterService['authorizer']>
179
+ ).authorize(
180
+ {
181
+ clientId,
182
+ redirectURI: demandedRedirectURI,
183
+ scope: demandedScope,
184
+ },
185
+ camelCaseObjectProperties(authorizeParameters),
186
+ );
187
+
188
+ url.searchParams.set('type', responseType);
189
+ url.searchParams.set('redirect_uri', redirectURI);
190
+ url.searchParams.set('scope', scope);
191
+ url.searchParams.set('client_id', applicationId);
192
+ } catch (err) {
193
+ log('debug', '👫 - OAuth2 initialization error', (err as YError).code);
194
+ log('error-stack', printStackTrace(err as Error));
195
+
196
+ url.searchParams.set('redirect_uri', demandedRedirectURI);
197
+ setURLError(
198
+ url,
199
+ err as YError,
200
+ ERRORS_DESCRIPTORS[(err as YError).code] || ERRORS_DESCRIPTORS.E_OAUTH2,
201
+ );
202
+ }
203
+
204
+ if (state) {
205
+ url.searchParams.set('state', state);
206
+ }
207
+
208
+ return {
209
+ status: 302,
210
+ headers: {
211
+ location: url.href,
212
+ },
213
+ };
214
+ };
215
+ }
216
+
217
+ export default location(autoService(initGetOAuth2Authorize), import.meta.url);
@@ -1,6 +1,7 @@
1
1
  import { describe, test, jest, expect } from '@jest/globals';
2
2
  import initPostAuthLogin from './postAuthLogin.js';
3
3
  import { type AuthCookiesService } from '../services/authCookies.js';
4
+ import { type WhookAuthenticationData } from '@whook/authorization';
4
5
 
5
6
  describe('postAuthLogin', () => {
6
7
  test('should work', async () => {
@@ -13,7 +14,7 @@ describe('postAuthLogin', () => {
13
14
  ROOT_AUTHENTICATION_DATA: {
14
15
  scope: 'user',
15
16
  applicationId: 'root_app_id',
16
- },
17
+ } as WhookAuthenticationData,
17
18
  authCookies,
18
19
  postOAuth2Token,
19
20
  });
@@ -0,0 +1,118 @@
1
+ import { autoService, location } from 'knifecycle';
2
+ import { YHTTPError } from 'yhttperror';
3
+ import initPostOauth2Token from './postOAuth2Token.js';
4
+ import { AUTH_API_PREFIX } from '../services/authCookies.js';
5
+ import { type WhookRouteDefinition } from '@whook/whook';
6
+ import {
7
+ type AuthCookiesService,
8
+ type AuthHandlersConfig,
9
+ } from '../services/authCookies.js';
10
+
11
+ export const definition = {
12
+ method: 'post',
13
+ path: `${AUTH_API_PREFIX}/login`,
14
+ config: {
15
+ environments: [],
16
+ },
17
+ operation: {
18
+ operationId: 'postAuthLogin',
19
+ summary: 'Logs a user in',
20
+ tags: ['auth'],
21
+ parameters: [],
22
+ requestBody: {
23
+ required: true,
24
+ content: {
25
+ 'application/json': {
26
+ schema: {
27
+ type: 'object',
28
+ required: ['username', 'password'],
29
+ properties: {
30
+ username: { type: 'string' },
31
+ password: { type: 'string' },
32
+ scope: { type: 'string' },
33
+ remember: { type: 'boolean' },
34
+ },
35
+ },
36
+ },
37
+ },
38
+ },
39
+ responses: {
40
+ 200: {
41
+ description: 'Successfuly logged in.',
42
+ content: {
43
+ 'application/json': {
44
+ schema: {
45
+ type: 'object',
46
+ properties: {
47
+ access_token: { type: 'string' },
48
+ expiration_date: { type: 'string' },
49
+ expires_in: { type: 'string' },
50
+ token_type: { type: 'string' },
51
+ },
52
+ },
53
+ },
54
+ },
55
+ },
56
+ },
57
+ },
58
+ } as const satisfies WhookRouteDefinition;
59
+
60
+ async function initPostAuthLogin({
61
+ ROOT_AUTHENTICATION_DATA,
62
+ authCookies,
63
+ postOAuth2Token,
64
+ }: AuthHandlersConfig & {
65
+ authCookies: Pick<AuthCookiesService, 'build'>;
66
+ postOAuth2Token: Awaited<ReturnType<typeof initPostOauth2Token>>;
67
+ }) {
68
+ return async ({
69
+ body,
70
+ }: {
71
+ body: {
72
+ username: string;
73
+ password: string;
74
+ scope: string;
75
+ remember: boolean;
76
+ };
77
+ }) => {
78
+ try {
79
+ const response = await postOAuth2Token({
80
+ body: {
81
+ grant_type: 'password',
82
+ scope: body.scope,
83
+ username: body.username,
84
+ password: body.password,
85
+ },
86
+ authenticationData: ROOT_AUTHENTICATION_DATA,
87
+ });
88
+
89
+ return {
90
+ ...response,
91
+ headers: {
92
+ ...(response.headers || {}),
93
+ 'Set-Cookie': authCookies.build(
94
+ response.status === 200 ? response.body : undefined,
95
+ { session: !body.remember },
96
+ ),
97
+ },
98
+ body: {
99
+ access_token: response.body.access_token,
100
+ expiration_date: response.body.expiration_date,
101
+ expires_in: response.body.expires_in,
102
+ token_type: response.body.token_type,
103
+ },
104
+ };
105
+ } catch (err) {
106
+ const newErr = YHTTPError.wrap(err as Error);
107
+
108
+ newErr.headers = {
109
+ ...((err as YHTTPError).headers || {}),
110
+ 'Set-Cookie': authCookies.build(),
111
+ };
112
+
113
+ throw newErr;
114
+ }
115
+ };
116
+ }
117
+
118
+ export default location(autoService(initPostAuthLogin), import.meta.url);
@@ -13,7 +13,7 @@ describe('postAuthLogout', () => {
13
13
 
14
14
  authCookies.build.mockReturnValueOnce(['the_build_cookies']);
15
15
 
16
- const response = await postAuthLogout({});
16
+ const response = await postAuthLogout();
17
17
 
18
18
  expect({
19
19
  response,
@@ -1,38 +1,38 @@
1
- import { autoHandler, location } from 'knifecycle';
1
+ import { autoService, location } from 'knifecycle';
2
2
  import { AUTH_API_PREFIX } from '../services/authCookies.js';
3
- import { type WhookAPIHandlerDefinition } from '@whook/whook';
3
+ import { type WhookRouteDefinition } from '@whook/whook';
4
4
  import { type AuthCookiesService } from '../services/authCookies.js';
5
5
 
6
- export const definition: WhookAPIHandlerDefinition = {
6
+ export const definition = {
7
7
  method: 'post',
8
8
  path: `${AUTH_API_PREFIX}/logout`,
9
+ config: {
10
+ environments: [],
11
+ },
9
12
  operation: {
10
13
  operationId: 'postAuthLogout',
11
14
  summary: 'Logs a user out',
12
15
  tags: ['auth'],
13
- 'x-whook': {
14
- disabled: true,
15
- },
16
16
  parameters: [],
17
17
  responses: {
18
18
  204: {
19
- description: 'Successfuly logged out!',
19
+ description: 'Successfully logged out!',
20
20
  },
21
21
  },
22
22
  },
23
- };
23
+ } as const satisfies WhookRouteDefinition;
24
24
 
25
- export default location(autoHandler(postAuthLogout), import.meta.url);
26
-
27
- async function postAuthLogout({
25
+ async function initPostAuthLogout({
28
26
  authCookies,
29
27
  }: {
30
28
  authCookies: Pick<AuthCookiesService, 'build'>;
31
29
  }) {
32
- return {
30
+ return async () => ({
33
31
  status: 204,
34
32
  headers: {
35
33
  'Set-Cookie': authCookies.build(),
36
34
  },
37
- };
35
+ });
38
36
  }
37
+
38
+ export default location(autoService(initPostAuthLogout), import.meta.url);
@@ -2,6 +2,7 @@
2
2
  import { describe, test, jest, expect } from '@jest/globals';
3
3
  import initPostAuthRefresh from './postAuthRefresh.js';
4
4
  import { type AuthCookiesService } from '../services/authCookies.js';
5
+ import { type WhookAuthenticationData } from '@whook/authorization';
5
6
 
6
7
  describe('postAuthRefresh', () => {
7
8
  test('should work', async () => {
@@ -14,7 +15,7 @@ describe('postAuthRefresh', () => {
14
15
  ROOT_AUTHENTICATION_DATA: {
15
16
  scope: 'user',
16
17
  applicationId: 'root_app_id',
17
- },
18
+ } as WhookAuthenticationData,
18
19
  authCookies,
19
20
  postOAuth2Token,
20
21
  });
@@ -0,0 +1,138 @@
1
+ import { autoService, location } from 'knifecycle';
2
+ import { YHTTPError } from 'yhttperror';
3
+ import initPostOauth2Token from './postOAuth2Token.js';
4
+ import { AUTH_API_PREFIX } from '../services/authCookies.js';
5
+ import {
6
+ refersTo,
7
+ type WhookRouteDefinition,
8
+ type WhookAPIParameterDefinition,
9
+ } from '@whook/whook';
10
+ import {
11
+ type AuthCookiesService,
12
+ type AuthHandlersConfig,
13
+ } from '../services/authCookies.js';
14
+
15
+ export const authCookieHeaderParameter = {
16
+ name: 'cookie',
17
+ example: 'access_token=an_access_token; refresh_token=a_refresh_token;',
18
+ parameter: {
19
+ name: 'cookie',
20
+ in: 'header',
21
+ required: false,
22
+ schema: {
23
+ type: 'string',
24
+ },
25
+ },
26
+ } as const satisfies WhookAPIParameterDefinition<string>;
27
+
28
+ export const definition = {
29
+ method: 'post',
30
+ path: `${AUTH_API_PREFIX}/refresh`,
31
+ config: {
32
+ environments: [],
33
+ },
34
+ operation: {
35
+ operationId: 'postAuthRefresh',
36
+ summary: 'Refreshs a user auth',
37
+ tags: ['auth'],
38
+ parameters: [refersTo(authCookieHeaderParameter)],
39
+ requestBody: {
40
+ required: true,
41
+ content: {
42
+ 'application/json': {
43
+ schema: {
44
+ type: 'object',
45
+ required: [],
46
+ properties: {
47
+ scope: { type: 'string' },
48
+ remember: { type: 'boolean' },
49
+ },
50
+ },
51
+ },
52
+ },
53
+ },
54
+ responses: {
55
+ 200: {
56
+ description: 'Successfuly refreshed.',
57
+ content: {
58
+ 'application/json': {
59
+ schema: {
60
+ type: 'object',
61
+ properties: {
62
+ access_token: { type: 'string' },
63
+ expiration_date: { type: 'string' },
64
+ expires_in: { type: 'string' },
65
+ token_type: { type: 'string' },
66
+ },
67
+ },
68
+ },
69
+ },
70
+ },
71
+ },
72
+ },
73
+ } as const satisfies WhookRouteDefinition;
74
+
75
+ export default location(autoService(initPostAuthRefresh), import.meta.url);
76
+
77
+ async function initPostAuthRefresh({
78
+ ROOT_AUTHENTICATION_DATA,
79
+ authCookies,
80
+ postOAuth2Token,
81
+ }: AuthHandlersConfig & {
82
+ authCookies: AuthCookiesService;
83
+ postOAuth2Token: Awaited<ReturnType<typeof initPostOauth2Token>>;
84
+ }) {
85
+ return async ({
86
+ body,
87
+ cookie = '',
88
+ }: {
89
+ body: {
90
+ scope: string;
91
+ remember: boolean;
92
+ };
93
+ cookie?: string;
94
+ }) => {
95
+ const parsedCookies = authCookies.parse(cookie);
96
+
97
+ try {
98
+ if (!parsedCookies.refresh_token) {
99
+ throw new YHTTPError(401, 'E_REFRESH_COOKIE', cookie);
100
+ }
101
+
102
+ const response = await postOAuth2Token({
103
+ body: {
104
+ grant_type: 'refresh_token',
105
+ scope: body.scope,
106
+ refresh_token: parsedCookies.refresh_token,
107
+ },
108
+ authenticationData: ROOT_AUTHENTICATION_DATA,
109
+ });
110
+
111
+ return {
112
+ ...response,
113
+ headers: {
114
+ ...(response.headers || {}),
115
+ 'Set-Cookie': authCookies.build(
116
+ response.status === 200 ? response.body : undefined,
117
+ { session: !body.remember },
118
+ ),
119
+ },
120
+ body: {
121
+ access_token: response.body.access_token,
122
+ expiration_date: response.body.expiration_date,
123
+ expires_in: response.body.expires_in,
124
+ token_type: response.body.token_type,
125
+ },
126
+ };
127
+ } catch (err) {
128
+ const newErr = YHTTPError.wrap(err as Error);
129
+
130
+ newErr.headers = {
131
+ ...((err as YHTTPError).headers || {}),
132
+ 'Set-Cookie': authCookies.build(),
133
+ };
134
+
135
+ throw newErr;
136
+ }
137
+ };
138
+ }