@unboundcx/sdk 4.13.145 → 4.13.146-security.0

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 (45) hide show
  1. package/README.md +7 -0
  2. package/base.js +74 -3
  3. package/index.js +7 -31
  4. package/lib/refreshInterceptor.js +127 -0
  5. package/package.json +2 -5
  6. package/services/layouts.js +4 -13
  7. package/services/licenses.js +330 -0
  8. package/services/login.js +21 -0
  9. package/services/messageTemplates.js +2 -109
  10. package/services/messaging/EmailTemplatesService.js +2 -10
  11. package/services/messaging/SmsService.js +3 -0
  12. package/services/messaging/SmsTemplatesService.js +125 -0
  13. package/services/messaging.js +2 -0
  14. package/services/oauth.js +159 -0
  15. package/services/objects.js +39 -12
  16. package/services/permissions.js +0 -21
  17. package/services/phoneNumbers.js +1037 -2
  18. package/services/recents.js +0 -16
  19. package/services/taskRouter/MetricsService.js +0 -3
  20. package/services/taskRouter/TaskRouterService.js +0 -2
  21. package/services/taskRouter/TaskService.js +10 -70
  22. package/services/voice.js +25 -47
  23. package/lib/journeyLayout.js +0 -132
  24. package/services/journeys/JourneyDraftService.js +0 -92
  25. package/services/journeys/JourneyGoalsService.js +0 -57
  26. package/services/journeys/JourneyMembersService.js +0 -246
  27. package/services/journeys/JourneyTypesService.js +0 -59
  28. package/services/journeys/JourneyWorklistService.js +0 -74
  29. package/services/journeys/JourneysService.js +0 -392
  30. package/services/operatorPanels.js +0 -226
  31. package/services/parking.js +0 -121
  32. package/services/phoneNumbers/carrier.js +0 -60
  33. package/services/phoneNumbers/cnam.js +0 -42
  34. package/services/phoneNumbers/index.js +0 -27
  35. package/services/phoneNumbers/order.js +0 -88
  36. package/services/phoneNumbers/porting-activity.js +0 -289
  37. package/services/phoneNumbers/porting-orders.js +0 -318
  38. package/services/phoneNumbers/search.js +0 -181
  39. package/services/phoneNumbers/update.js +0 -94
  40. package/services/schedules/SchedulesService.js +0 -232
  41. package/services/schedules/TimeOffService.js +0 -131
  42. package/services/skills.js +0 -207
  43. package/services/taskRouter/QueueService.js +0 -343
  44. package/services/voicemailDrops.js +0 -268
  45. package/services/workflowTemplates/WorkflowTemplatesService.js +0 -68
package/README.md CHANGED
@@ -297,6 +297,13 @@ await api.messaging.email.send({
297
297
  htmlBody: '<h1>Hello World!</h1>',
298
298
  });
299
299
 
300
+ // Templates
301
+ await api.messaging.sms.templates.create({
302
+ name: 'welcome',
303
+ message: 'Welcome {{name}}!',
304
+ variables: { name: 'string' },
305
+ });
306
+
300
307
  // Campaign Management
