@babelforce/manager-sdk 0.39.0 → 0.40.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.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,16 @@
3
3
  All notable changes to `@babelforce/manager-sdk` are documented here. This project adheres to
4
4
  [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## 0.40.0
7
+
8
+ - Added first-class **Authorization Code + PKCE** (RFC 7636) support: a new `refreshToken` auth mode
9
+ (transparent refresh with refresh-token rotation) plus the helpers `pkceChallenge`,
10
+ `buildAuthorizeUrl`, `authorizationCodeGrant`, and `refreshTokenGrant`. `clientCredentialsGrant` is
11
+ now exported too. `TokenResponse` gained an optional `refresh_token`.
12
+ - Consolidated the docs: the OAuth guide is merged into a single **Authentication** guide (overview +
13
+ one section per flow + when-to-use). Client credentials is documented with a security-review/limited-
14
+ availability caveat.
15
+
6
16
  ## 0.39.0
7
17
 
8
18
  - Refreshed the vendored manager API spec (richer endpoint descriptions/examples) and regenerated
package/README.md CHANGED
@@ -37,10 +37,14 @@ await mgr.users.enable(["new.user@acme.com"]);
37
37
 
38
38
  ### Authentication
39
39
 
40
- - `{ kind: "clientCredentials", clientId, clientSecret }` — recommended for server-to-server use;
41
- OAuth2 client_credentials grant against `/oauth/token` with transparent refresh.
40
+ - `{ kind: "refreshToken", refreshToken, clientId }` — a refresh token from the Authorization Code +
41
+ PKCE flow (helpers: `pkceChallenge`, `buildAuthorizeUrl`, `authorizationCodeGrant`); transparent
42
+ refresh with rotation. Best for apps acting on behalf of a user.
43
+ - `{ kind: "clientCredentials", clientId, clientSecret }` — OAuth2 client_credentials grant with
44
+ transparent refresh, for server-to-server use (credential issuance is in security review — see the
45
+ [Authentication guide](https://babelforce.github.io/manager-sdk/guides/authentication)).
42
46
  - `{ kind: "bearer", token }` — a token you already hold.
43
- - `{ kind: "password", user, pass }` — OAuth2 password grant with transparent refresh.
47
+ - `{ kind: "password", user, pass }` — OAuth2 password grant (legacy) with transparent refresh.
44
48
 
45
49
  ### Errors
46
50
 
package/dist/index.d.ts CHANGED
@@ -3,12 +3,17 @@ import { Client } from '@hey-api/client-fetch';
3
3
  /**
4
4
  * How the SDK authenticates against the manager API.
5
5
  *
6
- * - `clientCredentials` — the recommended server-to-server mode; OAuth2 client_credentials grant
7
- * against `/oauth/token`. The token is fetched lazily on the first request and refreshed
8
- * transparently before it expires.
9
- * - `bearer` — a bearer token you already obtained.
6
+ * - `clientCredentials` — server-to-server OAuth2 client_credentials grant against `/oauth/token`.
7
+ * The token is fetched lazily on the first request and refreshed transparently before it expires.
8
+ * Requires an OAuth2 application (client id/secret); see the Authentication guide for the current
9
+ * availability caveat.
10
+ * - `bearer` — a bearer token you already obtained (e.g. the access token from a PKCE flow).
10
11
  * - `password` — OAuth2 password grant against `/oauth/token`; the token is fetched lazily on the
11
12
  * first request and refreshed transparently before it expires. Convenience for interactive/dev use.
13
+ * - `refreshToken` — a refresh token obtained from the Authorization Code + PKCE flow. The SDK
14
+ * exchanges it for an access token lazily and refreshes transparently, capturing the rotated
15
+ * refresh token on each use (refresh tokens are single-use). The recommended way to run a
16
+ * long-lived client on behalf of a user.
12
17
  */
13
18
  type Auth = {
14
19
  kind: 'clientCredentials';
@@ -22,12 +27,46 @@ type Auth = {
22
27
  user: string;
23
28
  pass: string;
24
29
  clientId?: string;
30
+ } | {
31
+ kind: 'refreshToken';
32
+ refreshToken: string;
33
+ clientId?: string;
34
+ clientSecret?: string;
25
35
  };
26
36
  interface TokenResponse {
27
37
  access_token: string;
28
38
  expires_in?: number;
29
39
  token_type?: string;
40
+ /** Present for the authorization_code (offline) and refresh_token grants; rotated on every use. */
41
+ refresh_token?: string;
42
+ }
43
+ interface PkceChallenge {
44
+ /** The high-entropy secret to keep client-side and send with {@link authorizationCodeGrant}. */
45
+ codeVerifier: string;
46
+ /** The base64url(SHA-256(codeVerifier)) value to send with {@link buildAuthorizeUrl}. */
47
+ codeChallenge: string;
48
+ codeChallengeMethod: 'S256';
30
49
  }
50
+ /**
51
+ * Generate a PKCE code verifier + S256 challenge (RFC 7636). Pass `codeChallenge` to
52
+ * {@link buildAuthorizeUrl} and keep `codeVerifier` to later exchange the returned code via
53
+ * {@link authorizationCodeGrant}. Uses the Web Crypto API (Node 18+ / browsers).
54
+ */
55
+ declare function pkceChallenge(): Promise<PkceChallenge>;
56
+ interface AuthorizeUrlOptions {
57
+ baseUrl: string;
58
+ clientId: string;
59
+ redirectUri: string;
60
+ scope: string;
61
+ codeChallenge: string;
62
+ state?: string;
63
+ codeChallengeMethod?: 'S256' | 'plain';
64
+ }
65
+ /**
66
+ * Build the `GET {baseUrl}/oauth/authorize` URL that starts the Authorization Code + PKCE flow.
67
+ * Redirect the user to it; babelforce redirects back to `redirectUri` with a `code`.
68
+ */
69
+ declare function buildAuthorizeUrl(opts: AuthorizeUrlOptions): string;
31
70
  /**
32
71
  * Exchange a username/password for a bearer token via the manager OAuth2 password grant
33
72
  * (`POST {baseUrl}/oauth/token`). Exposed for callers who want to manage tokens themselves.
@@ -39,6 +78,42 @@ declare function passwordGrant(opts: {
39
78
  clientId?: string;
40
79
  fetch?: typeof fetch;
41
80
  }): Promise<TokenResponse>;
81
+ /**
82
+ * Exchange a client id/secret for a bearer token via the manager OAuth2 client_credentials grant
83
+ * (`POST {baseUrl}/oauth/token`). Exposed for callers who want to manage tokens themselves.
84
+ */
85
+ declare function clientCredentialsGrant(opts: {
86
+ baseUrl: string;
87
+ clientId: string;
88
+ clientSecret: string;
89
+ fetch?: typeof fetch;
90
+ }): Promise<TokenResponse>;
91
+ /**
92
+ * Exchange an authorization `code` (from the PKCE consent redirect) for tokens via the
93
+ * authorization_code grant. Public clients pass only `codeVerifier`; confidential clients may also
94
+ * pass `clientSecret`. Returns an access token and (for offline access) a rotating refresh token.
95
+ */
96
+ declare function authorizationCodeGrant(opts: {
97
+ baseUrl: string;
98
+ code: string;
99
+ redirectUri: string;
100
+ clientId: string;
101
+ codeVerifier: string;
102
+ clientSecret?: string;
103
+ fetch?: typeof fetch;
104
+ }): Promise<TokenResponse>;
105
+ /**
106
+ * Exchange the most-recently-issued refresh token for a fresh token set via the refresh_token grant.
107
+ * Refresh tokens are rotated on every use — the response carries the next one. Exposed for callers
108
+ * who want to manage tokens themselves; the `refreshToken` auth mode does this transparently.
109
+ */
110
+ declare function refreshTokenGrant(opts: {
111
+ baseUrl: string;
112
+ refreshToken: string;
113
+ clientId?: string;
114
+ clientSecret?: string;
115
+ fetch?: typeof fetch;
116
+ }): Promise<TokenResponse>;
42
117
 
43
118
  /**
44
119
  * Automatic request retries for the manager SDK.
@@ -7889,4 +7964,4 @@ declare class ManagerApiError extends Error {
7889
7964
  static from(response: Response, body: unknown): ManagerApiError;
7890
7965
  }
7891
7966
 
7892
- export { type Account, type AccountRole$1 as AccountRole, type AddOutboundLeadRequest, type Agent, type AgentGroup, type AgentGroupItemResponse, AgentGroupsResource, type AgentItemResponse, type AgentLineStatus, type AgentLogsQuery, type AgentOutboundCallRequest, type AgentStatus, AgentsResource, AppActionsResource, type Application, type ApplicationCreateBody, type ApplicationItemResponse, type ApplicationUpdateBody, ApplicationsResource, type Auth, AuthResource, type AuthorizeData, AutomationsResource, type Babeldesk, type BabeldeskItemResponse, BabeldeskResource, type BabeldeskWidget, type BabeldeskWidgetItemResponse, BabeldeskWidgetsResource, type BulkActionResponse, type BulkIdsRequest, type BulkUpdateIntegrationsRequest, type BulkUpdateRequest, type BusinessHour, type BusinessHourItemResponse, BusinessHoursResource, type Calendar, type CalendarItemResponse, CalendarsResource, type Call, type CallAttempt, type CallItemResponse, CallsResource, type CampaignHopperResponse, type CampaignItemResponse, type CampaignRealtimeStatusResponse, type CampaignStatisticsResponse, CampaignsResource, type Conference, type ConferenceItemResponse, ConferencesResource, type Conversation, type ConversationEvent, type ConversationItemResponse, type ConversationSessionVariables, ConversationsResource, type CreateCampaignRequest, type CreateListRequest, type CreateManagedUserRequest, type CreateOutboundListRequest, type CreateTestCall, DEFAULT_BASE_URL, type Dashboard, type DashboardCreateBody, type DashboardItemResponse, type DashboardUpdateBody, type DashboardUser, type DashboardUsersResponse, DashboardsResource, type DefaultV2MessageResponse, type DialerBehaviour, type DialerBehaviourItemResponse, type DialerBehaviourWriteBody, DialerBehavioursResource, DialerResource, type DialerSimpleReportingQuery, EventsResource, ExpressionsResource, type FileBulkDeleteRequest, type FileBulkDownloadRequest, FilesResource, type GenericItemResponse, type GlobalAutomation, type GlobalAutomationItemResponse, type ImportAgentsOptions, type Integration, type IntegrationBulkIdsRequest, type IntegrationCreateRequest, type IntegrationItemResponse, type IntegrationObjectListResponse, type IntegrationProvider, type IntegrationTokenItemResponse, type IntegrationTokenListResponse, type IntegrationUpdateRequest, IntegrationsResource, type InterruptionTargetStates, type IvrModule, type Lead, type LeadBulkDeleteRequest, type LeadListItemResponse, type LeadUploadRequest, type LeadUploadResponse, type ListAgentsQuery, type ListApplicationsQuery, type ListAuditLogsQuery, type ListAutomationsQuery, type ListBabeldeskWidgetsQuery, type ListBabeldesksQuery, type ListBusinessHoursQuery, type ListCalendarsQuery, type ListConferencesQuery, type ListConversationsQuery, type ListDashboardsQuery, type ListDialerBehavioursQuery, type ListFilesQuery, type ListIntegrationsQuery, type ListNumbersQuery, type ListOutboundAttemptsQuery, type ListOutboundLeadsQuery, type ListPhonebookQuery, type ListProcessedOutboundLeadsQuery, type ListPromptsQuery, type ListQueuesQuery, type ListRecordingsQuery, type ListRoutingsQuery, type ListSmsQuery, type ListTasksQuery, type ListTriggersQuery, type ListUsersQuery, type LocalAutomation, type LocalAutomationItemResponse, LogsResource, type ManagedUser, type ManagedUserItemResponse, ManagerApiError, ManagerClient, type ManagerClientOptions, MeResource, type MetricDefinitionItemResponse, type MetricIdItemsResponse, type MetricResponse, MetricsResource, NumbersResource, type OAuthRevokeRequest, type OAuthTokenRequest, type OAuthTokenResponse, type ObjectListResponse, type OutboundCampaign, type OutboundCampaignItemResponse, type OutboundLeadItemResponse, type OutboundList, type OutboundListItemResponse, OutboundResource, type OutboundSimpleReportingQuery, type PaginatedAttemptResponse, type PaginatedLeadResponse, type PaginatedRecordingResponse, type PhonebookCsvFile, type PhonebookEntry, type PhonebookEntryItemResponse, PhonebookResource, type Prompt, type PromptAudioFile, type PromptItemResponse, PromptsResource, type Queue, type QueueItemResponse, type QueueSelection, type QueueSelectionItemResponse, QueueSelectionsResource, type QueueTriggerListResponse, QueuesResource, type Recording, type RecordingItemResponse, type RecordingStartRequest, type RecordingState, type RecordingUpdateBody, RecordingsResource, type ReportingCall, type ReportingCallsQuery, ReportingResource, type RestCreateAgentBody, type RestCreateAgentGroupBody, type RestCreateBabeldeskBody, type RestCreateBabeldeskWidgetBody, type RestCreateBusinessHourBody, type RestCreateCalendarBody, type RestCreateConversationBody, type RestCreateGlobalAutomationBody, type RestCreateLocalAutomationBody, type RestCreatePhonebookEntryBody, type RestCreateQueueBody, type RestCreateQueueSelectionBody, type RestCreateRoutingBody, type RestCreateTriggerBody, type RestUpdateAgentBody, type RestUpdateAgentGroupBody, type RestUpdateBabeldeskBody, type RestUpdateBabeldeskWidgetBody, type RestUpdateBusinessHourBody, type RestUpdateCalendarBody, type RestUpdateConversationBody, type RestUpdateGlobalAutomationBody, type RestUpdateLocalAutomationBody, type RestUpdatePhonebookEntryBody, type RestUpdatePromptBody, type RestUpdateQueueBody, type RestUpdateQueueSelectionBody, type RestUpdateRoutingBody, type RestUpdateTriggerBody, type RetryOptions, type Routing, type RoutingItemResponse, RoutingResource, type ServiceNumber, type ServiceNumberItemResponse, type SessionResponse, SessionsResource, type SetCampaignListRequest, SettingAccessor, type SettingsAppAgentStatus, type SettingsAppConversations, type SettingsAppCustomerLogging, type SettingsAppIntegrations, type SettingsAuditDefault, SettingsResource, type SettingsRetentionPeriods, type SettingsTelephonyAgentInbound, type SettingsTelephonyAgentOutbound, type SettingsTelephonyAgentRecording, type SettingsTelephonyAgentWrapup, type SettingsTelephonyPostCall, type SettingsUiI18N, type SimpleReportingCallsQuery, type Sms, type SmsItemResponse, SmsResource, type StorageState, type StorageType, type StoredFile, type StoredFileItemResponse, type SubmitTaskBody, type SubmitTaskScheduleBody, SystemResource, type Tag, type Task, TaskMetricsResource, type TaskSchedule, TaskSchedulesResource, TaskScriptsResource, TaskSecretsResource, TaskSelectionConfigResource, type TaskTemplateOverrides, TasksResource, type TokenResponse, type Trigger, type TriggerConditionListResponse, type TriggerConditionsRequest, type TriggerItemResponse, type TriggerUsesResponse, TriggersResource, type UpdateAgentStatusRequest, type UpdateCampaignRequest, type UpdateSessionVariablesRequest, type UpdateTaskBody, type User, type UserCustomer, type UserCustomerItemResponse, type UserItemResponse, UsersResource, passwordGrant, withRetry };
7967
+ export { type Account, type AccountRole$1 as AccountRole, type AddOutboundLeadRequest, type Agent, type AgentGroup, type AgentGroupItemResponse, AgentGroupsResource, type AgentItemResponse, type AgentLineStatus, type AgentLogsQuery, type AgentOutboundCallRequest, type AgentStatus, AgentsResource, AppActionsResource, type Application, type ApplicationCreateBody, type ApplicationItemResponse, type ApplicationUpdateBody, ApplicationsResource, type Auth, AuthResource, type AuthorizeData, type AuthorizeUrlOptions, AutomationsResource, type Babeldesk, type BabeldeskItemResponse, BabeldeskResource, type BabeldeskWidget, type BabeldeskWidgetItemResponse, BabeldeskWidgetsResource, type BulkActionResponse, type BulkIdsRequest, type BulkUpdateIntegrationsRequest, type BulkUpdateRequest, type BusinessHour, type BusinessHourItemResponse, BusinessHoursResource, type Calendar, type CalendarItemResponse, CalendarsResource, type Call, type CallAttempt, type CallItemResponse, CallsResource, type CampaignHopperResponse, type CampaignItemResponse, type CampaignRealtimeStatusResponse, type CampaignStatisticsResponse, CampaignsResource, type Conference, type ConferenceItemResponse, ConferencesResource, type Conversation, type ConversationEvent, type ConversationItemResponse, type ConversationSessionVariables, ConversationsResource, type CreateCampaignRequest, type CreateListRequest, type CreateManagedUserRequest, type CreateOutboundListRequest, type CreateTestCall, DEFAULT_BASE_URL, type Dashboard, type DashboardCreateBody, type DashboardItemResponse, type DashboardUpdateBody, type DashboardUser, type DashboardUsersResponse, DashboardsResource, type DefaultV2MessageResponse, type DialerBehaviour, type DialerBehaviourItemResponse, type DialerBehaviourWriteBody, DialerBehavioursResource, DialerResource, type DialerSimpleReportingQuery, EventsResource, ExpressionsResource, type FileBulkDeleteRequest, type FileBulkDownloadRequest, FilesResource, type GenericItemResponse, type GlobalAutomation, type GlobalAutomationItemResponse, type ImportAgentsOptions, type Integration, type IntegrationBulkIdsRequest, type IntegrationCreateRequest, type IntegrationItemResponse, type IntegrationObjectListResponse, type IntegrationProvider, type IntegrationTokenItemResponse, type IntegrationTokenListResponse, type IntegrationUpdateRequest, IntegrationsResource, type InterruptionTargetStates, type IvrModule, type Lead, type LeadBulkDeleteRequest, type LeadListItemResponse, type LeadUploadRequest, type LeadUploadResponse, type ListAgentsQuery, type ListApplicationsQuery, type ListAuditLogsQuery, type ListAutomationsQuery, type ListBabeldeskWidgetsQuery, type ListBabeldesksQuery, type ListBusinessHoursQuery, type ListCalendarsQuery, type ListConferencesQuery, type ListConversationsQuery, type ListDashboardsQuery, type ListDialerBehavioursQuery, type ListFilesQuery, type ListIntegrationsQuery, type ListNumbersQuery, type ListOutboundAttemptsQuery, type ListOutboundLeadsQuery, type ListPhonebookQuery, type ListProcessedOutboundLeadsQuery, type ListPromptsQuery, type ListQueuesQuery, type ListRecordingsQuery, type ListRoutingsQuery, type ListSmsQuery, type ListTasksQuery, type ListTriggersQuery, type ListUsersQuery, type LocalAutomation, type LocalAutomationItemResponse, LogsResource, type ManagedUser, type ManagedUserItemResponse, ManagerApiError, ManagerClient, type ManagerClientOptions, MeResource, type MetricDefinitionItemResponse, type MetricIdItemsResponse, type MetricResponse, MetricsResource, NumbersResource, type OAuthRevokeRequest, type OAuthTokenRequest, type OAuthTokenResponse, type ObjectListResponse, type OutboundCampaign, type OutboundCampaignItemResponse, type OutboundLeadItemResponse, type OutboundList, type OutboundListItemResponse, OutboundResource, type OutboundSimpleReportingQuery, type PaginatedAttemptResponse, type PaginatedLeadResponse, type PaginatedRecordingResponse, type PhonebookCsvFile, type PhonebookEntry, type PhonebookEntryItemResponse, PhonebookResource, type PkceChallenge, type Prompt, type PromptAudioFile, type PromptItemResponse, PromptsResource, type Queue, type QueueItemResponse, type QueueSelection, type QueueSelectionItemResponse, QueueSelectionsResource, type QueueTriggerListResponse, QueuesResource, type Recording, type RecordingItemResponse, type RecordingStartRequest, type RecordingState, type RecordingUpdateBody, RecordingsResource, type ReportingCall, type ReportingCallsQuery, ReportingResource, type RestCreateAgentBody, type RestCreateAgentGroupBody, type RestCreateBabeldeskBody, type RestCreateBabeldeskWidgetBody, type RestCreateBusinessHourBody, type RestCreateCalendarBody, type RestCreateConversationBody, type RestCreateGlobalAutomationBody, type RestCreateLocalAutomationBody, type RestCreatePhonebookEntryBody, type RestCreateQueueBody, type RestCreateQueueSelectionBody, type RestCreateRoutingBody, type RestCreateTriggerBody, type RestUpdateAgentBody, type RestUpdateAgentGroupBody, type RestUpdateBabeldeskBody, type RestUpdateBabeldeskWidgetBody, type RestUpdateBusinessHourBody, type RestUpdateCalendarBody, type RestUpdateConversationBody, type RestUpdateGlobalAutomationBody, type RestUpdateLocalAutomationBody, type RestUpdatePhonebookEntryBody, type RestUpdatePromptBody, type RestUpdateQueueBody, type RestUpdateQueueSelectionBody, type RestUpdateRoutingBody, type RestUpdateTriggerBody, type RetryOptions, type Routing, type RoutingItemResponse, RoutingResource, type ServiceNumber, type ServiceNumberItemResponse, type SessionResponse, SessionsResource, type SetCampaignListRequest, SettingAccessor, type SettingsAppAgentStatus, type SettingsAppConversations, type SettingsAppCustomerLogging, type SettingsAppIntegrations, type SettingsAuditDefault, SettingsResource, type SettingsRetentionPeriods, type SettingsTelephonyAgentInbound, type SettingsTelephonyAgentOutbound, type SettingsTelephonyAgentRecording, type SettingsTelephonyAgentWrapup, type SettingsTelephonyPostCall, type SettingsUiI18N, type SimpleReportingCallsQuery, type Sms, type SmsItemResponse, SmsResource, type StorageState, type StorageType, type StoredFile, type StoredFileItemResponse, type SubmitTaskBody, type SubmitTaskScheduleBody, SystemResource, type Tag, type Task, TaskMetricsResource, type TaskSchedule, TaskSchedulesResource, TaskScriptsResource, TaskSecretsResource, TaskSelectionConfigResource, type TaskTemplateOverrides, TasksResource, type TokenResponse, type Trigger, type TriggerConditionListResponse, type TriggerConditionsRequest, type TriggerItemResponse, type TriggerUsesResponse, TriggersResource, type UpdateAgentStatusRequest, type UpdateCampaignRequest, type UpdateSessionVariablesRequest, type UpdateTaskBody, type User, type UserCustomer, type UserCustomerItemResponse, type UserItemResponse, UsersResource, authorizationCodeGrant, buildAuthorizeUrl, clientCredentialsGrant, passwordGrant, pkceChallenge, refreshTokenGrant, withRetry };
package/dist/index.js CHANGED
@@ -3,6 +3,29 @@ import { createClient, createConfig, urlSearchParamsBodySerializer, formDataBody
3
3
  // src/client.ts
4
4
 
5
5
  // src/auth.ts
6
+ function base64url(bytes) {
7
+ let bin = "";
8
+ for (const b of bytes) bin += String.fromCharCode(b);
9
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
10
+ }
11
+ async function pkceChallenge() {
12
+ const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
13
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(codeVerifier));
14
+ return { codeVerifier, codeChallenge: base64url(new Uint8Array(digest)), codeChallengeMethod: "S256" };
15
+ }
16
+ function buildAuthorizeUrl(opts) {
17
+ const base = opts.baseUrl.replace(/\/+$/, "");
18
+ const params = new URLSearchParams({
19
+ response_type: "code",
20
+ client_id: opts.clientId,
21
+ redirect_uri: opts.redirectUri,
22
+ scope: opts.scope,
23
+ code_challenge: opts.codeChallenge,
24
+ code_challenge_method: opts.codeChallengeMethod ?? "S256"
25
+ });
26
+ if (opts.state !== void 0) params.set("state", opts.state);
27
+ return `${base}/oauth/authorize?${params.toString()}`;
28
+ }
6
29
  async function passwordGrant(opts) {
7
30
  const base = opts.baseUrl.replace(/\/+$/, "");
8
31
  const body = new URLSearchParams({
@@ -42,18 +65,71 @@ async function clientCredentialsGrant(opts) {
42
65
  }
43
66
  return json;
44
67
  }
68
+ async function authorizationCodeGrant(opts) {
69
+ const base = opts.baseUrl.replace(/\/+$/, "");
70
+ const body = new URLSearchParams({
71
+ grant_type: "authorization_code",
72
+ code: opts.code,
73
+ redirect_uri: opts.redirectUri,
74
+ client_id: opts.clientId,
75
+ code_verifier: opts.codeVerifier
76
+ });
77
+ if (opts.clientSecret !== void 0) body.set("client_secret", opts.clientSecret);
78
+ const doFetch = opts.fetch ?? fetch;
79
+ const resp = await doFetch(`${base}/oauth/token`, {
80
+ method: "POST",
81
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
82
+ body
83
+ });
84
+ const json = await resp.json().catch(() => ({}));
85
+ if (!resp.ok || !json.access_token) {
86
+ throw new Error(`authorization_code grant failed (status ${resp.status})`);
87
+ }
88
+ return json;
89
+ }
90
+ async function refreshTokenGrant(opts) {
91
+ const base = opts.baseUrl.replace(/\/+$/, "");
92
+ const body = new URLSearchParams({
93
+ grant_type: "refresh_token",
94
+ refresh_token: opts.refreshToken
95
+ });
96
+ if (opts.clientId !== void 0) body.set("client_id", opts.clientId);
97
+ if (opts.clientSecret !== void 0) body.set("client_secret", opts.clientSecret);
98
+ const doFetch = opts.fetch ?? fetch;
99
+ const resp = await doFetch(`${base}/oauth/token`, {
100
+ method: "POST",
101
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
102
+ body
103
+ });
104
+ const json = await resp.json().catch(() => ({}));
105
+ if (!resp.ok || !json.access_token) {
106
+ throw new Error(`refresh_token grant failed (status ${resp.status})`);
107
+ }
108
+ return json;
109
+ }
45
110
  var TokenManager = class {
46
- constructor(grant) {
111
+ constructor(grant, initialRefresh) {
47
112
  this.grant = grant;
113
+ this.refreshToken = initialRefresh;
48
114
  }
49
115
  grant;
50
116
  token;
51
117
  expiresAt = 0;
118
+ refreshToken;
119
+ inflight;
52
120
  async get() {
53
121
  if (this.token && Date.now() < this.expiresAt - 3e4) return this.token;
54
- const tok = await this.grant();
122
+ if (this.inflight) return this.inflight;
123
+ this.inflight = this.fetchToken().finally(() => {
124
+ this.inflight = void 0;
125
+ });
126
+ return this.inflight;
127
+ }
128
+ async fetchToken() {
129
+ const tok = await this.grant(this.refreshToken);
55
130
  this.token = tok.access_token;
56
131
  this.expiresAt = Date.now() + (tok.expires_in ? tok.expires_in * 1e3 : 36e5);
132
+ if (tok.refresh_token) this.refreshToken = tok.refresh_token;
57
133
  return this.token;
58
134
  }
59
135
  };
@@ -71,6 +147,19 @@ function buildAuthConfig(auth, baseUrl, fetchImpl) {
71
147
  );
72
148
  return { auth: (scheme) => scheme.scheme === "bearer" ? tokens.get() : void 0 };
73
149
  }
150
+ case "refreshToken": {
151
+ const tokens = new TokenManager(
152
+ (current) => refreshTokenGrant({
153
+ baseUrl,
154
+ refreshToken: current ?? auth.refreshToken,
155
+ clientId: auth.clientId,
156
+ clientSecret: auth.clientSecret,
157
+ fetch: fetchImpl
158
+ }),
159
+ auth.refreshToken
160
+ );
161
+ return { auth: (scheme) => scheme.scheme === "bearer" ? tokens.get() : void 0 };
162
+ }
74
163
  }
75
164
  }
76
165
 
@@ -8560,4 +8649,4 @@ var ManagerClient = class _ManagerClient {
8560
8649
  }
8561
8650
  };
8562
8651
 
8563
- export { AgentGroupsResource, AgentsResource, AppActionsResource, ApplicationsResource, AuthResource, AutomationsResource, BabeldeskResource, BabeldeskWidgetsResource, BusinessHoursResource, CalendarsResource, CallsResource, CampaignsResource, ConferencesResource, ConversationsResource, DEFAULT_BASE_URL, DashboardsResource, DialerBehavioursResource, DialerResource, EventsResource, ExpressionsResource, FilesResource, IntegrationsResource, LogsResource, ManagerApiError, ManagerClient, MeResource, MetricsResource, NumbersResource, OutboundResource, PhonebookResource, PromptsResource, QueueSelectionsResource, QueuesResource, RecordingsResource, ReportingResource, RoutingResource, SessionsResource, SettingAccessor, SettingsResource, SmsResource, SystemResource, TaskMetricsResource, TaskSchedulesResource, TaskScriptsResource, TaskSecretsResource, TaskSelectionConfigResource, TasksResource, TriggersResource, UsersResource, passwordGrant, withRetry };
8652
+ export { AgentGroupsResource, AgentsResource, AppActionsResource, ApplicationsResource, AuthResource, AutomationsResource, BabeldeskResource, BabeldeskWidgetsResource, BusinessHoursResource, CalendarsResource, CallsResource, CampaignsResource, ConferencesResource, ConversationsResource, DEFAULT_BASE_URL, DashboardsResource, DialerBehavioursResource, DialerResource, EventsResource, ExpressionsResource, FilesResource, IntegrationsResource, LogsResource, ManagerApiError, ManagerClient, MeResource, MetricsResource, NumbersResource, OutboundResource, PhonebookResource, PromptsResource, QueueSelectionsResource, QueuesResource, RecordingsResource, ReportingResource, RoutingResource, SessionsResource, SettingAccessor, SettingsResource, SmsResource, SystemResource, TaskMetricsResource, TaskSchedulesResource, TaskScriptsResource, TaskSecretsResource, TaskSelectionConfigResource, TasksResource, TriggersResource, UsersResource, authorizationCodeGrant, buildAuthorizeUrl, clientCredentialsGrant, passwordGrant, pkceChallenge, refreshTokenGrant, withRetry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babelforce/manager-sdk",
3
- "version": "0.39.0",
3
+ "version": "0.40.0",
4
4
  "description": "TypeScript SDK for the babelforce manager APIs — auth, user & agent management, call reporting, metrics, and task automations.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",