wabe 0.6.9 → 0.6.10

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 (158) hide show
  1. package/README.md +138 -32
  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/email/interface.d.ts +1 -1
  7. package/dist/graphql/resolvers.d.ts +4 -2
  8. package/dist/hooks/index.d.ts +1 -0
  9. package/dist/index.d.ts +0 -1
  10. package/dist/index.js +8713 -8867
  11. package/dist/server/index.d.ts +4 -2
  12. package/dist/utils/crypto.d.ts +7 -0
  13. package/dist/utils/helper.d.ts +4 -1
  14. package/generated/schema.graphql +16 -14
  15. package/generated/wabe.ts +4 -4
  16. package/package.json +15 -15
  17. package/src/authentication/OTP.test.ts +69 -0
  18. package/src/authentication/OTP.ts +66 -0
  19. package/src/authentication/Session.test.ts +665 -0
  20. package/src/authentication/Session.ts +529 -0
  21. package/src/authentication/defaultAuthentication.ts +214 -0
  22. package/src/authentication/index.ts +3 -0
  23. package/src/authentication/interface.ts +157 -0
  24. package/src/authentication/oauth/GitHub.test.ts +105 -0
  25. package/src/authentication/oauth/GitHub.ts +133 -0
  26. package/src/authentication/oauth/Google.test.ts +105 -0
  27. package/src/authentication/oauth/Google.ts +110 -0
  28. package/src/authentication/oauth/Oauth2Client.test.ts +225 -0
  29. package/src/authentication/oauth/Oauth2Client.ts +140 -0
  30. package/src/authentication/oauth/index.ts +2 -0
  31. package/src/authentication/oauth/utils.test.ts +35 -0
  32. package/src/authentication/oauth/utils.ts +28 -0
  33. package/src/authentication/providers/EmailOTP.test.ts +138 -0
  34. package/src/authentication/providers/EmailOTP.ts +93 -0
  35. package/src/authentication/providers/EmailPassword.test.ts +187 -0
  36. package/src/authentication/providers/EmailPassword.ts +130 -0
  37. package/src/authentication/providers/EmailPasswordSRP.test.ts +206 -0
  38. package/src/authentication/providers/EmailPasswordSRP.ts +184 -0
  39. package/src/authentication/providers/GitHub.ts +30 -0
  40. package/src/authentication/providers/Google.ts +30 -0
  41. package/src/authentication/providers/OAuth.test.ts +185 -0
  42. package/src/authentication/providers/OAuth.ts +112 -0
  43. package/src/authentication/providers/PhonePassword.test.ts +187 -0
  44. package/src/authentication/providers/PhonePassword.ts +129 -0
  45. package/src/authentication/providers/QRCodeOTP.test.ts +79 -0
  46. package/src/authentication/providers/QRCodeOTP.ts +65 -0
  47. package/src/authentication/providers/index.ts +6 -0
  48. package/src/authentication/resolvers/refreshResolver.test.ts +37 -0
  49. package/src/authentication/resolvers/refreshResolver.ts +20 -0
  50. package/src/authentication/resolvers/signInWithResolver.inte.test.ts +59 -0
  51. package/src/authentication/resolvers/signInWithResolver.test.ts +307 -0
  52. package/src/authentication/resolvers/signInWithResolver.ts +102 -0
  53. package/src/authentication/resolvers/signOutResolver.test.ts +41 -0
  54. package/src/authentication/resolvers/signOutResolver.ts +22 -0
  55. package/src/authentication/resolvers/signUpWithResolver.test.ts +186 -0
  56. package/src/authentication/resolvers/signUpWithResolver.ts +69 -0
  57. package/src/authentication/resolvers/verifyChallenge.test.ts +136 -0
  58. package/src/authentication/resolvers/verifyChallenge.ts +69 -0
  59. package/src/authentication/roles.test.ts +59 -0
  60. package/src/authentication/roles.ts +40 -0
  61. package/src/authentication/utils.test.ts +99 -0
  62. package/src/authentication/utils.ts +43 -0
  63. package/src/cache/InMemoryCache.test.ts +62 -0
  64. package/src/cache/InMemoryCache.ts +45 -0
  65. package/src/cron/index.test.ts +17 -0
  66. package/src/cron/index.ts +46 -0
  67. package/src/database/DatabaseController.test.ts +625 -0
  68. package/src/database/DatabaseController.ts +983 -0
  69. package/src/database/index.test.ts +1230 -0
  70. package/src/database/index.ts +9 -0
  71. package/src/database/interface.ts +312 -0
  72. package/src/email/DevAdapter.ts +8 -0
  73. package/src/email/EmailController.test.ts +29 -0
  74. package/src/email/EmailController.ts +13 -0
  75. package/src/email/index.ts +2 -0
  76. package/src/email/interface.ts +36 -0
  77. package/src/email/templates/sendOtpCode.ts +120 -0
  78. package/src/file/FileController.ts +28 -0
  79. package/src/file/FileDevAdapter.ts +54 -0
  80. package/src/file/hookDeleteFile.ts +27 -0
  81. package/src/file/hookReadFile.ts +70 -0
  82. package/src/file/hookUploadFile.ts +53 -0
  83. package/src/file/index.test.ts +979 -0
  84. package/src/file/index.ts +2 -0
  85. package/src/file/interface.ts +42 -0
  86. package/src/graphql/GraphQLSchema.test.ts +4399 -0
  87. package/src/graphql/GraphQLSchema.ts +928 -0
  88. package/src/graphql/index.ts +2 -0
  89. package/src/graphql/parseGraphqlSchema.ts +94 -0
  90. package/src/graphql/parser.test.ts +217 -0
  91. package/src/graphql/parser.ts +566 -0
  92. package/src/graphql/pointerAndRelationFunction.ts +200 -0
  93. package/src/graphql/resolvers.ts +467 -0
  94. package/src/graphql/tests/aggregation.test.ts +1123 -0
  95. package/src/graphql/tests/e2e.test.ts +596 -0
  96. package/src/graphql/tests/scalars.test.ts +250 -0
  97. package/src/graphql/types.ts +219 -0
  98. package/src/hooks/HookObject.test.ts +122 -0
  99. package/src/hooks/HookObject.ts +168 -0
  100. package/src/hooks/authentication.ts +76 -0
  101. package/src/hooks/createUser.test.ts +77 -0
  102. package/src/hooks/createUser.ts +10 -0
  103. package/src/hooks/defaultFields.test.ts +187 -0
  104. package/src/hooks/defaultFields.ts +40 -0
  105. package/src/hooks/deleteSession.test.ts +181 -0
  106. package/src/hooks/deleteSession.ts +20 -0
  107. package/src/hooks/hashFieldHook.test.ts +163 -0
  108. package/src/hooks/hashFieldHook.ts +97 -0
  109. package/src/hooks/index.test.ts +207 -0
  110. package/src/hooks/index.ts +430 -0
  111. package/src/hooks/permissions.test.ts +424 -0
  112. package/src/hooks/permissions.ts +113 -0
  113. package/src/hooks/protected.test.ts +551 -0
  114. package/src/hooks/protected.ts +72 -0
  115. package/src/hooks/searchableFields.test.ts +166 -0
  116. package/src/hooks/searchableFields.ts +98 -0
  117. package/src/hooks/session.test.ts +138 -0
  118. package/src/hooks/session.ts +78 -0
  119. package/src/hooks/setEmail.test.ts +216 -0
  120. package/src/hooks/setEmail.ts +35 -0
  121. package/src/hooks/setupAcl.test.ts +589 -0
  122. package/src/hooks/setupAcl.ts +29 -0
  123. package/src/index.ts +9 -0
  124. package/src/schema/Schema.test.ts +484 -0
  125. package/src/schema/Schema.ts +795 -0
  126. package/src/schema/defaultResolvers.ts +94 -0
  127. package/src/schema/index.ts +1 -0
  128. package/src/schema/resolvers/meResolver.test.ts +62 -0
  129. package/src/schema/resolvers/meResolver.ts +14 -0
  130. package/src/schema/resolvers/newFile.ts +0 -0
  131. package/src/schema/resolvers/resetPassword.test.ts +345 -0
  132. package/src/schema/resolvers/resetPassword.ts +64 -0
  133. package/src/schema/resolvers/sendEmail.test.ts +118 -0
  134. package/src/schema/resolvers/sendEmail.ts +21 -0
  135. package/src/schema/resolvers/sendOtpCode.test.ts +153 -0
  136. package/src/schema/resolvers/sendOtpCode.ts +52 -0
  137. package/src/security.test.ts +3461 -0
  138. package/src/server/defaultSessionHandler.test.ts +66 -0
  139. package/src/server/defaultSessionHandler.ts +115 -0
  140. package/src/server/generateCodegen.ts +476 -0
  141. package/src/server/index.test.ts +552 -0
  142. package/src/server/index.ts +354 -0
  143. package/src/server/interface.ts +11 -0
  144. package/src/server/routes/authHandler.ts +187 -0
  145. package/src/server/routes/index.ts +40 -0
  146. package/src/utils/crypto.test.ts +41 -0
  147. package/src/utils/crypto.ts +121 -0
  148. package/src/utils/export.ts +13 -0
  149. package/src/utils/helper.ts +195 -0
  150. package/src/utils/index.test.ts +11 -0
  151. package/src/utils/index.ts +201 -0
  152. package/src/utils/preload.ts +8 -0
  153. package/src/utils/testHelper.ts +117 -0
  154. package/tsconfig.json +32 -0
  155. package/bunfig.toml +0 -4
  156. package/dist/ai/index.d.ts +0 -1
  157. package/dist/ai/interface.d.ts +0 -9
  158. /package/dist/server/{defaultHandlers.d.ts → defaultSessionHandler.d.ts} +0 -0