301
308
  await api.messaging.campaigns.tollFree.create({
302
309
  companyName: 'Acme Corp',
package/base.js CHANGED
@@ -13,6 +13,8 @@
13
13
  * npm install mime-types
14
14
  */
15
15
 
16
+ import { handleUnauthorized } from './lib/refreshInterceptor.js';
17
+
16
18
  const requestBySdk = new WeakMap();
17
19
  const SDK_REQUEST = Symbol.for('unbound.sdk.request');
18
20
 
@@ -49,12 +51,33 @@ export class BaseSDK {
49
51
  this.fwRequestId = arguments[3];
50
52
  } else {
51
53
  // New object-based parameters
52
- const { namespace, callId, token, fwRequestId, baseURL } = options;
54
+ const {
55
+ namespace,
56
+ callId,
57
+ token,
58
+ fwRequestId,
59
+ baseURL,
60
+ autoRefresh,
61
+ onUnauthorized,
62
+ refreshToken,
63
+ } = options;
53
64
  this.namespace = namespace || process?.env?.namespace;
54
65
  this.callId = callId;
55
66
  this.token = token;
56
67
  this.fwRequestId = fwRequestId;
57
68
  this._constructorBaseURL = baseURL;
69
+ // api#222 -- opt-in only (default false): existing callers get no
70
+ // behavior change. When on, a 401 from any non-/login* endpoint
71
+ // triggers one single-flight refresh + one retry (lib/refreshInterceptor.js).
72
+ this._autoRefresh = autoRefresh === true;
73
+ this._onUnauthorized =
74
+ typeof onUnauthorized === 'function' ? onUnauthorized : null;
75
+ // Bearer-delivery clients only: the raw refresh token, so autoRefresh
76
+ // has something to send to POST /login/refresh (cookie clients rely
77
+ // on the browser's own refreshToken cookie and never need this).
78
+ // Seeded via this option or setRefreshToken(); updated in place on
79
+ // every rotation by lib/refreshInterceptor.js.
80
+ this._refreshToken = refreshToken;
58
81
  }
59
82
  this.baseURL;
60
83
  this.transports = new Map();
@@ -104,6 +127,10 @@ export class BaseSDK {
104
127
  this.token = token;
105
128
  }
106
129
 
130
+ setRefreshToken(refreshToken) {
131
+ this._refreshToken = refreshToken;
132
+ }
133
+
107
134
  setNamespace(namespace) {
108
135
  this.namespace = namespace;
109
136
  const defaultDomain = 'api.unbound.cx';
@@ -278,6 +305,7 @@ export class BaseSDK {
278
305
  params,
279
306
  returnRawResponse,
280
307
  startTime,
308
+ forceFetch,
281
309
  );
282
310
  }
283
311
  } else {
@@ -292,6 +320,7 @@ export class BaseSDK {
292
320
  params,
293
321
  returnRawResponse,
294
322
  startTime,
323
+ forceFetch,
295
324
  );
296
325
  }
297
326
 
@@ -307,6 +336,7 @@ export class BaseSDK {
307
336
  method,
308
337
  endpoint,
309
338
  duration,
339
+ { originalParams: params, forceFetch },
310
340
  );
311
341
  }
312
342
 
@@ -357,6 +387,7 @@ export class BaseSDK {
357
387
  params = {},
358
388
  returnRawResponse = false,
359
389
  startTime = Date.now(),
390
+ forceFetch = false,
360
391
  ) {
361
392
  const { body, query, headers = {} } = params;
362
393
 
@@ -438,10 +469,20 @@ export class BaseSDK {
438
469
  return response;
439
470
  }
440
471
 
441
- return this._processResponse(response, 'https', method, endpoint, duration);
472
+ return this._processResponse(response, 'https', method, endpoint, duration, {
473
+ originalParams: params,
474
+ forceFetch,
475
+ });
442
476
  }
443
477
 
444
- async _processResponse(response, transport, method, endpoint, duration = 0) {
478
+ async _processResponse(
479
+ response,
480
+ transport,
481
+ method,
482
+ endpoint,
483
+ duration = 0,
484
+ retryCtx = {},
485
+ ) {
445
486
  // Check if the response indicates an HTTP error
446
487
  // These are API/configuration errors, not transport failures
447
488
 
@@ -518,6 +559,36 @@ export class BaseSDK {
518
559
  );
519
560
  }
520
561
 
562
+ // api#222 -- opt-in single-flight refresh + one retry on 401. Off by
563
+ // default (this._autoRefresh set only via the `autoRefresh` ctor
564
+ // option); the retry's own params carry `__skipAutoRefresh` so a 401
565
+ // on the RETRY itself always falls through to onUnauthorized instead
566
+ // of looping.
567
+ if (response.status === 401 && this._autoRefresh) {
568
+ return handleUnauthorized(this, {
569
+ status: response.status,
570
+ endpoint,
571
+ method,
572
+ alreadyRetried: retryCtx?.originalParams?.__skipAutoRefresh === true,
573
+ originalError: httpError,
574
+ retry: () =>
575
+ // forceFetch: true (not retryCtx.forceFetch) -- the retry must
576
+ // always go over plain HTTP, never the original transport. A
577
+ // socket transport call that 401'd still holds the pre-rotation
578
+ // JWT (the rotation reaches the socket asynchronously via NATS),
579
+ // so retrying over the same socket would 401 again and trigger
580
+ // onUnauthorized even though the refresh above just succeeded.
581
+ // See _getAvailableTransport (base.js:~185): forceFetch skips
582
+ // transports entirely and goes straight to HTTP.
583
+ this.#request(
584
+ endpoint,
585
+ method,
586
+ { ...(retryCtx.originalParams || {}), __skipAutoRefresh: true },
587
+ true,
588
+ ),
589
+ });
590
+ }
591
+
521
592
  throw httpError;
