@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.
- package/dist/browser/client/auth.js +24 -68
- package/dist/browser/client/client.js +2 -1
- package/dist/browser/client/token-manager.js +175 -73
- package/dist/browser/types/index.js +5 -1
- package/dist/cjs/client/auth.js +24 -68
- package/dist/cjs/client/client.js +2 -1
- package/dist/cjs/client/token-manager.js +163 -73
- package/dist/cjs/types/index.js +6 -0
- package/dist/esm/client/auth.js +24 -68
- package/dist/esm/client/client.js +2 -1
- package/dist/esm/client/token-manager.js +163 -73
- package/dist/esm/types/index.js +5 -1
- package/dist/types/client/auth.d.ts +2 -3
- package/dist/types/client/token-manager.d.ts +9 -1
- package/dist/types/types/index.d.ts +4 -1
- package/package.json +1 -1
|
@@ -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
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
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
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
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.
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/dist/cjs/types/index.js
CHANGED
|
@@ -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 = {}));
|
package/dist/esm/client/auth.js
CHANGED
|
@@ -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.
|
|
6
|
+
this.initializationPromise = null;
|
|
6
7
|
this.config = config;
|
|
7
8
|
this.tokenManager = TokenManager.getInstance();
|
|
8
|
-
if (this.config.authType ===
|
|
9
|
-
//
|
|
10
|
-
|
|
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
|
|
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
|
-
|
|
30
|
-
|
|
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
|
|
61
|
-
this.initialized = false;
|
|
62
|
-
throw error;
|
|
23
|
+
console.error('Failed to initialize auth:', error);
|
|
24
|
+
this.initialized = false;
|
|
63
25
|
}
|
|
64
26
|
finally {
|
|
65
|
-
this.
|
|
27
|
+
this.initializationPromise = null;
|
|
66
28
|
}
|
|
67
29
|
}
|
|
68
30
|
async ensureInitialized() {
|
|
69
|
-
if (this.config.authType !==
|
|
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
|
-
|
|
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 ===
|
|
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 ===
|
|
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
|
-
|
|
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 ||
|
|
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.');
|