@app-connect/core 1.7.36 → 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 (287) 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} +548 -450
  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/dist/lib/migrateCallLogsSchema.js +339 -0
  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 +13 -1
  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/migrateCallLogsSchema.js +0 -237
  198. package/lib/ringcentral.js +0 -267
  199. package/mcp/README.md +0 -420
  200. package/mcp/tools/index.js +0 -51
  201. package/mcp/ui/App/App.tsx +0 -358
  202. package/mcp/ui/App/components/AuthInfoForm.tsx +0 -113
  203. package/mcp/ui/App/components/AuthSuccess.tsx +0 -22
  204. package/mcp/ui/App/components/ConnectorList.tsx +0 -82
  205. package/mcp/ui/App/components/DebugPanel.tsx +0 -43
  206. package/mcp/ui/App/components/OAuthConnect.tsx +0 -270
  207. package/mcp/ui/App/lib/callTool.ts +0 -130
  208. package/mcp/ui/App/lib/debugLog.ts +0 -41
  209. package/mcp/ui/App/lib/developerPortal.ts +0 -111
  210. package/mcp/ui/App/main.css +0 -6
  211. package/mcp/ui/App/root.tsx +0 -13
  212. package/mcp/ui/dist/index.html +0 -53
  213. package/mcp/ui/vite.config.ts +0 -16
  214. package/models/accountDataModel.js +0 -34
  215. package/models/adminConfigModel.js +0 -35
  216. package/models/callLogModel.js +0 -39
  217. package/models/dynamo/connectorSchema.js +0 -146
  218. package/models/llmSessionModel.js +0 -17
  219. package/models/sequelize.js +0 -17
  220. package/models/userModel.js +0 -45
  221. package/test/connector/developerPortal.test.js +0 -166
  222. package/test/connector/mock.test.js +0 -131
  223. package/test/connector/proxy/engine.test.js +0 -211
  224. package/test/connector/proxy/index.test.js +0 -525
  225. package/test/connector/proxy/sample.json +0 -162
  226. package/test/connector/registry.test.js +0 -416
  227. package/test/handlers/admin.test.js +0 -960
  228. package/test/handlers/appointment.test.js +0 -260
  229. package/test/handlers/auth.test.js +0 -1096
  230. package/test/handlers/calldown.test.js +0 -310
  231. package/test/handlers/contact.test.js +0 -1014
  232. package/test/handlers/disposition.test.js +0 -396
  233. package/test/handlers/log.test.js +0 -1847
  234. package/test/handlers/managedAuth.test.js +0 -458
  235. package/test/handlers/managedOAuth.test.js +0 -262
  236. package/test/handlers/plugin.test.js +0 -429
  237. package/test/handlers/user.test.js +0 -381
  238. package/test/index.test.js +0 -301
  239. package/test/lib/analytics.test.js +0 -146
  240. package/test/lib/authSession.test.js +0 -173
  241. package/test/lib/cacheCleanup.test.js +0 -127
  242. package/test/lib/callLogComposer.test.js +0 -1231
  243. package/test/lib/debugTracer.test.js +0 -328
  244. package/test/lib/encode.test.js +0 -59
  245. package/test/lib/errorHandler.test.js +0 -246
  246. package/test/lib/generalErrorMessage.test.js +0 -82
  247. package/test/lib/jwt.test.js +0 -176
  248. package/test/lib/logger.test.js +0 -206
  249. package/test/lib/oauth.test.js +0 -359
  250. package/test/lib/ringcentral.test.js +0 -467
  251. package/test/lib/s3ErrorLogReport.test.js +0 -187
  252. package/test/lib/sharedSMSComposer.test.js +0 -1084
  253. package/test/lib/util.test.js +0 -329
  254. package/test/mcp/mcpHandler.test.js +0 -73
  255. package/test/mcp/mcpHandlerMore.test.js +0 -384
  256. package/test/mcp/tools/appointmentTools.test.js +0 -362
  257. package/test/mcp/tools/checkAuthStatus.test.js +0 -83
  258. package/test/mcp/tools/createCallLog.test.js +0 -436
  259. package/test/mcp/tools/createContact.test.js +0 -58
  260. package/test/mcp/tools/createMessageLog.test.js +0 -595
  261. package/test/mcp/tools/doAuth.test.js +0 -113
  262. package/test/mcp/tools/findContactByName.test.js +0 -275
  263. package/test/mcp/tools/findContactByPhone.test.js +0 -296
  264. package/test/mcp/tools/getCallLog.test.js +0 -298
  265. package/test/mcp/tools/getGoogleFilePicker.test.js +0 -281
  266. package/test/mcp/tools/getPublicConnectors.test.js +0 -107
  267. package/test/mcp/tools/getSessionInfo.test.js +0 -127
  268. package/test/mcp/tools/logout.test.js +0 -233
  269. package/test/mcp/tools/rcGetCallLogs.test.js +0 -56
  270. package/test/mcp/tools/updateCallLog.test.js +0 -360
  271. package/test/models/accountDataModel.test.js +0 -98
  272. package/test/models/callDownListModel.test.js +0 -125
  273. package/test/models/dynamo/connectorSchema.test.js +0 -189
  274. package/test/models/dynamo/lockSchema.test.js +0 -37
  275. package/test/models/dynamo/noteCacheSchema.test.js +0 -45
  276. package/test/models/llmSessionModel.test.js +0 -91
  277. package/test/models/models.test.js +0 -660
  278. package/test/routes/calldownRoutes.test.js +0 -224
  279. package/test/routes/coreRouterBroadRoutes.test.js +0 -855
  280. package/test/routes/dispositionRoutes.test.js +0 -192
  281. package/test/routes/managedAuthRoutes.test.js +0 -386
  282. package/test/routes/pluginRoutes.test.js +0 -262
  283. package/test/setup.js +0 -178
  284. /package/{mcp → dist/mcp}/ui/index.html +0 -0
  285. /package/{mcp → dist/mcp}/ui/package-lock.json +0 -0
  286. /package/{mcp → dist/mcp}/ui/package.json +0 -0
  287. /package/{mcp → dist/mcp}/ui/tsconfig.json +0 -0
