@whook/oauth2 8.3.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 (146) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +384 -0
  3. package/dist/handlers/getOAuth2Authorize.d.ts +26 -0
  4. package/dist/handlers/getOAuth2Authorize.js +192 -0
  5. package/dist/handlers/getOAuth2Authorize.js.map +1 -0
  6. package/dist/handlers/getOAuth2Authorize.mjs +169 -0
  7. package/dist/handlers/getOAuth2Authorize.mjs.map +1 -0
  8. package/dist/handlers/getOAuth2Authorize.test.d.ts +1 -0
  9. package/dist/handlers/getOAuth2Authorize.test.js +122 -0
  10. package/dist/handlers/getOAuth2Authorize.test.js.map +1 -0
  11. package/dist/handlers/getOAuth2Authorize.test.mjs +114 -0
  12. package/dist/handlers/getOAuth2Authorize.test.mjs.map +1 -0
  13. package/dist/handlers/postAuthLogin.d.ts +45 -0
  14. package/dist/handlers/postAuthLogin.js +125 -0
  15. package/dist/handlers/postAuthLogin.js.map +1 -0
  16. package/dist/handlers/postAuthLogin.mjs +108 -0
  17. package/dist/handlers/postAuthLogin.mjs.map +1 -0
  18. package/dist/handlers/postAuthLogin.test.d.ts +1 -0
  19. package/dist/handlers/postAuthLogin.test.js +90 -0
  20. package/dist/handlers/postAuthLogin.test.js.map +1 -0
  21. package/dist/handlers/postAuthLogin.test.mjs +85 -0
  22. package/dist/handlers/postAuthLogin.test.mjs.map +1 -0
  23. package/dist/handlers/postAuthLogout.d.ts +12 -0
  24. package/dist/handlers/postAuthLogout.js +46 -0
  25. package/dist/handlers/postAuthLogout.js.map +1 -0
  26. package/dist/handlers/postAuthLogout.mjs +33 -0
  27. package/dist/handlers/postAuthLogout.mjs.map +1 -0
  28. package/dist/handlers/postAuthLogout.test.d.ts +1 -0
  29. package/dist/handlers/postAuthLogout.test.js +35 -0
  30. package/dist/handlers/postAuthLogout.test.js.map +1 -0
  31. package/dist/handlers/postAuthLogout.test.mjs +30 -0
  32. package/dist/handlers/postAuthLogout.test.mjs.map +1 -0
  33. package/dist/handlers/postAuthRefresh.d.ts +45 -0
  34. package/dist/handlers/postAuthRefresh.js +140 -0
  35. package/dist/handlers/postAuthRefresh.js.map +1 -0
  36. package/dist/handlers/postAuthRefresh.mjs +122 -0
  37. package/dist/handlers/postAuthRefresh.mjs.map +1 -0
  38. package/dist/handlers/postAuthRefresh.test.d.ts +1 -0
  39. package/dist/handlers/postAuthRefresh.test.js +99 -0
  40. package/dist/handlers/postAuthRefresh.test.js.map +1 -0
  41. package/dist/handlers/postAuthRefresh.test.mjs +94 -0
  42. package/dist/handlers/postAuthRefresh.test.mjs.map +1 -0
  43. package/dist/handlers/postOAuth2Acknowledge.d.ts +28 -0
  44. package/dist/handlers/postOAuth2Acknowledge.js +165 -0
  45. package/dist/handlers/postOAuth2Acknowledge.js.map +1 -0
  46. package/dist/handlers/postOAuth2Acknowledge.mjs +150 -0
  47. package/dist/handlers/postOAuth2Acknowledge.mjs.map +1 -0
  48. package/dist/handlers/postOAuth2Acknowledge.test.d.ts +1 -0
  49. package/dist/handlers/postOAuth2Acknowledge.test.js +148 -0
  50. package/dist/handlers/postOAuth2Acknowledge.test.js.map +1 -0
  51. package/dist/handlers/postOAuth2Acknowledge.test.mjs +140 -0
  52. package/dist/handlers/postOAuth2Acknowledge.test.mjs.map +1 -0
  53. package/dist/handlers/postOAuth2Token.d.ts +36 -0
  54. package/dist/handlers/postOAuth2Token.js +263 -0
  55. package/dist/handlers/postOAuth2Token.js.map +1 -0
  56. package/dist/handlers/postOAuth2Token.mjs +242 -0
  57. package/dist/handlers/postOAuth2Token.mjs.map +1 -0
  58. package/dist/handlers/postOAuth2Token.test.d.ts +1 -0
  59. package/dist/handlers/postOAuth2Token.test.js +166 -0
  60. package/dist/handlers/postOAuth2Token.test.js.map +1 -0
  61. package/dist/handlers/postOAuth2Token.test.mjs +160 -0
  62. package/dist/handlers/postOAuth2Token.test.mjs.map +1 -0
  63. package/dist/index.d.ts +17 -0
  64. package/dist/index.js +230 -0
  65. package/dist/index.js.map +1 -0
  66. package/dist/index.mjs +15 -0
  67. package/dist/index.mjs.map +1 -0
  68. package/dist/index.test.d.ts +1 -0
  69. package/dist/index.test.js +759 -0
  70. package/dist/index.test.js.map +1 -0
  71. package/dist/index.test.mjs +748 -0
  72. package/dist/index.test.mjs.map +1 -0
  73. package/dist/services/authCookies.d.ts +26 -0
  74. package/dist/services/authCookies.js +74 -0
  75. package/dist/services/authCookies.js.map +1 -0
  76. package/dist/services/authCookies.mjs +58 -0
  77. package/dist/services/authCookies.mjs.map +1 -0
  78. package/dist/services/authCookies.test.d.ts +1 -0
  79. package/dist/services/authCookies.test.js +82 -0
  80. package/dist/services/authCookies.test.js.map +1 -0
  81. package/dist/services/authCookies.test.mjs +77 -0
  82. package/dist/services/authCookies.test.mjs.map +1 -0
  83. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +17 -0
  84. package/dist/services/oAuth2ClientCredentialsGranter.js +56 -0
  85. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -0
  86. package/dist/services/oAuth2ClientCredentialsGranter.mjs +41 -0
  87. package/dist/services/oAuth2ClientCredentialsGranter.mjs.map +1 -0
  88. package/dist/services/oAuth2CodeGranter.d.ts +17 -0
  89. package/dist/services/oAuth2CodeGranter.js +115 -0
  90. package/dist/services/oAuth2CodeGranter.js.map +1 -0
  91. package/dist/services/oAuth2CodeGranter.mjs +98 -0
  92. package/dist/services/oAuth2CodeGranter.mjs.map +1 -0
  93. package/dist/services/oAuth2CodeGranter.test.d.ts +1 -0
  94. package/dist/services/oAuth2CodeGranter.test.js +86 -0
  95. package/dist/services/oAuth2CodeGranter.test.js.map +1 -0
  96. package/dist/services/oAuth2CodeGranter.test.mjs +81 -0
  97. package/dist/services/oAuth2CodeGranter.test.mjs.map +1 -0
  98. package/dist/services/oAuth2Granters.d.ts +79 -0
  99. package/dist/services/oAuth2Granters.js +140 -0
  100. package/dist/services/oAuth2Granters.js.map +1 -0
  101. package/dist/services/oAuth2Granters.mjs +127 -0
  102. package/dist/services/oAuth2Granters.mjs.map +1 -0
  103. package/dist/services/oAuth2PasswordGranter.d.ts +16 -0
  104. package/dist/services/oAuth2PasswordGranter.js +55 -0
  105. package/dist/services/oAuth2PasswordGranter.js.map +1 -0
  106. package/dist/services/oAuth2PasswordGranter.mjs +40 -0
  107. package/dist/services/oAuth2PasswordGranter.mjs.map +1 -0
  108. package/dist/services/oAuth2RefreshTokenGranter.d.ts +15 -0
  109. package/dist/services/oAuth2RefreshTokenGranter.js +62 -0
  110. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -0
  111. package/dist/services/oAuth2RefreshTokenGranter.mjs +47 -0
  112. package/dist/services/oAuth2RefreshTokenGranter.mjs.map +1 -0
  113. package/dist/services/oAuth2TokenGranter.d.ts +15 -0
  114. package/dist/services/oAuth2TokenGranter.js +92 -0
  115. package/dist/services/oAuth2TokenGranter.js.map +1 -0
  116. package/dist/services/oAuth2TokenGranter.mjs +78 -0
  117. package/dist/services/oAuth2TokenGranter.mjs.map +1 -0
  118. package/package.json +205 -0
  119. package/src/__snapshots__/index.test.ts.snap +396 -0
  120. package/src/handlers/__snapshots__/getOAuth2Authorize.test.ts.snap +38 -0
  121. package/src/handlers/__snapshots__/postOAuth2Acknowledge.test.ts.snap +61 -0
  122. package/src/handlers/__snapshots__/postOAuth2Token.test.ts.snap +52 -0
  123. package/src/handlers/getOAuth2Authorize.test.ts +142 -0
  124. package/src/handlers/getOAuth2Authorize.ts +222 -0
  125. package/src/handlers/postAuthLogin.test.ts +88 -0
  126. package/src/handlers/postAuthLogin.ts +123 -0
  127. package/src/handlers/postAuthLogout.test.ts +33 -0
  128. package/src/handlers/postAuthLogout.ts +38 -0
  129. package/src/handlers/postAuthRefresh.test.ts +97 -0
  130. package/src/handlers/postAuthRefresh.ts +146 -0
  131. package/src/handlers/postOAuth2Acknowledge.test.ts +175 -0
  132. package/src/handlers/postOAuth2Acknowledge.ts +209 -0
  133. package/src/handlers/postOAuth2Token.test.ts +153 -0
  134. package/src/handlers/postOAuth2Token.ts +302 -0
  135. package/src/index.test.ts +936 -0
  136. package/src/index.ts +105 -0
  137. package/src/services/__snapshots__/oAuth2CodeGranter.test.ts.snap +49 -0
  138. package/src/services/authCookies.test.ts +93 -0
  139. package/src/services/authCookies.ts +82 -0
  140. package/src/services/oAuth2ClientCredentialsGranter.ts +76 -0
  141. package/src/services/oAuth2CodeGranter.test.ts +94 -0
  142. package/src/services/oAuth2CodeGranter.ts +133 -0
  143. package/src/services/oAuth2Granters.ts +274 -0
  144. package/src/services/oAuth2PasswordGranter.ts +75 -0
  145. package/src/services/oAuth2RefreshTokenGranter.ts +77 -0
  146. package/src/services/oAuth2TokenGranter.ts +105 -0
