@whook/oauth2 8.5.1 → 10.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 (133) hide show
  1. package/README.md +106 -70
  2. package/dist/handlers/getOAuth2Authorize.d.ts +8 -6
  3. package/dist/handlers/getOAuth2Authorize.js +122 -165
  4. package/dist/handlers/getOAuth2Authorize.js.map +1 -1
  5. package/dist/handlers/getOAuth2Authorize.test.js +117 -103
  6. package/dist/handlers/getOAuth2Authorize.test.js.map +1 -1
  7. package/dist/handlers/postAuthLogin.d.ts +3 -3
  8. package/dist/handlers/postAuthLogin.js +83 -120
  9. package/dist/handlers/postAuthLogin.js.map +1 -1
  10. package/dist/handlers/postAuthLogin.test.js +42 -44
  11. package/dist/handlers/postAuthLogin.test.js.map +1 -1
  12. package/dist/handlers/postAuthLogout.d.ts +1 -1
  13. package/dist/handlers/postAuthLogout.js +26 -42
  14. package/dist/handlers/postAuthLogout.js.map +1 -1
  15. package/dist/handlers/postAuthLogout.test.js +19 -21
  16. package/dist/handlers/postAuthLogout.test.js.map +1 -1
  17. package/dist/handlers/postAuthRefresh.d.ts +4 -4
  18. package/dist/handlers/postAuthRefresh.js +93 -131
  19. package/dist/handlers/postAuthRefresh.js.map +1 -1
  20. package/dist/handlers/postAuthRefresh.test.js +47 -49
  21. package/dist/handlers/postAuthRefresh.test.js.map +1 -1
  22. package/dist/handlers/postOAuth2Acknowledge.d.ts +11 -8
  23. package/dist/handlers/postOAuth2Acknowledge.js +119 -151
  24. package/dist/handlers/postOAuth2Acknowledge.js.map +1 -1
  25. package/dist/handlers/postOAuth2Acknowledge.test.js +139 -125
  26. package/dist/handlers/postOAuth2Acknowledge.test.js.map +1 -1
  27. package/dist/handlers/postOAuth2Token.d.ts +4 -4
  28. package/dist/handlers/postOAuth2Token.js +200 -232
  29. package/dist/handlers/postOAuth2Token.js.map +1 -1
  30. package/dist/handlers/postOAuth2Token.test.js +156 -153
  31. package/dist/handlers/postOAuth2Token.test.js.map +1 -1
  32. package/dist/index.d.ts +16 -16
  33. package/dist/index.js +14 -229
  34. package/dist/index.js.map +1 -1
  35. package/dist/index.test.js +697 -620
  36. package/dist/index.test.js.map +1 -1
  37. package/dist/services/authCookies.d.ts +8 -4
  38. package/dist/services/authCookies.js +40 -71
  39. package/dist/services/authCookies.js.map +1 -1
  40. package/dist/services/authCookies.test.js +57 -62
  41. package/dist/services/authCookies.test.js.map +1 -1
  42. package/dist/services/oAuth2ClientCredentialsGranter.d.ts +2 -2
  43. package/dist/services/oAuth2ClientCredentialsGranter.js +34 -52
  44. package/dist/services/oAuth2ClientCredentialsGranter.js.map +1 -1
  45. package/dist/services/oAuth2CodeGranter.d.ts +1 -1
  46. package/dist/services/oAuth2CodeGranter.js +66 -109
  47. package/dist/services/oAuth2CodeGranter.js.map +1 -1
  48. package/dist/services/oAuth2CodeGranter.test.js +65 -64
  49. package/dist/services/oAuth2CodeGranter.test.js.map +1 -1
  50. package/dist/services/oAuth2Granters.d.ts +22 -19
  51. package/dist/services/oAuth2Granters.js +131 -138
  52. package/dist/services/oAuth2Granters.js.map +1 -1
  53. package/dist/services/oAuth2PasswordGranter.d.ts +1 -1
  54. package/dist/services/oAuth2PasswordGranter.js +27 -52
  55. package/dist/services/oAuth2PasswordGranter.js.map +1 -1
  56. package/dist/services/oAuth2RefreshTokenGranter.d.ts +1 -1
  57. package/dist/services/oAuth2RefreshTokenGranter.js +34 -58
  58. package/dist/services/oAuth2RefreshTokenGranter.js.map +1 -1
  59. package/dist/services/oAuth2TokenGranter.d.ts +1 -1
  60. package/dist/services/oAuth2TokenGranter.js +50 -86
  61. package/dist/services/oAuth2TokenGranter.js.map +1 -1
  62. package/package.json +54 -96
  63. package/src/__snapshots__/index.test.ts.snap +23 -22
  64. package/src/handlers/__snapshots__/postOAuth2Acknowledge.test.ts.snap +1 -1
  65. package/src/handlers/getOAuth2Authorize.test.ts +49 -13
  66. package/src/handlers/getOAuth2Authorize.ts +17 -16
  67. package/src/handlers/postAuthLogin.test.ts +9 -5
  68. package/src/handlers/postAuthLogin.ts +8 -7
  69. package/src/handlers/postAuthLogout.test.ts +8 -4
  70. package/src/handlers/postAuthLogout.ts +2 -2
  71. package/src/handlers/postAuthRefresh.test.ts +10 -6
  72. package/src/handlers/postAuthRefresh.ts +8 -7
  73. package/src/handlers/postOAuth2Acknowledge.test.ts +83 -35
  74. package/src/handlers/postOAuth2Acknowledge.ts +48 -30
  75. package/src/handlers/postOAuth2Token.test.ts +79 -19
  76. package/src/handlers/postOAuth2Token.ts +7 -7
  77. package/src/index.test.ts +116 -72
  78. package/src/index.ts +21 -19
  79. package/src/services/authCookies.test.ts +2 -2
  80. package/src/services/authCookies.ts +10 -5
  81. package/src/services/oAuth2ClientCredentialsGranter.ts +28 -24
  82. package/src/services/oAuth2CodeGranter.test.ts +42 -18
  83. package/src/services/oAuth2CodeGranter.ts +68 -62
  84. package/src/services/oAuth2Granters.ts +59 -29
  85. package/src/services/oAuth2PasswordGranter.ts +25 -24
  86. package/src/services/oAuth2RefreshTokenGranter.ts +30 -26
  87. package/src/services/oAuth2TokenGranter.ts +45 -43
  88. package/dist/handlers/getOAuth2Authorize.mjs +0 -160
  89. package/dist/handlers/getOAuth2Authorize.mjs.map +0 -1
  90. package/dist/handlers/getOAuth2Authorize.test.mjs +0 -114
  91. package/dist/handlers/getOAuth2Authorize.test.mjs.map +0 -1
  92. package/dist/handlers/postAuthLogin.mjs +0 -108
  93. package/dist/handlers/postAuthLogin.mjs.map +0 -1
  94. package/dist/handlers/postAuthLogin.test.mjs +0 -85
  95. package/dist/handlers/postAuthLogin.test.mjs.map +0 -1
  96. package/dist/handlers/postAuthLogout.mjs +0 -33
  97. package/dist/handlers/postAuthLogout.mjs.map +0 -1
  98. package/dist/handlers/postAuthLogout.test.mjs +0 -30
  99. package/dist/handlers/postAuthLogout.test.mjs.map +0 -1
  100. package/dist/handlers/postAuthRefresh.mjs +0 -121
  101. package/dist/handlers/postAuthRefresh.mjs.map +0 -1
  102. package/dist/handlers/postAuthRefresh.test.mjs +0 -94
  103. package/dist/handlers/postAuthRefresh.test.mjs.map +0 -1
  104. package/dist/handlers/postOAuth2Acknowledge.mjs +0 -150
  105. package/dist/handlers/postOAuth2Acknowledge.mjs.map +0 -1
  106. package/dist/handlers/postOAuth2Acknowledge.test.mjs +0 -140
  107. package/dist/handlers/postOAuth2Acknowledge.test.mjs.map +0 -1
  108. package/dist/handlers/postOAuth2Token.mjs +0 -231
  109. package/dist/handlers/postOAuth2Token.mjs.map +0 -1
  110. package/dist/handlers/postOAuth2Token.test.mjs +0 -160
  111. package/dist/handlers/postOAuth2Token.test.mjs.map +0 -1
  112. package/dist/index.mjs +0 -15
  113. package/dist/index.mjs.map +0 -1
  114. package/dist/index.test.mjs +0 -748
  115. package/dist/index.test.mjs.map +0 -1
  116. package/dist/services/authCookies.mjs +0 -58
  117. package/dist/services/authCookies.mjs.map +0 -1
  118. package/dist/services/authCookies.test.mjs +0 -77
  119. package/dist/services/authCookies.test.mjs.map +0 -1
  120. package/dist/services/oAuth2ClientCredentialsGranter.mjs +0 -41
  121. package/dist/services/oAuth2ClientCredentialsGranter.mjs.map +0 -1
  122. package/dist/services/oAuth2CodeGranter.mjs +0 -98
  123. package/dist/services/oAuth2CodeGranter.mjs.map +0 -1
  124. package/dist/services/oAuth2CodeGranter.test.mjs +0 -81
  125. package/dist/services/oAuth2CodeGranter.test.mjs.map +0 -1
  126. package/dist/services/oAuth2Granters.mjs +0 -127
  127. package/dist/services/oAuth2Granters.mjs.map +0 -1
  128. package/dist/services/oAuth2PasswordGranter.mjs +0 -40
  129. package/dist/services/oAuth2PasswordGranter.mjs.map +0 -1
  130. package/dist/services/oAuth2RefreshTokenGranter.mjs +0 -47
  131. package/dist/services/oAuth2RefreshTokenGranter.mjs.map +0 -1
  132. package/dist/services/oAuth2TokenGranter.mjs +0 -78
  133. package/dist/services/oAuth2TokenGranter.mjs.map +0 -1
