wabe 0.6.9 → 0.6.11

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 (162) hide show
  1. package/README.md +156 -50
  2. package/bucket/b.txt +1 -0
  3. package/dev/index.ts +215 -0
  4. package/dist/authentication/Session.d.ts +4 -1
  5. package/dist/authentication/interface.d.ts +16 -0
  6. package/dist/cron/index.d.ts +0 -1
  7. package/dist/database/DatabaseController.d.ts +41 -13
  8. package/dist/database/interface.d.ts +1 -0
  9. package/dist/email/DevAdapter.d.ts +0 -1
  10. package/dist/email/interface.d.ts +1 -1
  11. package/dist/graphql/resolvers.d.ts +4 -2
  12. package/dist/hooks/index.d.ts +8 -2
  13. package/dist/index.d.ts +0 -1
  14. package/dist/index.js +32144 -32058
  15. package/dist/schema/Schema.d.ts +2 -1
  16. package/dist/server/index.d.ts +4 -2
  17. package/dist/utils/crypto.d.ts +7 -0
  18. package/dist/utils/helper.d.ts +5 -1
  19. package/generated/schema.graphql +22 -14
  20. package/generated/wabe.ts +4 -4
  21. package/package.json +23 -23
  22. package/src/authentication/OTP.test.ts +69 -0
  23. package/src/authentication/OTP.ts +64 -0
  24. package/src/authentication/Session.test.ts +629 -0
  25. package/src/authentication/Session.ts +493 -0
  26. package/src/authentication/defaultAuthentication.ts +209 -0
  27. package/src/authentication/index.ts +3 -0
  28. package/src/authentication/interface.ts +155 -0
  29. package/src/authentication/oauth/GitHub.test.ts +91 -0
  30. package/src/authentication/oauth/GitHub.ts +121 -0
  31. package/src/authentication/oauth/Google.test.ts +91 -0
  32. package/src/authentication/oauth/Google.ts +101 -0
  33. package/src/authentication/oauth/Oauth2Client.test.ts +219 -0
  34. package/src/authentication/oauth/Oauth2Client.ts +135 -0
  35. package/src/authentication/oauth/index.ts +2 -0
  36. package/src/authentication/oauth/utils.test.ts +33 -0
  37. package/src/authentication/oauth/utils.ts +27 -0
  38. package/src/authentication/providers/EmailOTP.test.ts +127 -0
  39. package/src/authentication/providers/EmailOTP.ts +84 -0
  40. package/src/authentication/providers/EmailPassword.test.ts +176 -0
  41. package/src/authentication/providers/EmailPassword.ts +116 -0
  42. package/src/authentication/providers/EmailPasswordSRP.test.ts +208 -0
  43. package/src/authentication/providers/EmailPasswordSRP.ts +179 -0
  44. package/src/authentication/providers/GitHub.ts +24 -0
  45. package/src/authentication/providers/Google.ts +24 -0
  46. package/src/authentication/providers/OAuth.test.ts +185 -0
  47. package/src/authentication/providers/OAuth.ts +106 -0
  48. package/src/authentication/providers/PhonePassword.test.ts +176 -0
  49. package/src/authentication/providers/PhonePassword.ts +115 -0
  50. package/src/authentication/providers/QRCodeOTP.test.ts +77 -0
  51. package/src/authentication/providers/QRCodeOTP.ts +58 -0
  52. package/src/authentication/providers/index.ts +6 -0
  53. package/src/authentication/resolvers/refreshResolver.test.ts +30 -0
  54. package/src/authentication/resolvers/refreshResolver.ts +19 -0
  55. package/src/authentication/resolvers/signInWithResolver.inte.test.ts +59 -0
  56. package/src/authentication/resolvers/signInWithResolver.test.ts +293 -0
  57. package/src/authentication/resolvers/signInWithResolver.ts +92 -0
  58. package/src/authentication/resolvers/signOutResolver.test.ts +38 -0
  59. package/src/authentication/resolvers/signOutResolver.ts +18 -0
  60. package/src/authentication/resolvers/signUpWithResolver.test.ts +180 -0
  61. package/src/authentication/resolvers/signUpWithResolver.ts +65 -0
  62. package/src/authentication/resolvers/verifyChallenge.test.ts +133 -0
  63. package/src/authentication/resolvers/verifyChallenge.ts +62 -0
  64. package/src/authentication/roles.test.ts +49 -0
  65. package/src/authentication/roles.ts +40 -0
  66. package/src/authentication/utils.test.ts +97 -0
  67. package/src/authentication/utils.ts +39 -0
  68. package/src/cache/InMemoryCache.test.ts +62 -0
  69. package/src/cache/InMemoryCache.ts +45 -0
  70. package/src/cron/index.test.ts +17 -0
  71. package/src/cron/index.ts +43 -0
  72. package/src/database/DatabaseController.test.ts +613 -0
  73. package/src/database/DatabaseController.ts +1007 -0
  74. package/src/database/index.test.ts +1372 -0
  75. package/src/database/index.ts +9 -0
  76. package/src/database/interface.ts +302 -0
  77. package/src/email/DevAdapter.ts +7 -0
  78. package/src/email/EmailController.test.ts +29 -0
  79. package/src/email/EmailController.ts +13 -0
  80. package/src/email/index.ts +2 -0
  81. package/src/email/interface.ts +36 -0
  82. package/src/email/templates/sendOtpCode.ts +120 -0
  83. package/src/file/FileController.ts +28 -0
  84. package/src/file/FileDevAdapter.ts +51 -0
  85. package/src/file/hookDeleteFile.ts +25 -0
  86. package/src/file/hookReadFile.ts +66 -0
  87. package/src/file/hookUploadFile.ts +50 -0
  88. package/src/file/index.test.ts +932 -0
  89. package/src/file/index.ts +2 -0
  90. package/src/file/interface.ts +39 -0
  91. package/src/graphql/GraphQLSchema.test.ts +4408 -0
  92. package/src/graphql/GraphQLSchema.ts +880 -0
  93. package/src/graphql/index.ts +2 -0
  94. package/src/graphql/parseGraphqlSchema.ts +85 -0
  95. package/src/graphql/parser.test.ts +203 -0
  96. package/src/graphql/parser.ts +542 -0
  97. package/src/graphql/pointerAndRelationFunction.ts +191 -0
  98. package/src/graphql/resolvers.ts +442 -0
  99. package/src/graphql/tests/aggregation.test.ts +1115 -0
  100. package/src/graphql/tests/e2e.test.ts +590 -0
  101. package/src/graphql/tests/scalars.test.ts +250 -0
  102. package/src/graphql/types.ts +227 -0
  103. package/src/hooks/HookObject.test.ts +122 -0
  104. package/src/hooks/HookObject.ts +165 -0
  105. package/src/hooks/authentication.ts +67 -0
  106. package/src/hooks/createUser.test.ts +77 -0
  107. package/src/hooks/createUser.ts +10 -0
  108. package/src/hooks/defaultFields.test.ts +176 -0
  109. package/src/hooks/defaultFields.ts +32 -0
  110. package/src/hooks/deleteSession.test.ts +181 -0
  111. package/src/hooks/deleteSession.ts +20 -0
  112. package/src/hooks/hashFieldHook.test.ts +152 -0
  113. package/src/hooks/hashFieldHook.ts +89 -0
  114. package/src/hooks/index.test.ts +258 -0
  115. package/src/hooks/index.ts +414 -0
  116. package/src/hooks/permissions.test.ts +412 -0
  117. package/src/hooks/permissions.ts +93 -0
  118. package/src/hooks/protected.test.ts +551 -0
  119. package/src/hooks/protected.ts +60 -0
  120. package/src/hooks/searchableFields.test.ts +147 -0
  121. package/src/hooks/searchableFields.ts +86 -0
  122. package/src/hooks/session.test.ts +134 -0
  123. package/src/hooks/session.ts +76 -0
  124. package/src/hooks/setEmail.test.ts +216 -0
  125. package/src/hooks/setEmail.ts +33 -0
  126. package/src/hooks/setupAcl.test.ts +618 -0
  127. package/src/hooks/setupAcl.ts +25 -0
  128. package/src/index.ts +9 -0
  129. package/src/schema/Schema.test.ts +482 -0
  130. package/src/schema/Schema.ts +757 -0
  131. package/src/schema/defaultResolvers.ts +93 -0
  132. package/src/schema/index.ts +1 -0
  133. package/src/schema/resolvers/meResolver.test.ts +62 -0
  134. package/src/schema/resolvers/meResolver.ts +10 -0
  135. package/src/schema/resolvers/resetPassword.test.ts +341 -0
  136. package/src/schema/resolvers/resetPassword.ts +63 -0
  137. package/src/schema/resolvers/sendEmail.test.ts +118 -0
  138. package/src/schema/resolvers/sendEmail.ts +21 -0
  139. package/src/schema/resolvers/sendOtpCode.test.ts +141 -0
  140. package/src/schema/resolvers/sendOtpCode.ts +52 -0
  141. package/src/security.test.ts +3434 -0
  142. package/src/server/defaultSessionHandler.test.ts +62 -0
  143. package/src/server/defaultSessionHandler.ts +105 -0
  144. package/src/server/generateCodegen.ts +433 -0
  145. package/src/server/index.test.ts +532 -0
  146. package/src/server/index.ts +334 -0
  147. package/src/server/interface.ts +11 -0
  148. package/src/server/routes/authHandler.ts +169 -0
  149. package/src/server/routes/index.ts +39 -0
  150. package/src/utils/crypto.test.ts +41 -0
  151. package/src/utils/crypto.ts +105 -0
  152. package/src/utils/export.ts +11 -0
  153. package/src/utils/helper.ts +204 -0
  154. package/src/utils/index.test.ts +11 -0
  155. package/src/utils/index.ts +189 -0
  156. package/src/utils/preload.ts +8 -0
  157. package/src/utils/testHelper.ts +116 -0
  158. package/tsconfig.json +32 -0
  159. package/bunfig.toml +0 -4
  160. package/dist/ai/index.d.ts +0 -1
  161. package/dist/ai/interface.d.ts +0 -9
  162. /package/dist/server/{defaultHandlers.d.ts → defaultSessionHandler.d.ts} +0 -0