@@ -1,160 +1,157 @@
1
- /* eslint-disable no-param-reassign */
2
- const ClientOAuth2 = require('client-oauth2');
3
- const moment = require('moment');
4
- const { UserModel } = require('../models/userModel');
5
- const connectorRegistry = require('../connector/registry');
6
- const logger = require('./logger');
7
- const { handleDatabaseError } = require('./errorHandler');
8
- // oauthApp strategy is default to 'code' which use credentials to get accessCode, then exchange for accessToken and refreshToken.
9
- // To change to other strategies, please refer to: https://github.com/mulesoft-labs/js-client-oauth2
10
- function getOAuthApp({ clientId, clientSecret, accessTokenUri, authorizationUri, redirectUri, scopes }) {
11
- return new ClientOAuth2({
12
- clientId: clientId,
13
- clientSecret: clientSecret,
14
- accessTokenUri: accessTokenUri,
15
- authorizationUri: authorizationUri,
16
- redirectUri: redirectUri,
17
- scopes: scopes
18
- });
19
- }
20
-
21
-
22
- async function checkAndRefreshAccessToken(oauthApp, user, tokenLockTimeout = 20) {
23
- const now = moment();
24
- const tokenExpiry = moment(user.tokenExpiry);
25
- const expiryBuffer = 2; // 2 minutes
26
- // Special case: Bullhorn
27
- if (user.platform) {
28
- const platformModule = connectorRegistry.getConnector(user.platform);
29
- if (platformModule.checkAndRefreshAccessToken) {
30
- return platformModule.checkAndRefreshAccessToken(oauthApp, user, tokenLockTimeout);
31
- }
32
- }
33
- // Other CRMs - check if token will expire within the buffer time
34
- if (user && user.accessToken && user.refreshToken && tokenExpiry.isBefore(now.clone().add(expiryBuffer, 'minutes'))) {
35
- // case: use dynamoDB to manage token refresh lock
36
- if (process.env.USE_TOKEN_REFRESH_LOCK_PLATFORMS?.split(',')?.includes(user.platform)) {
37
- let newLock;
38
- const { Lock } = require('../models/dynamo/lockSchema');
39
- // Try to atomically create lock only if it doesn't exist
40
- try {
41
- newLock = await Lock.create(
42
- {
43
- userId: user.id,
44
- ttl: now.unix() + tokenLockTimeout
45
- },
46
- {
47
- overwrite: false
48
- }
49
- );
50
- logger.info('lock created')
51
- } catch (e) {
52
- // If creation failed due to condition, a lock exists
53
- if (e.name === 'ConditionalCheckFailedException' || e.__type === 'com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException') {
54
- let lock = await Lock.get({ userId: user.id });
55
- if (!!lock?.ttl && moment(lock.ttl).unix() < now.unix()) {
56
- // Try to delete expired lock and create a new one atomically
57
- try {
58
- logger.info('lock expired.')
59
- await lock.delete();
60
- newLock = await Lock.create(
61
- {
62
- userId: user.id,
63
- ttl: now.unix() + tokenLockTimeout
64
- },
65
- {
66
- overwrite: false
67
- }
68
- );
69
- } catch (e2) {
70
- if (e2.name === 'ConditionalCheckFailedException' || e2.__type === 'com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException') {
71
- // Another process created a lock between our delete and create
72
- lock = await Lock.get({ userId: user.id });
73
- } else {
74
- throw e2;
75
- }
76
- }
77
- }
78
-
79
- if (lock && !newLock) {
80
- let processTime = 0;
81
- let delay = 500; // Start with 500ms
82
- const maxDelay = 8000; // Cap at 8 seconds
83
- while (!!lock && processTime < tokenLockTimeout) {
84
- await new Promise(resolve => setTimeout(resolve, delay));
85
- processTime += delay / 1000; // Convert to seconds for comparison
86
- delay = Math.min(delay * 2, maxDelay); // Exponential backoff with cap
87
- lock = await Lock.get({ userId: user.id });
88
- }
89
- // Timeout -> let users try another time
90
- if (processTime >= tokenLockTimeout) {
91
- throw new Error('Token lock timeout');
92
- }
93
- user = await UserModel.findByPk(user.id);
94
- logger.info('locked. bypass')
95
- return user;
96
- }
97
- } else {
98
- throw e;
99
- }
100
- }
101
- try {
102
- const startRefreshTime = moment();
103
- const token = oauthApp.createToken(user.accessToken, user.refreshToken);
104
- logger.info('token refreshing...')
105
- const { accessToken, refreshToken, expires } = await token.refresh();
106
- user.accessToken = accessToken;
107
- user.refreshToken = refreshToken;
108
- user.tokenExpiry = expires;
109
- try {
110
- await user.save();
111
- }
112
- catch (error) {
113
- return handleDatabaseError(error, 'Error saving user');
114
- }
115
- if (newLock) {
116
- const deletionStartTime = moment();
117
- await newLock.delete();
118
- const deletionEndTime = moment();
119
- logger.info(`lock deleted in ${deletionEndTime.diff(deletionStartTime)}ms`)
120
- }
121
- const endRefreshTime = moment();
122
- logger.info(`token refreshing finished in ${endRefreshTime.diff(startRefreshTime)}ms`)
123
- }
124
- catch (e) {
125
- console.log('token refreshing failed', e.stack)
126
- if (newLock) {
127
- await newLock.delete();
128
- }
129
- return null;
130
- }
131
- }
132
- // case: run withou token refresh lock
133
- else {
134
- try {
135
- logger.info('token refreshing...')
136
- const token = oauthApp.createToken(user.accessToken, user.refreshToken);
137
- const { accessToken, refreshToken, expires } = await token.refresh();
138
- user.accessToken = accessToken;
139
- user.refreshToken = refreshToken;
140
- user.tokenExpiry = expires;
141
- }
142
- catch (e) {
143
- console.log('token refreshing failed', e.stack)
144
- return null;
145
- }
146
- try {
147
- await user.save();
148
- }
149
- catch (error) {
150
- return handleDatabaseError(error, 'Error saving user');
151
- }
152
- logger.info('token refreshing finished')
153
- }
154
-
155
- }
156
- return user;
157
- }
158
-
159
- exports.checkAndRefreshAccessToken = checkAndRefreshAccessToken;
160
- exports.getOAuthApp = getOAuthApp;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkAndRefreshAccessToken = checkAndRefreshAccessToken;
4
+ exports.getOAuthApp = getOAuthApp;
5
+ const ClientOAuth2 = require('client-oauth2');
6
+ const moment = require('moment');
7
+ const { UserModel: UserModelImport } = require('../models/userModel');
8
+ const UserModel = UserModelImport;
9
+ const connectorRegistry = require('../connector/registry');
10
+ const logger = require('./logger');
11
+ const { handleDatabaseError } = require('./errorHandler');
12
+ // oauthApp strategy is default to 'code' which use credentials to get accessCode, then exchange for accessToken and refreshToken.
13
+ // To change to other strategies, please refer to: https://github.com/mulesoft-labs/js-client-oauth2
14
+ function getOAuthApp({ clientId, clientSecret, accessTokenUri, authorizationUri, redirectUri, scopes }) {
15
+ return new ClientOAuth2({
16
+ clientId: clientId,
17
+ clientSecret: clientSecret,
18
+ accessTokenUri: accessTokenUri,
19
+ authorizationUri: authorizationUri,
20
+ redirectUri: redirectUri,
21
+ scopes: scopes
22
+ });
23
+ }
24
+ async function checkAndRefreshAccessToken(oauthApp, user, tokenLockTimeout = 20) {
25
+ const now = moment();
26
+ const tokenExpiry = moment(user.tokenExpiry);
27
+ const expiryBuffer = 2; // 2 minutes
28
+ // Special case: Bullhorn
29
+ if (user.platform) {
30
+ const platformModule = connectorRegistry.getConnector(user.platform);
31
+ if (platformModule.checkAndRefreshAccessToken) {
32
+ return platformModule.checkAndRefreshAccessToken(oauthApp, user, tokenLockTimeout);
33
+ }
34
+ }
35
+ // Other CRMs - check if token will expire within the buffer time
36
+ if (user && user.accessToken && user.refreshToken && tokenExpiry.isBefore(now.clone().add(expiryBuffer, 'minutes'))) {
37
+ // case: use dynamoDB to manage token refresh lock
38
+ if (process.env.USE_TOKEN_REFRESH_LOCK_PLATFORMS?.split(',')?.includes(user.platform)) {
39
+ let newLock;
40
+ const { Lock } = require('../models/dynamo/lockSchema');
41
+ // Try to atomically create lock only if it doesn't exist
42
+ try {
43
+ newLock = await Lock.create({
44
+ userId: user.id,
45
+ ttl: now.unix() + tokenLockTimeout
46
+ }, {
47
+ overwrite: false
48
+ });
49
+ logger.info('lock created');
50
+ }
51
+ catch (e) {
52
+ const lockError = e;
53
+ // If creation failed due to condition, a lock exists
54
+ if (lockError.name === 'ConditionalCheckFailedException' || lockError.__type === 'com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException') {
55
+ let lock = await Lock.get({ userId: user.id });
56
+ if (!!lock?.ttl && moment(lock.ttl).unix() < now.unix()) {
57
+ // Try to delete expired lock and create a new one atomically
58
+ try {
59
+ logger.info('lock expired.');
60
+ await lock.delete();
61
+ newLock = await Lock.create({
62
+ userId: user.id,
63
+ ttl: now.unix() + tokenLockTimeout
64
+ }, {
65
+ overwrite: false
66
+ });
67
+ }
68
+ catch (e2) {
69
+ const expiredLockError = e2;
70
+ if (expiredLockError.name === 'ConditionalCheckFailedException' || expiredLockError.__type === 'com.amazonaws.dynamodb.v20120810#ConditionalCheckFailedException') {
71
+ // Another process created a lock between our delete and create
72
+ lock = await Lock.get({ userId: user.id });
73
+ }
74
+ else {
75
+ throw e2;
76
+ }
77
+ }
78
+ }
79
+ if (lock && !newLock) {
80
+ let processTime = 0;
81
+ let delay = 500; // Start with 500ms
82
+ const maxDelay = 8000; // Cap at 8 seconds
83
+ while (!!lock && processTime < tokenLockTimeout) {
84
+ await new Promise(resolve => setTimeout(resolve, delay));
85
+ processTime += delay / 1000; // Convert to seconds for comparison
86
+ delay = Math.min(delay * 2, maxDelay); // Exponential backoff with cap
87
+ lock = await Lock.get({ userId: user.id });
88
+ }
89
+ // Timeout -> let users try another time
90
+ if (processTime >= tokenLockTimeout) {
91
+ throw new Error('Token lock timeout');
92
+ }
93
+ user = await UserModel.findByPk(user.id);
94
+ logger.info('locked. bypass');
95
+ return user;
96
+ }
97
+ }
98
+ else {
99
+ throw e;
100
+ }
101
+ }
102
+ try {
103
+ const startRefreshTime = moment();
104
+ const token = oauthApp.createToken(user.accessToken, user.refreshToken);
105
+ logger.info('token refreshing...');
106
+ const { accessToken, refreshToken, expires } = await token.refresh();
107
+ user.accessToken = accessToken;
108
+ user.refreshToken = refreshToken;
109
+ user.tokenExpiry = expires;
110
+ try {
111
+ await user.save();
112
+ }
113
+ catch (error) {
114
+ return handleDatabaseError(error, 'Error saving user');
115
+ }
116
+ if (newLock) {
117
+ const deletionStartTime = moment();
118
+ await newLock.delete();
119
+ const deletionEndTime = moment();
120
+ logger.info(`lock deleted in ${deletionEndTime.diff(deletionStartTime)}ms`);
121
+ }
122
+ const endRefreshTime = moment();
123
+ logger.info(`token refreshing finished in ${endRefreshTime.diff(startRefreshTime)}ms`);
124
+ }
125
+ catch (e) {
126
+ console.log('token refreshing failed', e.stack);
127
+ if (newLock) {
128
+ await newLock.delete();
129
+ }
130
+ return null;
131
+ }
132
+ }
133
+ // case: run withou token refresh lock
134
+ else {
135
+ try {
136
+ logger.info('token refreshing...');
137
+ const token = oauthApp.createToken(user.accessToken, user.refreshToken);
138
+ const { accessToken, refreshToken, expires } = await token.refresh();
139
+ user.accessToken = accessToken;
140
+ user.refreshToken = refreshToken;
141
+ user.tokenExpiry = expires;
142
+ }
143
+ catch (e) {
144
+ console.log('token refreshing failed', e.stack);
145
+ return null;
146
+ }
147
+ try {
148
+ await user.save();
149
+ }
150
+ catch (error) {
151
+ return handleDatabaseError(error, 'Error saving user');
152
+ }
153
+ logger.info('token refreshing finished');
154
+ }
155
+ }
156
+ return user;
157
+ }
@@ -0,0 +1,24 @@
1
+ import type { RingCentralCallsAggregationParams, RingCentralFetchResponse, RingCentralGenerateTokenParams, RingCentralLoginUrlParams, RingCentralOptions, RingCentralPaginatedDataParams, RingCentralRequestOptions, RingCentralSubscriptionParams, RingCentralToken } from '../types';
2
+ declare function isRefreshTokenValid(token: RingCentralToken, handicap?: number): boolean;
3
+ declare function isAccessTokenValid(token: RingCentralToken, handicap?: number): boolean;
4
+ declare class RingCentral {
5
+ _options: RingCentralOptions;
6
+ constructor(options: RingCentralOptions);
7
+ loginUrl({ state }: RingCentralLoginUrlParams): string;
8
+ generateToken({ code }: RingCentralGenerateTokenParams): Promise<RingCentralToken>;
9
+ refreshToken(token: RingCentralToken): Promise<RingCentralToken>;
10
+ revokeToken(token: RingCentralToken): Promise<void>;
11
+ _tokenRequest(path: string, body: Record<string, any>): Promise<RingCentralFetchResponse>;
12
+ request({ server, path, query, body, method, accept }: RingCentralRequestOptions, token: RingCentralToken): Promise<RingCentralFetchResponse>;
13
+ createSubscription({ eventFilters, webhookUri }: RingCentralSubscriptionParams, token: RingCentralToken): Promise<any>;
14
+ getExtensionInfo(extensionId: string | number, token: RingCentralToken): Promise<any>;
15
+ getAccountInfo(token: RingCentralToken): Promise<any>;
16
+ getCallsAggregationData({ token, timezone, timeFrom, timeTo, groupBy }: RingCentralCallsAggregationParams): Promise<any>;
17
+ getCallLogData({ extensionId, token, timeFrom, timeTo }: RingCentralPaginatedDataParams): Promise<{
18
+ records: any[];
19
+ }>;
20
+ getSMSData({ extensionId, token, timeFrom, timeTo }: RingCentralPaginatedDataParams): Promise<{
21
+ records: any[];
22
+ }>;
23
+ }
24
+ export { RingCentral, isRefreshTokenValid, isAccessTokenValid };
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RingCentral = void 0;
4
+ exports.isRefreshTokenValid = isRefreshTokenValid;
5
+ exports.isAccessTokenValid = isAccessTokenValid;
6
+ const fetch = require('node-fetch');
7
+ const DEFAULT_RENEW_HANDICAP_MS = 60 * 1000;
8
+ const REFRESH_RENEW_HANDICAP_MS = 10 * 1000;
9
+ function stringifyQuery(query) {
10
+ const queryParams = new URLSearchParams(query);
11
+ return queryParams.toString();
12
+ }
13
+ function isRefreshTokenValid(token, handicap = REFRESH_RENEW_HANDICAP_MS) {
14
+ const expireTime = token.refresh_token_expire_time || 0;
15
+ return expireTime - handicap > Date.now();
16
+ }
17
+ function isAccessTokenValid(token, handicap = DEFAULT_RENEW_HANDICAP_MS) {
18
+ const expireTime = token.expire_time || 0;
19
+ return expireTime - handicap > Date.now();
20
+ }
21
+ class RingCentral {
22
+ constructor(options) {
23
+ this._options = options;
24
+ }
25
+ loginUrl({ state }) {
26
+ const query = {
27
+ response_type: 'code',
28
+ redirect_uri: this._options.redirectUri,
29
+ client_id: this._options.clientId,
30
+ response_hint: 'brand_id contracted_country_code'
31
+ };
32
+ if (state) {
33
+ query.state = state;
34
+ }
35
+ return `${this._options.server}/restapi/oauth/authorize?${stringifyQuery(query)}`;
36
+ }
37
+ async generateToken({ code }) {
38
+ const body = {
39
+ code,
40
+ grant_type: 'authorization_code',
41
+ redirect_uri: this._options.redirectUri
42
+ };
43
+ const response = await this._tokenRequest('/restapi/oauth/token', body);
44
+ if (Number.parseInt(response.status, 10) >= 400) {
45
+ throw new Error('Generate Token error', response.status);
46
+ }
47
+ const { expires_in, refresh_token_expires_in, ...token } = await response.json();
48
+ return {
49
+ ...token,
50
+ expire_time: Date.now() + parseInt(expires_in, 10) * 1000,
51
+ refresh_token_expire_time: Date.now() + parseInt(refresh_token_expires_in, 10) * 1000
52
+ };
53
+ }
54
+ async refreshToken(token) {
55
+ const body = {
56
+ grant_type: 'refresh_token',
57
+ refresh_token: token.refresh_token,
58
+ access_token_ttl: token.expires_in,
59
+ refresh_token_ttl: token.refresh_token_expires_in
60
+ };
61
+ const response = await this._tokenRequest('/restapi/oauth/token', body);
62
+ if (Number.parseInt(response.status, 10) >= 400) {
63
+ const error = new Error('Refresh Token error', response.status);
64
+ error.response = response;
65
+ throw error;
66
+ }
67
+ const { expires_in, refresh_token_expires_in, ...newToken } = await response.json();
68
+ return {
69
+ ...newToken,
70
+ expire_time: Date.now() + parseInt(expires_in, 10) * 1000,
71
+ refresh_token_expire_time: Date.now() + parseInt(refresh_token_expires_in, 10) * 1000
72
+ };
73
+ }
74
+ async revokeToken(token) {
75
+ const body = {
76
+ token: token.access_token
77
+ };
78
+ const response = await this._tokenRequest('/restapi/oauth/revoke', body);
79
+ if (Number.parseInt(response.status, 10) >= 400) {
80
+ throw new Error('Revoke Token error', response.status);
81
+ }
82
+ }
83
+ async _tokenRequest(path, body) {
84
+ const authorization = `${this._options.clientId}:${this._options.clientSecret}`;
85
+ const response = await fetch(`${this._options.server}${path}`, {
86
+ method: 'POST',
87
+ body: stringifyQuery(body),
88
+ headers: {
89
+ 'Accept': 'application/json',
90
+ 'Content-Type': 'application/x-www-form-urlencoded',
91
+ 'Authorization': `Basic ${Buffer.from(authorization).toString('base64')}`
92
+ }
93
+ });
94
+ return response;
95
+ }
96
+ async request({ server = this._options.server, path, query, body, method, accept = 'application/json' }, token) {
97
+ let uri = `${server}${path}`;
98
+ if (query) {
99
+ uri = uri + (uri.includes('?') ? '&' : '?') + stringifyQuery(query);
100
+ }
101
+ const response = await fetch(uri, {
102
+ method,
103
+ body: body ? JSON.stringify(body) : body,
104
+ headers: {
105
+ 'Accept': accept,
106
+ 'Content-Type': 'application/json',
107
+ 'Authorization': `${token.token_type} ${token.access_token}`
108
+ }
109
+ });
110
+ if (Number.parseInt(response.status, 10) >= 400) {
111
+ const error = new Error(`request data error ${response.status}`);
112
+ const errorText = await response.text();
113
+ error.message = errorText;
114
+ error.response = response;
115
+ throw error;
116
+ }
117
+ return response;
118
+ }
119
+ async createSubscription({ eventFilters, webhookUri }, token) {
120
+ const response = await this.request({
121
+ method: 'POST',
122
+ path: '/restapi/v1.0/subscription',
123
+ body: {
124
+ eventFilters,
125
+ deliveryMode: {
126
+ transportType: 'WebHook',
127
+ address: webhookUri
128
+ },
129
+ expiresIn: 7 * 24 * 3600
130
+ }
131
+ }, token);
132
+ const { ...subscription } = await response.json();
133
+ return subscription;
134
+ }
135
+ async getExtensionInfo(extensionId, token) {
136
+ const response = await this.request({
137
+ method: 'GET',
138
+ path: `/restapi/v1.0/account/~/extension/${extensionId}`
139
+ }, token);
140
+ return response.json();
141
+ }
142
+ async getAccountInfo(token) {
143
+ const response = await this.request({
144
+ method: 'GET',
145
+ path: `/restapi/v1.0/account/~`
146
+ }, token);
147
+ return response.json();
148
+ }
149
+ async getCallsAggregationData({ token, timezone, timeFrom, timeTo, groupBy }) {
150
+ const body = {
151
+ grouping: {
152
+ groupBy
153
+ },
154
+ timeSettings: {
155
+ timeZone: timezone,
156
+ timeRange: {
157
+ timeFrom,
158
+ timeTo
159
+ }
160
+ },
161
+ responseOptions: {
162
+ counters: {
163
+ callsByDirection: {
164
+ aggregationType: 'Sum'
165
+ },
166
+ callsByResponse: {
167
+ aggregationType: 'Sum'
168
+ }
169
+ },
170
+ timers: {
171
+ allCallsDuration: {
172
+ aggregationType: 'Sum'
173
+ }
174
+ }
175
+ }
176
+ };
177
+ const response = await this.request({
178
+ method: 'POST',
179
+ path: `/analytics/calls/v1/accounts/~/aggregation/fetch`,
180
+ body,
181
+ accept: 'application/json'
182
+ }, token);
183
+ return response.json();
184
+ }
185
+ async getCallLogData({ extensionId = '~', token, timeFrom, timeTo }) {
186
+ let pageStart = 1;
187
+ let isFinalPage = false;
188
+ let result = { records: [] };
189
+ while (!isFinalPage) {
190
+ const callLogResponse = await this.request({
191
+ method: 'GET',
192
+ path: `/restapi/v1.0/account/~/extension/${extensionId}/call-log?dateFrom=${timeFrom}&dateTo=${timeTo}&page=${pageStart}&view=Simple&perPage=1000`
193
+ }, token);
194
+ const resultJson = await callLogResponse.json();
195
+ result.records.push(...resultJson.records);
196
+ if (resultJson.navigation?.nextPage) {
197
+ pageStart++;
198
+ }
199
+ else {
200
+ isFinalPage = true;
201
+ }
202
+ }
203
+ return result;
204
+ }
205
+ async getSMSData({ extensionId = '~', token, timeFrom, timeTo }) {
206
+ let pageStart = 1;
207
+ let isFinalPage = false;
208
+ let result = { records: [] };
209
+ while (!isFinalPage) {
210
+ const smsLogResponse = await this.request({
211
+ method: 'GET',
212
+ path: `/restapi/v1.0/account/~/extension/${extensionId}/message-store?dateFrom=${timeFrom}&dateTo=${timeTo}&page=${pageStart}&perPage=100`
213
+ }, token);
214
+ const resultJson = await smsLogResponse.json();
215
+ result.records.push(...resultJson.records);
216
+ if (resultJson.navigation?.nextPage) {
217
+ pageStart++;
218
+ }
219
+ else {
220
+ isFinalPage = true;
221
+ }
222
+ }
223
+ return result;
224
+ }
225
+ }
226
+ exports.RingCentral = RingCentral;
@@ -0,0 +1,4 @@
1
+ import type { UploadUrlParams } from '../types';
2
+ declare function ensureBucketExists(): Promise<void>;
3
+ declare function getUploadUrl({ userId, platform, metadata }: UploadUrlParams): Promise<string>;
4
+ export { ensureBucketExists, getUploadUrl };
@@ -1,13 +1,14 @@
1
- // packages/core/lib/s3ErrorReport.js
2
- const { S3Client, PutObjectCommand, GetObjectCommand, CreateBucketCommand, HeadBucketCommand } = require('@aws-sdk/client-s3');
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ensureBucketExists = ensureBucketExists;
4
+ exports.getUploadUrl = getUploadUrl;
5
+ const { S3Client, PutObjectCommand, CreateBucketCommand, HeadBucketCommand } = require('@aws-sdk/client-s3');
3
6
  const { getSignedUrl } = require('@aws-sdk/s3-request-presigner');
