@app-connect/core 1.7.37 → 1.7.38

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 (286) hide show
  1. package/README.md +17 -16
  2. package/dist/connector/developerPortal.d.ts +6 -0
  3. package/{connector → dist/connector}/developerPortal.js +29 -12
  4. package/dist/connector/mock.d.ts +1 -0
  5. package/{connector → dist/connector}/mock.js +33 -17
  6. package/dist/connector/proxy/engine.d.ts +10 -0
  7. package/dist/connector/proxy/engine.js +222 -0
  8. package/dist/connector/proxy/index.d.ts +5 -0
  9. package/dist/connector/proxy/index.js +511 -0
  10. package/dist/connector/registry.d.ts +1 -0
  11. package/dist/connector/registry.js +243 -0
  12. package/dist/handlers/admin.d.ts +1 -0
  13. package/{handlers → dist/handlers}/admin.js +137 -78
  14. package/dist/handlers/appointment.d.ts +9 -0
  15. package/{handlers → dist/handlers}/appointment.js +58 -29
  16. package/dist/handlers/auth.d.ts +9 -0
  17. package/{handlers → dist/handlers}/auth.js +68 -40
  18. package/dist/handlers/calldown.d.ts +10 -0
  19. package/dist/handlers/calldown.js +134 -0
  20. package/dist/handlers/contact.d.ts +1 -0
  21. package/{handlers → dist/handlers}/contact.js +61 -39
  22. package/dist/handlers/disposition.d.ts +1 -0
  23. package/{handlers → dist/handlers}/disposition.js +20 -10
  24. package/dist/handlers/log.d.ts +1 -0
  25. package/{handlers → dist/handlers}/log.js +91 -124
  26. package/dist/handlers/managedAuth.d.ts +1 -0
  27. package/{handlers → dist/handlers}/managedAuth.js +134 -61
  28. package/dist/handlers/managedOAuth.d.ts +13 -0
  29. package/{handlers → dist/handlers}/managedOAuth.js +102 -30
  30. package/dist/handlers/plugin.d.ts +1 -0
  31. package/{handlers → dist/handlers}/plugin.js +59 -27
  32. package/dist/handlers/user.d.ts +1 -0
  33. package/{handlers → dist/handlers}/user.js +45 -27
  34. package/dist/index.d.ts +1 -0
  35. package/{index.js → dist/index.js} +538 -449
  36. package/dist/jest.config.d.ts +1 -0
  37. package/dist/jest.config.js +65 -0
  38. package/dist/lib/analytics.d.ts +4 -0
  39. package/{lib → dist/lib}/analytics.js +8 -6
  40. package/dist/lib/authSession.d.ts +5 -0
  41. package/{lib → dist/lib}/authSession.js +15 -43
  42. package/dist/lib/cacheCleanup.d.ts +4 -0
  43. package/{lib → dist/lib}/cacheCleanup.js +5 -17
  44. package/dist/lib/callLogComposer.d.ts +109 -0
  45. package/{lib → dist/lib}/callLogComposer.js +157 -197
  46. package/dist/lib/callLogLookup.d.ts +6 -0
  47. package/{lib → dist/lib}/callLogLookup.js +12 -34
  48. package/dist/lib/constants.d.ts +6 -0
  49. package/dist/lib/constants.js +9 -0
  50. package/dist/lib/debugTracer.d.ts +17 -0
  51. package/{lib → dist/lib}/debugTracer.js +7 -83
  52. package/dist/lib/encode.d.ts +3 -0
  53. package/dist/lib/encode.js +50 -0
  54. package/dist/lib/errorHandler.d.ts +7 -0
  55. package/dist/lib/errorHandler.js +161 -0
  56. package/dist/lib/generalErrorMessage.d.ts +7 -0
  57. package/{lib → dist/lib}/generalErrorMessage.js +6 -6
  58. package/dist/lib/jwt.d.ts +4 -0
  59. package/dist/lib/jwt.js +18 -0
  60. package/dist/lib/logger.d.ts +24 -0
  61. package/dist/lib/logger.js +126 -0
  62. package/dist/lib/migrateCallLogsSchema.d.ts +32 -0
  63. package/{lib → dist/lib}/migrateCallLogsSchema.js +75 -160
  64. package/dist/lib/oauth.d.ts +4 -0
  65. package/{lib → dist/lib}/oauth.js +157 -160
  66. package/dist/lib/ringcentral.d.ts +24 -0
  67. package/dist/lib/ringcentral.js +226 -0
  68. package/dist/lib/s3ErrorLogReport.d.ts +4 -0
  69. package/{lib → dist/lib}/s3ErrorLogReport.js +11 -23
  70. package/dist/lib/sharedSMSComposer.d.ts +7 -0
  71. package/{lib → dist/lib}/sharedSMSComposer.js +21 -107
  72. package/dist/lib/util.d.ts +7 -0
  73. package/{lib → dist/lib}/util.js +9 -20
  74. package/dist/mcp/lib/oauthError.d.ts +1 -0
  75. package/dist/mcp/lib/oauthError.js +25 -0
  76. package/dist/mcp/lib/validator.d.ts +1 -0
  77. package/{mcp → dist/mcp}/lib/validator.js +16 -20
  78. package/dist/mcp/lib/widgetSessionToken.d.ts +1 -0
  79. package/dist/mcp/lib/widgetSessionToken.js +46 -0
  80. package/dist/mcp/mcpHandler.d.ts +8 -0
  81. package/{mcp → dist/mcp}/mcpHandler.js +98 -88
  82. package/dist/mcp/tools/cancelAppointment.d.ts +1 -0
  83. package/{mcp → dist/mcp}/tools/cancelAppointment.js +7 -16
  84. package/dist/mcp/tools/checkAuthStatus.d.ts +1 -0
  85. package/{mcp → dist/mcp}/tools/checkAuthStatus.js +21 -14
  86. package/dist/mcp/tools/confirmAppointment.d.ts +1 -0
  87. package/{mcp → dist/mcp}/tools/confirmAppointment.js +7 -16
  88. package/dist/mcp/tools/createAppointment.d.ts +1 -0
  89. package/{mcp → dist/mcp}/tools/createAppointment.js +7 -19
  90. package/dist/mcp/tools/createCallLog.d.ts +1 -0
  91. package/{mcp → dist/mcp}/tools/createCallLog.js +18 -29
  92. package/dist/mcp/tools/createContact.d.ts +1 -0
  93. package/{mcp → dist/mcp}/tools/createContact.js +8 -20
  94. package/dist/mcp/tools/createMessageLog.d.ts +1 -0
  95. package/{mcp → dist/mcp}/tools/createMessageLog.js +14 -26
  96. package/dist/mcp/tools/doAuth.d.ts +1 -0
  97. package/{mcp → dist/mcp}/tools/doAuth.js +17 -13
  98. package/dist/mcp/tools/findContactByName.d.ts +1 -0
  99. package/{mcp → dist/mcp}/tools/findContactByName.js +9 -15
  100. package/dist/mcp/tools/findContactByPhone.d.ts +1 -0
  101. package/{mcp → dist/mcp}/tools/findContactByPhone.js +8 -15
  102. package/dist/mcp/tools/getCallLog.d.ts +1 -0
  103. package/{mcp → dist/mcp}/tools/getCallLog.js +12 -21
  104. package/dist/mcp/tools/getGoogleFilePicker.d.ts +1 -0
  105. package/{mcp → dist/mcp}/tools/getGoogleFilePicker.js +9 -18
  106. package/dist/mcp/tools/getHelp.d.ts +1 -0
  107. package/{mcp → dist/mcp}/tools/getHelp.js +5 -6
  108. package/dist/mcp/tools/getPublicConnectors.d.ts +1 -0
  109. package/{mcp → dist/mcp}/tools/getPublicConnectors.js +19 -18
  110. package/dist/mcp/tools/getSessionInfo.d.ts +1 -0
  111. package/{mcp → dist/mcp}/tools/getSessionInfo.js +10 -16
  112. package/dist/mcp/tools/index.d.ts +8 -0
  113. package/dist/mcp/tools/index.js +50 -0
  114. package/dist/mcp/tools/listAppointments.d.ts +1 -0
  115. package/{mcp → dist/mcp}/tools/listAppointments.js +7 -19
  116. package/dist/mcp/tools/logout.d.ts +1 -0
  117. package/{mcp → dist/mcp}/tools/logout.js +16 -14
  118. package/dist/mcp/tools/rcGetCallLogs.d.ts +1 -0
  119. package/{mcp → dist/mcp}/tools/rcGetCallLogs.js +10 -8
  120. package/dist/mcp/tools/updateAppointment.d.ts +1 -0
  121. package/{mcp → dist/mcp}/tools/updateAppointment.js +17 -22
  122. package/dist/mcp/tools/updateCallLog.d.ts +1 -0
  123. package/{mcp → dist/mcp}/tools/updateCallLog.js +16 -26
  124. package/dist/models/accountDataModel.d.ts +3 -0
  125. package/dist/models/accountDataModel.js +39 -0
  126. package/dist/models/adminConfigModel.d.ts +2 -0
  127. package/dist/models/adminConfigModel.js +39 -0
  128. package/dist/models/cacheModel.d.ts +2 -0
  129. package/{models → dist/models}/cacheModel.js +7 -3
  130. package/dist/models/callDownListModel.d.ts +2 -0
  131. package/{models → dist/models}/callDownListModel.js +8 -4
  132. package/dist/models/callLogModel.d.ts +2 -0
  133. package/dist/models/callLogModel.js +43 -0
  134. package/dist/models/dynamo/connectorSchema.d.ts +2 -0
  135. package/dist/models/dynamo/connectorSchema.js +141 -0
  136. package/dist/models/dynamo/lockSchema.d.ts +2 -0
  137. package/{models → dist/models}/dynamo/lockSchema.js +5 -7
  138. package/dist/models/dynamo/noteCacheSchema.d.ts +2 -0
  139. package/{models → dist/models}/dynamo/noteCacheSchema.js +4 -6
  140. package/dist/models/llmSessionModel.d.ts +2 -0
  141. package/dist/models/llmSessionModel.js +21 -0
  142. package/dist/models/messageLogModel.d.ts +2 -0
  143. package/{models → dist/models}/messageLogModel.js +8 -4
  144. package/dist/models/sequelize.d.ts +2 -0
  145. package/dist/models/sequelize.js +68 -0
  146. package/dist/models/userModel.d.ts +2 -0
  147. package/dist/models/userModel.js +49 -0
  148. package/dist/package.json +100 -0
  149. package/dist/releaseNotes.json +1222 -0
  150. package/dist/tsconfig.json +14 -0
  151. package/dist/types/admin.d.ts +141 -0
  152. package/dist/types/analytics.d.ts +14 -0
  153. package/dist/types/appointment.d.ts +50 -0
  154. package/dist/types/auth.d.ts +137 -0
  155. package/dist/types/authSession.d.ts +35 -0
  156. package/dist/types/cacheCleanup.d.ts +12 -0
  157. package/dist/types/calldown.d.ts +54 -0
  158. package/dist/types/common.d.ts +46 -0
  159. package/dist/types/connector.d.ts +165 -0
  160. package/dist/types/contact.d.ts +125 -0
  161. package/dist/types/errorHandler.d.ts +60 -0
  162. package/dist/types/index.d.ts +76 -0
  163. package/dist/types/json.d.ts +9 -0
  164. package/dist/types/jwt.d.ts +8 -0
  165. package/dist/types/logging.d.ts +224 -0
  166. package/dist/types/managedAuth.d.ts +114 -0
  167. package/dist/types/managedOAuth.d.ts +59 -0
  168. package/dist/types/manifest.d.ts +120 -0
  169. package/dist/types/migration.d.ts +15 -0
  170. package/dist/types/plugin.d.ts +74 -0
  171. package/dist/types/ringcentral.d.ts +61 -0
  172. package/dist/types/s3ErrorLogReport.d.ts +16 -0
  173. package/dist/types/sharedSMSComposer.d.ts +105 -0
  174. package/dist/types/user.d.ts +46 -0
  175. package/dist/types/util.d.ts +7 -0
  176. package/package.json +34 -6
  177. package/releaseNotes.json +8 -0
  178. package/.env.test +0 -5
  179. package/connector/proxy/engine.js +0 -165
  180. package/connector/proxy/index.js +0 -500
  181. package/connector/registry.js +0 -252
  182. package/docs/README.md +0 -50
  183. package/docs/architecture.md +0 -94
  184. package/docs/connectors.md +0 -116
  185. package/docs/handlers.md +0 -128
  186. package/docs/libraries.md +0 -98
  187. package/docs/models.md +0 -146
  188. package/docs/routes.md +0 -119
  189. package/docs/tests.md +0 -73
  190. package/handlers/calldown.js +0 -99
  191. package/jest.config.js +0 -57
  192. package/lib/constants.js +0 -9
  193. package/lib/encode.js +0 -30
  194. package/lib/errorHandler.js +0 -218
  195. package/lib/jwt.js +0 -18
  196. package/lib/logger.js +0 -190
  197. package/lib/ringcentral.js +0 -267
  198. package/mcp/README.md +0 -420
  199. package/mcp/tools/index.js +0 -51
  200. package/mcp/ui/App/App.tsx +0 -358
  201. package/mcp/ui/App/components/AuthInfoForm.tsx +0 -113
  202. package/mcp/ui/App/components/AuthSuccess.tsx +0 -22
  203. package/mcp/ui/App/components/ConnectorList.tsx +0 -82
  204. package/mcp/ui/App/components/DebugPanel.tsx +0 -43
  205. package/mcp/ui/App/components/OAuthConnect.tsx +0 -270
  206. package/mcp/ui/App/lib/callTool.ts +0 -130
  207. package/mcp/ui/App/lib/debugLog.ts +0 -41
  208. package/mcp/ui/App/lib/developerPortal.ts +0 -111
  209. package/mcp/ui/App/main.css +0 -6
  210. package/mcp/ui/App/root.tsx +0 -13
  211. package/mcp/ui/dist/index.html +0 -53
  212. package/mcp/ui/vite.config.ts +0 -16
  213. package/models/accountDataModel.js +0 -34
  214. package/models/adminConfigModel.js +0 -35
  215. package/models/callLogModel.js +0 -39
  216. package/models/dynamo/connectorSchema.js +0 -146
  217. package/models/llmSessionModel.js +0 -17
  218. package/models/sequelize.js +0 -17
  219. package/models/userModel.js +0 -45
  220. package/test/connector/developerPortal.test.js +0 -166
  221. package/test/connector/mock.test.js +0 -131
  222. package/test/connector/proxy/engine.test.js +0 -211
  223. package/test/connector/proxy/index.test.js +0 -525
  224. package/test/connector/proxy/sample.json +0 -162
  225. package/test/connector/registry.test.js +0 -416
  226. package/test/handlers/admin.test.js +0 -960
  227. package/test/handlers/appointment.test.js +0 -260
  228. package/test/handlers/auth.test.js +0 -1096
  229. package/test/handlers/calldown.test.js +0 -310
  230. package/test/handlers/contact.test.js +0 -1014
  231. package/test/handlers/disposition.test.js +0 -396
  232. package/test/handlers/log.test.js +0 -1847
  233. package/test/handlers/managedAuth.test.js +0 -458
  234. package/test/handlers/managedOAuth.test.js +0 -262
  235. package/test/handlers/plugin.test.js +0 -429
  236. package/test/handlers/user.test.js +0 -381
  237. package/test/index.test.js +0 -301
  238. package/test/lib/analytics.test.js +0 -146
  239. package/test/lib/authSession.test.js +0 -173
  240. package/test/lib/cacheCleanup.test.js +0 -127
  241. package/test/lib/callLogComposer.test.js +0 -1231
  242. package/test/lib/debugTracer.test.js +0 -328
  243. package/test/lib/encode.test.js +0 -59
  244. package/test/lib/errorHandler.test.js +0 -246
  245. package/test/lib/generalErrorMessage.test.js +0 -82
  246. package/test/lib/jwt.test.js +0 -176
  247. package/test/lib/logger.test.js +0 -206
  248. package/test/lib/oauth.test.js +0 -359
  249. package/test/lib/ringcentral.test.js +0 -467
  250. package/test/lib/s3ErrorLogReport.test.js +0 -187
  251. package/test/lib/sharedSMSComposer.test.js +0 -1084
  252. package/test/lib/util.test.js +0 -329
  253. package/test/mcp/mcpHandler.test.js +0 -73
  254. package/test/mcp/mcpHandlerMore.test.js +0 -384
  255. package/test/mcp/tools/appointmentTools.test.js +0 -362
  256. package/test/mcp/tools/checkAuthStatus.test.js +0 -83
  257. package/test/mcp/tools/createCallLog.test.js +0 -436
  258. package/test/mcp/tools/createContact.test.js +0 -58
  259. package/test/mcp/tools/createMessageLog.test.js +0 -595
  260. package/test/mcp/tools/doAuth.test.js +0 -113
  261. package/test/mcp/tools/findContactByName.test.js +0 -275
  262. package/test/mcp/tools/findContactByPhone.test.js +0 -296
  263. package/test/mcp/tools/getCallLog.test.js +0 -298
  264. package/test/mcp/tools/getGoogleFilePicker.test.js +0 -281
  265. package/test/mcp/tools/getPublicConnectors.test.js +0 -107
  266. package/test/mcp/tools/getSessionInfo.test.js +0 -127
  267. package/test/mcp/tools/logout.test.js +0 -233
  268. package/test/mcp/tools/rcGetCallLogs.test.js +0 -56
  269. package/test/mcp/tools/updateCallLog.test.js +0 -360
  270. package/test/models/accountDataModel.test.js +0 -98
  271. package/test/models/callDownListModel.test.js +0 -125
  272. package/test/models/dynamo/connectorSchema.test.js +0 -189
  273. package/test/models/dynamo/lockSchema.test.js +0 -37
  274. package/test/models/dynamo/noteCacheSchema.test.js +0 -45
  275. package/test/models/llmSessionModel.test.js +0 -91
  276. package/test/models/models.test.js +0 -660
  277. package/test/routes/calldownRoutes.test.js +0 -224
  278. package/test/routes/coreRouterBroadRoutes.test.js +0 -855
  279. package/test/routes/dispositionRoutes.test.js +0 -192
  280. package/test/routes/managedAuthRoutes.test.js +0 -386
  281. package/test/routes/pluginRoutes.test.js +0 -262
  282. package/test/setup.js +0 -178
  283. /package/{mcp → dist/mcp}/ui/index.html +0 -0
  284. /package/{mcp → dist/mcp}/ui/package-lock.json +0 -0
  285. /package/{mcp → dist/mcp}/ui/package.json +0 -0
  286. /package/{mcp → dist/mcp}/ui/tsconfig.json +0 -0