package/src/index.ts ADDED
@@ -0,0 +1,105 @@
1
+ import initGetOAuth2Authorize, {
2
+ definition as getOAuth2AuthorizeDefinition,
3
+ responseTypeParameter as getOAuth2AuthorizeResponseTypeParameter,
4
+ clientIdParameter as getOAuth2AuthorizeClientIdParameter,
5
+ redirectURIParameter as getOAuth2AuthorizeRedirectURIParameter,
6
+ scopeParameter as getOAuth2AuthorizeScopeParameter,
7
+ stateParameter as getOAuth2AuthorizeStateParameter,
8
+ } from './handlers/getOAuth2Authorize';
9
+ import initPostOAuth2Acknowledge, {
10
+ definition as postOAuth2AcknowledgeDefinition,
11
+ } from './handlers/postOAuth2Acknowledge';
12
+ import initPostOAuth2Token, {
13
+ definition as postOAuth2TokenDefinition,
14
+ authorizationCodeTokenRequestBodySchema as postOAuth2TokenAuthorizationCodeTokenRequestBodySchema,
15
+ passwordTokenRequestBodySchema as postOAuth2TokenPasswordTokenRequestBodySchema,
16
+ clientCredentialsTokenRequestBodySchema as postOAuth2TokenClientCredentialsTokenRequestBodySchema,
17
+ refreshTokenRequestBodySchema as postOAuth2TokenRefreshTokenRequestBodySchema,
18
+ tokenBodySchema as postOAuth2TokenTokenBodySchema,
19
+ } from './handlers/postOAuth2Token';
20
+ import initOAuth2Granters, {
21
+ OAUTH2_ERRORS_DESCRIPTORS,
22
+ } from './services/oAuth2Granters';
23
+ import initOAuth2ClientCredentialsGranter from './services/oAuth2ClientCredentialsGranter';
24
+ import initOAuth2CodeGranter from './services/oAuth2CodeGranter';
25
+ import initOAuth2PasswordGranter from './services/oAuth2PasswordGranter';
26
+ import initOAuth2RefreshTokenGranter from './services/oAuth2RefreshTokenGranter';
27
+ import initOAuth2TokenGranter from './services/oAuth2TokenGranter';
28
+ import type {
29
+ OAuth2CodeService,
30
+ OAuth2PasswordService,
31
+ OAuth2AccessTokenService,
32
+ OAuth2RefreshTokenService,
33
+ CheckApplicationService,
34
+ OAuth2GranterService,
35
+ OAuth2Options,
36
+ OAuth2Config,
37
+ } from './services/oAuth2Granters';
38
+ import initPostAuthLogin, {
39
+ definition as postAuthLoginDefinition,
40
+ } from './handlers/postAuthLogin';
41
+ import initPostAuthLogout, {
42
+ definition as postAuthLogoutDefinition,
43
+ } from './handlers/postAuthLogout';
44
+ import initPostAuthRefresh, {
45
+ authCookieHeaderParameter,
46
+ definition as postAuthRefreshDefinition,
47
+ } from './handlers/postAuthRefresh';
48
+ import initAuthCookiesService, {
49
+ AUTH_API_PREFIX,
50
+ } from './services/authCookies';
51
+ import type {
52
+ AuthHandlersConfig,
53
+ AuthCookiesService,
54
+ AuthCookiesConfig,
55
+ AuthCookiesData,
56
+ } from './services/authCookies';
57
+
58
+ export type {
59
+ OAuth2CodeService,
60
+ OAuth2PasswordService,
61
+ OAuth2AccessTokenService,
62
+ OAuth2RefreshTokenService,
63
+ CheckApplicationService,
64
+ OAuth2GranterService,
65
+ OAuth2Options,
66
+ OAuth2Config,
67
+ AuthHandlersConfig,
68
+ AuthCookiesService,
69
+ AuthCookiesConfig,
70
+ AuthCookiesData,
71
+ };
72
+ export {
73
+ initGetOAuth2Authorize,
74
+ getOAuth2AuthorizeDefinition,
75
+ getOAuth2AuthorizeResponseTypeParameter,
76
+ getOAuth2AuthorizeClientIdParameter,
77
+ getOAuth2AuthorizeRedirectURIParameter,
78
+ getOAuth2AuthorizeScopeParameter,
79
+ getOAuth2AuthorizeStateParameter,
80
+ initPostOAuth2Acknowledge,
81
+ postOAuth2AcknowledgeDefinition,
82
+ initPostOAuth2Token,
83
+ postOAuth2TokenDefinition,
84
+ postOAuth2TokenAuthorizationCodeTokenRequestBodySchema,
85
+ postOAuth2TokenPasswordTokenRequestBodySchema,
86
+ postOAuth2TokenClientCredentialsTokenRequestBodySchema,
87
+ postOAuth2TokenRefreshTokenRequestBodySchema,
88
+ postOAuth2TokenTokenBodySchema,
89
+ OAUTH2_ERRORS_DESCRIPTORS,
90
+ initOAuth2Granters,
91
+ initOAuth2ClientCredentialsGranter,
92
+ initOAuth2CodeGranter,
93
+ initOAuth2PasswordGranter,
94
+ initOAuth2RefreshTokenGranter,
95
+ initOAuth2TokenGranter,
96
+ AUTH_API_PREFIX,
97
+ authCookieHeaderParameter,
98
+ initPostAuthLogin,
99
+ postAuthLoginDefinition,
100
+ initPostAuthLogout,
101
+ postAuthLogoutDefinition,
102
+ initPostAuthRefresh,
103
+ postAuthRefreshDefinition,
104
+ initAuthCookiesService,
105
+ };
@@ -0,0 +1,49 @@
1
+ // Jest Snapshot v1, https://goo.gl/fbAQLP
2
+
3
+ exports[`OAuth2CodeGranter should work with a complete valid flow 2`] = `
4
+ Object {
5
+ "checkApplicationCalls": Array [
6
+ Array [
7
+ Object {
8
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
9
+ "redirectURI": "https://www.example.com/oauth2/code",
10
+ "scope": "user",
11
+ "type": "code",
12
+ },
13
+ ],
14
+ Array [
15
+ Object {
16
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
17
+ "scope": "",
18
+ "type": "code",
19
+ },
20
+ ],
21
+ ],
22
+ "logCalls": Array [
23
+ Array [
24
+ "debug",
25
+ "👫 - OAuth2CodeGranter Service Initialized!",
26
+ ],
27
+ ],
28
+ "oAuth2CodeCheckCalls": Array [
29
+ Array [
30
+ Object {
31
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
32
+ "scope": "user",
33
+ },
34
+ "yolo",
35
+ "https://www.example.com/oauth2/code",
36
+ ],
37
+ ],
38
+ "oAuth2CodeCreateCalls": Array [
39
+ Array [
40
+ Object {
41
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
42
+ "scope": "user",
43
+ },
44
+ "https://www.example.com/oauth2/code",
45
+ Object {},
46
+ ],
47
+ ],
48
+ }
49
+ `;
@@ -0,0 +1,93 @@
1
+ import initAuthCookies from './authCookies';
2
+ import type { AuthCookiesConfig } from './authCookies';
3
+
4
+ describe('authCookies', () => {
5
+ describe('.build()', () => {
6
+ test('should work with new auth data', async () => {
7
+ const ENV = {};
8
+ const COOKIES: AuthCookiesConfig['COOKIES'] = {
9
+ domain: 'api.example.com',
10
+ };
11
+
12
+ const authCookies = await initAuthCookies({
13
+ ENV,
14
+ COOKIES,
15
+ });
16
+
17
+ const result = await authCookies.build({
18
+ access_token: 'a_access_token',
19
+ refresh_token: 'a_refresh_token',
20
+ });
21
+
22
+ expect(result).toMatchInlineSnapshot(`
23
+ Array [
24
+ "access_token=a_access_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict",
25
+ "refresh_token=a_refresh_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict",
26
+ ]
27
+ `);
28
+ });
29
+
30
+ test('should allow to reset auth data', async () => {
31
+ const ENV = {};
32
+ const COOKIES: AuthCookiesConfig['COOKIES'] = {
33
+ domain: 'api.example.com',
34
+ };
35
+
36
+ const authCookies = await initAuthCookies({
37
+ ENV,
38
+ COOKIES,
39
+ });
40
+
41
+ const result = await authCookies.build({
42
+ access_token: '',
43
+ refresh_token: '',
44
+ });
45
+
46
+ expect(result).toMatchInlineSnapshot(`
47
+ Array [
48
+ "access_token=; Max-Age=0; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict",
49
+ "refresh_token=; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict",
50
+ ]
51
+ `);
52
+ });
53
+ });
54
+ describe('.parse()', () => {
55
+ test('should work with no cookies', async () => {
56
+ const ENV = {};
57
+ const COOKIES: AuthCookiesConfig['COOKIES'] = {
58
+ domain: 'api.example.com',
59
+ };
60
+
61
+ const authCookies = await initAuthCookies({
62
+ ENV,
63
+ COOKIES,
64
+ });
65
+
66
+ const result = await authCookies.parse('');
67
+
68
+ expect(result).toMatchInlineSnapshot(`Object {}`);
69
+ });
70
+ test('should work with cookies', async () => {
71
+ const ENV = {};
72
+ const COOKIES: AuthCookiesConfig['COOKIES'] = {
73
+ domain: 'api.example.com',
74
+ };
75
+
76
+ const authCookies = await initAuthCookies({
77
+ ENV,
78
+ COOKIES,
79
+ });
80
+
81
+ const result = await authCookies.parse(
82
+ 'access_token=a_access_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict; refresh_token=a_refresh_token; Domain=api.example.com; Path=/auth; HttpOnly; Secure; SameSite=Strict',
83
+ );
84
+
85
+ expect(result).toMatchInlineSnapshot(`
86
+ Object {
87
+ "access_token": "a_access_token",
88
+ "refresh_token": "a_refresh_token",
89
+ }
90
+ `);
91
+ });
92
+ });
93
+ });
@@ -0,0 +1,82 @@
1
+ import ms from 'ms';
2
+ import cookie from 'cookie';
3
+ import { autoService } from 'knifecycle';
4
+ import type { BaseAuthenticationData } from '@whook/authorization';
5
+
6
+ export const AUTH_API_PREFIX = '/auth';
7
+
8
+ export type AuthHandlersConfig<
9
+ AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
10
+ > = {
11
+ ROOT_AUTHENTICATION_DATA: AUTHENTICATION_DATA;
12
+ };
13
+
14
+ export type AuthCookiesConfig = {
15
+ ENV?: {
16
+ DEV_MODE?: string;
17
+ };
18
+ COOKIES: {
19
+ domain: string;
20
+ };
21
+ BASE_PATH?: string;
22
+ };
23
+
24
+ export type AuthCookiesData = {
25
+ refresh_token: string;
26
+ access_token: string;
27
+ };
28
+
29
+ export type AuthCookiesService = {
30
+ build: (
31
+ data?: Partial<AuthCookiesData>,
32
+ options?: { session: boolean },
33
+ ) => string[];
34
+ parse: (content: string) => Partial<AuthCookiesData>;
35
+ };
36
+
37
+ export default autoService(initAuthCookies);
38
+
39
+ async function initAuthCookies({
40
+ ENV = {},
41
+ COOKIES,
42
+ BASE_PATH = '',
43
+ }: AuthCookiesConfig): Promise<AuthCookiesService> {
44
+ function build(data: Partial<AuthCookiesData> = {}, { session = true } = {}) {
45
+ return [
46
+ cookie.serialize('access_token', data.access_token || '', {
47
+ path: BASE_PATH + AUTH_API_PREFIX,
48
+ httpOnly: true,
49
+ domain: ENV.DEV_MODE ? undefined : COOKIES.domain,
50
+ secure: !ENV.DEV_MODE,
51
+ ...(ENV.DEV_MODE ? {} : { sameSite: true }),
52
+ ...(data.access_token ? {} : { maxAge: 0 }),
53
+ }),
54
+ cookie.serialize('refresh_token', data.refresh_token || '', {
55
+ path: BASE_PATH + AUTH_API_PREFIX,
56
+ httpOnly: true,
57
+ domain: ENV.DEV_MODE ? undefined : COOKIES.domain,
58
+ secure: !ENV.DEV_MODE,
59
+ ...(ENV.DEV_MODE ? {} : { sameSite: true }),
60
+ ...(session ? {} : { maxAge: Math.round(ms('100y') / 1000) }),
61
+ }),
62
+ ];
63
+ }
64
+
65
+ function parse(cookieHeader: string): Partial<AuthCookiesData> {
66
+ const data = cookie.parse(cookieHeader);
67
+
68
+ if (data.access_token && data.refresh_token) {
69
+ return {
70
+ access_token: data.access_token,
71
+ refresh_token: data.refresh_token,
72
+ };
73
+ }
74
+
75
+ return {};
76
+ }
77
+
78
+ return {
79
+ build,
80
+ parse,
81
+ };
82
+ }
@@ -0,0 +1,76 @@
1
+ import { autoService } from 'knifecycle';
2
+ import { noop } from '@whook/whook';
3
+ import YError from 'yerror';
4
+ import type { LogService } from 'common-services';
5
+ import type {
6
+ OAuth2GranterService,
7
+ CheckApplicationService,
8
+ } from './oAuth2Granters';
9
+ import type { BaseAuthenticationData } from '@whook/authorization';
10
+ import type { OAuth2Options } from '..';
11
+
12
+ export type OAuth2ClientCredentialsGranterDependencies = {
13
+ OAUTH2: OAuth2Options;
14
+ checkApplication: CheckApplicationService;
15
+ log?: LogService;
16
+ };
17
+ export type OAuth2ClientCredentialsGranterParameters<
18
+ AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
19
+ > = {
20
+ username: string;
21
+ password: string;
22
+ scope?: AUTHENTICATION_DATA['scope'];
23
+ };
24
+ export type OAuth2ClientCredentialsGranterService<
25
+ AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
26
+ > = OAuth2GranterService<
27
+ Record<string, unknown>,
28
+ Record<string, unknown>,
29
+ OAuth2ClientCredentialsGranterParameters,
30
+ AUTHENTICATION_DATA
31
+ >;
32
+
33
+ export default autoService(initOAuth2ClientCredentialsGranter);
34
+
35
+ // Client Credentials Grant
36
+ // https://tools.ietf.org/html/rfc6749#section-4.4
37
+ async function initOAuth2ClientCredentialsGranter({
38
+ OAUTH2,
39
+ checkApplication,
40
+ log = noop,
41
+ }: OAuth2ClientCredentialsGranterDependencies): Promise<OAuth2ClientCredentialsGranterService> {
42
+ const authenticateWithClientCredentials: OAuth2ClientCredentialsGranterService['authenticator']['authenticate'] =
43
+ async ({ scope: demandedScope = '' }, authenticationData) => {
44
+ // The client must be authenticated
45
+ if (!authenticationData) {
46
+ throw new YError('E_UNAUTHORIZED');
47
+ }
48
+
49
+ // Checking the scope and availability of the demanded
50
+ // grant type
51
+ await checkApplication({
52
+ applicationId: authenticationData.applicationId,
53
+ type: 'client_credentials',
54
+ scope: demandedScope,
55
+ });
56
+
57
+ return {
58
+ ...authenticationData,
59
+ scope: demandedScope
60
+ ? demandedScope
61
+ : OAUTH2.defaultToClientScope
62
+ ? authenticationData.scope
63
+ : '',
64
+ };
65
+ };
66
+
67
+ log('debug', '👫 - OAuth2ClientCredentialsGranter Service Initialized!');
68
+
69
+ return {
70
+ type: 'client_credentials',
71
+ authenticator: {
72
+ grantType: 'client_credentials',
73
+ authenticate: authenticateWithClientCredentials,
74
+ },
75
+ };
76
+ }
@@ -0,0 +1,94 @@
1
+ import initOAuth2CodeGranter from './oAuth2CodeGranter';
2
+
3
+ describe('OAuth2CodeGranter', () => {
4
+ const oAuth2Code = {
5
+ create: jest.fn(),
6
+ check: jest.fn(),
7
+ };
8
+ const checkApplication = jest.fn();
9
+ const log = jest.fn();
10
+
11
+ beforeEach(() => {
12
+ oAuth2Code.create.mockReset();
13
+ oAuth2Code.check.mockReset();
14
+ checkApplication.mockReset();
15
+ log.mockReset();
16
+ });
17
+
18
+ it('should work with a complete valid flow', async () => {
19
+ const oAuth2CodeGranter = await initOAuth2CodeGranter({
20
+ checkApplication,
21
+ oAuth2Code,
22
+ log,
23
+ });
24
+
25
+ checkApplication.mockResolvedValue({
26
+ redirectURI: 'https://www.example.com',
27
+ });
28
+ oAuth2Code.create.mockResolvedValueOnce('yolo');
29
+ oAuth2Code.check.mockResolvedValueOnce({
30
+ applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
31
+ scope: 'user',
32
+ });
33
+
34
+ const authorizerResult = await oAuth2CodeGranter.authorizer.authorize({
35
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
36
+ redirectURI: 'https://www.example.com/oauth2/code',
37
+ scope: 'user',
38
+ });
39
+ const acknowledgerResult = await oAuth2CodeGranter.acknowledger.acknowledge(
40
+ {
41
+ applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
42
+ scope: 'user, admin',
43
+ },
44
+ {
45
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
46
+ redirectURI: 'https://www.example.com/oauth2/code',
47
+ scope: 'user',
48
+ },
49
+ {},
50
+ );
51
+ const authenticatorResult =
52
+ await oAuth2CodeGranter.authenticator.authenticate(
53
+ {
54
+ clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
55
+ redirectURI: 'https://www.example.com/oauth2/code',
56
+ code: 'yolo',
57
+ },
58
+ {
59
+ applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
60
+ scope: 'user',
61
+ },
62
+ );
63
+
64
+ expect({
65
+ authorizerResult,
66
+ acknowledgerResult,
67
+ authenticatorResult,
68
+ }).toMatchInlineSnapshot(`
69
+ Object {
70
+ "acknowledgerResult": Object {
71
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
72
+ "code": "yolo",
73
+ "redirectURI": "https://www.example.com/oauth2/code",
74
+ "scope": "user",
75
+ },
76
+ "authenticatorResult": Object {
77
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
78
+ "scope": "user",
79
+ },
80
+ "authorizerResult": Object {
81
+ "applicationId": "abbacaca-abba-caca-abba-cacaabbacaca",
82
+ "redirectURI": "https://www.example.com",
83
+ "scope": "user",
84
+ },
85
+ }
86
+ `);
87
+ expect({
88
+ oAuth2CodeCreateCalls: oAuth2Code.create.mock.calls,
89
+ oAuth2CodeCheckCalls: oAuth2Code.check.mock.calls,
90
+ checkApplicationCalls: checkApplication.mock.calls,
91
+ logCalls: log.mock.calls,
92
+ }).toMatchSnapshot();
93
+ });
94
+ });
@@ -0,0 +1,133 @@
1
+ import { autoService } from 'knifecycle';
2
+ import { noop } from '@whook/whook';
3
+ import YError from 'yerror';
4
+ import type { LogService } from 'common-services';
5
+ import type {
6
+ OAuth2GranterService,
7
+ OAuth2CodeService,
8
+ CheckApplicationService,
9
+ } from './oAuth2Granters';
10
+ import type { BaseAuthenticationData } from '@whook/authorization';
11
+
12
+ export const CODE_GRANTER_TYPE = 'code';
13
+
14
+ export type OAuth2CodeGranterDependencies = {
15
+ oAuth2Code: OAuth2CodeService;
16
+ checkApplication: CheckApplicationService;
17
+ log?: LogService;
18
+ };
19
+ export type OAuth2CodeGranterParameters = {
20
+ code: string;
21
+ redirectURI: string;
22
+ clientId: string;
23
+ };
24
+ export type OAuth2CodeGranterService<
25
+ AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,
26
+ > = OAuth2GranterService<
27
+ Record<string, unknown>,
28
+ Record<string, unknown>,
29
+ OAuth2CodeGranterParameters,
30
+ AUTHENTICATION_DATA
31
+ >;
32
+
33
+ export default autoService(initOAuth2CodeGranter);
34
+
35
+ // Authorization Code Grant
36
+ // https://tools.ietf.org/html/rfc6749#section-4.1
37
+ async function initOAuth2CodeGranter({
38
+ oAuth2Code,
39
+ checkApplication,
40
+ log = noop,
41
+ }: OAuth2CodeGranterDependencies): Promise<OAuth2CodeGranterService> {
42
+ const authorizeWithCode: OAuth2CodeGranterService['authorizer']['authorize'] =
43
+ async ({ clientId, redirectURI, scope = '' }) => {
44
+ const { redirectURI: finalRedirectURI } = await checkApplication({
45
+ applicationId: clientId,
46
+ type: CODE_GRANTER_TYPE,
47
+ redirectURI,
48
+ scope,
49
+ });
50
+
51
+ return {
52
+ applicationId: clientId,
53
+ redirectURI: finalRedirectURI,
54
+ scope,
55
+ };
56
+ };
57
+
58
+ // Authorization Code Response:
59
+ // https://tools.ietf.org/html/rfc6749#section-4.1.2
60
+ const acknowledgeWithCode: OAuth2CodeGranterService['acknowledger']['acknowledge'] =
61
+ async (
62
+ authenticationData,
63
+ { clientId, redirectURI, scope },
64
+ additionalParameters,
65
+ ) => {
66
+ const code = await oAuth2Code.create(
67
+ { ...authenticationData, applicationId: clientId, scope },
68
+ redirectURI,
69
+ additionalParameters,
70
+ );
71
+
72
+ return {
73
+ applicationId: clientId,
74
+ redirectURI,
75
+ scope,
76
+ code,
77
+ };
78
+ };
79
+
80
+ const authenticateWithCode: OAuth2CodeGranterService['authenticator']['authenticate'] =
81
+ async ({ code, clientId, redirectURI }, authenticationData) => {
82
+ // The client must be authenticated (for now, see below)
83
+ if (!authenticationData) {
84
+ throw new YError('E_UNAUTHORIZED');
85
+ }
86
+
87
+ // This check is not really necessary atm but it acts
88
+ // as a reminder that this grant type could be used
89
+ // without authenticating the client. In this
90
+ // scenario, the authenticationData should be deducted
91
+ // from the clientId and the code given in parameters
92
+ // See https://tools.ietf.org/html/rfc6749#section-4.1.3
93
+ if (clientId && clientId !== authenticationData.applicationId) {
94
+ throw new YError(
95
+ 'E_UNAUTHORIZED',
96
+ clientId,
97
+ authenticationData.applicationId,
98
+ );
99
+ }
100
+
101
+ await checkApplication({
102
+ applicationId: authenticationData.applicationId,
103
+ type: CODE_GRANTER_TYPE,
104
+ scope: '',
105
+ });
106
+
107
+ const newAuthenticationData = await oAuth2Code.check(
108
+ authenticationData,
109
+ code,
110
+ redirectURI,
111
+ );
112
+
113
+ return newAuthenticationData;
114
+ };
115
+
116
+ log('debug', '👫 - OAuth2CodeGranter Service Initialized!');
117
+
118
+ return {
119
+ type: CODE_GRANTER_TYPE,
120
+ authorizer: {
121
+ responseType: 'code',
122
+ authorize: authorizeWithCode,
123
+ },
124
+ acknowledger: {
125
+ acknowledgmentType: 'code',
126
+ acknowledge: acknowledgeWithCode,
127
+ },
128
+ authenticator: {
129
+ grantType: 'authorization_code',
130
+ authenticate: authenticateWithCode,
131
+ },
132
+ };
133
+ }