522
593
  }
523
594
 
package/index.js CHANGED
@@ -23,11 +23,6 @@ import { DealRegistrationsService } from './services/dealRegistrations.js';
23
23
  import { SipEndpointsService } from './services/sipEndpoints.js';
24
24
  import { RingGroupsService } from './services/ringGroups.js';
25
25
  import { LineGroupsService } from './services/lineGroups.js';
26
- import { ParkingService } from './services/parking.js';
27
- import { OperatorPanelsService } from './services/operatorPanels.js';
28
- import { SchedulesService } from './services/schedules/SchedulesService.js';
29
- import { JourneysService } from './services/journeys/JourneysService.js';
30
- import { WorkflowTemplatesService } from './services/workflowTemplates/WorkflowTemplatesService.js';
31
26
  import { EmergencyService } from './services/emergency.js';
32
27
  import { WebchatService } from './services/webchat.js';
33
28
  import { CobrowseService } from './services/cobrowse.js';
@@ -41,12 +36,12 @@ import { RecordTypesService } from './services/recordTypes.js';
41
36
  import { GenerateIdService } from './services/generateId.js';
42
37
  import { EngagementMetricsService } from './services/engagementMetrics.js';
43
38
  import { TaskRouterService } from './services/taskRouter.js';
44
- import { SkillsService } from './services/skills.js';
45
39
  import { KnowledgeBaseService } from './services/knowledgeBase.js';
46
40
  import { FaxService } from './services/fax.js';
47
41
  import { DocumentsService } from './services/documents.js';
48
42
  import { EsignService } from './services/esign.js';
49
43
  import { PermissionsService } from './services/permissions.js';
44
+ import { LicensesService } from './services/licenses.js';
50
45
  import { UsersService } from './services/users.js';
51
46
  import { TriggersService } from './services/triggers.js';
52
47
  import { RecentsService } from './services/recents.js';
@@ -56,11 +51,11 @@ import { ChatService } from './services/chat.js';
56
51
  import { DeveloperApisService } from './services/developerApis.js';
57
52
  import { TextService } from './services/text.js';
58
53
  import { ReportingService } from './services/reporting.js';
54
+ import { OAuthService } from './services/oauth.js';
59
55
  import {
60
56
  DataImportService,
61
57
  DataExportService,
62
58
  } from './services/dataImport.js';
63
- import { VoicemailDropsService } from './services/voicemailDrops.js';
64
59
 
