@flexbe/sdk 0.1.2 → 0.1.3

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.
@@ -3,10 +3,15 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TokenManager = void 0;
4
4
  const TOKEN_STORAGE_KEY = 'flexbe_jwt_token';
5
5
  const REFRESH_THRESHOLD = 0.8; // Refresh when 80% of token lifetime has passed
6
+ const REFRESH_CHECK_INTERVAL = 30 * 1000; // Check every 30 seconds
7
+ const MAX_REFRESH_DELAY = 10000; // Maximum random delay of 10 seconds
6
8
  class TokenManager {
7
9
  constructor() {
8
10
  this.token = null;
9
11
  this.refreshInterval = null;
12
+ this.refreshTimeout = null;
13
+ this.tokenPromise = null;
14
+ this.debug = false;
10
15
  this.initializeFromStorage();
11
16
  this.setupStorageListener();
12
17
  }
@@ -17,59 +22,61 @@ class TokenManager {
17
22
  return TokenManager.instance;
18
23
  }
19
24
  initializeFromStorage() {
20
- if (typeof window !== 'undefined') {
21
- const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
22
- if (storedToken) {
23
- try {
24
- this.token = JSON.parse(storedToken);
25
- if (this.token.expiresAt > Date.now()) {
26
- console.log('Reusing stored token:', {
27
- expiresIn: `${Math.round((this.token.expiresAt - Date.now()) / 1000)} seconds`,
28
- expiresAt: new Date(this.token.expiresAt).toISOString(),
29
- });
30
- this.startRefreshInterval();
31
- }
32
- else {
33
- this.clearToken();
34
- }
35
- }
36
- catch (error) {
37
- console.error('Failed to parse stored token:', error);
38
- this.clearToken();
39
- }
25
+ if (typeof window === 'undefined')
26
+ return;
27
+ const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
28
+ if (!storedToken)
29
+ return;
30
+ try {
31
+ this.token = JSON.parse(storedToken);
32
+ if (this.token.expiresAt > Date.now()) {
33
+ this.logTokenStatus('Token loaded from storage');
34
+ this.startRefreshInterval();
35
+ }
36
+ else {
37
+ this.clearToken();
40
38
  }
41
39
  }
40
+ catch (error) {
41
+ console.error('Failed to parse stored token:', error);
42
+ this.clearToken();
43
+ }
42
44
  }
43
45
  setupStorageListener() {
44
- if (typeof window !== 'undefined') {
45
- window.addEventListener('storage', (event) => {
46
- if (event.key === TOKEN_STORAGE_KEY) {
47
- if (event.newValue) {
48
- try {
49
- const newToken = JSON.parse(event.newValue);
50
- if (newToken.expiresAt > Date.now()) {
51
- this.token = newToken;
52
- console.log('Token updated from storage:', {
53
- expiresIn: `${Math.round((newToken.expiresAt - Date.now()) / 1000)} seconds`,
54
- expiresAt: new Date(newToken.expiresAt).toISOString(),
55
- });
56
- this.startRefreshInterval();
57
- }
58
- else {
59
- this.clearToken();
60
- }
61
- }
62
- catch (error) {
63
- console.error('Failed to parse token from storage event:', error);
64
- this.clearToken();
65
- }
66
- }
67
- else {
68
- this.clearToken();
69
- }
46
+ if (typeof window === 'undefined')
47
+ return;
48
+ window.addEventListener('storage', (event) => {
49
+ if (event.key !== TOKEN_STORAGE_KEY)
50
+ return;
51
+ if (!event.newValue) {
52
+ this.clearToken();
53
+ void this.retrieveToken();
54
+ return;
55
+ }
56
+ try {
57
+ const newToken = JSON.parse(event.newValue);
58
+ // Skip if the new token is exactly the same as current token
59
+ if (this.token &&
60
+ this.token.accessToken === newToken.accessToken &&
61
+ this.token.expiresAt === newToken.expiresAt) {
62
+ return;
70
63
  }
71
- });
72
- }
64
+ if (newToken.expiresAt > Date.now()) {
65
+ this.token = newToken;
66
+ this.logTokenStatus('Token updated from storage');
67
+ this.startRefreshInterval();
68
+ }
69
+ else {
70
+ this.clearToken();
71
+ void this.retrieveToken();
72
+ }
73
+ }
74
+ catch (error) {
75
+ console.error('Failed to parse token from storage event:', error);
76
+ this.clearToken();
77
+ void this.retrieveToken();
78
+ }
79
+ });
73
80
  }
74
81
  getExpirationFromToken(token) {
75
82
  try {
@@ -82,32 +89,125 @@ class TokenManager {
82
89
  return Date.now() + (4 * 60 * 1000); // Default to 4 minutes if parsing fails
83
90
  }
84
91
  }
92
+ async getToken() {
93
+ const token = this.token;
94
+ if (token && token.expiresAt && token.expiresAt > Date.now()) {
95
+ return token.accessToken;
96
+ }
97
+ await this.retrieveToken();
98
+ return this.token?.accessToken ?? null;
99
+ }
100
+ async retrieveToken() {
101
+ if (this.tokenPromise) {
102
+ await this.tokenPromise;
103
+ return;
104
+ }
105
+ this.tokenPromise = this.doRetrieveToken();
106
+ try {
107
+ await this.tokenPromise;
108
+ }
109
+ finally {
110
+ this.tokenPromise = null;
111
+ }
112
+ }
113
+ async doRetrieveToken() {
114
+ const controller = new AbortController();
115
+ const timeoutId = setTimeout(() => controller.abort(), 30000);
116
+ try {
117
+ const response = await fetch('/oauth/token', {
118
+ method: 'POST',
119
+ headers: { 'Content-Type': 'application/json' },
120
+ body: JSON.stringify({ grant_type: 'client_credentials' }),
121
+ credentials: 'include',
122
+ signal: controller.signal,
123
+ });
124
+ clearTimeout(timeoutId);
125
+ if (!response.ok) {
126
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
127
+ throw new Error(errorData.message || response.statusText);
128
+ }
129
+ const data = await response.json();
130
+ this.setToken(data);
131
+ }
132
+ catch (error) {
133
+ console.error('Failed to retrieve token:', error);
134
+ this.clearToken();
135
+ throw error;
136
+ }
137
+ }
85
138
  startRefreshInterval() {
139
+ this.clearRefreshTimers();
140
+ if (!this.token)
141
+ return;
142
+ const tokenLifetime = this.token.expiresAt - Date.now();
143
+ const refreshThreshold = Math.round(tokenLifetime * REFRESH_THRESHOLD);
144
+ const timeUntilRefresh = refreshThreshold - (Math.random() * MAX_REFRESH_DELAY);
145
+ this.logTokenStatus('Starting refresh interval', {
146
+ tokenLifetime: `${Math.round(tokenLifetime / 1000)} seconds`,
147
+ refreshThreshold: `${Math.round(refreshThreshold / 1000)} seconds`,
148
+ timeUntilRefresh: `${Math.round(timeUntilRefresh / 1000)} seconds`,
149
+ });
150
+ this.scheduleRefresh(timeUntilRefresh);
151
+ this.refreshInterval = window.setInterval(() => {
152
+ if (!this.token)
153
+ return;
154
+ const timeUntilExpiry = this.token.expiresAt - Date.now();
155
+ if (timeUntilExpiry <= 0) {
156
+ this.logTokenStatus('Token expired');
157
+ this.clearToken();
158
+ void this.retrieveToken();
159
+ return;
160
+ }
161
+ const refreshThreshold = Math.round(timeUntilExpiry * REFRESH_THRESHOLD);
162
+ if (timeUntilExpiry <= refreshThreshold) {
163
+ this.logTokenStatus('Refreshing token', {
164
+ timeUntilExpiry: `${Math.round(timeUntilExpiry / 1000)} seconds`,
165
+ refreshThreshold: `${Math.round(refreshThreshold / 1000)} seconds`,
166
+ });
167
+ this.scheduleRefresh(refreshThreshold - (Math.random() * MAX_REFRESH_DELAY));
168
+ }
169
+ }, REFRESH_CHECK_INTERVAL);
170
+ }
171
+ scheduleRefresh(delay) {
172
+ if (this.refreshTimeout) {
173
+ window.clearTimeout(this.refreshTimeout);
174
+ }
175
+ this.refreshTimeout = window.setTimeout(() => {
176
+ const token = this.token;
177
+ if (token && token.expiresAt - Date.now() <= token.expiresAt * REFRESH_THRESHOLD) {
178
+ void this.retrieveToken();
179
+ }
180
+ }, delay);
181
+ }
182
+ clearRefreshTimers() {
86
183
  if (this.refreshInterval) {
87
184
  clearInterval(this.refreshInterval);
185
+ this.refreshInterval = null;
88
186
  }
89
- if (this.token) {
90
- const tokenLifetime = this.token.expiresAt - (this.token.expiresAt - 4 * 60 * 1000); // 4 minutes in milliseconds
91
- const refreshTime = Math.round(tokenLifetime * REFRESH_THRESHOLD);
92
- console.log('Setting up token refresh:', {
93
- tokenLifetime: `${Math.round(tokenLifetime / 1000)} seconds`,
94
- refreshIn: `${Math.round(refreshTime / 1000)} seconds`,
95
- refreshAt: new Date(Date.now() + refreshTime).toISOString(),
96
- });
97
- this.refreshInterval = window.setInterval(() => {
98
- this.clearToken();
99
- }, refreshTime);
187
+ if (this.refreshTimeout) {
188
+ window.clearTimeout(this.refreshTimeout);
189
+ this.refreshTimeout = null;
100
190
  }
101
191
  }
192
+ logTokenStatus(message, additionalInfo = {}) {
193
+ if (!this.debug)
194
+ return;
195
+ const token = this.token;
196
+ if (!token)
197
+ return;
198
+ console.log(message, {
199
+ expiresIn: `${Math.round((token.expiresAt - Date.now()) / 1000)} seconds`,
200
+ expiresAt: new Date(token.expiresAt).toISOString(),
201
+ ...additionalInfo,
202
+ });
203
+ }
102
204
  setToken(tokenResponse) {
103
205
  const expiresAt = this.getExpirationFromToken(tokenResponse.accessToken);
104
206
  this.token = {
105
207
  accessToken: tokenResponse.accessToken,
106
208
  expiresAt,
107
209
  };
108
- const expiresIn = Math.round((expiresAt - Date.now()) / 1000);
109
- console.log('New access token obtained:', {
110
- expiresIn: `${expiresIn} seconds`,
210
+ this.logTokenStatus('Token set', {
111
211
  expiresAt: new Date(expiresAt).toISOString(),
112
212
  });
113
213
  if (typeof window !== 'undefined') {
@@ -115,19 +215,9 @@ class TokenManager {
115
215
  }
116
216
  this.startRefreshInterval();
117
217
  }
118
- getToken() {
119
- if (this.token && this.token.expiresAt > Date.now()) {
120
- return this.token.accessToken;
121
- }
122
- this.clearToken();
123
- return null;
124
- }
125
218
  clearToken() {
126
219
  this.token = null;
127
- if (this.refreshInterval) {
128
- clearInterval(this.refreshInterval);
129
- this.refreshInterval = null;
130
- }
220
+ this.clearRefreshTimers();
131
221
  if (typeof window !== 'undefined') {
132
222
  localStorage.removeItem(TOKEN_STORAGE_KEY);
133
223
  }
@@ -1,2 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FlexbeAuthType = void 0;
4
+ var FlexbeAuthType;
5
+ (function (FlexbeAuthType) {
6
+ FlexbeAuthType["API_KEY"] = "apiKey";
7
+ FlexbeAuthType["BEARER"] = "bearer";
8
+ })(FlexbeAuthType || (exports.FlexbeAuthType = FlexbeAuthType = {}));
@@ -1,103 +1,59 @@
1
+ import { FlexbeAuthType } from '../types';
1
2
  import { TokenManager } from './token-manager';
2
3
  export class FlexbeAuth {
3
4
  constructor(config) {
4
5
  this.initialized = false;
5
- this.initializing = false;
6
+ this.initializationPromise = null;
6
7
  this.config = config;
7
8
  this.tokenManager = TokenManager.getInstance();
8
- if (this.config.authType === 'bearer') {
9
- // Check if we have a valid token in storage
10
- const existingToken = this.tokenManager.getToken();
11
- if (existingToken) {
12
- this.initialized = true;
13
- }
14
- // Don't start initialization here, let ensureInitialized handle it
9
+ if (this.config.authType === FlexbeAuthType.BEARER) {
10
+ // Start initialization but don't wait for it
11
+ this.initializationPromise = this.initialize();
15
12
  }
16
13
  else {
17
14
  this.initialized = true;
18
15
  }
19
16
  }
20
- async initializeBearerAuth() {
21
- if (this.initializing) {
22
- // Wait for the ongoing initialization to complete
23
- while (this.initializing) {
24
- await new Promise(resolve => setTimeout(resolve, 100));
25
- }
26
- return;
27
- }
17
+ async initialize() {
28
18
  try {
29
- this.initializing = true;
30
- const controller = new AbortController();
31
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
32
- const response = await fetch('/oauth/token', {
33
- method: 'POST',
34
- headers: {
35
- 'Content-Type': 'application/json',
36
- },
37
- body: JSON.stringify({
38
- grant_type: 'client_credentials',
39
- }),
40
- credentials: 'include',
41
- signal: controller.signal,
42
- });
43
- clearTimeout(timeoutId);
44
- if (!response.ok) {
45
- const defaultError = { message: response.statusText };
46
- const errorData = await response.json().catch(() => defaultError);
47
- const error = {
48
- message: errorData.message || response.statusText,
49
- code: errorData.code,
50
- status: response.status,
51
- details: errorData.details,
52
- };
53
- throw error;
54
- }
55
- const data = await response.json();
56
- this.tokenManager.setToken(data);
57
- this.initialized = true;
19
+ const token = await this.tokenManager.getToken();
20
+ this.initialized = !!token;
58
21
  }
59
22
  catch (error) {
60
- console.error('Failed to initialize bearer authentication:', error);
61
- this.initialized = false; // Reset initialized state on error
62
- throw error;
23
+ console.error('Failed to initialize auth:', error);
24
+ this.initialized = false;
63
25
  }
64
26
  finally {
65
- this.initializing = false;
27
+ this.initializationPromise = null;
66
28
  }
67
29
  }
68
30
  async ensureInitialized() {
69
- if (this.config.authType !== 'bearer' || this.initialized) {
31
+ if (this.config.authType !== FlexbeAuthType.BEARER || this.initialized) {
32
+ return;
33
+ }
34
+ // If initialization is in progress, wait for it
35
+ if (this.initializationPromise) {
36
+ await this.initializationPromise;
70
37
  return;
71
38
  }
72
- await this.initializeBearerAuth();
39
+ // If not initialized and no initialization in progress, start one
40
+ await this.initialize();
73
41
  }
74
42
  async getAuthHeaders() {
75
43
  await this.ensureInitialized();
76
44
  const headers = {
77
45
  'Content-Type': 'application/json',
78
46
  };
79
- if (this.config.authType === 'apiKey') {
47
+ if (this.config.authType === FlexbeAuthType.API_KEY) {
80
48
  headers['x-api-key'] = this.config.apiKey;
81
49
  }
82
- else if (this.config.authType === 'bearer') {
83
- const token = this.tokenManager.getToken();
50
+ else if (this.config.authType === FlexbeAuthType.BEARER) {
51
+ const token = await this.tokenManager.getToken();
84
52
  if (!token) {
85
- // If no token is available, try to initialize again
86
- this.initialized = false;
87
- await this.ensureInitialized();
88
- const newToken = this.tokenManager.getToken();
89
- if (!newToken) {
90
- throw new Error('No valid bearer token available');
91
- }
92
- headers['Authorization'] = `Bearer ${newToken}`;
93
- }
94
- else {
95
- headers['Authorization'] = `Bearer ${token}`;
53
+ throw new Error('No valid bearer token available');
96
54
  }
55
+ headers['Authorization'] = `Bearer ${token}`;
97
56
  }
98
57
  return headers;
99
58
  }
100
- isInitialized() {
101
- return this.initialized;
102
- }
103
59
  }
@@ -1,3 +1,4 @@
1
+ import { FlexbeAuthType } from '../types';
1
2
  import { Pages } from './pages';
2
3
  import { ApiClient } from './api-client';
3
4
  export class FlexbeClient {
@@ -13,7 +14,7 @@ export class FlexbeClient {
13
14
  timeout: config?.timeout || 30000,
14
15
  apiKey: config?.apiKey || getEnvVar('FLEXBE_API_KEY') || '',
15
16
  siteId: config?.siteId || getEnvVar('FLEXBE_SITE_ID'),
16
- authType: config?.authType || 'apiKey',
17
+ authType: config?.authType || FlexbeAuthType.API_KEY,
17
18
  };
18
19
  if (this.config.authType === 'apiKey' && !this.config.apiKey) {
19
20
  throw new Error('API key is required when using apiKey authentication. Please provide it either through config or FLEXBE_API_KEY environment variable.');