@@ -0,0 +1,69 @@
1
+ import type { SignUpWithInput } from '../../../generated/wabe'
2
+ import type { WabeContext } from '../../server/interface'
3
+ import { Session } from '../Session'
4
+
5
+ // 0 - Get the authentication method
6
+ // 1 - We check if the signUp is possible (call onSign)
7
+ // 2 - We create the user
8
+ // 3 - We create session
9
+ export const signUpWithResolver = async (
10
+ _: any,
11
+ {
12
+ input,
13
+ }: {
14
+ input: SignUpWithInput
15
+ },
16
+ context: WabeContext<any>,
17
+ ) => {
18
+ if (context.wabe.config.authentication?.disableSignUp)
19
+ throw new Error('SignUp is disabled')
20
+
21
+ // Create object call the provider signUp
22
+ const res = await context.wabe.controllers.database.createObject({
23
+ className: 'User',
24
+ data: {
25
+ authentication: input.authentication,
26
+ },
27
+ context,
28
+ select: { id: true },
29
+ })
30
+
31
+ const createdUserId = res?.id
32
+
33
+ const session = new Session()
34
+
35
+ if (!createdUserId) throw new Error('User not created')
36
+
37
+ const { accessToken, refreshToken, csrfToken } = await session.create(
38
+ createdUserId,
39
+ context,
40
+ )
41
+
42
+ if (context.wabe.config.authentication?.session?.cookieSession) {
43
+ context.response?.setCookie('refreshToken', refreshToken, {
44
+ httpOnly: true,
45
+ path: '/',
46
+ sameSite: 'Strict',
47
+ secure: true,
48
+ expires: session.getRefreshTokenExpireAt(context.wabe.config),
49
+ })
50
+
51
+ context.response?.setCookie('accessToken', accessToken, {
52
+ httpOnly: true,
53
+ path: '/',
54
+ sameSite: 'Strict',
55
+ secure: true,
56
+ expires: session.getAccessTokenExpireAt(context.wabe.config),
57
+ })
58
+
59
+ context.response?.setCookie('csrfToken', csrfToken, {
60
+ httpOnly: true,
61
+ path: '/',
62
+ sameSite: 'Strict',
63
+ secure: true,
64
+ expires: session.getAccessTokenExpireAt(context.wabe.config),
65
+ })
66
+ }
67
+
68
+ return { accessToken, refreshToken, csrfToken, id: createdUserId }
69
+ }
@@ -0,0 +1,136 @@
1
+ import { describe, expect, it, beforeEach, mock, spyOn } from 'bun:test'
2
+ import { verifyChallengeResolver } from './verifyChallenge'
3
+ import type { WabeContext } from '../../server/interface'
4
+ import { Session } from '../Session'
5
+
6
+ describe('verifyChallenge', () => {
7
+ const mockOnVerifyChallenge = mock(() => Promise.resolve(true))
8
+
9
+ const context: WabeContext<any> = {
10
+ sessionId: 'sessionId',
11
+ user: {
12
+ id: 'userId',
13
+ } as any,
14
+ wabe: {
15
+ config: {
16
+ authentication: {
17
+ customAuthenticationMethods: [
18
+ {
19
+ name: 'fakeOtp',
20
+ input: {
21
+ code: {
22
+ type: 'String',
23
+ required: true,
24
+ },
25
+ },
26
+ provider: {
27
+ onVerifyChallenge: mockOnVerifyChallenge,
28
+ onSendChallenge: () => Promise.resolve(),
29
+ },
30
+ },
31
+ ],
32
+ },
33
+ },
34
+ },
35
+ } as any
36
+
37
+ beforeEach(() => {
38
+ mockOnVerifyChallenge.mockClear()
39
+ })
40
+
41
+ it('should throw an error if no one factor is provided', () => {
42
+ expect(
43
+ verifyChallengeResolver(
44
+ undefined,
45
+ {
46
+ input: {},
47
+ },
48
+ context,
49
+ ),
50
+ ).rejects.toThrow('One factor is required')
51
+ })
52
+
53
+ it('should throw an error if more than one factor is provided', () => {
54
+ expect(
55
+ verifyChallengeResolver(
56
+ undefined,
57
+ {
58
+ input: {
59
+ secondFA: {
60
+ // @ts-expect-error
61
+ factor1: {},
62
+ factor2: {},
63
+ },
64
+ },
65
+ },
66
+ context,
67
+ ),
68
+ ).rejects.toThrow('Only one factor is allowed')
69
+ })
70
+
71
+ it('should throw an error if the onVerifyChallenge failed', () => {
72
+ mockOnVerifyChallenge.mockResolvedValue(false as never)
73
+
74
+ expect(
75
+ verifyChallengeResolver(
76
+ undefined,
77
+ {
78
+ input: {
79
+ secondFA: {
80
+ // @ts-expect-error
81
+ fakeOtp: {
82
+ code: '123456',
83
+ },
84
+ },
85
+ },
86
+ },
87
+ context,
88
+ ),
89
+ ).rejects.toThrow('Invalid challenge')
90
+ })
91
+
92
+ it('should return userId if the verifyChallenge is correct', async () => {
93
+ const spyCreateSession = spyOn(
94
+ Session.prototype,
95
+ 'create',
96
+ ).mockResolvedValue({
97
+ accessToken: 'accessToken',
98
+ refreshToken: 'refreshToken',
99
+ sessionId: 'sessionId',
100
+ csrfToken: 'csrfToken',
101
+ })
102
+
103
+ mockOnVerifyChallenge.mockResolvedValue({ userId: 'userId' } as never)
104
+
105
+ expect(
106
+ await verifyChallengeResolver(
107
+ undefined,
108
+ {
109
+ input: {
110
+ secondFA: {
111
+ // @ts-expect-error
112
+ fakeOtp: {
113
+ code: '123456',
114
+ },
115
+ },
116
+ },
117
+ },
118
+ context,
119
+ ),
120
+ ).toEqual({
121
+ accessToken: 'accessToken',
122
+ srp: undefined,
123
+ })
124
+
125
+ expect(mockOnVerifyChallenge).toHaveBeenCalledTimes(1)
126
+ expect(mockOnVerifyChallenge).toHaveBeenCalledWith({
127
+ input: { code: '123456' },
128
+ context: expect.any(Object),
129
+ })
130
+
131
+ expect(spyCreateSession).toHaveBeenCalledTimes(1)
132
+ expect(spyCreateSession).toHaveBeenCalledWith('userId', context)
133
+
134
+ spyCreateSession.mockRestore()
135
+ })
136
+ })
@@ -0,0 +1,69 @@
1
+ import type { VerifyChallengeInput } from '../../../generated/wabe'
2
+ import type { WabeContext } from '../../server/interface'
3
+ import type { DevWabeTypes } from '../../utils/helper'
4
+ import { Session } from '../Session'
5
+ import type { SecondaryProviderInterface } from '../interface'
6
+ import { getAuthenticationMethod } from '../utils'
7
+
8
+ export const verifyChallengeResolver = async (
9
+ _: any,
10
+ {
11
+ input,
12
+ }: {
13
+ input: VerifyChallengeInput
14
+ },
15
+ context: WabeContext<DevWabeTypes>,
16
+ ) => {
17
+ if (!input.secondFA) throw new Error('One factor is required')
18
+
19
+ const listOfFactor = Object.keys(input.secondFA)
20
+
21
+ if (listOfFactor.length > 1) throw new Error('Only one factor is allowed')
22
+
23
+ const { provider, name } = getAuthenticationMethod<
24
+ any,
25
+ SecondaryProviderInterface<DevWabeTypes>
26
+ >(listOfFactor, context)
27
+
28
+ const result = await provider.onVerifyChallenge({
29
+ context,
30
+ // @ts-expect-error
31
+ input: input.secondFA[name],
32
+ })
33
+
34
+ if (!result?.userId) throw new Error('Invalid challenge')
35
+
36
+ const session = new Session()
37
+
38
+ const { accessToken, refreshToken } = await session.create(
39
+ result.userId,
40
+ context,
41
+ )
42
+
43
+ if (context.wabe.config.authentication?.session?.cookieSession) {
44
+ const accessTokenExpiresAt = session.getAccessTokenExpireAt(
45
+ context.wabe.config,
46
+ )
47
+ const refreshTokenExpiresAt = session.getRefreshTokenExpireAt(
48
+ context.wabe.config,
49
+ )
50
+
51
+ context.response?.setCookie('refreshToken', refreshToken, {
52
+ httpOnly: true,
53
+ path: '/',
54
+ sameSite: 'None',
55
+ secure: true,
56
+ expires: refreshTokenExpiresAt,
57
+ })
58
+
59
+ context.response?.setCookie('accessToken', accessToken, {
60
+ httpOnly: true,
61
+ path: '/',
62
+ sameSite: 'None',
63
+ secure: true,
64
+ expires: accessTokenExpiresAt,
65
+ })
66
+ }
67
+
68
+ return { accessToken, srp: result.srp }
69
+ }
@@ -0,0 +1,59 @@
1
+ import { afterAll, beforeAll, describe, it, expect } from 'bun:test'
2
+ import type { Wabe } from '../server'
3
+ import type { DevWabeTypes } from '../utils/helper'
4
+ import { initializeRoles } from './roles'
5
+ import { setupTests, closeTests } from '../utils/testHelper'
6
+
7
+ describe('roles', () => {
8
+ let wabe: Wabe<DevWabeTypes>
9
+
10
+ beforeAll(async () => {
11
+ const setup = await setupTests()
12
+ wabe = setup.wabe
13
+ })
14
+
15
+ afterAll(async () => {
16
+ await closeTests(wabe)
17
+ })
18
+
19
+ it('should create all roles', async () => {
20
+ await wabe.controllers.database.clearDatabase()
21
+
22
+ await initializeRoles(wabe)
23
+
24
+ const res = await wabe.controllers.database.getObjects({
25
+ className: 'Role',
26
+ context: { isRoot: true, wabe: wabe },
27
+ select: { name: true },
28
+ })
29
+
30
+ expect(res.length).toEqual(4)
31
+ expect(res.map((role) => role?.name)).toEqual([
32
+ 'Client',
33
+ 'Client2',
34
+ 'Client3',
35
+ 'Admin',
36
+ ])
37
+ })
38
+
39
+ it('should not create all roles if there already exist', async () => {
40
+ await wabe.controllers.database.clearDatabase()
41
+
42
+ await initializeRoles(wabe)
43
+ await initializeRoles(wabe)
44
+
45
+ const res = await wabe.controllers.database.getObjects({
46
+ className: 'Role',
47
+ context: { isRoot: true, wabe: wabe },
48
+ select: { name: true },
49
+ })
50
+
51
+ expect(res.length).toEqual(4)
52
+ expect(res.map((role) => role?.name)).toEqual([
53
+ 'Client',
54
+ 'Client2',
55
+ 'Client3',
56
+ 'Admin',
57
+ ])
58
+ })
59
+ })
@@ -0,0 +1,40 @@
1
+ import { notEmpty, type Wabe } from '..'
2
+ import type { DevWabeTypes } from '../utils/helper'
3
+
4
+ export const initializeRoles = async (wabe: Wabe<DevWabeTypes>) => {
5
+ const roles = wabe.config?.authentication?.roles || []
6
+
7
+ if (roles.length === 0) return
8
+
9
+ const res = await wabe.controllers.database.getObjects({
10
+ className: 'Role',
11
+ context: {
12
+ isRoot: true,
13
+ wabe,
14
+ },
15
+ select: { name: true },
16
+ where: {
17
+ name: {
18
+ in: roles,
19
+ },
20
+ },
21
+ })
22
+
23
+ const alreadyCreatedRoles = res.map((role) => role?.name).filter(notEmpty)
24
+
25
+ const objectsToCreate = roles
26
+ .filter((role) => !alreadyCreatedRoles.includes(role))
27
+ .map((role) => ({ name: role }))
28
+
29
+ if (objectsToCreate.length === 0) return
30
+
31
+ await wabe.controllers.database.createObjects({
32
+ className: 'Role',
33
+ context: {
34
+ isRoot: true,
35
+ wabe,
36
+ },
37
+ data: objectsToCreate,
38
+ select: {},
39
+ })
40
+ }
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it, mock } from 'bun:test'
2
+ import { getAuthenticationMethod } from './utils'
3
+
4
+ describe('Authentication utils', () => {
5
+ const mockOnSignIn = mock(() => Promise.resolve({}))
6
+ const mockOnSignUp = mock(() => Promise.resolve({}))
7
+
8
+ const mockOnSendChallenge = mock(() => Promise.resolve())
9
+ const mockOnVerifyChallenge = mock(() => Promise.resolve(true))
10
+
11
+ const config = {
12
+ authentication: {
13
+ customAuthenticationMethods: [
14
+ {
15
+ name: 'otp',
16
+ input: {
17
+ code: {
18
+ type: 'String',
19
+ required: true,
20
+ },
21
+ },
22
+ provider: {
23
+ name: 'otp',
24
+ onSendChallenge: mockOnSendChallenge as any,
25
+ onVerifyChallenge: mockOnVerifyChallenge as any,
26
+ },
27
+ isSecondaryFactor: true,
28
+ dataToStore: {},
29
+ },
30
+ {
31
+ name: 'emailPassword',
32
+ input: {
33
+ email: {
34
+ type: 'Email',
35
+ required: true,
36
+ },
37
+ password: {
38
+ type: 'String',
39
+ required: true,
40
+ },
41
+ },
42
+ provider: {
43
+ name: 'emailPassword',
44
+ onSignUp: mockOnSignIn as any,
45
+ onSignIn: mockOnSignUp as any,
46
+ },
47
+ dataToStore: {},
48
+ },
49
+ ],
50
+ },
51
+ } as any
52
+
53
+ it('should throw an error if we provided two authentication methods', () => {
54
+ expect(() =>
55
+ getAuthenticationMethod(['emailPassword', 'otherAuthenticationMethod'], {
56
+ wabe: { config },
57
+ } as any),
58
+ ).toThrow('One authentication method is required at the time')
59
+ })
60
+
61
+ it('should throw an error if no authentication methods is provided', () => {
62
+ expect(() =>
63
+ getAuthenticationMethod([], { wabe: { config } } as any),
64
+ ).toThrow('One authentication method is required at the time')
65
+ })
66
+
67
+ it('should throw an error if no one authentication method is found', () => {
68
+ expect(() =>
69
+ getAuthenticationMethod(['otherAuthenticationMethod'], {
70
+ wabe: { config },
71
+ } as any),
72
+ ).toThrow('No available custom authentication methods found')
73
+ })
74
+
75
+ it('should find a secondary factor method', () => {
76
+ expect(
77
+ getAuthenticationMethod(['otp'], { wabe: { config } } as any),
78
+ ).toEqual({
79
+ name: 'otp',
80
+ input: expect.any(Object),
81
+ provider: expect.any(Object),
82
+ isSecondaryFactor: true,
83
+ dataToStore: {},
84
+ })
85
+ })
86
+
87
+ it('should return the valid authentication method', () => {
88
+ expect(
89
+ getAuthenticationMethod(['emailPassword'], {
90
+ wabe: { config },
91
+ } as any),
92
+ ).toEqual({
93
+ name: 'emailPassword',
94
+ input: expect.any(Object),
95
+ provider: expect.any(Object),
96
+ dataToStore: {},
97
+ })
98
+ })
99
+ })
@@ -0,0 +1,43 @@
1
+ import type { WabeTypes } from '../server'
2
+ import type { WabeContext } from '../server/interface'
3
+ import type {
4
+ CustomAuthenticationMethods,
5
+ ProviderInterface,
6
+ SecondaryProviderInterface,
7
+ } from './interface'
8
+
9
+ export const getAuthenticationMethod = <
10
+ T extends WabeTypes,
11
+ U = ProviderInterface<T> | SecondaryProviderInterface<T>,
12
+ >(
13
+ listOfMethods: string[],
14
+ context: WabeContext<any>,
15
+ ): CustomAuthenticationMethods<T, U> => {
16
+ const customAuthenticationConfig =
17
+ context.wabe.config?.authentication?.customAuthenticationMethods
18
+
19
+ if (!customAuthenticationConfig)
20
+ throw new Error('No custom authentication methods found')
21
+
22
+ // We remove the secondary factor to only get all authentication methods
23
+ const authenticationMethods = listOfMethods.filter(
24
+ (method) => method !== 'secondaryFactor',
25
+ )
26
+
27
+ // We check if the client don't use multiple authentication methods at the same time
28
+ if (authenticationMethods.length > 1 || authenticationMethods.length === 0)
29
+ throw new Error('One authentication method is required at the time')
30
+
31
+ const authenticationMethod = authenticationMethods[0]
32
+
33
+ // We check if the authentication method is valid
34
+ const validAuthenticationMethod = customAuthenticationConfig.find(
35
+ (method) =>
36
+ method.name.toLowerCase() === authenticationMethod?.toLowerCase(),
37
+ )
38
+
39
+ if (!validAuthenticationMethod)
40
+ throw new Error('No available custom authentication methods found')
41
+
42
+ return validAuthenticationMethod as CustomAuthenticationMethods<T, U>
43
+ }
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it, beforeEach, spyOn } from 'bun:test'
2
+ import { InMemoryCache } from './InMemoryCache'
3
+
4
+ describe('InMemoryCache', () => {
5
+ const inMemoryCache = new InMemoryCache({
6
+ interval: 100,
7
+ })
8
+
9
+ beforeEach(() => {
10
+ inMemoryCache.clear()
11
+ })
12
+
13
+ it('should init a InMemoryCache', () => {
14
+ const spySetInterval = spyOn(global, 'setInterval')
15
+ const spyClearInterval = spyOn(global, 'clearInterval')
16
+
17
+ const store = new InMemoryCache({ interval: 100 })
18
+
19
+ store.stop()
20
+
21
+ expect(spySetInterval).toHaveBeenCalledTimes(1)
22
+ expect(spySetInterval).toHaveBeenCalledWith(expect.any(Function), 100)
23
+ expect(spyClearInterval).toHaveBeenCalledTimes(1)
24
+ expect(spyClearInterval).toHaveBeenCalledWith(store.intervalId)
25
+ })
26
+
27
+ it('should store a value', () => {
28
+ inMemoryCache.set('key', 'value')
29
+
30
+ expect(inMemoryCache.get('key')).toBe('value')
31
+ })
32
+
33
+ it('should clear an in memory cache', () => {
34
+ inMemoryCache.set('key', 'value')
35
+
36
+ expect(inMemoryCache.get('key')).toBe('value')
37
+
38
+ inMemoryCache.clear()
39
+
40
+ expect(inMemoryCache.get('key')).toBeUndefined()
41
+ })
42
+
43
+ it('should return undefined if the key does not exist', () => {
44
+ expect(inMemoryCache.get('key2')).toBeUndefined()
45
+ })
46
+
47
+ it('should clear a cache after timeLimit', () => {
48
+ const localInMemoryCache = new InMemoryCache({
49
+ interval: 100,
50
+ })
51
+
52
+ localInMemoryCache.set('key', 'value')
53
+
54
+ setTimeout(() => {
55
+ expect(localInMemoryCache.get('key')).not.toBeUndefined()
56
+ }, 50)
57
+
58
+ setTimeout(() => {
59
+ expect(localInMemoryCache.get('key')).toBeUndefined()
60
+ }, 100)
61
+ })
62
+ })
@@ -0,0 +1,45 @@
1
+ export interface InMemoryCacheOptions {
2
+ /**
3
+ * Interval in ms to clear the cache
4
+ */
5
+ interval: number
6
+ }
7
+
8
+ /**
9
+ * InMemoryCache is a class that stores data for a certain amount of time
10
+ */
11
+ export class InMemoryCache<T> {
12
+ private options: InMemoryCacheOptions
13
+ private store: Record<string, any>
14
+
15
+ public intervalId: Timer | undefined = undefined
16
+
17
+ constructor(options: InMemoryCacheOptions) {
18
+ this.options = options
19
+ this.store = {}
20
+
21
+ this._init()
22
+ }
23
+
24
+ _init() {
25
+ this.intervalId = setInterval(() => {
26
+ this.clear()
27
+ }, this.options.interval)
28
+ }
29
+
30
+ set(key: string, value: T) {
31
+ this.store[key] = value
32
+ }
33
+
34
+ get(key: string): T | undefined {
35
+ return this.store[key]
36
+ }
37
+
38
+ clear() {
39
+ this.store = {}
40
+ }
41
+
42
+ stop() {
43
+ clearInterval(this.intervalId)
44
+ }
45
+ }
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it, mock } from 'bun:test'
2
+ import { cron } from '.'
3
+
4
+ describe('cron', () => {
5
+ it('should run the function', () => {
6
+ const run = mock()
7
+
8
+ const job = cron({
9
+ pattern: '* * * * * *',
10
+ run,
11
+ })({} as any)
12
+
13
+ job.trigger()
14
+
15
+ expect(run).toHaveBeenCalledTimes(1)
16
+ })
17
+ })
@@ -0,0 +1,46 @@
1
+ import { Cron } from 'croner'
2
+ import type { Wabe, WabeTypes } from '../server'
3
+
4
+ export type OutputCron<T extends WabeTypes> = (wabe: Wabe<T>) => Cron
5
+
6
+ export const cron =
7
+ <T extends WabeTypes>({
8
+ pattern,
9
+ run,
10
+ maxRuns,
11
+ enabledProtectedRuns,
12
+ }: {
13
+ pattern: string
14
+ maxRuns?: number
15
+ enabledProtectedRuns?: boolean
16
+ run: (wabe: Wabe<T>) => any | Promise<any>
17
+ }): OutputCron<T> =>
18
+ (wabe: Wabe<T>) =>
19
+ new Cron(pattern, { maxRuns, protect: enabledProtectedRuns }, () =>
20
+ run(wabe),
21
+ )
22
+
23
+ export enum CronExpressions {
24
+ EVERY_SECOND = '* * * * * *',
25
+ EVERY_MINUTE = '0 * * * * *',
26
+ EVERY_HOUR = '0 0 * * * *',
27
+ EVERY_DAY_AT_MIDNIGHT = '0 0 0 * * *',
28
+ EVERY_WEEK = '0 0 0 * * 0',
29
+ EVERY_MONTH = '0 0 0 1 * *',
30
+ EVERY_YEAR = '0 0 0 1 1 *',
31
+ WEEKDAYS_MORNING = '0 0 7 * * 1-5', // Every weekday at 7 AM
32
+ WEEKENDS_EVENING = '0 0 19 * * 6-7', // Every weekend at 7 PM
33
+ FIRST_DAY_OF_MONTH = '0 0 0 1 * *',
34
+ LAST_DAY_OF_MONTH = '0 0 0 L * *', // L stands for the last day of the month
35
+ EVERY_15_MINUTES = '0 */15 * * * *',
36
+ EVERY_30_MINUTES = '0 */30 * * * *',
37
+ EVERY_2_HOURS = '0 0 */2 * * *',
38
+ EVERY_6_HOURS = '0 0 */6 * * *',
39
+ EVERY_12_HOURS = '0 0 */12 * * *',
40
+ }
41
+
42
+ export type CronConfig<T extends WabeTypes> = Array<{
43
+ name: string
44
+ cron: OutputCron<T>
45
+ job?: Cron
46
+ }>