65
60
  class UnboundSDK extends BaseSDK {
66
61
  constructor(options = {}) {
@@ -132,11 +127,6 @@ class UnboundSDK extends BaseSDK {
132
127
  this.sipEndpoints = new SipEndpointsService(this);
133
128
  this.ringGroups = new RingGroupsService(this);
134
129
  this.lineGroups = new LineGroupsService(this);
135
- this.parking = new ParkingService(this);
136
- this.operatorPanels = new OperatorPanelsService(this);
137
- this.schedules = new SchedulesService(this);
138
- this.journeys = new JourneysService(this);
139
- this.workflowTemplates = new WorkflowTemplatesService(this);
140
130
  this.emergency = new EmergencyService(this);
141
131
  this.webchat = new WebchatService(this);
142
132
  this.cobrowse = new CobrowseService(this);
@@ -150,24 +140,24 @@ class UnboundSDK extends BaseSDK {
150
140
  this.generateId = new GenerateIdService(this);
151
141
  this.engagementMetrics = new EngagementMetricsService(this);
152
142
  this.taskRouter = new TaskRouterService(this);
153
- this.skills = new SkillsService(this);
154
143
  this.text = new TextService(this);
155
144
  this.knowledgeBase = new KnowledgeBaseService(this);
156
145
  this.fax = new FaxService(this);
157
146
  this.documents = new DocumentsService(this);
158
147
  this.esign = new EsignService(this);
159
148
  this.permissions = new PermissionsService(this);
149
+ this.licenses = new LicensesService(this);
160
150
  this.users = new UsersService(this);
161
151
  this.reporting = new ReportingService(this);
162
152
  this.triggers = new TriggersService(this);
163
153
  this.recents = new RecentsService(this);
164
154
  this.search = new SearchService(this);
165
155
  this.directory = new DirectoryService(this);
156
+ this.oauth = new OAuthService(this);
166
157
  this.chat = new ChatService(this);
167
158
  this.developerApis = new DeveloperApisService(this);
168
159
  this.dataImport = new DataImportService(this);
169
160
  this.dataExport = new DataExportService(this);
170
- this.voicemailDrops = new VoicemailDropsService(this);
171
161
 
172
162
  // Add additional services that might be missing
173
163
  this._initializeAdditionalServices();
@@ -342,21 +332,10 @@ export { DealRegistrationsService } from './services/dealRegistrations.js';
342
332
  export { SipEndpointsService } from './services/sipEndpoints.js';
343
333
  export { RingGroupsService } from './services/ringGroups.js';
344
334
  export { LineGroupsService } from './services/lineGroups.js';
345
- export { ParkingService } from './services/parking.js';
346
- export { SchedulesService } from './services/schedules/SchedulesService.js';
347
- export { TimeOffService } from './services/schedules/TimeOffService.js';
348
- export { JourneysService } from './services/journeys/JourneysService.js';
349
- export { JourneyMembersService } from './services/journeys/JourneyMembersService.js';
350
- export { JourneyDraftService } from './services/journeys/JourneysService.js';
351
- export { JourneyWorklistService } from './services/journeys/JourneyWorklistService.js';
352
- export { WorkflowTemplatesService } from './services/workflowTemplates/WorkflowTemplatesService.js';
353
335
  export { EmergencyService } from './services/emergency.js';
354
336
  export { WebchatService, WebchatWidgetsService } from './services/webchat.js';
355
337
  export { CobrowseService, CobrowseVisitorService } from './services/cobrowse.js';
356
- export {
357
- MessageTemplatesService,
358
- MessageTemplateVersionsService,
359
- } from './services/messageTemplates.js';
338
+ export { MessageTemplatesService } from './services/messageTemplates.js';
360
339
  export { WebchatVisitorService } from './services/webchat/VisitorService.js';
361
340
  export { ExternalOAuthService } from './services/externalOAuth.js';
362
341
  export { GoogleCalendarService } from './services/googleCalendar.js';
@@ -378,20 +357,17 @@ export { KnowledgeBaseService } from './services/knowledgeBase.js';
378
357
  export { FaxService } from './services/fax.js';
379
358
  export { EsignService, EsignPublicService } from './services/esign.js';
380
359
  export { PermissionsService } from './services/permissions.js';
360
+ export { LicensesService } from './services/licenses.js';
381
361
  export { UsersService } from './services/users.js';
382
362
  export { ReportingService } from './services/reporting.js';
383
363
  export { RecentsService } from './services/recents.js';
384
364
  export { SearchService } from './services/search.js';
385
365
  export { DirectoryService } from './services/directory.js';
366
+ export { OAuthService } from './services/oauth.js';
386
367
  export { ChatService } from './services/chat.js';
387
368
  export { DeveloperApisService } from './services/developerApis.js';
388
369
  export {
389
370
  DataImportService,
390
371
  DataExportService,
391
372
  } from './services/dataImport.js';
392
- export {
393
- VoicemailDropsService,
394
- VoicemailDropTypesService,
395
- } from './services/voicemailDrops.js';
396
373
  export { BaseSDK } from './base.js';
397
- export { layoutJourney, MAX_LANES as JOURNEY_LAYOUT_MAX_LANES } from './lib/journeyLayout.js';
@@ -0,0 +1,127 @@
1
+ // api#222 client contract -- single-flight 401 -> refresh -> retry-once.
2
+ // base.js's `#request` funnels BOTH the Socket.IO transport and the plain
3
+ // HTTP fallback through the same `_processResponse` (see base.js), so this
4
+ // one hook covers every transport without a per-transport copy.
5
+ //
6
+ // Usage (base.js only -- app code never imports this directly):
7
+ // handleUnauthorized(sdk, { status, endpoint, retry, originalError })
8
+ //
9
+ // `retry` is a caller-supplied () => Promise that re-issues the ORIGINAL
10
+ // request. It has to come from the caller because #request is a private
11
+ // class field method -- this module can't call it directly.
12
+
13
+ // Keyed per SDK instance: a shared module-level variable would let one
14
+ // SDK instance's refresh starve a concurrent, unrelated SDK instance's own
15
+ // 401 recovery (a different user/session in the same Node process -- the
16
+ // API itself increasingly consumes this SDK server-side). Each instance
17
+ // still single-flights its own concurrent 401s against itself.
18
+ const inFlightRefreshBySdk = new WeakMap();
19
+
20
+ // Only the routes that WOULD cause a refresh loop (or make no sense to
21
+ // refresh) are excluded: refreshing itself (POST /login/refresh), the
22
+ // initial password login (POST /login), and logout (DELETE /login). Every
23
+ // other /login/* call -- notably GET /login/validate, which a page reload
24
+ // hits with a stale access cookie -- is refreshable: a valid refresh cookie
25
+ // must be able to recover it instead of bouncing the user to the password
26
+ // form.
27
+ function isNonRefreshableLoginRoute(method, endpoint) {
28
+ if (typeof endpoint !== 'string') return false;
29
+ const m = typeof method === 'string' ? method.toUpperCase() : '';
30
+ if (endpoint === '/login/refresh' && m === 'POST') return true;
31
+ if (endpoint === '/login' && (m === 'POST' || m === 'DELETE')) return true;
32
+ return false;
33
+ }
34
+
35
+ export function shouldAttemptRefresh(sdk, status, endpoint, method) {
36
+ return (
37
+ status === 401 &&
38
+ sdk?._autoRefresh === true &&
39
+ !isNonRefreshableLoginRoute(method, endpoint) &&
40
+ typeof sdk?.login?.refresh === 'function'
41
+ );
42
+ }
43
+
44
+ async function runRefresh(sdk) {
45
+ let inFlight = inFlightRefreshBySdk.get(sdk);
46
+ if (!inFlight) {
47
+ // Bearer clients (constructed with a raw token, no browser cookie jar)
48
+ // have to hand their raw refresh token back on every call -- the SDK
49
+ // never gets one implicitly the way a cookie client's browser does.
50
+ // sdk._refreshToken is set from login/refresh's own response below, or
51
+ // may be seeded via sdk.setRefreshToken() by a caller that obtained it
52
+ // out of band. Cookie clients simply have no stored value: `undefined`
53
+ // is fine, refresh() omits body.refreshToken and relies on the cookie.
54
+ inFlight = sdk.login
55
+ .refresh(sdk._refreshToken)
56
+ .then((result) => {
57
+ // Bearer clients get a new access token AND a new (rotated) refresh
58
+ // token back in the body; cookie clients rely on the Set-Cookie
59
+ // pair the refresh response already sent -- there is no token
60
+ // string to apply to the SDK instance for them.
61
+ if (result?.token) {
62
+ sdk.setToken(result.token);
63
+ } else if (typeof sdk?.setToken === 'function') {
64
+ // Cookie-mode refresh: no token string comes back (the Set-Cookie
65
+ // pair already rotated the browser's cookies), but a stale
66
+ // in-memory access token left on the SDK would keep going out as
67
+ // an Authorization header, which checkApiAuth prefers over the
68
+ // fresh cookie. Clear it so the next request relies on the cookie.
69
+ sdk.setToken(null);
70
+ }
71
+ if (result?.refreshToken) sdk._refreshToken = result.refreshToken;
72
+ return result;
73
+ })
74
+ .finally(() => {
75
+ inFlightRefreshBySdk.delete(sdk);
76
+ });
77
+ inFlightRefreshBySdk.set(sdk, inFlight);
78
+ }
79
+ return inFlight;
80
+ }
81
+
82
+ function notifyUnauthorized(sdk, err) {
83
+ if (typeof sdk?._onUnauthorized !== 'function') return;
84
+ try {
85
+ sdk._onUnauthorized(err);
86
+ } catch (callbackErr) {
87
+ console.error(
88
+ 'refreshInterceptor :: onUnauthorized callback threw ::',
89
+ callbackErr,
90
+ );
91
+ }
92
+ }
93
+
94
+ /**
95
+ * @param {object} sdk
96
+ * @param {object} ctx
97
+ * @param {number} ctx.status
98
+ * @param {string} ctx.endpoint
99
+ * @param {string} [ctx.method]
100
+ * @param {() => Promise<any>} ctx.retry
101
+ * @param {Error} ctx.originalError -- rethrown whenever refresh isn't
102
+ * attempted, fails, or the retry itself still comes back 401 (never loop
103
+ * past one retry).
104
+ * @param {boolean} [ctx.alreadyRetried]
105
+ */
106
+ export async function handleUnauthorized(
107
+ sdk,
108
+ { status, endpoint, method, retry, originalError, alreadyRetried = false },
109
+ ) {
110
+ if (alreadyRetried || !shouldAttemptRefresh(sdk, status, endpoint, method)) {
111
+ throw originalError;
112
+ }
113
+
114
+ try {
115
+ await runRefresh(sdk);
116
+ } catch (refreshErr) {
117
+ notifyUnauthorized(sdk, originalError);
118
+ throw originalError;
119
+ }
120
+
121
+ try {
122
+ return await retry();
123
+ } catch (retryErr) {
124
+ if (retryErr?.status === 401) notifyUnauthorized(sdk, retryErr);
125
+ throw retryErr;
126
+ }
127
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unboundcx/sdk",
3
- "version": "4.13.145",
3
+ "version": "4.13.146-security.0",
4
4
  "description": "Official JavaScript SDK for the Unbound API - A comprehensive toolkit for integrating with Unbound's communication, AI, and data management services",
5
5
  "main": "index.js",
6
6
  "type": "module",
@@ -40,11 +40,11 @@
40
40
  "*.js",
41
41
  "services/**/*.js",
42
42
  "transports/**/*.js",
43
+ "lib/**/*.js",
43
44
  "types/**/*.d.ts",
44
45
  "proto/**/*.proto",
45
46
  "schemas/**/*.js",
46
47
  "schemas/**/*.md",
47
- "lib/**/*.js",
48
48
  "README.md",
49
49
  "LICENSE"
50
50
  ],
@@ -64,9 +64,6 @@
64
64
  },
65
65
  "./schemas/*": {
66
66
  "import": "./schemas/*.js"
67
- },
68
- "./lib/*": {
69
- "import": "./lib/*.js"
70
67
  }
71
68
  },
72
69
  "scripts": {
@@ -177,24 +177,15 @@ export class LayoutsService {
177
177
  return result;
178
178
  }
179
179
 
180
- async listSystem() {
181
- const result = await internalRequest(this.sdk, '/layouts/system', 'GET', {});
182
- return result;
183
- }
184
-
185
- // recordTypeId is only sent when provided -- cloning a GLOBAL system layout
186
- // into a tenant row targets a specific record type.
187
- async clone(id, { name, recordTypeId } = {}) {
180
+ async clone(id, { name } = {}) {
188
181
  this.sdk.validateParams(
189
182
  { id },
190
183
  { id: { type: 'string', required: true } },
191
184
  );
192
185
 
193
- const body = { name };
194
- if (recordTypeId !== undefined && recordTypeId !== null) {
195
- body.recordTypeId = recordTypeId;
196
- }
197
- const params = { body };
186
+ const params = {
187
+ body: { name },
188
+ };
198
189
 
199
190
  const result = await internalRequest(this.sdk, `/layouts/${id}/clone`, 'POST', params);
200
191
  return result;