@@ -1,33 +0,0 @@
1
- import { handler as _handler } from 'knifecycle';
2
- import { AUTH_API_PREFIX } from '../services/authCookies';
3
- export const definition = {
4
- method: 'post',
5
- path: `${AUTH_API_PREFIX}/logout`,
6
- operation: {
7
- operationId: 'postAuthLogout',
8
- summary: 'Logs a user out',
9
- tags: ['auth'],
10
- 'x-whook': {
11
- disabled: true
12
- },
13
- parameters: [],
14
- responses: {
15
- 204: {
16
- description: 'Successfuly logged out!'
17
- }
18
- }
19
- }
20
- };
21
- export default _handler(postAuthLogout, "postAuthLogout", ["authCookies"]);
22
-
23
- async function postAuthLogout({
24
- authCookies
25
- }) {
26
- return {
27
- status: 204,
28
- headers: {
29
- 'Set-Cookie': authCookies.build()
30
- }
31
- };
32
- }
33
- //# sourceMappingURL=postAuthLogout.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/handlers/postAuthLogout.ts"],"names":["autoHandler","AUTH_API_PREFIX","definition","method","path","operation","operationId","summary","tags","disabled","parameters","responses","description","postAuthLogout","authCookies","status","headers","build"],"mappings":"AAAA,SAASA,OAAW,IAAXA,QAAT,QAA4B,YAA5B;AACA,SAASC,eAAT,QAAgC,yBAAhC;AAIA,OAAO,MAAMC,UAAqC,GAAG;AACnDC,EAAAA,MAAM,EAAE,MAD2C;AAEnDC,EAAAA,IAAI,EAAG,GAAEH,eAAgB,SAF0B;AAGnDI,EAAAA,SAAS,EAAE;AACTC,IAAAA,WAAW,EAAE,gBADJ;AAETC,IAAAA,OAAO,EAAE,iBAFA;AAGTC,IAAAA,IAAI,EAAE,CAAC,MAAD,CAHG;AAIT,eAAW;AACTC,MAAAA,QAAQ,EAAE;AADD,KAJF;AAOTC,IAAAA,UAAU,EAAE,EAPH;AAQTC,IAAAA,SAAS,EAAE;AACT,WAAK;AACHC,QAAAA,WAAW,EAAE;AADV;AADI;AARF;AAHwC,CAA9C;AAmBP,eAAeZ,QAAW,CAACa,cAAD,oCAA1B;;AAEA,eAAeA,cAAf,CAA8B;AAC5BC,EAAAA;AAD4B,CAA9B,EAIG;AACD,SAAO;AACLC,IAAAA,MAAM,EAAE,GADH;AAELC,IAAAA,OAAO,EAAE;AACP,oBAAcF,WAAW,CAACG,KAAZ;AADP;AAFJ,GAAP;AAMD","sourcesContent":["import { autoHandler } from 'knifecycle';\nimport { AUTH_API_PREFIX } from '../services/authCookies';\nimport type { WhookAPIHandlerDefinition } from '@whook/whook';\nimport type { AuthCookiesService } from '../services/authCookies';\n\nexport const definition: WhookAPIHandlerDefinition = {\n method: 'post',\n path: `${AUTH_API_PREFIX}/logout`,\n operation: {\n operationId: 'postAuthLogout',\n summary: 'Logs a user out',\n tags: ['auth'],\n 'x-whook': {\n disabled: true,\n },\n parameters: [],\n responses: {\n 204: {\n description: 'Successfuly logged out!',\n },\n },\n },\n};\n\nexport default autoHandler(postAuthLogout);\n\nasync function postAuthLogout({\n authCookies,\n}: {\n authCookies: Pick<AuthCookiesService, 'build'>;\n}) {\n return {\n status: 204,\n headers: {\n 'Set-Cookie': authCookies.build(),\n },\n };\n}\n"],"file":"postAuthLogout.mjs"}
@@ -1,30 +0,0 @@
1
- import initPostAuthLogout from './postAuthLogout';
2
- describe('postAuthLogout', () => {
3
- test('should work', async () => {
4
- const authCookies = {
5
- build: jest.fn()
6
- };
7
- const postAuthLogout = await initPostAuthLogout({
8
- authCookies
9
- });
10
- authCookies.build.mockReturnValueOnce('the_build_cookies');
11
- const response = await postAuthLogout({});
12
- expect({
13
- response,
14
- authCookiesBuildCalls: authCookies.build.mock.calls
15
- }).toMatchInlineSnapshot(`
16
- Object {
17
- "authCookiesBuildCalls": Array [
18
- Array [],
19
- ],
20
- "response": Object {
21
- "headers": Object {
22
- "Set-Cookie": "the_build_cookies",
23
- },
24
- "status": 204,
25
- },
26
- }
27
- `);
28
- });
29
- });
30
- //# sourceMappingURL=postAuthLogout.test.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/handlers/postAuthLogout.test.ts"],"names":["initPostAuthLogout","describe","test","authCookies","build","jest","fn","postAuthLogout","mockReturnValueOnce","response","expect","authCookiesBuildCalls","mock","calls","toMatchInlineSnapshot"],"mappings":"AAAA,OAAOA,kBAAP,MAA+B,kBAA/B;AAEAC,QAAQ,CAAC,gBAAD,EAAmB,MAAM;AAC/BC,EAAAA,IAAI,CAAC,aAAD,EAAgB,YAAY;AAC9B,UAAMC,WAAW,GAAG;AAClBC,MAAAA,KAAK,EAAEC,IAAI,CAACC,EAAL;AADW,KAApB;AAGA,UAAMC,cAAc,GAAG,MAAMP,kBAAkB,CAAC;AAC9CG,MAAAA;AAD8C,KAAD,CAA/C;AAIAA,IAAAA,WAAW,CAACC,KAAZ,CAAkBI,mBAAlB,CAAsC,mBAAtC;AAEA,UAAMC,QAAQ,GAAG,MAAMF,cAAc,CAAC,EAAD,CAArC;AAEAG,IAAAA,MAAM,CAAC;AACLD,MAAAA,QADK;AAELE,MAAAA,qBAAqB,EAAER,WAAW,CAACC,KAAZ,CAAkBQ,IAAlB,CAAuBC;AAFzC,KAAD,CAAN,CAGGC,qBAHH,CAG0B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAfI;AAgBD,GA5BG,CAAJ;AA6BD,CA9BO,CAAR","sourcesContent":["import initPostAuthLogout from './postAuthLogout';\n\ndescribe('postAuthLogout', () => {\n test('should work', async () => {\n const authCookies = {\n build: jest.fn(),\n };\n const postAuthLogout = await initPostAuthLogout({\n authCookies,\n });\n\n authCookies.build.mockReturnValueOnce('the_build_cookies');\n\n const response = await postAuthLogout({});\n\n expect({\n response,\n authCookiesBuildCalls: authCookies.build.mock.calls,\n }).toMatchInlineSnapshot(`\n Object {\n \"authCookiesBuildCalls\": Array [\n Array [],\n ],\n \"response\": Object {\n \"headers\": Object {\n \"Set-Cookie\": \"the_build_cookies\",\n },\n \"status\": 204,\n },\n }\n `);\n });\n});\n"],"file":"postAuthLogout.test.mjs"}
@@ -1,121 +0,0 @@
1
- import { handler as _handler } from 'knifecycle';
2
- import YHTTPError from 'yhttperror';
3
- import { refersTo } from '@whook/whook';
4
- import { AUTH_API_PREFIX } from '../services/authCookies';
5
- export const authCookieHeaderParameter = {
6
- name: 'cookie',
7
- example: 'access_token=an_access_token; refresh_token=a_refresh_token;',
8
- parameter: {
9
- name: 'cookie',
10
- in: 'header',
11
- required: false,
12
- schema: {
13
- type: 'string'
14
- }
15
- }
16
- };
17
- export const definition = {
18
- method: 'post',
19
- path: `${AUTH_API_PREFIX}/refresh`,
20
- operation: {
21
- operationId: 'postAuthRefresh',
22
- summary: 'Refreshs a user auth',
23
- tags: ['auth'],
24
- 'x-whook': {
25
- disabled: true
26
- },
27
- parameters: [refersTo(authCookieHeaderParameter)],
28
- requestBody: {
29
- required: true,
30
- content: {
31
- 'application/json': {
32
- schema: {
33
- type: 'object',
34
- required: [],
35
- properties: {
36
- scope: {
37
- type: 'string'
38
- },
39
- remember: {
40
- type: 'boolean'
41
- }
42
- }
43
- }
44
- }
45
- }
46
- },
47
- responses: {
48
- 200: {
49
- description: 'Successfuly refreshed.',
50
- content: {
51
- 'application/json': {
52
- schema: {
53
- type: 'object',
54
- properties: {
55
- access_token: {
56
- type: 'string'
57
- },
58
- expiration_date: {
59
- type: 'string'
60
- },
61
- expires_in: {
62
- type: 'string'
63
- },
64
- token_type: {
65
- type: 'string'
66
- }
67
- }
68
- }
69
- }
70
- }
71
- }
72
- }
73
- }
74
- };
75
- export default _handler(postAuthRefresh, "postAuthRefresh", ["ROOT_AUTHENTICATION_DATA", "authCookies", "postOAuth2Token"]);
76
-
77
- async function postAuthRefresh({
78
- ROOT_AUTHENTICATION_DATA,
79
- authCookies,
80
- postOAuth2Token
81
- }, {
82
- body,
83
- cookie = ''
84
- }) {
85
- const parsedCookies = authCookies.parse(cookie);
86
-
87
- try {
88
- if (!parsedCookies.refresh_token) {
89
- throw new YHTTPError(401, 'E_REFRESH_COOKIE', cookie);
90
- }
91
-
92
- const response = await postOAuth2Token({
93
- body: {
94
- grant_type: 'refresh_token',
95
- scope: body.scope,
96
- refresh_token: parsedCookies.refresh_token
97
- },
98
- authenticationData: ROOT_AUTHENTICATION_DATA
99
- });
100
- return { ...response,
101
- headers: { ...(response.headers || {}),
102
- 'Set-Cookie': authCookies.build(response.status === 200 ? response.body : undefined, {
103
- session: !body.remember
104
- })
105
- },
106
- body: {
107
- access_token: response.body.access_token,
108
- expiration_date: response.body.expiration_date,
109
- expires_in: response.body.expires_in,
110
- token_type: response.body.token_type
111
- }
112
- };
113
- } catch (err) {
114
- const newErr = YHTTPError.wrap(err);
115
- newErr.headers = { ...(err.headers || {}),
116
- 'Set-Cookie': authCookies.build()
117
- };
118
- throw newErr;
119
- }
120
- }
121
- //# sourceMappingURL=postAuthRefresh.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/handlers/postAuthRefresh.ts"],"names":["autoHandler","YHTTPError","refersTo","AUTH_API_PREFIX","authCookieHeaderParameter","name","example","parameter","in","required","schema","type","definition","method","path","operation","operationId","summary","tags","disabled","parameters","requestBody","content","properties","scope","remember","responses","description","access_token","expiration_date","expires_in","token_type","postAuthRefresh","ROOT_AUTHENTICATION_DATA","authCookies","postOAuth2Token","body","cookie","parsedCookies","parse","refresh_token","response","grant_type","authenticationData","headers","build","status","undefined","session","err","newErr","wrap"],"mappings":"AAAA,SAASA,OAAW,IAAXA,QAAT,QAA4B,YAA5B;AACA,OAAOC,UAAP,MAAuB,YAAvB;AACA,SAASC,QAAT,QAAyB,cAAzB;AAEA,SAASC,eAAT,QAAgC,yBAAhC;AAYA,OAAO,MAAMC,yBAA8D,GAAG;AAC5EC,EAAAA,IAAI,EAAE,QADsE;AAE5EC,EAAAA,OAAO,EAAE,8DAFmE;AAG5EC,EAAAA,SAAS,EAAE;AACTF,IAAAA,IAAI,EAAE,QADG;AAETG,IAAAA,EAAE,EAAE,QAFK;AAGTC,IAAAA,QAAQ,EAAE,KAHD;AAITC,IAAAA,MAAM,EAAE;AACNC,MAAAA,IAAI,EAAE;AADA;AAJC;AAHiE,CAAvE;AA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U,QAAQ,CAACL,IAAT,CAAcL;AAJtB;AATD,KAAP;AAgBD,GA9BD,CA8BE,OAAOkB,GAAP,EAAY;AACZ,UAAMC,MAAM,GAAGjD,UAAU,CAACkD,IAAX,CAAgBF,GAAhB,CAAf;AAEAC,IAAAA,MAAM,CAACN,OAAP,GAAiB,EACf,IAAIK,GAAG,CAACL,OAAJ,IAAe,EAAnB,CADe;AAEf,oBAAcV,WAAW,CAACW,KAAZ;AAFC,KAAjB;AAKA,UAAMK,MAAN;AACD;AACF","sourcesContent":["import { autoHandler } from 'knifecycle';\nimport YHTTPError from 'yhttperror';\nimport { refersTo } from '@whook/whook';\nimport initPostOauth2Token from './postOAuth2Token';\nimport { AUTH_API_PREFIX } from '../services/authCookies';\nimport type {\n WhookAPIHandlerDefinition,\n WhookAPIParameterDefinition,\n} from '@whook/whook';\nimport type {\n AuthCookiesService,\n AuthHandlersConfig,\n} from '../services/authCookies';\nimport type { AsyncReturnType } from 'type-fest';\nimport type { BaseAuthenticationData } from '@whook/authorization';\n\nexport const authCookieHeaderParameter: WhookAPIParameterDefinition<string> = {\n name: 'cookie',\n example: 'access_token=an_access_token; refresh_token=a_refresh_token;',\n parameter: {\n name: 'cookie',\n in: 'header',\n required: false,\n schema: {\n type: 'string',\n },\n },\n};\n\nexport const definition: WhookAPIHandlerDefinition = {\n method: 'post',\n path: `${AUTH_API_PREFIX}/refresh`,\n operation: {\n operationId: 'postAuthRefresh',\n summary: 'Refreshs a user auth',\n tags: ['auth'],\n 'x-whook': {\n disabled: true,\n },\n parameters: [refersTo(authCookieHeaderParameter)],\n requestBody: {\n required: true,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n required: [],\n properties: {\n scope: { type: 'string' },\n remember: { type: 'boolean' },\n },\n },\n },\n },\n },\n responses: {\n 200: {\n description: 'Successfuly refreshed.',\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n properties: {\n access_token: { type: 'string' },\n expiration_date: { type: 'string' },\n expires_in: { type: 'string' },\n token_type: { type: 'string' },\n },\n },\n },\n },\n },\n },\n },\n};\n\nexport default autoHandler(postAuthRefresh);\n\nasync function postAuthRefresh<\n AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,\n>(\n {\n ROOT_AUTHENTICATION_DATA,\n authCookies,\n postOAuth2Token,\n }: AuthHandlersConfig<AUTHENTICATION_DATA> & {\n authCookies: AuthCookiesService;\n postOAuth2Token: AsyncReturnType<typeof initPostOauth2Token>;\n },\n {\n body,\n cookie = '',\n }: {\n body: {\n scope: string;\n remember: boolean;\n };\n cookie?: string;\n },\n) {\n const parsedCookies = authCookies.parse(cookie);\n\n try {\n if (!parsedCookies.refresh_token) {\n throw new YHTTPError(401, 'E_REFRESH_COOKIE', cookie);\n }\n\n const response = await postOAuth2Token({\n body: {\n grant_type: 'refresh_token',\n scope: body.scope,\n refresh_token: parsedCookies.refresh_token,\n },\n authenticationData: ROOT_AUTHENTICATION_DATA,\n });\n\n return {\n ...response,\n headers: {\n ...(response.headers || {}),\n 'Set-Cookie': authCookies.build(\n response.status === 200 ? response.body : undefined,\n { session: !body.remember },\n ),\n },\n body: {\n access_token: response.body.access_token,\n expiration_date: response.body.expiration_date,\n expires_in: response.body.expires_in,\n token_type: response.body.token_type,\n },\n };\n } catch (err) {\n const newErr = YHTTPError.wrap(err);\n\n newErr.headers = {\n ...(err.headers || {}),\n 'Set-Cookie': authCookies.build(),\n };\n\n throw newErr;\n }\n}\n"],"file":"postAuthRefresh.mjs"}
@@ -1,94 +0,0 @@
1
- import initPostAuthRefresh from './postAuthRefresh';
2
- describe('postAuthRefresh', () => {
3
- test('should work', async () => {
4
- const authCookies = {
5
- parse: jest.fn(),
6
- build: jest.fn()
7
- };
8
- const postOAuth2Token = jest.fn();
9
- const postAuthRefresh = await initPostAuthRefresh({
10
- ROOT_AUTHENTICATION_DATA: {
11
- scope: 'user',
12
- applicationId: 'root_app_id'
13
- },
14
- authCookies,
15
- postOAuth2Token
16
- });
17
- authCookies.parse.mockReturnValueOnce({
18
- access_token: 'an_access_token',
19
- refresh_token: 'a_refresh_token'
20
- });
21
- authCookies.build.mockReturnValueOnce('the_build_cookies');
22
- postOAuth2Token.mockResolvedValueOnce({
23
- status: 200,
24
- body: {
25
- access_token: 'an_access_token',
26
- expiration_date: '2020-02-02T20:22:02Z',
27
- expires_in: 3600,
28
- token_type: 'bearer'
29
- }
30
- });
31
- const response = await postAuthRefresh({
32
- cookie: 'a_given_cookie',
33
- body: {
34
- remember: false,
35
- scope: 'user'
36
- }
37
- });
38
- expect({
39
- response,
40
- authCookiesParseCalls: authCookies.parse.mock.calls,
41
- authCookiesBuildCalls: authCookies.build.mock.calls,
42
- postOAuth2TokenCalls: postOAuth2Token.mock.calls
43
- }).toMatchInlineSnapshot(`
44
- Object {
45
- "authCookiesBuildCalls": Array [
46
- Array [
47
- Object {
48
- "access_token": "an_access_token",
49
- "expiration_date": "2020-02-02T20:22:02Z",
50
- "expires_in": 3600,
51
- "token_type": "bearer",
52
- },
53
- Object {
54
- "session": true,
55
- },
56
- ],
57
- ],
58
- "authCookiesParseCalls": Array [
59
- Array [
60
- "a_given_cookie",
61
- ],
62
- ],
63
- "postOAuth2TokenCalls": Array [
64
- Array [
65
- Object {
66
- "authenticationData": Object {
67
- "applicationId": "root_app_id",
68
- "scope": "user",
69
- },
70
- "body": Object {
71
- "grant_type": "refresh_token",
72
- "refresh_token": "a_refresh_token",
73
- "scope": "user",
74
- },
75
- },
76
- ],
77
- ],
78
- "response": Object {
79
- "body": Object {
80
- "access_token": "an_access_token",
81
- "expiration_date": "2020-02-02T20:22:02Z",
82
- "expires_in": 3600,
83
- "token_type": "bearer",
84
- },
85
- "headers": Object {
86
- "Set-Cookie": "the_build_cookies",
87
- },
88
- "status": 200,
89
- },
90
- }
91
- `);
92
- });
93
- });
94
- //# sourceMappingURL=postAuthRefresh.test.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/handlers/postAuthRefresh.test.ts"],"names":["initPostAuthRefresh","describe","test","authCookies","parse","jest","fn","build","postOAuth2Token","postAuthRefresh","ROOT_AUTHENTICATION_DATA","scope","applicationId","mockReturnValueOnce","access_token","refresh_token","mockResolvedValueOnce","status","body","expiration_date","expires_in","token_type","response","cookie","remember","expect","authCookiesParseCalls","mock","calls","authCookiesBuildCalls","postOAuth2TokenCalls","toMatchInlineSnapshot"],"mappings":"AAAA,OAAOA,mBAAP,MAAgC,mBAAhC;AAEAC,QAAQ,CAAC,iBAAD,EAAoB,MAAM;AAChCC,EAAAA,IAAI,CAAC,aAAD,EAAgB,YAAY;AAC9B,UAAMC,WAAW,GAAG;AAClBC,MAAAA,KAAK,EAAEC,IAAI,CAACC,EAAL,EADW;AAElBC,MAAAA,KAAK,EAAEF,IAAI,CAACC,EAAL;AAFW,KAApB;AAIA,UAAME,eAAe,GAAGH,IAAI,CAACC,EAAL,EAAxB;AACA,UAAMG,eAAe,GAAG,MAAMT,mBAAmB,CAAC;AAChDU,MAAAA,wBAAwB,EAAE;AACxBC,QAAAA,KAAK,EAAE,MADiB;AAExBC,QAAAA,aAAa,EAAE;AAFS,OADsB;AAKhDT,MAAAA,WALgD;AAMhDK,MAAAA;AANgD,KAAD,CAAjD;AASAL,IAAAA,WAAW,CAACC,KAAZ,CAAkBS,mBAAlB,CAAsC;AACpCC,MAAAA,YAAY,EAAE,iBADsB;AAEpCC,MAAAA,aAAa,EAAE;AAFqB,KAAtC;AAIAZ,IAAAA,WAAW,CAACI,KAAZ,CAAkBM,mBAAlB,CAAsC,mBAAtC;AACAL,IAAAA,eAAe,CAACQ,qBAAhB,CAAsC;AACpCC,MAAAA,MAAM,EAAE,GAD4B;AAEpCC,MAAAA,IAAI,EAAE;AACJJ,QAAAA,YAAY,EAAE,iBADV;AAEJK,QAAAA,eAAe,EAAE,sBAFb;AAGJC,QAAAA,UAAU,EAAE,IAHR;AAIJC,QAAAA,UAAU,EAAE;AAJR;AAF8B,KAAtC;AAUA,UAAMC,QAAQ,GAAG,MAAMb,eAAe,CAAC;AACrCc,MAAAA,MAAM,EAAE,gBAD6B;AAErCL,MAAAA,IAAI,EAAE;AACJM,QAAAA,QAAQ,EAAE,KADN;AAEJb,QAAAA,KAAK,EAAE;AAFH;AAF+B,KAAD,CAAtC;AAQAc,IAAAA,MAAM,CAAC;AACLH,MAAAA,QADK;AAELI,MAAAA,qBAAqB,EAAEvB,WAAW,CAACC,KAAZ,CAAkBuB,IAAlB,CAAuBC,KAFzC;AAGLC,MAAAA,qBAAqB,EAAE1B,WAAW,CAACI,KAAZ,CAAkBoB,IAAlB,CAAuBC,KAHzC;AAILE,MAAAA,oBAAoB,EAAEtB,eAAe,CAACmB,IAAhB,CAAqBC;AAJtC,KAAD,CAAN,CAKGG,qBALH,CAK0B;AAC9B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KArDI;AAsDD,GA5FG,CAAJ;AA6FD,CA9FO,CAAR","sourcesContent":["import initPostAuthRefresh from './postAuthRefresh';\n\ndescribe('postAuthRefresh', () => {\n test('should work', async () => {\n const authCookies = {\n parse: jest.fn(),\n build: jest.fn(),\n };\n const postOAuth2Token = jest.fn();\n const postAuthRefresh = await initPostAuthRefresh({\n ROOT_AUTHENTICATION_DATA: {\n scope: 'user',\n applicationId: 'root_app_id',\n },\n authCookies,\n postOAuth2Token,\n });\n\n authCookies.parse.mockReturnValueOnce({\n access_token: 'an_access_token',\n refresh_token: 'a_refresh_token',\n });\n authCookies.build.mockReturnValueOnce('the_build_cookies');\n postOAuth2Token.mockResolvedValueOnce({\n status: 200,\n body: {\n access_token: 'an_access_token',\n expiration_date: '2020-02-02T20:22:02Z',\n expires_in: 3600,\n token_type: 'bearer',\n },\n });\n\n const response = await postAuthRefresh({\n cookie: 'a_given_cookie',\n body: {\n remember: false,\n scope: 'user',\n },\n });\n\n expect({\n response,\n authCookiesParseCalls: authCookies.parse.mock.calls,\n authCookiesBuildCalls: authCookies.build.mock.calls,\n postOAuth2TokenCalls: postOAuth2Token.mock.calls,\n }).toMatchInlineSnapshot(`\n Object {\n \"authCookiesBuildCalls\": Array [\n Array [\n Object {\n \"access_token\": \"an_access_token\",\n \"expiration_date\": \"2020-02-02T20:22:02Z\",\n \"expires_in\": 3600,\n \"token_type\": \"bearer\",\n },\n Object {\n \"session\": true,\n },\n ],\n ],\n \"authCookiesParseCalls\": Array [\n Array [\n \"a_given_cookie\",\n ],\n ],\n \"postOAuth2TokenCalls\": Array [\n Array [\n Object {\n \"authenticationData\": Object {\n \"applicationId\": \"root_app_id\",\n \"scope\": \"user\",\n },\n \"body\": Object {\n \"grant_type\": \"refresh_token\",\n \"refresh_token\": \"a_refresh_token\",\n \"scope\": \"user\",\n },\n },\n ],\n ],\n \"response\": Object {\n \"body\": Object {\n \"access_token\": \"an_access_token\",\n \"expiration_date\": \"2020-02-02T20:22:02Z\",\n \"expires_in\": 3600,\n \"token_type\": \"bearer\",\n },\n \"headers\": Object {\n \"Set-Cookie\": \"the_build_cookies\",\n },\n \"status\": 200,\n },\n }\n `);\n });\n});\n"],"file":"postAuthRefresh.test.mjs"}
@@ -1,150 +0,0 @@
1
- import { handler as _handler } from 'knifecycle';
2
- import YError from 'yerror';
3
- import { setURLError } from './getOAuth2Authorize';
4
-
5
- /* Architecture Note #2: OAuth2 acknowledge
6
- This endpoint is to be used by the authentication SSR frontend
7
- to acknowlege that the user accepted the client request in it.
8
- */
9
- export const definition = {
10
- method: 'post',
11
- path: '/oauth2/acknowledge',
12
- operation: {
13
- operationId: 'postOAuth2Acknowledge',
14
- summary: `Implements the logic that allow the authentication frontend
15
- to get the [Redirection Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1.2).`,
16
- tags: ['oauth2'],
17
- 'x-whook': {
18
- private: true
19
- },
20
- requestBody: {
21
- required: true,
22
- content: {
23
- 'application/json': {
24
- schema: {
25
- type: 'object',
26
- required: ['responseType', 'clientId', 'redirectURI', 'scope', 'state', 'acknowledged'],
27
- properties: {
28
- responseType: {
29
- type: 'string'
30
- },
31
- clientId: {
32
- type: 'string'
33
- },
34
- redirectURI: {
35
- type: 'string',
36
- pattern: '^https?://',
37
- format: 'uri'
38
- },
39
- scope: {
40
- type: 'string',
41
- description: 'See https://tools.ietf.org/html/rfc6749#section-3.3'
42
- },
43
- state: {
44
- type: 'string'
45
- },
46
- acknowledged: {
47
- type: 'boolean',
48
- description: 'Wether the user acknowledged the delegation or not.'
49
- }
50
- }
51
- }
52
- }
53
- }
54
- },
55
- responses: {
56
- '201': {
57
- description: 'Redirection endpoint URI computed.',
58
- content: {
59
- 'application/json': {
60
- schema: {
61
- type: 'object',
62
- required: ['redirectURI'],
63
- properties: {
64
- redirectURI: {
65
- type: 'string',
66
- pattern: '^https?://',
67
- format: 'uri'
68
- }
69
- }
70
- }
71
- }
72
- }
73
- }
74
- }
75
- }
76
- };
77
- export default _handler(postOAuth2Acknowledge, "postOAuth2Acknowledge", ["ERRORS_DESCRIPTORS", "oAuth2Granters", "checkApplication", "log"]);
78
-
79
- async function postOAuth2Acknowledge({
80
- ERRORS_DESCRIPTORS,
81
- oAuth2Granters,
82
- checkApplication,
83
- log
84
- }, {
85
- authenticationData,
86
- body: {
87
- responseType,
88
- clientId,
89
- redirectURI,
90
- scope: demandedScope,
91
- state,
92
- acknowledged = false,
93
- ...additionalParameters
94
- }
95
- }) {
96
- if (!authenticationData) {
97
- throw new YError('E_UNAUTHORIZED');
98
- } // Here we check the applicationId has the right to authenticate a user
99
- // with the special type 'root'
100
-
101
-
102
- await checkApplication({
103
- applicationId: authenticationData.applicationId,
104
- type: 'root',
105
- scope: ''
106
- });
107
- const url = new URL(redirectURI);
108
-
109
- try {
110
- if (!acknowledged) {
111
- throw new YError('E_ACCESS_DENIED', clientId);
112
- }
113
-
114
- const granter = oAuth2Granters.find(granter => granter.acknowledger && granter.acknowledger.acknowledgmentType === responseType);
115
-
116
- if (!granter) {
117
- throw new YError('E_UNKNOWN_ACKNOWLEDGOR_TYPE', responseType);
118
- }
119
-
120
- const {
121
- applicationId,
122
- scope,
123
- ...additionalProperties
124
- } = await granter.acknowledger.acknowledge(authenticationData, {
125
- clientId,
126
- redirectURI,
127
- scope: demandedScope
128
- }, additionalParameters);
129
- url.searchParams.set('client_id', applicationId);
130
- url.searchParams.set('scope', scope);
131
- url.searchParams.set('state', state);
132
- Object.keys(additionalProperties).forEach(key => url.searchParams.set(snakeCase(key), additionalProperties[key]));
133
- } catch (err) {
134
- log('debug', '👫 - OAuth2 acknowledge error', err.code);
135
- log('debug-stack', err.stack);
136
- setURLError(url, err, ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2);
137
- }
138
-
139
- return {
140
- status: 302,
141
- headers: {
142
- location: url.href
143
- }
144
- };
145
- }
146
-
147
- function snakeCase(s) {
148
- return s.split(/(?=(?<![A-Z])[A-Z])|[^a-zA-Z]+/).map(s => s.toLowerCase()).join('_');
149
- }
150
- //# sourceMappingURL=postOAuth2Acknowledge.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/handlers/postOAuth2Acknowledge.ts"],"names":["autoHandler","YError","setURLError","definition","method","path","operation","operationId","summary","tags","private","requestBody","required","content","schema","type","properties","responseType","clientId","redirectURI","pattern","format","scope","description","state","acknowledged","responses","postOAuth2Acknowledge","ERRORS_DESCRIPTORS","oAuth2Granters","checkApplication","log","authenticationData","body","demandedScope","additionalParameters","applicationId","url","URL","granter","find","acknowledger","acknowledgmentType","additionalProperties","acknowledge","searchParams","set","Object","keys","forEach","key","snakeCase","err","code","stack","E_OAUTH2","status","headers","location","href","s","split","map","toLowerCase","join"],"mappings":"AAAA,SAASA,OAAW,IAAXA,QAAT,QAA4B,YAA5B;AACA,OAAOC,MAAP,MAAmB,QAAnB;AACA,SAASC,WA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AE,GADH;AAELC,IAAAA,OAAO,EAAE;AACPC,MAAAA,QAAQ,EAAErB,GAAG,CAACsB;AADP;AAFJ,GAAP;AAMD;;AAED,SAASR,SAAT,CAAmBS,CAAnB,EAAsC;AACpC,SAAOA,CAAC,CACLC,KADI,CACE,gCADF,EAEJC,GAFI,CAECF,CAAD,IAAOA,CAAC,CAACG,WAAF,EAFP,EAGJC,IAHI,CAGC,GAHD,CAAP;AAID","sourcesContent":["import { autoHandler } from 'knifecycle';\nimport YError from 'yerror';\nimport { setURLError } from './getOAuth2Authorize';\nimport type {\n WhookAPIHandlerDefinition,\n WhookErrorsDescriptors,\n WhookAPIOperationConfig,\n} from '@whook/whook';\nimport type {\n CheckApplicationService,\n OAuth2GranterService,\n} from '../services/oAuth2Granters';\nimport type { LogService } from 'common-services';\nimport type { BaseAuthenticationData } from '@whook/authorization';\n\n/* Architecture Note #2: OAuth2 acknowledge\nThis endpoint is to be used by the authentication SSR frontend\n to acknowlege that the user accepted the client request in it.\n*/\n\nexport const definition: WhookAPIHandlerDefinition = {\n method: 'post',\n path: '/oauth2/acknowledge',\n operation: {\n operationId: 'postOAuth2Acknowledge',\n summary: `Implements the logic that allow the authentication frontend\n to get the [Redirection Endpoint](https://tools.ietf.org/html/rfc6749#section-3.1.2).`,\n tags: ['oauth2'],\n 'x-whook': {\n private: true,\n } as WhookAPIOperationConfig,\n requestBody: {\n required: true,\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n required: [\n 'responseType',\n 'clientId',\n 'redirectURI',\n 'scope',\n 'state',\n 'acknowledged',\n ],\n properties: {\n responseType: {\n type: 'string',\n },\n clientId: {\n type: 'string',\n },\n redirectURI: {\n type: 'string',\n pattern: '^https?://',\n format: 'uri',\n },\n scope: {\n type: 'string',\n description:\n 'See https://tools.ietf.org/html/rfc6749#section-3.3',\n },\n state: {\n type: 'string',\n },\n acknowledged: {\n type: 'boolean',\n description:\n 'Wether the user acknowledged the delegation or not.',\n },\n },\n },\n },\n },\n },\n responses: {\n '201': {\n description: 'Redirection endpoint URI computed.',\n content: {\n 'application/json': {\n schema: {\n type: 'object',\n required: ['redirectURI'],\n properties: {\n redirectURI: {\n type: 'string',\n pattern: '^https?://',\n format: 'uri',\n },\n },\n },\n },\n },\n },\n },\n },\n};\n\nexport default autoHandler(postOAuth2Acknowledge);\n\nasync function postOAuth2Acknowledge<\n AUTHENTICATION_DATA extends BaseAuthenticationData = BaseAuthenticationData,\n>(\n {\n ERRORS_DESCRIPTORS,\n oAuth2Granters,\n checkApplication,\n log,\n }: {\n ERRORS_DESCRIPTORS: WhookErrorsDescriptors;\n oAuth2Granters: OAuth2GranterService[];\n checkApplication: CheckApplicationService;\n log: LogService;\n },\n {\n authenticationData,\n body: {\n responseType,\n clientId,\n redirectURI,\n scope: demandedScope,\n state,\n acknowledged = false,\n ...additionalParameters\n },\n }: {\n authenticationData: AUTHENTICATION_DATA;\n body: {\n responseType: string;\n clientId: string;\n redirectURI: string;\n scope: string;\n state: string;\n acknowledged: boolean;\n [name: string]: unknown;\n };\n },\n) {\n if (!authenticationData) {\n throw new YError('E_UNAUTHORIZED');\n }\n\n // Here we check the applicationId has the right to authenticate a user\n // with the special type 'root'\n await checkApplication({\n applicationId: authenticationData.applicationId,\n type: 'root',\n scope: '',\n });\n\n const url = new URL(redirectURI);\n\n try {\n if (!acknowledged) {\n throw new YError('E_ACCESS_DENIED', clientId);\n }\n\n const granter = oAuth2Granters.find(\n (granter) =>\n granter.acknowledger &&\n granter.acknowledger.acknowledgmentType === responseType,\n );\n\n if (!granter) {\n throw new YError('E_UNKNOWN_ACKNOWLEDGOR_TYPE', responseType);\n }\n\n const { applicationId, scope, ...additionalProperties } =\n await granter.acknowledger.acknowledge(\n authenticationData,\n {\n clientId,\n redirectURI,\n scope: demandedScope,\n },\n additionalParameters,\n );\n\n url.searchParams.set('client_id', applicationId);\n url.searchParams.set('scope', scope);\n url.searchParams.set('state', state);\n Object.keys(additionalProperties).forEach((key) =>\n url.searchParams.set(snakeCase(key), additionalProperties[key] as string),\n );\n } catch (err) {\n log('debug', '👫 - OAuth2 acknowledge error', err.code);\n log('debug-stack', err.stack);\n\n setURLError(\n url,\n err,\n ERRORS_DESCRIPTORS[err.code] || ERRORS_DESCRIPTORS.E_OAUTH2,\n );\n }\n\n return {\n status: 302,\n headers: {\n location: url.href,\n },\n };\n}\n\nfunction snakeCase(s: string): string {\n return s\n .split(/(?=(?<![A-Z])[A-Z])|[^a-zA-Z]+/)\n .map((s) => s.toLowerCase())\n .join('_');\n}\n"],"file":"postOAuth2Acknowledge.mjs"}
@@ -1,140 +0,0 @@
1
- import initPostOAuth2Acknowledge from './postOAuth2Acknowledge';
2
- import YError from 'yerror';
3
- import { DEFAULT_ERRORS_DESCRIPTORS } from '@whook/whook';
4
- import { OAUTH2_ERRORS_DESCRIPTORS } from '../services/oAuth2Granters';
5
- describe('postOAuth2Acknowledge', () => {
6
- const ERRORS_DESCRIPTORS = { ...DEFAULT_ERRORS_DESCRIPTORS,
7
- ...OAUTH2_ERRORS_DESCRIPTORS
8
- };
9
- const checkApplication = jest.fn();
10
- const log = jest.fn();
11
- const codeGranter = {
12
- type: 'code',
13
- authorizer: {
14
- responseType: 'code',
15
- authorize: jest.fn()
16
- },
17
- acknowledger: {
18
- acknowledgmentType: 'code',
19
- acknowledge: jest.fn()
20
- },
21
- authenticator: {
22
- grantType: 'authorization_code',
23
- authenticate: jest.fn()
24
- }
25
- };
26
- const tokenGranter = {
27
- type: 'token',
28
- authorizer: {
29
- responseType: 'token',
30
- authorize: jest.fn()
31
- },
32
- acknowledger: {
33
- acknowledgmentType: 'token',
34
- acknowledge: jest.fn()
35
- }
36
- };
37
- const oAuth2Granters = [codeGranter, tokenGranter];
38
- beforeEach(() => {
39
- checkApplication.mockReset();
40
- log.mockReset();
41
- [codeGranter.authorizer.authorize, codeGranter.acknowledger.acknowledge, codeGranter.authenticator.authenticate, tokenGranter.authorizer.authorize, tokenGranter.acknowledger.acknowledge].forEach(mock => mock.mockReset());
42
- });
43
- test('should redirect', async () => {
44
- [codeGranter.authorizer.authorize, codeGranter.authenticator.authenticate, tokenGranter.authorizer.authorize, tokenGranter.acknowledger.acknowledge].forEach(mock => mock.mockRejectedValueOnce(new YError('E_NOT_SUPPOSED_TO_BE_HERE')));
45
- codeGranter.acknowledger.acknowledge.mockResolvedValueOnce({
46
- applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
47
- redirectURI: 'http://lol',
48
- scope: 'user',
49
- userId: 1
50
- });
51
- const postOAuth2Acknowledge = await initPostOAuth2Acknowledge({
52
- ERRORS_DESCRIPTORS,
53
- oAuth2Granters,
54
- checkApplication,
55
- log
56
- });
57
- const response = await postOAuth2Acknowledge({
58
- authenticationData: {
59
- applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
60
- scope: 'auth',
61
- userId: 1
62
- },
63
- body: {
64
- responseType: 'code',
65
- clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
66
- redirectURI: 'https://www.example.com',
67
- scope: 'user',
68
- state: 'bancal',
69
- acknowledged: true
70
- }
71
- });
72
- expect({
73
- response
74
- }).toMatchInlineSnapshot(`
75
- Object {
76
- "response": Object {
77
- "headers": Object {
78
- "location": "https://www.example.com/?client_id=abbacaca-abba-caca-abba-cacaabbacaca&scope=user&state=bancal&redirect_uri=http%3A%2F%2Flol&user_id=1",
79
- },
80
- "status": 302,
81
- },
82
- }
83
- `);
84
- expect({
85
- logCalls: log.mock.calls.filter(([type]) => !type.endsWith('stack')),
86
- checkApplicationCalls: checkApplication.mock.calls,
87
- codeGranterAuthorizerAuthorizeCalls: codeGranter.authorizer.authorize.mock.calls,
88
- codeGranterAcknowledgerAcknowledgeCalls: codeGranter.acknowledger.acknowledge.mock.calls,
89
- codeGranterAuthenticatorAuthenticateCalls: codeGranter.authenticator.authenticate.mock.calls,
90
- tokenGranterAuthorizerAuthorizeCalls: tokenGranter.authorizer.authorize.mock.calls,
91
- tokenGranterAcknowledgerAcknowledgeCalls: tokenGranter.acknowledger.acknowledge.mock.calls
92
- }).toMatchSnapshot();
93
- });
94
- test('should redirect errors too', async () => {
95
- [codeGranter.authorizer.authorize, codeGranter.authenticator.authenticate, tokenGranter.authorizer.authorize, tokenGranter.acknowledger.acknowledge, codeGranter.acknowledger.acknowledge].forEach(mock => mock.mockRejectedValueOnce(new YError('E_NOT_SUPPOSED_TO_BE_HERE')));
96
- const postOAuth2Acknowledge = await initPostOAuth2Acknowledge({
97
- ERRORS_DESCRIPTORS,
98
- oAuth2Granters,
99
- checkApplication,
100
- log
101
- });
102
- const response = await postOAuth2Acknowledge({
103
- authenticationData: {
104
- applicationId: 'abbacaca-abba-caca-abba-cacaabbacaca',
105
- scope: 'auth',
106
- userId: 1
107
- },
108
- body: {
109
- responseType: 'yolo',
110
- clientId: 'abbacaca-abba-caca-abba-cacaabbacaca',
111
- redirectURI: 'https://www.example.com',
112
- scope: 'user',
113
- state: 'bancal',
114
- acknowledged: true
115
- }
116
- });
117
- expect({
118
- response
119
- }).toMatchInlineSnapshot(`
120
- Object {
121
- "response": Object {
122
- "headers": Object {
123
- "location": "https://www.example.com/?error=unsupported_response_type&error_decription=Type+%22yolo%22+not+supported.",
124
- },
125
- "status": 302,
126
- },
127
- }
128
- `);
129
- expect({
130
- logCalls: log.mock.calls.filter(([type]) => !type.endsWith('stack')),
131
- checkApplicationCalls: checkApplication.mock.calls,
132
- codeGranterAuthorizerAuthorizeCalls: codeGranter.authorizer.authorize.mock.calls,
133
- codeGranterAcknowledgerAcknowledgeCalls: codeGranter.acknowledger.acknowledge.mock.calls,
134
- codeGranterAuthenticatorAuthenticateCalls: codeGranter.authenticator.authenticate.mock.calls,
135
- tokenGranterAuthorizerAuthorizeCalls: tokenGranter.authorizer.authorize.mock.calls,
136
- tokenGranterAcknowledgerAcknowledgeCalls: tokenGranter.acknowledger.acknowledge.mock.calls
137
- }).toMatchSnapshot();
138
- });
139
- });
140
- //# sourceMappingURL=postOAuth2Acknowledge.test.mjs.map