@app-connect/core 1.7.25 → 1.7.27

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