@@ -1,1096 +0,0 @@
1
- const authHandler = require('../../handlers/auth');
2
- const connectorRegistry = require('../../connector/registry');
3
-
4
- // Mock the connector registry
5
- jest.mock('../../connector/registry');
6
- jest.mock('../../lib/oauth');
7
- jest.mock('../../models/dynamo/connectorSchema', () => ({
8
- Connector: {
9
- getProxyConfig: jest.fn()
10
- }
11
- }));
12
- jest.mock('../../lib/ringcentral', () => ({
13
- RingCentral: jest.fn().mockImplementation(() => ({
14
- generateToken: jest.fn()
15
- }))
16
- }));
17
- jest.mock('../../handlers/admin', () => ({
18
- updateAdminRcTokens: jest.fn()
19
- }));
20
-
21
- const oauth = require('../../lib/oauth');
22
- const { Connector } = require('../../models/dynamo/connectorSchema');
23
- const { RingCentral } = require('../../lib/ringcentral');
24
- const adminCore = require('../../handlers/admin');
25
- const { AccountDataModel } = require('../../models/accountDataModel');
26
- const { CacheModel } = require('../../models/cacheModel');
27
- const { encode } = require('../../lib/encode');
28
- const { getHashValue } = require('../../lib/util');
29
-
30
- describe('Auth Handler', () => {
31
- const originalEnv = process.env;
32
-
33
- beforeEach(() => {
34
- // Reset mocks
35
- jest.clearAllMocks();
36
- global.testUtils.resetConnectorRegistry();
37
- process.env = { ...originalEnv };
38
- process.env.APP_SERVER_SECRET_KEY = 'test-app-server-secret-key-123456';
39
- });
40
-
41
- afterEach(() => {
42
- process.env = originalEnv;
43
- });
44
-
45
- describe('onApiKeyLogin', () => {
46
- afterEach(async () => {
47
- await AccountDataModel.destroy({ where: {} });
48
- });
49
-
50
- test('should handle successful API key login', async () => {
51
- // Arrange
52
- const mockUserInfo = {
53
- successful: true,
54
- platformUserInfo: {
55
- id: 'test-user-id',
56
- name: 'Test User',
57
- timezoneName: 'America/Los_Angeles',
58
- timezoneOffset: 0,
59
- platformAdditionalInfo: {}
60
- },
61
- returnMessage: {
62
- messageType: 'success',
63
- message: 'Login successful',
64
- ttl: 1000
65
- }
66
- };
67
-
68
- const mockConnector = global.testUtils.createMockConnector({
69
- getBasicAuth: jest.fn().mockReturnValue('dGVzdC1hcGkta2V5Og=='),
70
- getUserInfo: jest.fn().mockResolvedValue(mockUserInfo)
71
- });
72
-
73
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
74
-
75
- const requestData = {
76
- platform: 'testCRM',
77
- hostname: 'test.example.com',
78
- apiKey: 'test-api-key',
79
- additionalInfo: {}
80
- };
81
-
82
- // Act
83
- const result = await authHandler.onApiKeyLogin(requestData);
84
-
85
- // Assert
86
- expect(result.userInfo).toBeDefined();
87
- expect(result.userInfo.id).toBe('test-user-id');
88
- expect(result.userInfo.name).toBe('Test User');
89
- expect(result.returnMessage).toEqual(mockUserInfo.returnMessage);
90
- expect(mockConnector.getBasicAuth).toHaveBeenCalledWith({ apiKey: 'test-api-key' });
91
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith({
92
- authHeader: 'Basic dGVzdC1hcGkta2V5Og==',
93
- hostname: 'test.example.com',
94
- additionalInfo: { apiKey: 'test-api-key' },
95
- apiKey: 'test-api-key',
96
- platform: 'testCRM',
97
- proxyId: undefined
98
- });
99
- });
100
-
101
- test('should handle failed API key login', async () => {
102
- // Arrange
103
- const mockUserInfo = {
104
- successful: false,
105
- platformUserInfo: null,
106
- returnMessage: {
107
- messageType: 'error',
108
- message: 'Invalid API key',
109
- ttl: 3000
110
- }
111
- };
112
-
113
- const mockConnector = global.testUtils.createMockConnector({
114
- getBasicAuth: jest.fn().mockReturnValue('dGVzdC1hcGkta2V5Og=='),
115
- getUserInfo: jest.fn().mockResolvedValue(mockUserInfo)
116
- });
117
-
118
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
119
-
120
- const requestData = {
121
- platform: 'testCRM',
122
- hostname: 'test.example.com',
123
- apiKey: 'invalid-api-key',
124
- additionalInfo: {}
125
- };
126
-
127
- // Act
128
- const result = await authHandler.onApiKeyLogin(requestData);
129
-
130
- // Assert
131
- expect(result.userInfo).toBeNull();
132
- expect(result.returnMessage).toEqual(mockUserInfo.returnMessage);
133
- });
134
-
135
- test('should mark managed auth auto-login failure so the next attempt can fall back to manual auth', async () => {
136
- connectorRegistry.getManifest.mockReturnValue({
137
- platforms: {
138
- testCRM: {
139
- auth: {
140
- type: 'apiKey',
141
- apiKey: {
142
- page: {
143
- content: [
144
- { const: 'tenantId', required: true, managed: true, managedScope: 'account' },
145
- { const: 'apiKey', required: true, managed: true, managedScope: 'user' }
146
- ]
147
- }
148
- }
149
- }
150
- }
151
- }
152
- });
153
-
154
- await AccountDataModel.create({
155
- rcAccountId: 'rc-account-fail',
156
- platformName: 'testCRM',
157
- dataKey: 'managed-auth-org',
158
- data: {
159
- fields: {
160
- tenantId: { version: 1, encrypted: true, value: encode(JSON.stringify('tenant-1')) }
161
- }
162
- }
163
- });
164
- await AccountDataModel.create({
165
- rcAccountId: 'rc-account-fail',
166
- platformName: 'testCRM',
167
- dataKey: 'managed-auth-user:101',
168
- data: {
169
- rcExtensionId: '101',
170
- rcUserName: 'Agent 101',
171
- fields: {
172
- apiKey: { version: 1, encrypted: true, value: encode(JSON.stringify('bad-stored-key')) }
173
- }
174
- }
175
- });
176
-
177
- const mockConnector = global.testUtils.createMockConnector({
178
- getBasicAuth: jest.fn().mockReturnValue('encoded-bad-key'),
179
- getUserInfo: jest.fn().mockResolvedValue({
180
- successful: false,
181
- platformUserInfo: null,
182
- returnMessage: {
183
- messageType: 'error',
184
- message: 'Invalid API key',
185
- ttl: 3000
186
- }
187
- })
188
- });
189
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
190
-
191
- const result = await authHandler.onApiKeyLogin({
192
- platform: 'testCRM',
193
- hostname: 'test.example.com',
194
- rcAccountId: 'rc-account-fail',
195
- rcExtensionId: '101',
196
- additionalInfo: {}
197
- });
198
-
199
- expect(result.userInfo).toBeNull();
200
- const failureRecord = await AccountDataModel.findOne({
201
- where: {
202
- rcAccountId: 'rc-account-fail',
203
- platformName: 'testCRM',
204
- dataKey: 'managed-auth-login-failure:101'
205
- }
206
- });
207
- expect(failureRecord).not.toBeNull();
208
- });
209
-
210
- test('should merge stored org managed auth values into additionalInfo', async () => {
211
- connectorRegistry.getManifest.mockReturnValue({
212
- platforms: {
213
- testCRM: {
214
- auth: {
215
- type: 'apiKey',
216
- apiKey: {
217
- page: {
218
- content: [
219
- { const: 'apiKey', required: true, managed: true, managedScope: 'account' },
220
- { const: 'tenantId', required: true, managed: true, managedScope: 'account' },
221
- { const: 'userToken', required: true }
222
- ]
223
- }
224
- }
225
- }
226
- }
227
- }
228
- });
229
- await AccountDataModel.create({
230
- rcAccountId: 'rc-account-1',
231
- platformName: 'testCRM',
232
- dataKey: 'managed-auth-org',
233
- data: {
234
- fields: {
235
- apiKey: { version: 1, encrypted: true, value: encode(JSON.stringify('stored-api-key')) },
236
- tenantId: { version: 1, encrypted: true, value: encode(JSON.stringify('tenant-1')) }
237
- }
238
- }
239
- });
240
-
241
- const mockUserInfo = {
242
- successful: true,
243
- platformUserInfo: {
244
- id: 'test-user-id',
245
- name: 'Test User',
246
- platformAdditionalInfo: {}
247
- },
248
- returnMessage: { messageType: 'success', message: 'ok' }
249
- };
250
- const mockConnector = global.testUtils.createMockConnector({
251
- getBasicAuth: jest.fn().mockReturnValue('encoded-shared'),
252
- getUserInfo: jest.fn().mockResolvedValue(mockUserInfo)
253
- });
254
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
255
-
256
- await authHandler.onApiKeyLogin({
257
- platform: 'testCRM',
258
- hostname: 'test.example.com',
259
- rcAccountId: 'rc-account-1',
260
- additionalInfo: { userToken: 'user-token-1' }
261
- });
262
-
263
- expect(mockConnector.getBasicAuth).toHaveBeenCalledWith({ apiKey: 'stored-api-key' });
264
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith(expect.objectContaining({
265
- additionalInfo: expect.objectContaining({
266
- apiKey: 'stored-api-key',
267
- tenantId: 'tenant-1',
268
- userToken: 'user-token-1'
269
- })
270
- }));
271
- });
272
-
273
- test('should allow submitted shared fields to satisfy missing required managed auth values', async () => {
274
- connectorRegistry.getManifest.mockReturnValue({
275
- platforms: {
276
- testCRM: {
277
- auth: {
278
- type: 'apiKey',
279
- apiKey: {
280
- page: {
281
- content: [
282
- { const: 'companyId', required: true, managed: true, managedScope: 'account' },
283
- { const: 'userToken', required: true }
284
- ]
285
- }
286
- }
287
- }
288
- }
289
- }
290
- });
291
-
292
- const mockConnector = global.testUtils.createMockConnector({
293
- getBasicAuth: jest.fn(),
294
- getUserInfo: jest.fn().mockResolvedValue({
295
- successful: true,
296
- platformUserInfo: {
297
- id: 'test-user-id',
298
- name: 'Test User',
299
- platformAdditionalInfo: {}
300
- },
301
- returnMessage: { messageType: 'success', message: 'ok' }
302
- })
303
- });
304
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
305
-
306
- const result = await authHandler.onApiKeyLogin({
307
- platform: 'testCRM',
308
- hostname: 'test.example.com',
309
- rcAccountId: 'rc-account-2',
310
- additionalInfo: {
311
- companyId: 'company-123',
312
- userToken: 'user-token-1'
313
- }
314
- });
315
-
316
- expect(result.userInfo).not.toBeNull();
317
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith(expect.objectContaining({
318
- additionalInfo: expect.objectContaining({
319
- companyId: 'company-123',
320
- userToken: 'user-token-1'
321
- })
322
- }));
323
- });
324
-
325
- test('should not persist submitted managed auth values from end users', async () => {
326
- connectorRegistry.getManifest.mockReturnValue({
327
- platforms: {
328
- testCRM: {
329
- auth: {
330
- type: 'apiKey',
331
- apiKey: {
332
- page: {
333
- content: [
334
- { const: 'companyId', required: false, managed: true, managedScope: 'account' },
335
- { const: 'userToken', required: true }
336
- ]
337
- }
338
- }
339
- }
340
- }
341
- }
342
- });
343
-
344
- const mockUserInfo = {
345
- successful: true,
346
- platformUserInfo: {
347
- id: 'test-user-id',
348
- name: 'Test User',
349
- platformAdditionalInfo: {}
350
- },
351
- returnMessage: { messageType: 'success', message: 'ok' }
352
- };
353
- const mockConnector = global.testUtils.createMockConnector({
354
- getBasicAuth: jest.fn().mockReturnValue('encoded'),
355
- getUserInfo: jest.fn().mockResolvedValue(mockUserInfo)
356
- });
357
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
358
-
359
- await authHandler.onApiKeyLogin({
360
- platform: 'testCRM',
361
- hostname: 'test.example.com',
362
- rcAccountId: 'rc-account-2',
363
- additionalInfo: {
364
- companyId: 'company-123',
365
- userToken: 'user-token-1'
366
- }
367
- });
368
-
369
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith(expect.objectContaining({
370
- additionalInfo: expect.objectContaining({
371
- companyId: 'company-123',
372
- userToken: 'user-token-1'
373
- })
374
- }));
375
-
376
- const stored = await AccountDataModel.findOne({
377
- where: {
378
- rcAccountId: 'rc-account-2',
379
- platformName: 'testCRM',
380
- dataKey: 'managed-auth-org'
381
- }
382
- });
383
- expect(stored).toBeNull();
384
- });
385
-
386
- test('should allow manual fallback values to override stored managed credentials and clear failure state after success', async () => {
387
- connectorRegistry.getManifest.mockReturnValue({
388
- platforms: {
389
- testCRM: {
390
- auth: {
391
- type: 'apiKey',
392
- apiKey: {
393
- page: {
394
- content: [
395
- { const: 'apiKey', required: true, managed: true, managedScope: 'user' },
396
- { const: 'tenantId', required: true, managed: true, managedScope: 'account' }
397
- ]
398
- }
399
- }
400
- }
401
- }
402
- }
403
- });
404
-
405
- await AccountDataModel.create({
406
- rcAccountId: 'rc-account-recover',
407
- platformName: 'testCRM',
408
- dataKey: 'managed-auth-org',
409
- data: {
410
- fields: {
411
- tenantId: { version: 1, encrypted: true, value: encode(JSON.stringify('stored-tenant')) }
412
- }
413
- }
414
- });
415
- await AccountDataModel.create({
416
- rcAccountId: 'rc-account-recover',
417
- platformName: 'testCRM',
418
- dataKey: 'managed-auth-user:202',
419
- data: {
420
- rcExtensionId: '202',
421
- rcUserName: 'Agent 202',
422
- fields: {
423
- apiKey: { version: 1, encrypted: true, value: encode(JSON.stringify('stored-bad-key')) }
424
- }
425
- }
426
- });
427
- await AccountDataModel.create({
428
- rcAccountId: 'rc-account-recover',
429
- platformName: 'testCRM',
430
- dataKey: 'managed-auth-login-failure:202',
431
- data: {
432
- failedAt: '2026-04-07T00:00:00.000Z'
433
- }
434
- });
435
-
436
- const mockConnector = global.testUtils.createMockConnector({
437
- getBasicAuth: jest.fn().mockReturnValue('encoded-manual-key'),
438
- getUserInfo: jest.fn().mockResolvedValue({
439
- successful: true,
440
- platformUserInfo: {
441
- id: 'test-user-id',
442
- name: 'Recovered User',
443
- platformAdditionalInfo: {}
444
- },
445
- returnMessage: { messageType: 'success', message: 'ok' }
446
- })
447
- });
448
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
449
-
450
- const result = await authHandler.onApiKeyLogin({
451
- platform: 'testCRM',
452
- hostname: 'test.example.com',
453
- rcAccountId: 'rc-account-recover',
454
- rcExtensionId: '202',
455
- additionalInfo: {
456
- apiKey: 'manual-good-key',
457
- tenantId: 'manual-tenant'
458
- }
459
- });
460
-
461
- expect(result.userInfo).not.toBeNull();
462
- expect(mockConnector.getBasicAuth).toHaveBeenCalledWith({ apiKey: 'manual-good-key' });
463
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith(expect.objectContaining({
464
- additionalInfo: {
465
- apiKey: 'manual-good-key',
466
- tenantId: 'manual-tenant'
467
- }
468
- }));
469
-
470
- const failureRecord = await AccountDataModel.findOne({
471
- where: {
472
- rcAccountId: 'rc-account-recover',
473
- platformName: 'testCRM',
474
- dataKey: 'managed-auth-login-failure:202'
475
- }
476
- });
477
- expect(failureRecord).toBeNull();
478
- });
479
-
480
- test('should return warning when required auth fields are missing', async () => {
481
- connectorRegistry.getManifest.mockReturnValue({
482
- platforms: {
483
- testCRM: {
484
- auth: {
485
- type: 'apiKey',
486
- apiKey: {
487
- page: {
488
- content: [
489
- { const: 'tenantId', required: true, managed: true, managedScope: 'account' },
490
- { const: 'userToken', required: true }
491
- ]
492
- }
493
- }
494
- }
495
- }
496
- }
497
- });
498
-
499
- const mockConnector = global.testUtils.createMockConnector({
500
- getBasicAuth: jest.fn(),
501
- getUserInfo: jest.fn()
502
- });
503
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
504
-
505
- const result = await authHandler.onApiKeyLogin({
506
- platform: 'testCRM',
507
- hostname: 'test.example.com',
508
- rcAccountId: 'rc-account-4',
509
- additionalInfo: {}
510
- });
511
-
512
- expect(result.userInfo).toBeNull();
513
- expect(result.returnMessage).toEqual({
514
- messageType: 'warning',
515
- message: 'Missing required authentication fields.',
516
- ttl: 3000,
517
- missingRequiredFieldConsts: ['tenantId', 'userToken']
518
- });
519
- expect(mockConnector.getBasicAuth).not.toHaveBeenCalled();
520
- expect(mockConnector.getUserInfo).not.toHaveBeenCalled();
521
- });
522
-
523
- test('should throw error when connector not found', async () => {
524
- // Arrange
525
- connectorRegistry.getConnector.mockImplementation(() => {
526
- throw new Error('Connector not found for platform: testCRM');
527
- });
528
-
529
- const requestData = {
530
- platform: 'testCRM',
531
- hostname: 'test.example.com',
532
- apiKey: 'test-api-key',
533
- additionalInfo: {}
534
- };
535
-
536
- // Act & Assert
537
- await expect(authHandler.onApiKeyLogin(requestData))
538
- .rejects.toThrow('Connector not found for platform: testCRM');
539
- });
540
- });
541
-
542
- describe('authValidation', () => {
543
- test('should validate user authentication successfully', async () => {
544
- // Arrange
545
- const mockUser = global.testUtils.createMockUser();
546
- const mockValidationResponse = {
547
- successful: true,
548
- returnMessage: {
549
- messageType: 'success',
550
- message: 'Authentication valid',
551
- ttl: 1000
552
- },
553
- status: 200
554
- };
555
-
556
- const mockConnector = global.testUtils.createMockConnector({
557
- getOauthInfo: jest.fn().mockResolvedValue({}),
558
- authValidation: jest.fn().mockResolvedValue(mockValidationResponse)
559
- });
560
-
561
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
562
-
563
- // Mock UserModel.findOne to return a user
564
- const { UserModel } = require('../../models/userModel');
565
- jest.spyOn(UserModel, 'findOne').mockResolvedValue(mockUser);
566
-
567
- // Mock oauth.checkAndRefreshAccessToken
568
- const oauth = require('../../lib/oauth');
569
- jest.spyOn(oauth, 'checkAndRefreshAccessToken').mockResolvedValue(mockUser);
570
-
571
- const requestData = {
572
- platform: 'testCRM',
573
- userId: 'test-user-id'
574
- };
575
-
576
- // Act
577
- const result = await authHandler.authValidation(requestData);
578
-
579
- // Assert
580
- expect(result).toEqual({
581
- ...mockValidationResponse,
582
- failReason: ''
583
- });
584
- expect(mockConnector.authValidation).toHaveBeenCalledWith({ user: mockUser });
585
- });
586
-
587
- test('should handle user not found in database', async () => {
588
- // Arrange
589
- const mockConnector = global.testUtils.createMockConnector();
590
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
591
-
592
- // Mock UserModel.findOne to return null (user not found)
593
- const { UserModel } = require('../../models/userModel');
594
- jest.spyOn(UserModel, 'findOne').mockResolvedValue(null);
595
-
596
- const requestData = {
597
- platform: 'testCRM',
598
- userId: 'non-existent-user'
599
- };
600
-
601
- // Act
602
- const result = await authHandler.authValidation(requestData);
603
-
604
- // Assert
605
- expect(result).toEqual({
606
- successful: false,
607
- status: 404,
608
- failReason: 'App Connect. User not found in database'
609
- });
610
- });
611
-
612
- test('should handle validation failure', async () => {
613
- // Arrange
614
- const mockUser = global.testUtils.createMockUser();
615
- const mockValidationResponse = {
616
- successful: false,
617
- returnMessage: {
618
- messageType: 'error',
619
- message: 'Authentication failed',
620
- ttl: 3000
621
- },
622
- status: 401
623
- };
624
-
625
- const mockConnector = global.testUtils.createMockConnector({
626
- getOauthInfo: jest.fn().mockResolvedValue({}),
627
- authValidation: jest.fn().mockResolvedValue(mockValidationResponse)
628
- });
629
-
630
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
631
-
632
- // Mock UserModel.findOne to return a user
633
- const { UserModel } = require('../../models/userModel');
634
- jest.spyOn(UserModel, 'findOne').mockResolvedValue(mockUser);
635
-
636
- // Mock oauth.checkAndRefreshAccessToken
637
- const oauth = require('../../lib/oauth');
638
- jest.spyOn(oauth, 'checkAndRefreshAccessToken').mockResolvedValue(mockUser);
639
-
640
- const requestData = {
641
- platform: 'testCRM',
642
- userId: 'test-user-id'
643
- };
644
-
645
- // Act
646
- const result = await authHandler.authValidation(requestData);
647
-
648
- // Assert
649
- expect(result).toEqual({
650
- ...mockValidationResponse,
651
- failReason: 'CRM. API failed'
652
- });
653
- expect(result.successful).toBe(false);
654
- });
655
- });
656
-
657
- describe('onOAuthCallback', () => {
658
- const mockOAuthApp = {
659
- code: {
660
- getToken: jest.fn()
661
- }
662
- };
663
-
664
- beforeEach(() => {
665
- oauth.getOAuthApp.mockReturnValue(mockOAuthApp);
666
- });
667
-
668
- afterEach(async () => {
669
- await AccountDataModel.destroy({ where: {} });
670
- await CacheModel.destroy({ where: {} });
671
- });
672
-
673
- test('should handle successful OAuth callback', async () => {
674
- // Arrange
675
- const mockUserInfo = {
676
- successful: true,
677
- platformUserInfo: {
678
- id: 'oauth-user-id',
679
- name: 'OAuth User',
680
- timezoneName: 'America/New_York',
681
- timezoneOffset: -300,
682
- platformAdditionalInfo: {}
683
- },
684
- returnMessage: {
685
- messageType: 'success',
686
- message: 'Connected successfully'
687
- }
688
- };
689
-
690
- const mockConnector = global.testUtils.createMockConnector({
691
- getOauthInfo: jest.fn().mockResolvedValue({
692
- clientId: 'client-id',
693
- clientSecret: 'client-secret',
694
- accessTokenUri: 'https://api.example.com/oauth/token',
695
- authorizationUri: 'https://api.example.com/oauth/authorize'
696
- }),
697
- getUserInfo: jest.fn().mockResolvedValue(mockUserInfo)
698
- });
699
-
700
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
701
-
702
- mockOAuthApp.code.getToken.mockResolvedValue({
703
- accessToken: 'new-access-token',
704
- refreshToken: 'new-refresh-token',
705
- expires: new Date()
706
- });
707
-
708
- const requestData = {
709
- platform: 'testCRM',
710
- hostname: 'api.example.com',
711
- tokenUrl: 'https://api.example.com/oauth/token',
712
- query: {
713
- callbackUri: 'https://app.example.com/callback?code=auth-code-123',
714
- rcAccountId: 'rc-account-123'
715
- }
716
- };
717
-
718
- // Act
719
- const result = await authHandler.onOAuthCallback(requestData);
720
-
721
- // Assert
722
- expect(result.userInfo).toBeDefined();
723
- expect(result.userInfo.id).toBe('oauth-user-id');
724
- expect(oauth.getOAuthApp).toHaveBeenCalled();
725
- expect(mockOAuthApp.code.getToken).toHaveBeenCalled();
726
- });
727
-
728
- test('should return fail message when oauthInfo has error', async () => {
729
- // Arrange
730
- const mockConnector = global.testUtils.createMockConnector({
731
- getOauthInfo: jest.fn().mockResolvedValue({
732
- failMessage: 'OAuth configuration not found'
733
- })
734
- });
735
-
736
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
737
-
738
- const requestData = {
739
- platform: 'testCRM',
740
- hostname: 'api.example.com',
741
- tokenUrl: '',
742
- query: { callbackUri: 'https://app.example.com/callback', rcAccountId: 'rc-123' }
743
- };
744
-
745
- // Act
746
- const result = await authHandler.onOAuthCallback(requestData);
747
-
748
- // Assert
749
- expect(result.userInfo).toBeNull();
750
- expect(result.returnMessage.messageType).toBe('danger');
751
- expect(result.returnMessage.message).toBe('OAuth configuration not found');
752
- });
753
-
754
- test('should handle failed user info retrieval', async () => {
755
- // Arrange
756
- const mockConnector = global.testUtils.createMockConnector({
757
- getOauthInfo: jest.fn().mockResolvedValue({ clientId: 'id', clientSecret: 'secret' }),
758
- getUserInfo: jest.fn().mockResolvedValue({
759
- successful: false,
760
- returnMessage: { messageType: 'error', message: 'User not authorized' }
761
- })
762
- });
763
-
764
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
765
-
766
- mockOAuthApp.code.getToken.mockResolvedValue({
767
- accessToken: 'token',
768
- refreshToken: 'refresh',
769
- expires: new Date()
770
- });
771
-
772
- const requestData = {
773
- platform: 'testCRM',
774
- hostname: 'api.example.com',
775
- tokenUrl: '',
776
- query: { callbackUri: 'https://app.example.com/callback', rcAccountId: 'rc-123' }
777
- };
778
-
779
- // Act
780
- const result = await authHandler.onOAuthCallback(requestData);
781
-
782
- // Assert
783
- expect(result.userInfo).toBeNull();
784
- expect(result.returnMessage.message).toBe('User not authorized');
785
- });
786
-
787
- test('should handle proxyId in OAuth callback', async () => {
788
- // Arrange
789
- const proxyConfig = { name: 'Proxy Config', settings: {} };
790
- Connector.getProxyConfig.mockResolvedValue(proxyConfig);
791
-
792
- const mockConnector = global.testUtils.createMockConnector({
793
- getOauthInfo: jest.fn().mockResolvedValue({ clientId: 'id', clientSecret: 'secret' }),
794
- getUserInfo: jest.fn().mockResolvedValue({
795
- successful: true,
796
- platformUserInfo: { id: 'proxy-user', name: 'Proxy User' },
797
- returnMessage: { messageType: 'success', message: 'OK' }
798
- })
799
- });
800
-
801
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
802
-
803
- mockOAuthApp.code.getToken.mockResolvedValue({
804
- accessToken: 'token',
805
- refreshToken: 'refresh',
806
- expires: new Date()
807
- });
808
-
809
- const requestData = {
810
- platform: 'testCRM',
811
- hostname: 'api.example.com',
812
- tokenUrl: '',
813
- query: {
814
- callbackUri: 'https://app.example.com/callback',
815
- proxyId: 'proxy-123',
816
- rcAccountId: 'rc-123'
817
- }
818
- };
819
-
820
- // Act
821
- await authHandler.onOAuthCallback(requestData);
822
-
823
- // Assert
824
- expect(Connector.getProxyConfig).toHaveBeenCalledWith('proxy-123');
825
- });
826
-
827
- test('should call postSaveUserInfo if platform implements it', async () => {
828
- // Arrange
829
- const postSaveResult = { id: 'user-id', name: 'User', extra: 'data' };
830
- const mockConnector = global.testUtils.createMockConnector({
831
- getOauthInfo: jest.fn().mockResolvedValue({ clientId: 'id', clientSecret: 'secret' }),
832
- getUserInfo: jest.fn().mockResolvedValue({
833
- successful: true,
834
- platformUserInfo: { id: 'user-id', name: 'User' },
835
- returnMessage: { messageType: 'success', message: 'OK' }
836
- }),
837
- postSaveUserInfo: jest.fn().mockResolvedValue(postSaveResult)
838
- });
839
-
840
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
841
-
842
- mockOAuthApp.code.getToken.mockResolvedValue({
843
- accessToken: 'token',
844
- refreshToken: 'refresh',
845
- expires: new Date()
846
- });
847
-
848
- const requestData = {
849
- platform: 'testCRM',
850
- hostname: 'api.example.com',
851
- tokenUrl: '',
852
- query: { callbackUri: 'https://app.example.com/callback', rcAccountId: 'rc-123' }
853
- };
854
-
855
- // Act
856
- const result = await authHandler.onOAuthCallback(requestData);
857
-
858
- // Assert
859
- expect(mockConnector.postSaveUserInfo).toHaveBeenCalled();
860
- expect(result.userInfo).toEqual(postSaveResult);
861
- });
862
-
863
- test('should use overriding OAuth option if provided', async () => {
864
- // Arrange
865
- const overridingOption = { redirect_uri: 'custom-redirect' };
866
- const oauthInfo = { clientId: 'id', clientSecret: 'secret' };
867
- const mockConnector = global.testUtils.createMockConnector({
868
- getOauthInfo: jest.fn().mockResolvedValue(oauthInfo),
869
- getOverridingOAuthOption: jest.fn().mockReturnValue(overridingOption),
870
- getUserInfo: jest.fn().mockResolvedValue({
871
- successful: true,
872
- platformUserInfo: { id: 'user-id', name: 'User' },
873
- returnMessage: { messageType: 'success', message: 'OK' }
874
- })
875
- });
876
-
877
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
878
-
879
- mockOAuthApp.code.getToken.mockResolvedValue({
880
- accessToken: 'token',
881
- refreshToken: 'refresh',
882
- expires: new Date()
883
- });
884
-
885
- const requestData = {
886
- platform: 'testCRM',
887
- hostname: 'api.example.com',
888
- tokenUrl: '',
889
- query: { callbackUri: 'https://app.example.com/callback?code=code123', rcAccountId: 'rc-123' }
890
- };
891
-
892
- // Act
893
- await authHandler.onOAuthCallback(requestData);
894
-
895
- // Assert
896
- expect(mockConnector.getOverridingOAuthOption).toHaveBeenCalledWith({
897
- code: 'code123',
898
- oauthInfo: { clientId: 'id', clientSecret: 'secret' }
899
- });
900
- expect(mockOAuthApp.code.getToken).toHaveBeenCalledWith(
901
- expect.any(String),
902
- overridingOption
903
- );
904
- });
905
-
906
- test('should use pending managed OAuth info and promote it after successful callback', async () => {
907
- await CacheModel.create({
908
- id: 'rc-managed-managed-oauth-account',
909
- status: 'pending',
910
- userId: 'rc-managed',
911
- cacheKey: 'managed-oauth-account',
912
- expiry: new Date(Date.now() + 60000),
913
- data: {
914
- fields: {
915
- clientId: { version: 1, encrypted: true, value: encode(JSON.stringify('managed-client-id')) },
916
- clientSecret: { version: 1, encrypted: true, value: encode(JSON.stringify('managed-client-secret')) },
917
- accessTokenUri: { version: 1, encrypted: true, value: encode(JSON.stringify('https://managed.example.com/token')) },
918
- authorizationUri: { version: 1, encrypted: true, value: encode(JSON.stringify('https://managed.example.com/authorize')) },
919
- redirectUri: { version: 1, encrypted: true, value: encode(JSON.stringify('https://ringcentral.github.io/ringcentral-embeddable/redirect.html')) },
920
- hostname: { version: 1, encrypted: true, value: encode(JSON.stringify('managed.example.com')) }
921
- }
922
- }
923
- });
924
-
925
- const mockConnector = global.testUtils.createMockConnector({
926
- getOauthInfo: jest.fn(),
927
- getUserInfo: jest.fn().mockResolvedValue({
928
- successful: true,
929
- platformUserInfo: { id: 'managed-oauth-user', name: 'Managed OAuth User' },
930
- returnMessage: { messageType: 'success', message: 'OK' }
931
- })
932
- });
933
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
934
- mockOAuthApp.code.getToken.mockResolvedValue({
935
- accessToken: 'token',
936
- refreshToken: 'refresh',
937
- expires: new Date()
938
- });
939
-
940
- const result = await authHandler.onOAuthCallback({
941
- platform: 'testCRM',
942
- hostname: 'old.example.com',
943
- tokenUrl: '',
944
- query: {
945
- callbackUri: 'https://app.example.com/callback?code=code123',
946
- rcAccountId: 'rc-managed'
947
- }
948
- });
949
-
950
- expect(result.userInfo.id).toBe('managed-oauth-user');
951
- expect(mockConnector.getOauthInfo).not.toHaveBeenCalled();
952
- expect(oauth.getOAuthApp).toHaveBeenCalledWith(expect.objectContaining({
953
- clientId: 'managed-client-id',
954
- clientSecret: 'managed-client-secret',
955
- accessTokenUri: 'https://managed.example.com/token',
956
- authorizationUri: 'https://managed.example.com/authorize'
957
- }));
958
- expect(mockConnector.getUserInfo).toHaveBeenCalledWith(expect.objectContaining({
959
- hostname: 'managed.example.com',
960
- tokenUrl: 'https://managed.example.com/token'
961
- }));
962
- const promoted = await AccountDataModel.findOne({
963
- where: {
964
- rcAccountId: 'rc-managed',
965
- platformName: 'testCRM',
966
- dataKey: 'managed-oauth-account'
967
- }
968
- });
969
- expect(promoted).not.toBeNull();
970
- const pending = await CacheModel.findByPk('rc-managed-managed-oauth-account');
971
- expect(pending).toBeNull();
972
- });
973
- });
974
-
975
- describe('getLicenseStatus', () => {
976
- test('should return license status from platform module', async () => {
977
- // Arrange
978
- const mockUser = global.testUtils.createMockUser({ id: 'user-123' });
979
- const mockLicenseStatus = {
980
- isValid: true,
981
- expiresAt: '2025-12-31',
982
- features: ['call_logging', 'sms_logging']
983
- };
984
-
985
- const mockConnector = global.testUtils.createMockConnector({
986
- getLicenseStatus: jest.fn().mockResolvedValue(mockLicenseStatus)
987
- });
988
-
989
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
990
-
991
- const { UserModel } = require('../../models/userModel');
992
- jest.spyOn(UserModel, 'findByPk').mockResolvedValue(mockUser);
993
-
994
- // Act
995
- const result = await authHandler.getLicenseStatus({
996
- userId: 'user-123',
997
- platform: 'testCRM'
998
- });
999
-
1000
- // Assert
1001
- expect(result).toEqual(mockLicenseStatus);
1002
- expect(mockConnector.getLicenseStatus).toHaveBeenCalledWith({
1003
- userId: 'user-123',
1004
- platform: 'testCRM',
1005
- user: mockUser
1006
- });
1007
- });
1008
-
1009
- test('should return invalid license status when user not found', async () => {
1010
- // Arrange
1011
- const mockConnector = global.testUtils.createMockConnector({
1012
- getLicenseStatus: jest.fn()
1013
- });
1014
- connectorRegistry.getConnector.mockReturnValue(mockConnector);
1015
-
1016
- const { UserModel } = require('../../models/userModel');
1017
- jest.spyOn(UserModel, 'findByPk').mockResolvedValue(null);
1018
-
1019
- // Act
1020
- const result = await authHandler.getLicenseStatus({
1021
- userId: 'missing-user',
1022
- platform: 'testCRM'
1023
- });
1024
-
1025
- // Assert
1026
- expect(result).toEqual({
1027
- isLicenseValid: false,
1028
- licenseStatus: 'Invalid (User not found)',
1029
- licenseStatusDescription: ''
1030
- });
1031
- expect(connectorRegistry.getConnector).not.toHaveBeenCalled();
1032
- expect(mockConnector.getLicenseStatus).not.toHaveBeenCalled();
1033
- });
1034
- });
1035
-
1036
- describe('onRingcentralOAuthCallback', () => {
1037
- beforeEach(() => {
1038
- process.env.RINGCENTRAL_SERVER = 'https://platform.ringcentral.com';
1039
- process.env.RINGCENTRAL_CLIENT_ID = 'rc-client-id';
1040
- process.env.RINGCENTRAL_CLIENT_SECRET = 'rc-client-secret';
1041
- process.env.APP_SERVER = 'https://app.example.com';
1042
- });
1043
-
1044
- test('should handle successful RingCentral OAuth callback', async () => {
1045
- // Arrange
1046
- process.env.HASH_KEY = 'test-hash-key';
1047
- const rcAccountId = 'rc-account-id';
1048
- const mockGenerateToken = jest.fn().mockResolvedValue({
1049
- access_token: 'rc-access-token',
1050
- refresh_token: 'rc-refresh-token',
1051
- expire_time: Date.now() + 3600000
1052
- });
1053
-
1054
- RingCentral.mockImplementation(() => ({
1055
- generateToken: mockGenerateToken
1056
- }));
1057
-
1058
- // Act
1059
- await authHandler.onRingcentralOAuthCallback({
1060
- code: 'rc-auth-code',
1061
- rcAccountId
1062
- });
1063
-
1064
- // Assert
1065
- expect(RingCentral).toHaveBeenCalledWith({
1066
- server: 'https://platform.ringcentral.com',
1067
- clientId: 'rc-client-id',
1068
- clientSecret: 'rc-client-secret',
1069
- redirectUri: 'https://app.example.com/ringcentral/oauth/callback'
1070
- });
1071
- expect(mockGenerateToken).toHaveBeenCalledWith({ code: 'rc-auth-code' });
1072
- expect(adminCore.updateAdminRcTokens).toHaveBeenCalledWith({
1073
- hashedRcAccountId: getHashValue(rcAccountId, 'test-hash-key'),
1074
- adminAccessToken: 'rc-access-token',
1075
- adminRefreshToken: 'rc-refresh-token',
1076
- adminTokenExpiry: expect.any(Number)
1077
- });
1078
- });
1079
-
1080
- test('should return early if environment variables are not set', async () => {
1081
- // Arrange
1082
- delete process.env.RINGCENTRAL_SERVER;
1083
-
1084
- // Act
1085
- const result = await authHandler.onRingcentralOAuthCallback({
1086
- code: 'rc-auth-code',
1087
- rcAccountId: 'hashed-rc-account-id'
1088
- });
1089
-
1090
- // Assert
1091
- expect(result).toBeUndefined();
1092
- expect(RingCentral).not.toHaveBeenCalled();
1093
- });
1094
- });
1095
- });
1096
-