4
7
  const shortid = require('shortid');
5
-
6
8
  const BUCKET_NAME = process.env.ERROR_REPORT_S3_BUCKET || 'error-reports-bucket';
7
9
  const PRESIGN_EXPIRY = 300; // 5 minutes
8
10
  const IS_LOCAL = !process.env.ERROR_REPORT_S3_BUCKET;
9
11
  const LOCALSTACK_ENDPOINT = process.env.LOCALSTACK_ENDPOINT || 'http://localhost:9001';
10
-
11
12
  const s3Client = new S3Client({
12
13
  region: process.env.AWS_REGION || 'us-east-1',
13
14
  ...(IS_LOCAL && {
@@ -19,33 +20,25 @@ const s3Client = new S3Client({
19
20
  }
20
21
  })
21
22
  });
22
-
23
- /**
24
- * Ensure bucket exists (useful for local testing)
25
- */
26
23
  async function ensureBucketExists() {
27
- if (!IS_LOCAL) return;
28
-
24
+ if (!IS_LOCAL)
25
+ return;
29
26
  try {
30
27
  await s3Client.send(new HeadBucketCommand({ Bucket: BUCKET_NAME }));
31
- } catch (err) {
32
- if (err.name === 'NotFound' || err.$metadata?.httpStatusCode === 404) {
28
+ }
29
+ catch (err) {
30
+ const awsError = err;
31
+ if (awsError.name === 'NotFound' || awsError.$metadata?.httpStatusCode === 404) {
33
32
  await s3Client.send(new CreateBucketCommand({ Bucket: BUCKET_NAME }));
34
33
  console.log(`[LocalStack] Created bucket: ${BUCKET_NAME}`);
35
34
  }
36
35
  }
37
36
  }
38
-
39
- /**
40
- * Generate presigned URL for upload
41
- */
42
37
  async function getUploadUrl({ userId, platform, metadata }) {
43
38
  await ensureBucketExists();
44
-
45
39
  const reportId = shortid.generate();
46
40
  const timestamp = new Date().toISOString().split('T')[0]; // YYYY-MM-DD
47
41
  const key = `error-reports/${timestamp}/${userId}-${reportId}.json`;
48
-
49
42
  const command = new PutObjectCommand({
50
43
  Bucket: BUCKET_NAME,
51
44
  Key: key,
@@ -56,11 +49,6 @@ async function getUploadUrl({ userId, platform, metadata }) {
56
49
  ...metadata
57
50
  }
58
51
  });
59
-
60
52
  const uploadUrl = await getSignedUrl(s3Client, command, { expiresIn: PRESIGN_EXPIRY });
61
-
62
53
  return uploadUrl;
63
54
  }
64
-
65
- exports.getUploadUrl = getUploadUrl;
66
- exports.ensureBucketExists = ensureBucketExists;