@@ -0,0 +1,219 @@
1
+ import { describe, expect, it, spyOn, mock, afterAll } from 'bun:test'
2
+ import { fail } from 'node:assert'
3
+ import { OAuth2Client } from './Oauth2Client'
4
+ import { base64URLencode } from './utils'
5
+
6
+ const mockFetch = mock(() => {})
7
+
8
+ const originalFetch = global.fetch
9
+
10
+ // @ts-expect-error
11
+ global.fetch = mockFetch
12
+
13
+ describe('Oauth2Client', () => {
14
+ const oauthClient = new OAuth2Client(
15
+ 'clientId',
16
+ 'https://authorizationEndpoint',
17
+ 'https://tokenEndpoint',
18
+ 'https://redirectURI',
19
+ )
20
+
21
+ afterAll(() => {
22
+ global.fetch = originalFetch
23
+ })
24
+
25
+ it('should create authorization URl', () => {
26
+ const authorizationURL = oauthClient.createAuthorizationURL()
27
+
28
+ expect(authorizationURL.toString()).toEqual(
29
+ 'https://authorizationendpoint/?response_type=code&client_id=clientId&redirect_uri=https%3A%2F%2FredirectURI',
30
+ )
31
+
32
+ const authorizationURLWithState = oauthClient.createAuthorizationURL({
33
+ state: 'state',
34
+ })
35
+
36
+ expect(authorizationURLWithState.toString()).toEqual(
37
+ 'https://authorizationendpoint/?response_type=code&client_id=clientId&state=state&redirect_uri=https%3A%2F%2FredirectURI',
38
+ )
39
+
40
+ const authorizationURLWithScopes = oauthClient.createAuthorizationURL({
41
+ scopes: ['scope1', 'scope2'],
42
+ })
43
+
44
+ expect(authorizationURLWithScopes.toString()).toEqual(
45
+ 'https://authorizationendpoint/?response_type=code&client_id=clientId&scope=scope1+scope2&redirect_uri=https%3A%2F%2FredirectURI',
46
+ )
47
+
48
+ const authorizationURLWithCodeVerifier = oauthClient.createAuthorizationURL({
49
+ codeVerifier: 'codeVerifier',
50
+ })
51
+
52
+ const codeChallenge = base64URLencode('codeVerifier')
53
+
54
+ expect(authorizationURLWithCodeVerifier.toString()).toEqual(
55
+ `https://authorizationendpoint/?response_type=code&client_id=clientId&redirect_uri=https%3A%2F%2FredirectURI&code_challenge_method=S256&code_challenge=${codeChallenge.replace(
56
+ '/',
57
+ '%2F',
58
+ )}`,
59
+ )
60
+ })
61
+
62
+ it('should validate authorization code', async () => {
63
+ const spySendTokenRequest = spyOn(
64
+ OAuth2Client.prototype,
65
+ '_sendTokenRequest',
66
+ ).mockResolvedValue({} as any)
67
+
68
+ await oauthClient.validateAuthorizationCode('code')
69
+
70
+ const expectedBody = new URLSearchParams()
71
+ expectedBody.set('code', 'code')
72
+ expectedBody.set('client_id', 'clientId')
73
+ expectedBody.set('grant_type', 'authorization_code')
74
+ expectedBody.set('redirect_uri', 'https://redirectURI')
75
+
76
+ expect(spySendTokenRequest).toHaveBeenCalledTimes(1)
77
+ const body = spySendTokenRequest.mock.calls[0]?.[0]
78
+ const options = spySendTokenRequest.mock.calls[0]?.[1]
79
+ expect(body?.toString()).toEqual(expectedBody.toString())
80
+ expect(options).toBeUndefined()
81
+
82
+ await oauthClient.validateAuthorizationCode('code', {
83
+ codeVerifier: 'codeVerifier',
84
+ authenticateWith: 'http_basic_auth',
85
+ credentials: 'credentials',
86
+ })
87
+
88
+ const expectedBody2 = new URLSearchParams()
89
+ expectedBody2.set('code', 'code')
90
+ expectedBody2.set('client_id', 'clientId')
91
+ expectedBody2.set('grant_type', 'authorization_code')
92
+ expectedBody2.set('redirect_uri', 'https://redirectURI')
93
+ expectedBody2.set('code_verifier', 'codeVerifier')
94
+
95
+ expect(spySendTokenRequest).toHaveBeenCalledTimes(2)
96
+ const body2 = spySendTokenRequest.mock.calls[1]?.[0]
97
+ const options2 = spySendTokenRequest.mock.calls[1]?.[1]
98
+ expect(body2?.toString()).toEqual(expectedBody2.toString())
99
+ expect(options2).toEqual({
100
+ codeVerifier: 'codeVerifier',
101
+ authenticateWith: 'http_basic_auth',
102
+ credentials: 'credentials',
103
+ } as any)
104
+
105
+ spySendTokenRequest.mockRestore()
106
+ })
107
+
108
+ it('should refresh access token', async () => {
109
+ const spySendTokenRequest = spyOn(
110
+ OAuth2Client.prototype,
111
+ '_sendTokenRequest',
112
+ ).mockResolvedValue({} as any)
113
+
114
+ await oauthClient.refreshAccessToken('refreshToken')
115
+
116
+ const expectedBody = new URLSearchParams()
117
+ expectedBody.set('refresh_token', 'refreshToken')
118
+ expectedBody.set('client_id', 'clientId')
119
+ expectedBody.set('grant_type', 'refresh_token')
120
+
121
+ expect(spySendTokenRequest).toHaveBeenCalledTimes(1)
122
+ const body = spySendTokenRequest.mock.calls[0]?.[0]
123
+ const options = spySendTokenRequest.mock.calls[0]?.[1]
124
+ expect(body?.toString()).toEqual(expectedBody.toString())
125
+ expect(options).toBeUndefined()
126
+
127
+ await oauthClient.refreshAccessToken('refreshToken', {
128
+ authenticateWith: 'http_basic_auth',
129
+ credentials: 'credentials',
130
+ })
131
+
132
+ const expectedBody2 = new URLSearchParams()
133
+ expectedBody2.set('refresh_token', 'refreshToken')
134
+ expectedBody2.set('client_id', 'clientId')
135
+ expectedBody2.set('grant_type', 'refresh_token')
136
+
137
+ expect(spySendTokenRequest).toHaveBeenCalledTimes(2)
138
+ const body2 = spySendTokenRequest.mock.calls[1]?.[0]
139
+ const options2 = spySendTokenRequest.mock.calls[1]?.[1]
140
+ expect(body2?.toString()).toEqual(expectedBody2.toString())
141
+ expect(options2).toEqual({
142
+ authenticateWith: 'http_basic_auth',
143
+ credentials: 'credentials',
144
+ })
145
+
146
+ spySendTokenRequest.mockRestore()
147
+ })
148
+
149
+ it('should send token request', async () => {
150
+ mockFetch.mockResolvedValue({
151
+ json: () => Promise.resolve({ access_token: 'access_token' }),
152
+ ok: true,
153
+ status: 200,
154
+ } as never)
155
+
156
+ await oauthClient._sendTokenRequest(new URLSearchParams(), {
157
+ authenticateWith: 'http_basic_auth',
158
+ credentials: 'credentials',
159
+ })
160
+
161
+ const encodeCredentials = btoa('clientId:credentials')
162
+
163
+ expect(mockFetch).toHaveBeenCalledTimes(1)
164
+ // @ts-expect-error
165
+ const receivedRequest = mockFetch.mock.calls[0][0] as any
166
+
167
+ if (!receivedRequest) fail()
168
+ expect(receivedRequest.url).toEqual('https://tokenendpoint/')
169
+ expect(receivedRequest.method).toEqual('POST')
170
+ expect(receivedRequest.headers.get('content-type')).toEqual('application/x-www-form-urlencoded')
171
+ expect(receivedRequest.headers.get('accept')).toEqual('application/json')
172
+ expect(receivedRequest.headers.get('user-agent')).toEqual('wabe')
173
+ expect(receivedRequest.headers.get('authorization')).toEqual(`Basic ${encodeCredentials}`)
174
+
175
+ mockFetch.mockRestore()
176
+ })
177
+
178
+ it('should throw an error if the result of the request is not valid', () => {
179
+ mockFetch.mockResolvedValue({
180
+ json: () => Promise.resolve({}),
181
+ ok: false,
182
+ } as never)
183
+
184
+ expect(
185
+ oauthClient._sendTokenRequest(new URLSearchParams(), {
186
+ authenticateWith: 'http_basic_auth',
187
+ credentials: 'credentials',
188
+ }),
189
+ ).rejects.toThrow('Error in token request')
190
+
191
+ mockFetch.mockResolvedValue({
192
+ json: () => Promise.resolve({}),
193
+ ok: true,
194
+ status: 400,
195
+ } as never)
196
+
197
+ expect(
198
+ oauthClient._sendTokenRequest(new URLSearchParams(), {
199
+ authenticateWith: 'http_basic_auth',
200
+ credentials: 'credentials',
201
+ }),
202
+ ).rejects.toThrow('Error in token request')
203
+
204
+ mockFetch.mockResolvedValue({
205
+ json: () => Promise.resolve({}),
206
+ ok: true,
207
+ status: 200,
208
+ } as never)
209
+
210
+ expect(
211
+ oauthClient._sendTokenRequest(new URLSearchParams(), {
212
+ authenticateWith: 'http_basic_auth',
213
+ credentials: 'credentials',
214
+ }),
215
+ ).rejects.toThrow('Error in token request')
216
+
217
+ mockFetch.mockRestore()
218
+ })
219
+ })
@@ -0,0 +1,135 @@
1
+ // Code inspired by Oslo : https://github.com/pilcrowOnPaper/oslo/blob/main/src/oauth2/index.ts
2
+
3
+ import { base64URLencode } from './utils'
4
+
5
+ export interface TokenResponseBody {
6
+ access_token: string
7
+ token_type?: string
8
+ expires_in?: number
9
+ refresh_token?: string
10
+ scope?: string
11
+ }
12
+
13
+ export class OAuth2Client {
14
+ public clientId: string
15
+
16
+ private authorizeEndpoint: string
17
+ private tokenEndpoint: string
18
+ private redirectURI: string
19
+
20
+ constructor(
21
+ clientId: string,
22
+ authorizeEndpoint: string,
23
+ tokenEndpoint: string,
24
+ redirectURI: string,
25
+ ) {
26
+ this.clientId = clientId
27
+ this.authorizeEndpoint = authorizeEndpoint
28
+ this.tokenEndpoint = tokenEndpoint
29
+ this.redirectURI = redirectURI
30
+ }
31
+
32
+ createAuthorizationURL(options?: {
33
+ state?: string
34
+ codeVerifier?: string
35
+ scopes?: string[]
36
+ }): URL {
37
+ const scopes = Array.from(new Set(options?.scopes || [])) // remove duplicates
38
+ const authorizationUrl = new URL(this.authorizeEndpoint)
39
+ authorizationUrl.searchParams.set('response_type', 'code')
40
+ authorizationUrl.searchParams.set('client_id', this.clientId)
41
+
42
+ if (options?.state !== undefined) authorizationUrl.searchParams.set('state', options.state)
43
+
44
+ if (scopes.length > 0) authorizationUrl.searchParams.set('scope', scopes.join(' '))
45
+
46
+ if (this.redirectURI !== null)
47
+ authorizationUrl.searchParams.set('redirect_uri', this.redirectURI)
48
+
49
+ if (options?.codeVerifier !== undefined) {
50
+ const codeChallenge = base64URLencode(options.codeVerifier)
51
+
52
+ authorizationUrl.searchParams.set('code_challenge_method', 'S256')
53
+ authorizationUrl.searchParams.set('code_challenge', codeChallenge)
54
+ }
55
+
56
+ return authorizationUrl
57
+ }
58
+
59
+ validateAuthorizationCode<_TokenResponseBody extends TokenResponseBody>(
60
+ authorizationCode: string,
61
+ options?: {
62
+ codeVerifier?: string
63
+ credentials?: string
64
+ authenticateWith?: 'http_basic_auth' | 'request_body'
65
+ },
66
+ ): Promise<_TokenResponseBody> {
67
+ const body = new URLSearchParams()
68
+ body.set('code', authorizationCode)
69
+ body.set('client_id', this.clientId)
70
+ body.set('grant_type', 'authorization_code')
71
+
72
+ if (this.redirectURI !== null) body.set('redirect_uri', this.redirectURI)
73
+
74
+ if (options?.codeVerifier !== undefined) body.set('code_verifier', options.codeVerifier)
75
+
76
+ return this._sendTokenRequest<_TokenResponseBody>(body, options)
77
+ }
78
+
79
+ async refreshAccessToken<_TokenResponseBody extends TokenResponseBody>(
80
+ refreshToken: string,
81
+ options?: {
82
+ credentials?: string
83
+ authenticateWith?: 'http_basic_auth' | 'request_body'
84
+ scopes?: string[]
85
+ },
86
+ ): Promise<_TokenResponseBody> {
87
+ const body = new URLSearchParams()
88
+ body.set('refresh_token', refreshToken)
89
+ body.set('client_id', this.clientId)
90
+ body.set('grant_type', 'refresh_token')
91
+
92
+ const scopes = Array.from(new Set(options?.scopes ?? [])) // remove duplicates
93
+ if (scopes.length > 0) body.set('scope', scopes.join(' '))
94
+
95
+ return await this._sendTokenRequest<_TokenResponseBody>(body, options)
96
+ }
97
+
98
+ async _sendTokenRequest<_TokenResponseBody extends TokenResponseBody>(
99
+ body: URLSearchParams,
100
+ options?: {
101
+ credentials?: string
102
+ authenticateWith?: 'http_basic_auth' | 'request_body'
103
+ },
104
+ ): Promise<_TokenResponseBody> {
105
+ const headers = new Headers()
106
+ headers.set('Content-Type', 'application/x-www-form-urlencoded')
107
+ headers.set('Accept', 'application/json')
108
+ headers.set('User-Agent', 'wabe')
109
+
110
+ if (options?.credentials !== undefined) {
111
+ const authenticateWith = options?.authenticateWith || 'http_basic_auth'
112
+ if (authenticateWith === 'http_basic_auth') {
113
+ const encodedCredentials = btoa(`${this.clientId}:${options.credentials}`)
114
+ headers.set('Authorization', `Basic ${encodedCredentials}`)
115
+ } else {
116
+ body.set('client_secret', options.credentials)
117
+ }
118
+ }
119
+
120
+ const request = new Request(this.tokenEndpoint, {
121
+ method: 'POST',
122
+ headers,
123
+ body,
124
+ })
125
+
126
+ const response = await fetch(request)
127
+ const result: _TokenResponseBody = await response.json()
128
+
129
+ // providers are allowed to return non-400 status code for errors
130
+ if (!('access_token' in result) || response.status !== 200 || !response.ok)
131
+ throw new Error('Error in token request')
132
+
133
+ return result
134
+ }
135
+ }
@@ -0,0 +1,2 @@
1
+ export * from './Oauth2Client'
2
+ export * from './Google'
@@ -0,0 +1,33 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { base64URLencode, generateRandomValues } from './utils'
3
+
4
+ describe('Oauth utils', () => {
5
+ it('should encode url with base64', () => {
6
+ const content = 'test'
7
+
8
+ // Keep Bun. here to be sure the compatibility between node and Bun implem
9
+ const hasher = new Bun.CryptoHasher('sha256')
10
+ hasher.update(new TextEncoder().encode(content))
11
+ const resultWithPadding = hasher.digest('base64')
12
+
13
+ const result = base64URLencode(content)
14
+
15
+ expect(resultWithPadding).toBe('n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg=')
16
+ expect(result).toBe('n4bQgYhMfWWaL-qgxVrQFaO_TxsrC4Is0V1sFbDwCgg')
17
+ })
18
+
19
+ // Real use case check with oauth simulator
20
+ it('should encode correctly with base64', () => {
21
+ const content = 'bIaNJCsNzrZE7QEzYjwbl0fa1CyzF49moM6Ua4H0d5cG-l7d'
22
+ const result = base64URLencode(content)
23
+
24
+ expect(result).toBe('1pdL2CLvBbNBnrfBZeNYlFzpedMhUTbgyhn0CnWVYoc')
25
+ })
26
+
27
+ it('should generate random values for code_verifier or state', () => {
28
+ const randomValue = generateRandomValues()
29
+
30
+ // Google recommends an entropy between 43 and 128 characters for the code_verifier
31
+ expect(randomValue.length).toEqual(80)
32
+ })
33
+ })
@@ -0,0 +1,27 @@
1
+ import crypto from 'node:crypto'
2
+
3
+ export interface Tokens {
4
+ accessToken: string
5
+ refreshToken?: string | null
6
+ accessTokenExpiresAt?: Date
7
+ refreshTokenExpiresAt?: Date | null
8
+ idToken?: string
9
+ }
10
+
11
+ export interface OAuth2ProviderWithPKCE {
12
+ createAuthorizationURL(state: string, codeVerifier: string): URL
13
+ validateAuthorizationCode(code: string, codeVerifier: string): Promise<Tokens>
14
+ refreshAccessToken?(refreshToken: string): Promise<Tokens>
15
+ }
16
+
17
+ // https://datatracker.ietf.org/doc/html/rfc7636#appendix-A
18
+ export const base64URLencode = (content: string) => {
19
+ const hasher = crypto.createHash('sha256').update(content)
20
+
21
+ const result = hasher.digest('base64')
22
+
23
+ // @ts-expect-error
24
+ return result.split('=')[0].replaceAll('+', '-').replaceAll('/', '_')
25
+ }
26
+
27
+ export const generateRandomValues = () => crypto.randomBytes(60).toString('base64url')
@@ -0,0 +1,127 @@
1
+ import { describe, expect, it, spyOn, beforeAll, afterAll, afterEach } from 'bun:test'
2
+ import { EmailOTP } from './EmailOTP'
3
+ import type { DevWabeTypes } from '../../utils/helper'
4
+ import { setupTests, closeTests } from '../../utils/testHelper'
5
+ import { EmailDevAdapter, type Wabe } from '../..'
6
+ import * as sendOtpCodeTemplate from '../../email/templates/sendOtpCode'
7
+ import { OTP } from '../OTP'
8
+
9
+ describe('EmailOTPProvider', () => {
10
+ const spyEmailSend = spyOn(EmailDevAdapter.prototype, 'send')
11
+ const spySendOtpCodeTemplate = spyOn(sendOtpCodeTemplate, 'sendOtpCodeTemplate')
12
+
13
+ let wabe: Wabe<DevWabeTypes>
14
+
15
+ beforeAll(async () => {
16
+ const setup = await setupTests()
17
+ wabe = setup.wabe
18
+ })
19
+
20
+ afterAll(async () => {
21
+ await closeTests(wabe)
22
+ })
23
+
24
+ afterEach(async () => {
25
+ spyEmailSend.mockClear()
26
+ spySendOtpCodeTemplate.mockClear()
27
+
28
+ await wabe.controllers.database.clearDatabase()
29
+ })
30
+
31
+ it("should send an OTP code to the user's email", async () => {
32
+ const createdUser = await wabe.controllers.database.createObject({
33
+ className: 'User',
34
+ context: {
35
+ wabe,
36
+ isRoot: true,
37
+ },
38
+ data: {
39
+ email: 'email@test.fr',
40
+ },
41
+ select: {
42
+ id: true,
43
+ email: true,
44
+ },
45
+ })
46
+
47
+ if (!createdUser) throw new Error('User not created')
48
+
49
+ const emailOTP = new EmailOTP()
50
+
51
+ await emailOTP.onSendChallenge({
52
+ context: {
53
+ wabe,
54
+ isRoot: false,
55
+ },
56
+ user: createdUser,
57
+ })
58
+
59
+ expect(spyEmailSend).toHaveBeenCalledTimes(1)
60
+ expect(spyEmailSend).toHaveBeenCalledWith(
61
+ expect.objectContaining({
62
+ from: 'main.email@wabe.com',
63
+ to: ['email@test.fr'],
64
+ subject: 'Your OTP code',
65
+ }),
66
+ )
67
+
68
+ const otp = spySendOtpCodeTemplate.mock.calls[0]?.[0]
69
+
70
+ expect(spySendOtpCodeTemplate).toHaveBeenCalledTimes(1)
71
+ expect(otp?.length).toBe(6)
72
+ })
73
+
74
+ it('should return the userId if the OTP code is valid', async () => {
75
+ const createdUser = await wabe.controllers.database.createObject({
76
+ className: 'User',
77
+ context: {
78
+ wabe,
79
+ isRoot: true,
80
+ },
81
+ data: {
82
+ email: 'email@test.fr',
83
+ },
84
+ select: {
85
+ id: true,
86
+ },
87
+ })
88
+
89
+ if (!createdUser) throw new Error('User not created')
90
+
91
+ const otp = new OTP(wabe.config.rootKey).generate(createdUser.id)
92
+
93
+ const emailOTP = new EmailOTP()
94
+
95
+ expect(
96
+ await emailOTP.onVerifyChallenge({
97
+ context: {
98
+ wabe,
99
+ isRoot: false,
100
+ },
101
+ input: {
102
+ email: 'email@test.fr',
103
+ otp,
104
+ },
105
+ }),
106
+ ).toEqual({
107
+ userId: createdUser.id,
108
+ })
109
+ })
110
+
111
+ it("should return null if the user doesn't exist", async () => {
112
+ const emailOTP = new EmailOTP()
113
+
114
+ expect(
115
+ await emailOTP.onVerifyChallenge({
116
+ context: {
117
+ wabe,
118
+ isRoot: false,
119
+ },
120
+ input: {
121
+ email: 'email@test.fr',
122
+ otp: '123456',
123
+ },
124
+ }),
125
+ ).toEqual(null)
126
+ })
127
+ })
@@ -0,0 +1,84 @@
1
+ import { contextWithRoot } from '../..'
2
+ import { sendOtpCodeTemplate } from '../../email/templates/sendOtpCode'
3
+ import type { DevWabeTypes } from '../../utils/helper'
4
+ import type {
5
+ OnSendChallengeOptions,
6
+ OnVerifyChallengeOptions,
7
+ SecondaryProviderInterface,
8
+ } from '../interface'
9
+ import { OTP } from '../OTP'
10
+
11
+ const DUMMY_USER_ID = '00000000-0000-0000-0000-000000000000'
12
+
13
+ type EmailOTPInterface = {
14
+ email: string
15
+ otp: string
16
+ }
17
+
18
+ export class EmailOTP implements SecondaryProviderInterface<DevWabeTypes, EmailOTPInterface> {
19
+ async onSendChallenge({ context, user }: OnSendChallengeOptions<DevWabeTypes>) {
20
+ const emailController = context.wabe.controllers.email
21
+
22
+ if (!emailController) throw new Error('Email controller not found')
23
+
24
+ const mainEmail = context.wabe.config.email?.mainEmail
25
+
26
+ if (!mainEmail) throw new Error('No main email found')
27
+
28
+ if (!user.email) throw new Error('No user email found')
29
+
30
+ const otpClass = new OTP(context.wabe.config.rootKey)
31
+
32
+ const otp = otpClass.generate(user.id)
33
+
34
+ const template = context.wabe.config.email?.htmlTemplates?.sendOTPCode
35
+
36
+ await emailController.send({
37
+ from: mainEmail,
38
+ to: [user.email],
39
+ subject: template?.subject || 'Your OTP code',
40
+ html: template?.fn ? await template.fn({ otp }) : sendOtpCodeTemplate(otp),
41
+ })
42
+ }
43
+
44
+ async onVerifyChallenge({
45
+ context,
46
+ input,
47
+ }: OnVerifyChallengeOptions<DevWabeTypes, EmailOTPInterface>) {
48
+ const users = await context.wabe.controllers.database.getObjects({
49
+ className: 'User',
50
+ where: {
51
+ email: {
52
+ equalTo: input.email,
53
+ },
54
+ },
55
+ select: {
56
+ authentication: true,
57
+ role: true,
58
+ secondFA: true,
59
+ email: true,
60
+ id: true,
61
+ provider: true,
62
+ isOauth: true,
63
+ createdAt: true,
64
+ updatedAt: true,
65
+ },
66
+ first: 1,
67
+ context: contextWithRoot(context),
68
+ })
69
+
70
+ const realUser = users.length > 0 ? users[0] : null
71
+ const userId = realUser?.id ?? DUMMY_USER_ID
72
+
73
+ const isDevBypass =
74
+ !context.wabe.config.isProduction && input.otp === '000000' && realUser !== null
75
+
76
+ const otpClass = new OTP(context.wabe.config.rootKey)
77
+
78
+ const isOtpValid = otpClass.verify(input.otp, userId)
79
+
80
+ if (realUser && (isOtpValid || isDevBypass)) return { userId: realUser.id }
81
+
82
+ return null
83
+ }
84
+ }