@ahoo-wang/fetcher-cosec 1.8.2 → 1.8.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/authorizationRequestInterceptor.d.ts +14 -0
- package/dist/authorizationRequestInterceptor.d.ts.map +1 -0
- package/dist/{cosecResponseInterceptor.d.ts → authorizationResponseInterceptor.d.ts} +10 -10
- package/dist/authorizationResponseInterceptor.d.ts.map +1 -0
- package/dist/cosecRequestInterceptor.d.ts +4 -4
- package/dist/cosecRequestInterceptor.d.ts.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +121 -110
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/types.d.ts +10 -7
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/cosecResponseInterceptor.d.ts.map +0 -1
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { JwtTokenManagerCapable } from './types';
|
|
3
|
+
export interface AuthorizationInterceptorOptions extends JwtTokenManagerCapable {
|
|
4
|
+
}
|
|
5
|
+
export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME = "AuthorizationRequestInterceptor";
|
|
6
|
+
export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER: number;
|
|
7
|
+
export declare class AuthorizationRequestInterceptor implements RequestInterceptor {
|
|
8
|
+
private readonly options;
|
|
9
|
+
readonly name = "AuthorizationRequestInterceptor";
|
|
10
|
+
readonly order: number;
|
|
11
|
+
constructor(options: AuthorizationInterceptorOptions);
|
|
12
|
+
intercept(exchange: FetchExchange): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=authorizationRequestInterceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorizationRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/authorizationRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAEvE,OAAO,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG/D,MAAM,WAAW,+BAAgC,SAAQ,sBAAsB;CAC9E;AAED,eAAO,MAAM,sCAAsC,oCAAoC,CAAC;AACxF,eAAO,MAAM,uCAAuC,QAAyC,CAAC;AAE9F,qBAAa,+BAAgC,YAAW,kBAAkB;IAI5D,OAAO,CAAC,QAAQ,CAAC,OAAO;IAHpC,QAAQ,CAAC,IAAI,qCAA0C;IACvD,QAAQ,CAAC,KAAK,SAA2C;gBAE5B,OAAO,EAAE,+BAA+B;IAG/D,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAyBxD"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { CoSecOptions } from './types';
|
|
2
1
|
import { FetchExchange, ResponseInterceptor } from '@ahoo-wang/fetcher';
|
|
2
|
+
import { AuthorizationInterceptorOptions } from './authorizationRequestInterceptor';
|
|
3
3
|
/**
|
|
4
|
-
* The name of the
|
|
4
|
+
* The name of the AuthorizationResponseInterceptor.
|
|
5
5
|
*/
|
|
6
|
-
export declare const
|
|
6
|
+
export declare const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME = "AuthorizationResponseInterceptor";
|
|
7
7
|
/**
|
|
8
|
-
* The order of the
|
|
8
|
+
* The order of the AuthorizationResponseInterceptor.
|
|
9
9
|
* Set to a high negative value to ensure it runs early in the interceptor chain.
|
|
10
10
|
*/
|
|
11
|
-
export declare const
|
|
11
|
+
export declare const AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER: number;
|
|
12
12
|
/**
|
|
13
13
|
* CoSecResponseInterceptor is responsible for handling unauthorized responses (401)
|
|
14
14
|
* by attempting to refresh the authentication token and retrying the original request.
|
|
@@ -19,19 +19,19 @@ export declare const COSEC_RESPONSE_INTERCEPTOR_ORDER: number;
|
|
|
19
19
|
* 3. On successful refresh, stores the new token and retries the original request
|
|
20
20
|
* 4. On refresh failure, clears stored tokens and propagates the error
|
|
21
21
|
*/
|
|
22
|
-
export declare class
|
|
23
|
-
readonly name = "
|
|
22
|
+
export declare class AuthorizationResponseInterceptor implements ResponseInterceptor {
|
|
23
|
+
readonly name = "AuthorizationResponseInterceptor";
|
|
24
24
|
readonly order: number;
|
|
25
25
|
private options;
|
|
26
26
|
/**
|
|
27
|
-
* Creates a new
|
|
27
|
+
* Creates a new AuthorizationResponseInterceptor instance.
|
|
28
28
|
* @param options - The CoSec configuration options including token storage and refresher
|
|
29
29
|
*/
|
|
30
|
-
constructor(options:
|
|
30
|
+
constructor(options: AuthorizationInterceptorOptions);
|
|
31
31
|
/**
|
|
32
32
|
* Intercepts the response and handles unauthorized responses by refreshing tokens.
|
|
33
33
|
* @param exchange - The fetch exchange containing request and response information
|
|
34
34
|
*/
|
|
35
35
|
intercept(exchange: FetchExchange): Promise<void>;
|
|
36
36
|
}
|
|
37
|
-
//# sourceMappingURL=
|
|
37
|
+
//# sourceMappingURL=authorizationResponseInterceptor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"authorizationResponseInterceptor.d.ts","sourceRoot":"","sources":["../src/authorizationResponseInterceptor.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAC7E,OAAO,EACL,+BAA+B,EAChC,MAAM,mCAAmC,CAAC;AAE3C;;GAEG;AACH,eAAO,MAAM,uCAAuC,qCAAqC,CAAC;AAE1F;;;GAGG;AACH,eAAO,MAAM,wCAAwC,QAAiC,CAAC;AAEvF;;;;;;;;;GASG;AACH,qBAAa,gCAAiC,YAAW,mBAAmB;IAC1E,QAAQ,CAAC,IAAI,sCAA2C;IACxD,QAAQ,CAAC,KAAK,SAA4C;IAC1D,OAAO,CAAC,OAAO,CAAkC;IAEjD;;;OAGG;gBACS,OAAO,EAAE,+BAA+B;IAIpD;;;OAGG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAyBxD"}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';
|
|
2
|
-
import {
|
|
2
|
+
import { AppIdCapable, DeviceIdStorageCapable } from './types';
|
|
3
|
+
export interface CoSecRequestOptions extends AppIdCapable, DeviceIdStorageCapable {
|
|
4
|
+
}
|
|
3
5
|
/**
|
|
4
6
|
* The name of the CoSecRequestInterceptor.
|
|
5
7
|
*/
|
|
@@ -16,7 +18,6 @@ export declare const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = "Ignore-Refresh-Token"
|
|
|
16
18
|
* This interceptor adds the following headers to each request:
|
|
17
19
|
* - CoSec-Device-Id: Device identifier (stored in localStorage or generated)
|
|
18
20
|
* - CoSec-App-Id: Application identifier
|
|
19
|
-
* - Authorization: Bearer token
|
|
20
21
|
* - CoSec-Request-Id: Unique request identifier for each request
|
|
21
22
|
*
|
|
22
23
|
* @remarks
|
|
@@ -35,7 +36,7 @@ export declare class CoSecRequestInterceptor implements RequestInterceptor {
|
|
|
35
36
|
* Creates a new CoSecRequestInterceptor instance.
|
|
36
37
|
* @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager
|
|
37
38
|
*/
|
|
38
|
-
constructor(options:
|
|
39
|
+
constructor(options: CoSecRequestOptions);
|
|
39
40
|
/**
|
|
40
41
|
* Intercept requests to add CoSec authentication headers.
|
|
41
42
|
*
|
|
@@ -43,7 +44,6 @@ export declare class CoSecRequestInterceptor implements RequestInterceptor {
|
|
|
43
44
|
* - CoSec-App-Id: The application identifier from the CoSec options
|
|
44
45
|
* - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated
|
|
45
46
|
* - CoSec-Request-Id: A unique identifier for this specific request
|
|
46
|
-
* - Authorization: Bearer token if available in token storage
|
|
47
47
|
*
|
|
48
48
|
* @param exchange - The fetch exchange containing the request to process
|
|
49
49
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,EAEb,KAAK,kBAAkB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,
|
|
1
|
+
{"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,EAEb,KAAK,kBAAkB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG7E,MAAM,WAAW,mBAAoB,SAAQ,YAAY,EAAE,sBAAsB;CAChF;AAED;;GAEG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;GAGG;AACH,eAAO,MAAM,+BAA+B,QACL,CAAC;AAExC,eAAO,MAAM,kCAAkC,yBAAyB,CAAC;AAEzE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,uBAAwB,YAAW,kBAAkB;IAChE,QAAQ,CAAC,IAAI,6BAAkC;IAC/C,QAAQ,CAAC,KAAK,SAAmC;IACjD,OAAO,CAAC,OAAO,CAAsB;IAErC;;;OAGG;gBACS,OAAO,EAAE,mBAAmB;IAIxC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa;CAgBxC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
|
+
export * from './authorizationRequestInterceptor';
|
|
2
|
+
export * from './authorizationResponseInterceptor';
|
|
1
3
|
export * from './cosecRequestInterceptor';
|
|
2
|
-
export * from './cosecResponseInterceptor';
|
|
3
4
|
export * from './deviceIdStorage';
|
|
4
5
|
export * from './idGenerator';
|
|
5
6
|
export * from './jwts';
|
|
6
7
|
export * from './jwtToken';
|
|
7
8
|
export * from './jwtTokenManager';
|
|
9
|
+
export * from './resourceAttributionRequestInterceptor';
|
|
8
10
|
export * from './tokenRefresher';
|
|
9
11
|
export * from './tokenStorage';
|
|
10
12
|
export * from './types';
|
|
11
|
-
export * from './resourceAttributionRequestInterceptor';
|
|
12
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,mCAAmC,CAAC;AAClD,cAAc,oCAAoC,CAAC;AACnD,cAAc,2BAA2B,CAAC;AAC1C,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC;AAC9B,cAAc,QAAQ,CAAC;AACvB,cAAc,YAAY,CAAC;AAC3B,cAAc,mBAAmB,CAAC;AAClC,cAAc,yCAAyC,CAAC;AACxD,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,SAAS,CAAC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { REQUEST_BODY_INTERCEPTOR_ORDER as
|
|
2
|
-
import { nanoid as
|
|
3
|
-
const
|
|
1
|
+
import { REQUEST_BODY_INTERCEPTOR_ORDER as A, ResultExtractors as N } from "@ahoo-wang/fetcher";
|
|
2
|
+
import { nanoid as S } from "nanoid";
|
|
3
|
+
const a = class a {
|
|
4
4
|
};
|
|
5
|
-
|
|
6
|
-
let
|
|
5
|
+
a.DEVICE_ID = "CoSec-Device-Id", a.APP_ID = "CoSec-App-Id", a.AUTHORIZATION = "Authorization", a.REQUEST_ID = "CoSec-Request-Id";
|
|
6
|
+
let o = a;
|
|
7
7
|
const d = class d {
|
|
8
8
|
};
|
|
9
9
|
d.UNAUTHORIZED = 401;
|
|
@@ -15,24 +15,24 @@ const B = {
|
|
|
15
15
|
TOKEN_EXPIRED: { authorized: !1, reason: "Token Expired" },
|
|
16
16
|
TOO_MANY_REQUESTS: { authorized: !1, reason: "Too Many Requests" }
|
|
17
17
|
};
|
|
18
|
-
class
|
|
18
|
+
class P {
|
|
19
19
|
/**
|
|
20
20
|
* Generate a unique request ID.
|
|
21
21
|
*
|
|
22
22
|
* @returns A unique request ID
|
|
23
23
|
*/
|
|
24
24
|
generateId() {
|
|
25
|
-
return
|
|
25
|
+
return S();
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
const
|
|
28
|
+
const f = new P(), C = "CoSecRequestInterceptor", p = A + 1e3, g = "Ignore-Refresh-Token";
|
|
29
29
|
class Y {
|
|
30
30
|
/**
|
|
31
31
|
* Creates a new CoSecRequestInterceptor instance.
|
|
32
32
|
* @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager
|
|
33
33
|
*/
|
|
34
34
|
constructor(e) {
|
|
35
|
-
this.name =
|
|
35
|
+
this.name = C, this.order = p, this.options = e;
|
|
36
36
|
}
|
|
37
37
|
/**
|
|
38
38
|
* Intercept requests to add CoSec authentication headers.
|
|
@@ -41,7 +41,6 @@ class Y {
|
|
|
41
41
|
* - CoSec-App-Id: The application identifier from the CoSec options
|
|
42
42
|
* - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated
|
|
43
43
|
* - CoSec-Request-Id: A unique identifier for this specific request
|
|
44
|
-
* - Authorization: Bearer token if available in token storage
|
|
45
44
|
*
|
|
46
45
|
* @param exchange - The fetch exchange containing the request to process
|
|
47
46
|
*
|
|
@@ -58,20 +57,29 @@ class Y {
|
|
|
58
57
|
* It will attempt to refresh the token before adding the Authorization header to the request.
|
|
59
58
|
*/
|
|
60
59
|
async intercept(e) {
|
|
61
|
-
const t =
|
|
62
|
-
o
|
|
63
|
-
let n = this.options.tokenManager.currentToken;
|
|
64
|
-
!n || o[i.AUTHORIZATION] || (!e.attributes.has(R) && n.isRefreshNeeded && n.isRefreshable && await this.options.tokenManager.refresh(), n = this.options.tokenManager.currentToken, n && (o[i.AUTHORIZATION] = `Bearer ${n.access.token}`));
|
|
60
|
+
const t = f.generateId(), r = this.options.deviceIdStorage.getOrCreate(), n = e.ensureRequestHeaders();
|
|
61
|
+
n[o.APP_ID] = this.options.appId, n[o.DEVICE_ID] = r, n[o.REQUEST_ID] = t;
|
|
65
62
|
}
|
|
66
63
|
}
|
|
67
|
-
const
|
|
64
|
+
const U = "AuthorizationRequestInterceptor", D = p + 1e3;
|
|
68
65
|
class F {
|
|
66
|
+
constructor(e) {
|
|
67
|
+
this.options = e, this.name = U, this.order = D;
|
|
68
|
+
}
|
|
69
|
+
async intercept(e) {
|
|
70
|
+
let t = this.options.tokenManager.currentToken;
|
|
71
|
+
const r = e.ensureRequestHeaders();
|
|
72
|
+
!t || r[o.AUTHORIZATION] || (!e.attributes.has(g) && t.isRefreshNeeded && t.isRefreshable && await this.options.tokenManager.refresh(), t = this.options.tokenManager.currentToken, t && (r[o.AUTHORIZATION] = `Bearer ${t.access.token}`));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const z = "AuthorizationResponseInterceptor", v = Number.MIN_SAFE_INTEGER + 1e3;
|
|
76
|
+
class G {
|
|
69
77
|
/**
|
|
70
|
-
* Creates a new
|
|
78
|
+
* Creates a new AuthorizationResponseInterceptor instance.
|
|
71
79
|
* @param options - The CoSec configuration options including token storage and refresher
|
|
72
80
|
*/
|
|
73
81
|
constructor(e) {
|
|
74
|
-
this.name =
|
|
82
|
+
this.name = z, this.order = v, this.options = e;
|
|
75
83
|
}
|
|
76
84
|
/**
|
|
77
85
|
* Intercepts the response and handles unauthorized responses by refreshing tokens.
|
|
@@ -87,10 +95,10 @@ class F {
|
|
|
87
95
|
}
|
|
88
96
|
}
|
|
89
97
|
}
|
|
90
|
-
function
|
|
98
|
+
function k() {
|
|
91
99
|
return typeof window < "u";
|
|
92
100
|
}
|
|
93
|
-
class
|
|
101
|
+
class b {
|
|
94
102
|
constructor() {
|
|
95
103
|
this.store = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set();
|
|
96
104
|
}
|
|
@@ -157,7 +165,7 @@ class z {
|
|
|
157
165
|
* @param eventInit - The initialization object for the StorageEvent
|
|
158
166
|
*/
|
|
159
167
|
notifyListeners(e) {
|
|
160
|
-
|
|
168
|
+
k() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {
|
|
161
169
|
try {
|
|
162
170
|
t(e);
|
|
163
171
|
} catch (r) {
|
|
@@ -166,7 +174,7 @@ class z {
|
|
|
166
174
|
});
|
|
167
175
|
}
|
|
168
176
|
}
|
|
169
|
-
class
|
|
177
|
+
class L {
|
|
170
178
|
/**
|
|
171
179
|
* Creates a new BrowserListenableStorage instance.
|
|
172
180
|
* @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)
|
|
@@ -189,7 +197,7 @@ class v {
|
|
|
189
197
|
const t = (r) => {
|
|
190
198
|
r.storageArea === this.storage && e(r);
|
|
191
199
|
};
|
|
192
|
-
return window.addEventListener(
|
|
200
|
+
return window.addEventListener(R, t), () => window.removeEventListener(R, t);
|
|
193
201
|
}
|
|
194
202
|
/**
|
|
195
203
|
* Clears all items from the storage.
|
|
@@ -229,8 +237,8 @@ class v {
|
|
|
229
237
|
this.storage.setItem(e, t);
|
|
230
238
|
}
|
|
231
239
|
}
|
|
232
|
-
const
|
|
233
|
-
class
|
|
240
|
+
const R = "storage", l = () => k() ? new L(window.localStorage) : new b();
|
|
241
|
+
class w {
|
|
234
242
|
/**
|
|
235
243
|
* Returns the value as-is without serialization
|
|
236
244
|
* @param value The value to pass through
|
|
@@ -259,11 +267,11 @@ class k {
|
|
|
259
267
|
return e;
|
|
260
268
|
}
|
|
261
269
|
}
|
|
262
|
-
const
|
|
263
|
-
function
|
|
264
|
-
return
|
|
270
|
+
const M = new w();
|
|
271
|
+
function V() {
|
|
272
|
+
return M;
|
|
265
273
|
}
|
|
266
|
-
class
|
|
274
|
+
class O {
|
|
267
275
|
/**
|
|
268
276
|
* Creates a new KeyStorage instance
|
|
269
277
|
* @param options Configuration options for the storage
|
|
@@ -271,7 +279,7 @@ class w {
|
|
|
271
279
|
constructor(e) {
|
|
272
280
|
this.cacheValue = null, this.refreshCacheListener = (t) => {
|
|
273
281
|
this.cacheValue = null, t.newValue && this.refreshCache(t.newValue);
|
|
274
|
-
}, this.key = e.key, this.serializer = e.serializer ??
|
|
282
|
+
}, this.key = e.key, this.serializer = e.serializer ?? V(), this.storage = e.storage ?? l(), this.addListener(this.refreshCacheListener);
|
|
275
283
|
}
|
|
276
284
|
/**
|
|
277
285
|
* Refreshes the cached value by deserializing the provided string
|
|
@@ -314,12 +322,12 @@ class w {
|
|
|
314
322
|
this.storage.removeItem(this.key), this.cacheValue = null;
|
|
315
323
|
}
|
|
316
324
|
}
|
|
317
|
-
const
|
|
318
|
-
class
|
|
319
|
-
constructor(e =
|
|
325
|
+
const q = "cosec-device-id";
|
|
326
|
+
class j extends O {
|
|
327
|
+
constructor(e = q) {
|
|
320
328
|
super({
|
|
321
329
|
key: e,
|
|
322
|
-
serializer: new
|
|
330
|
+
serializer: new w(),
|
|
323
331
|
storage: l()
|
|
324
332
|
});
|
|
325
333
|
}
|
|
@@ -329,7 +337,7 @@ class G extends w {
|
|
|
329
337
|
* @returns A newly generated device ID
|
|
330
338
|
*/
|
|
331
339
|
generateDeviceId() {
|
|
332
|
-
return
|
|
340
|
+
return f.generateId();
|
|
333
341
|
}
|
|
334
342
|
/**
|
|
335
343
|
* Get or create a device ID.
|
|
@@ -341,52 +349,52 @@ class G extends w {
|
|
|
341
349
|
return e || (e = this.generateDeviceId(), this.set(e)), e;
|
|
342
350
|
}
|
|
343
351
|
}
|
|
344
|
-
function
|
|
352
|
+
function _(s) {
|
|
345
353
|
try {
|
|
346
354
|
const e = s.split(".");
|
|
347
355
|
if (e.length !== 3)
|
|
348
356
|
return null;
|
|
349
|
-
const r = e[1].replace(/-/g, "+").replace(/_/g, "/"),
|
|
357
|
+
const r = e[1].replace(/-/g, "+").replace(/_/g, "/"), n = r.padEnd(
|
|
350
358
|
r.length + (4 - r.length % 4) % 4,
|
|
351
359
|
"="
|
|
352
|
-
),
|
|
353
|
-
atob(
|
|
354
|
-
return "%" + ("00" +
|
|
360
|
+
), c = decodeURIComponent(
|
|
361
|
+
atob(n).split("").map(function(i) {
|
|
362
|
+
return "%" + ("00" + i.charCodeAt(0).toString(16)).slice(-2);
|
|
355
363
|
}).join("")
|
|
356
364
|
);
|
|
357
|
-
return JSON.parse(
|
|
365
|
+
return JSON.parse(c);
|
|
358
366
|
} catch (e) {
|
|
359
367
|
return console.error("Failed to parse JWT token", e), null;
|
|
360
368
|
}
|
|
361
369
|
}
|
|
362
|
-
function
|
|
363
|
-
const t = typeof s == "string" ?
|
|
370
|
+
function K(s, e = 0) {
|
|
371
|
+
const t = typeof s == "string" ? _(s) : s;
|
|
364
372
|
if (!t)
|
|
365
373
|
return !0;
|
|
366
374
|
const r = t.exp;
|
|
367
375
|
return r ? Date.now() / 1e3 > r - e : !1;
|
|
368
376
|
}
|
|
369
|
-
class
|
|
377
|
+
class T {
|
|
370
378
|
/**
|
|
371
379
|
* Creates a new JwtToken instance
|
|
372
380
|
*/
|
|
373
381
|
constructor(e, t = 0) {
|
|
374
|
-
this.token = e, this.earlyPeriod = t, this.payload =
|
|
382
|
+
this.token = e, this.earlyPeriod = t, this.payload = _(e);
|
|
375
383
|
}
|
|
376
384
|
/**
|
|
377
385
|
* Checks if the token is expired
|
|
378
386
|
* @returns true if the token is expired, false otherwise
|
|
379
387
|
*/
|
|
380
388
|
get isExpired() {
|
|
381
|
-
return this.payload ?
|
|
389
|
+
return this.payload ? K(this.payload, this.earlyPeriod) : !0;
|
|
382
390
|
}
|
|
383
391
|
}
|
|
384
|
-
class
|
|
392
|
+
class y {
|
|
385
393
|
/**
|
|
386
394
|
* Creates a new JwtCompositeToken instance
|
|
387
395
|
*/
|
|
388
396
|
constructor(e, t = 0) {
|
|
389
|
-
this.token = e, this.earlyPeriod = t, this.access = new
|
|
397
|
+
this.token = e, this.earlyPeriod = t, this.access = new T(e.accessToken, t), this.refresh = new T(e.refreshToken, t);
|
|
390
398
|
}
|
|
391
399
|
/**
|
|
392
400
|
* Checks if the access token needs to be refreshed
|
|
@@ -403,7 +411,7 @@ class m {
|
|
|
403
411
|
return !this.refresh.isExpired;
|
|
404
412
|
}
|
|
405
413
|
}
|
|
406
|
-
class
|
|
414
|
+
class m {
|
|
407
415
|
constructor(e = 0) {
|
|
408
416
|
this.earlyPeriod = e;
|
|
409
417
|
}
|
|
@@ -414,7 +422,7 @@ class S {
|
|
|
414
422
|
*/
|
|
415
423
|
deserialize(e) {
|
|
416
424
|
const t = JSON.parse(e);
|
|
417
|
-
return new
|
|
425
|
+
return new y(t, this.earlyPeriod);
|
|
418
426
|
}
|
|
419
427
|
/**
|
|
420
428
|
* Serializes a JwtCompositeToken to a JSON string
|
|
@@ -425,8 +433,8 @@ class S {
|
|
|
425
433
|
return JSON.stringify(e.token);
|
|
426
434
|
}
|
|
427
435
|
}
|
|
428
|
-
const
|
|
429
|
-
class
|
|
436
|
+
const X = new m();
|
|
437
|
+
class W {
|
|
430
438
|
/**
|
|
431
439
|
* Creates a new JwtTokenManager instance
|
|
432
440
|
* @param tokenStorage The storage used to persist tokens
|
|
@@ -478,7 +486,34 @@ class j {
|
|
|
478
486
|
return this.currentToken ? this.currentToken.isRefreshable : !1;
|
|
479
487
|
}
|
|
480
488
|
}
|
|
481
|
-
|
|
489
|
+
const x = "ResourceAttributionRequestInterceptor", J = Number.MAX_SAFE_INTEGER;
|
|
490
|
+
class $ {
|
|
491
|
+
/**
|
|
492
|
+
* Creates a new ResourceAttributionRequestInterceptor
|
|
493
|
+
* @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage
|
|
494
|
+
*/
|
|
495
|
+
constructor({ tenantId: e = "tenantId", ownerId: t = "ownerId", tokenStorage: r }) {
|
|
496
|
+
this.name = x, this.order = J, this.tenantIdPathKey = e, this.ownerIdPathKey = t, this.tokenStorage = r;
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Intercepts outgoing requests and automatically adds tenant and owner ID path parameters
|
|
500
|
+
* if they are defined in the URL template but not provided in the request.
|
|
501
|
+
* @param exchange - The fetch exchange containing the request information
|
|
502
|
+
*/
|
|
503
|
+
intercept(e) {
|
|
504
|
+
const t = this.tokenStorage.get();
|
|
505
|
+
if (!t)
|
|
506
|
+
return;
|
|
507
|
+
const r = t.access.payload;
|
|
508
|
+
if (!r || !r.tenantId && !r.sub)
|
|
509
|
+
return;
|
|
510
|
+
const n = e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url), c = this.tenantIdPathKey, i = e.ensureRequestUrlParams().path, I = r.tenantId;
|
|
511
|
+
I && n.includes(c) && !i[c] && (i[c] = I);
|
|
512
|
+
const h = this.ownerIdPathKey, E = r.sub;
|
|
513
|
+
E && n.includes(h) && !i[h] && (i[h] = E);
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
class ee {
|
|
482
517
|
/**
|
|
483
518
|
* Creates a new instance of CoSecTokenRefresher.
|
|
484
519
|
*
|
|
@@ -500,81 +535,57 @@ class H {
|
|
|
500
535
|
body: e
|
|
501
536
|
},
|
|
502
537
|
{
|
|
503
|
-
resultExtractor:
|
|
504
|
-
attributes: /* @__PURE__ */ new Map([[
|
|
538
|
+
resultExtractor: N.Json,
|
|
539
|
+
attributes: /* @__PURE__ */ new Map([[g, !0]])
|
|
505
540
|
}
|
|
506
541
|
);
|
|
507
542
|
}
|
|
508
543
|
}
|
|
509
|
-
const
|
|
510
|
-
class
|
|
511
|
-
constructor(e =
|
|
544
|
+
const Q = "cosec-token";
|
|
545
|
+
class te extends O {
|
|
546
|
+
constructor(e = Q, t = 0) {
|
|
512
547
|
super({
|
|
513
548
|
key: e,
|
|
514
549
|
storage: l(),
|
|
515
|
-
serializer: new
|
|
550
|
+
serializer: new m(t)
|
|
516
551
|
}), this.earlyPeriod = t;
|
|
517
552
|
}
|
|
518
553
|
setCompositeToken(e) {
|
|
519
554
|
this.set(
|
|
520
|
-
new
|
|
555
|
+
new y(e)
|
|
521
556
|
);
|
|
522
557
|
}
|
|
523
558
|
}
|
|
524
|
-
const K = "ResourceAttributionRequestInterceptor", x = Number.MAX_SAFE_INTEGER;
|
|
525
|
-
class W {
|
|
526
|
-
/**
|
|
527
|
-
* Creates a new ResourceAttributionRequestInterceptor
|
|
528
|
-
* @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage
|
|
529
|
-
*/
|
|
530
|
-
constructor({ tenantId: e = "tenantId", ownerId: t = "ownerId", tokenStorage: r }) {
|
|
531
|
-
this.name = K, this.order = x, this.tenantIdPathKey = e, this.ownerIdPathKey = t, this.tokenStorage = r;
|
|
532
|
-
}
|
|
533
|
-
/**
|
|
534
|
-
* Intercepts outgoing requests and automatically adds tenant and owner ID path parameters
|
|
535
|
-
* if they are defined in the URL template but not provided in the request.
|
|
536
|
-
* @param exchange - The fetch exchange containing the request information
|
|
537
|
-
*/
|
|
538
|
-
intercept(e) {
|
|
539
|
-
const t = this.tokenStorage.get();
|
|
540
|
-
if (!t)
|
|
541
|
-
return;
|
|
542
|
-
const r = t.access.payload;
|
|
543
|
-
if (!r || !r.tenantId && !r.sub)
|
|
544
|
-
return;
|
|
545
|
-
const o = e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url), n = this.tenantIdPathKey, a = e.ensureRequestUrlParams().path, E = r.tenantId;
|
|
546
|
-
E && o.includes(n) && !a[n] && (a[n] = E);
|
|
547
|
-
const h = this.ownerIdPathKey, I = r.sub;
|
|
548
|
-
I && o.includes(h) && !a[h] && (a[h] = I);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
559
|
export {
|
|
560
|
+
U as AUTHORIZATION_REQUEST_INTERCEPTOR_NAME,
|
|
561
|
+
D as AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER,
|
|
562
|
+
z as AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME,
|
|
563
|
+
v as AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER,
|
|
564
|
+
F as AuthorizationRequestInterceptor,
|
|
565
|
+
G as AuthorizationResponseInterceptor,
|
|
552
566
|
B as AuthorizeResults,
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
U as COSEC_RESPONSE_INTERCEPTOR_ORDER,
|
|
557
|
-
i as CoSecHeaders,
|
|
567
|
+
C as COSEC_REQUEST_INTERCEPTOR_NAME,
|
|
568
|
+
p as COSEC_REQUEST_INTERCEPTOR_ORDER,
|
|
569
|
+
o as CoSecHeaders,
|
|
558
570
|
Y as CoSecRequestInterceptor,
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
m as
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
W as ResourceAttributionRequestInterceptor,
|
|
571
|
+
ee as CoSecTokenRefresher,
|
|
572
|
+
q as DEFAULT_COSEC_DEVICE_ID_KEY,
|
|
573
|
+
Q as DEFAULT_COSEC_TOKEN_KEY,
|
|
574
|
+
j as DeviceIdStorage,
|
|
575
|
+
g as IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,
|
|
576
|
+
y as JwtCompositeToken,
|
|
577
|
+
m as JwtCompositeTokenSerializer,
|
|
578
|
+
T as JwtToken,
|
|
579
|
+
W as JwtTokenManager,
|
|
580
|
+
P as NanoIdGenerator,
|
|
581
|
+
x as RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME,
|
|
582
|
+
J as RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER,
|
|
583
|
+
$ as ResourceAttributionRequestInterceptor,
|
|
573
584
|
u as ResponseCodes,
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
585
|
+
te as TokenStorage,
|
|
586
|
+
f as idGenerator,
|
|
587
|
+
K as isTokenExpired,
|
|
588
|
+
X as jwtCompositeTokenSerializer,
|
|
589
|
+
_ as parseJwtPayload
|
|
579
590
|
};
|
|
580
591
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../../storage/dist/index.es.js","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts","../src/resourceAttributionRequestInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","function a() {\n return typeof window < \"u\";\n}\nclass n {\n constructor() {\n this.store = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set();\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.store.size;\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.store.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n const t = this.store.get(e);\n return t !== void 0 ? t : null;\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return Array.from(this.store.keys())[e] || null;\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n const t = this.getItem(e);\n this.store.has(e) && (this.store.delete(e), this.notifyListeners({\n key: e,\n oldValue: t,\n newValue: null\n }));\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n const r = this.getItem(e);\n this.store.set(e, t), this.notifyListeners({ key: e, oldValue: r, newValue: t });\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n return this.listeners.add(e), () => this.listeners.delete(e);\n }\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n notifyListeners(e) {\n a() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {\n try {\n t(e);\n } catch (r) {\n console.error(\"Error in storage change listener:\", r);\n }\n });\n }\n}\nclass o {\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(e) {\n this.storage = e;\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.storage.length;\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n const t = (r) => {\n r.storageArea === this.storage && e(r);\n };\n return window.addEventListener(i, t), () => window.removeEventListener(i, t);\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.storage.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n return this.storage.getItem(e);\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return this.storage.key(e);\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n this.storage.removeItem(e);\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n this.storage.setItem(e, t);\n }\n}\nconst i = \"storage\", h = () => a() ? new o(window.localStorage) : new n();\nclass l {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(e) {\n return JSON.stringify(e);\n }\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize(e) {\n return JSON.parse(e);\n }\n}\nclass c {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(e) {\n return e;\n }\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(e) {\n return e;\n }\n}\nconst d = new l(), u = new c();\nfunction g() {\n return u;\n}\nclass w {\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(e) {\n this.cacheValue = null, this.refreshCacheListener = (t) => {\n this.cacheValue = null, t.newValue && this.refreshCache(t.newValue);\n }, this.key = e.key, this.serializer = e.serializer ?? g(), this.storage = e.storage ?? h(), this.addListener(this.refreshCacheListener);\n }\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n refreshCache(e) {\n this.cacheValue = this.serializer.deserialize(e);\n }\n addListener(e) {\n const t = (r) => {\n r.key === this.key && e(r);\n };\n return this.storage.addListener(t);\n }\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get() {\n if (this.cacheValue)\n return this.cacheValue;\n const e = this.storage.getItem(this.key);\n return e ? (this.refreshCache(e), this.cacheValue) : null;\n }\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(e) {\n const t = this.serializer.serialize(e);\n this.storage.setItem(this.key, t), this.cacheValue = e;\n }\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove() {\n this.storage.removeItem(this.key), this.cacheValue = null;\n }\n}\nexport {\n o as BrowserListenableStorage,\n c as IdentitySerializer,\n n as InMemoryListenableStorage,\n l as JsonSerializer,\n w as KeyStorage,\n i as STORAGE_EVENT_TYPE,\n h as createListenableStorage,\n u as identitySerializer,\n a as isBrowser,\n d as jsonSerializer,\n g as typedIdentitySerializer\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, IdentitySerializer, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload | null;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload | null;\n\n /**\n * Creates a new JwtToken instance\n */\n constructor(\n public readonly token: string,\n public readonly earlyPeriod: number = 0,\n ) {\n this.payload = parseJwtPayload<Payload>(token);\n }\n\n /**\n * Checks if the token is expired\n * @returns true if the token is expired, false otherwise\n */\n get isExpired(): boolean {\n if (!this.payload) {\n return true;\n }\n return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\nimport { createListenableStorage, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { TokenStorage } from './tokenStorage';\n\n/**\n * Configuration options for resource attribution\n */\nexport interface ResourceAttributionOptions {\n /**\n * The path parameter key used for tenant ID in URL templates\n */\n tenantId?: string;\n /**\n * The path parameter key used for owner ID in URL templates\n */\n ownerId?: string;\n /**\n * Storage mechanism for retrieving current authentication tokens\n */\n tokenStorage: TokenStorage;\n}\n\n/**\n * Name identifier for the ResourceAttributionRequestInterceptor\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME = 'ResourceAttributionRequestInterceptor';\n/**\n * Order priority for the ResourceAttributionRequestInterceptor, set to maximum safe integer to ensure it runs last\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER;\n\n/**\n * Request interceptor that automatically adds tenant and owner ID path parameters to requests\n * based on the current authentication token. This is useful for multi-tenant applications where\n * requests need to include tenant-specific information in the URL path.\n */\nexport class ResourceAttributionRequestInterceptor implements RequestInterceptor {\n\n readonly name = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME;\n readonly order = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER;\n private readonly tenantIdPathKey: string;\n private readonly ownerIdPathKey: string;\n private readonly tokenStorage: TokenStorage;\n\n /**\n * Creates a new ResourceAttributionRequestInterceptor\n * @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage\n */\n constructor({ tenantId = 'tenantId', ownerId = 'ownerId', tokenStorage }: ResourceAttributionOptions) {\n this.tenantIdPathKey = tenantId;\n this.ownerIdPathKey = ownerId;\n this.tokenStorage = tokenStorage;\n }\n\n /**\n * Intercepts outgoing requests and automatically adds tenant and owner ID path parameters\n * if they are defined in the URL template but not provided in the request.\n * @param exchange - The fetch exchange containing the request information\n */\n intercept(exchange: FetchExchange): void {\n const currentToken = this.tokenStorage.get();\n if (!currentToken) {\n return;\n }\n const principal = currentToken.access.payload;\n if (!principal) {\n return;\n }\n if (!principal.tenantId && !principal.sub) {\n return;\n }\n\n // Extract path parameters from the URL template\n const extractedPathParams = exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(exchange.request.url);\n const tenantIdPathKey = this.tenantIdPathKey;\n const requestPathParams = exchange.ensureRequestUrlParams().path;\n const tenantId = principal.tenantId;\n\n // Add tenant ID to path parameters if it's part of the URL template and not already provided\n if (tenantId && extractedPathParams.includes(tenantIdPathKey) && !requestPathParams[tenantIdPathKey]) {\n requestPathParams[tenantIdPathKey] = tenantId;\n }\n\n const ownerIdPathKey = this.ownerIdPathKey;\n const ownerId = principal.sub;\n\n // Add owner ID to path parameters if it's part of the URL template and not already provided\n if (ownerId && extractedPathParams.includes(ownerIdPathKey) && !requestPathParams[ownerIdPathKey]) {\n requestPathParams[ownerIdPathKey] = ownerId;\n }\n }\n\n}"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","error","a","n","o","i","h","c","u","g","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey"],"mappings":";;AAmBO,MAAMA,IAAN,MAAMA,EAAa;AAK1B;AAJEA,EAAgB,YAAY,mBAC5BA,EAAgB,SAAS,gBACzBA,EAAgB,gBAAgB,iBAChCA,EAAgB,aAAa;AAJxB,IAAMC,IAAND;AAOA,MAAME,IAAN,MAAMA,EAAc;AAE3B;AADEA,EAAgB,eAAe;AAD1B,IAAMC,IAAND;AAgCA,MAA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Ac;AAAA,IAAA;AAAA,EAExC;AACF;ACJO,MAAMW,IAAgD,yCAIhDC,IAAiD,OAAO;AAO9D,MAAMC,EAAoE;AAAA;AAAA;AAAA;AAAA;AAAA,EAY/E,YAAY,EAAE,UAAAC,IAAW,YAAY,SAAAC,IAAU,WAAW,cAAAZ,KAA4C;AAVtG,SAAS,OAAOQ,GAChB,KAAS,QAAQC,GAUf,KAAK,kBAAkBE,GACvB,KAAK,iBAAiBC,GACtB,KAAK,eAAeZ;AAAA,EACtB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,UAAUzC,GAA+B;AACvC,UAAMI,IAAe,KAAK,aAAa,IAAA;AACvC,QAAI,CAACA;AACH;AAEF,UAAMkD,IAAYlD,EAAa,OAAO;AAItC,QAHI,CAACkD,KAGD,CAACA,EAAU,YAAY,CAACA,EAAU;AACpC;AAIF,UAAMC,IAAsBvD,EAAS,QAAQ,WAAW,oBAAoB,kBAAkBA,EAAS,QAAQ,GAAG,GAC5GwD,IAAkB,KAAK,iBACvBC,IAAoBzD,EAAS,uBAAA,EAAyB,MACtDoD,IAAWE,EAAU;AAG3B,IAAIF,KAAYG,EAAoB,SAASC,CAAe,KAAK,CAACC,EAAkBD,CAAe,MACjGC,EAAkBD,CAAe,IAAIJ;AAGvC,UAAMM,IAAiB,KAAK,gBACtBL,IAAUC,EAAU;AAG1B,IAAID,KAAWE,EAAoB,SAASG,CAAc,KAAK,CAACD,EAAkBC,CAAc,MAC9FD,EAAkBC,CAAc,IAAIL;AAAA,EAExC;AAEF;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../../storage/dist/index.es.js","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/resourceAttributionRequestInterceptor.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\nexport interface AppIdCapable {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n}\n\nexport interface DeviceIdStorageCapable {\n deviceIdStorage: DeviceIdStorage;\n}\n\nexport interface JwtTokenManagerCapable {\n tokenManager: JwtTokenManager;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions extends AppIdCapable, DeviceIdStorageCapable, JwtTokenManagerCapable {\n\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { AppIdCapable, CoSecHeaders, DeviceIdStorageCapable } from './types';\nimport { idGenerator } from './idGenerator';\n\nexport interface CoSecRequestOptions extends AppIdCapable, DeviceIdStorageCapable {\n}\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecRequestOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecRequestOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { COSEC_REQUEST_INTERCEPTOR_ORDER, IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME = 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER = COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n async intercept(exchange: FetchExchange): Promise<void> {\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\nimport {\n AuthorizationInterceptorOptions,\n} from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME = 'AuthorizationResponseInterceptor';\n\n/**\n * The order of the AuthorizationResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class AuthorizationResponseInterceptor implements ResponseInterceptor {\n readonly name = AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER;\n private options: AuthorizationInterceptorOptions;\n\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: AuthorizationInterceptorOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","function a() {\n return typeof window < \"u\";\n}\nclass n {\n constructor() {\n this.store = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set();\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.store.size;\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.store.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n const t = this.store.get(e);\n return t !== void 0 ? t : null;\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return Array.from(this.store.keys())[e] || null;\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n const t = this.getItem(e);\n this.store.has(e) && (this.store.delete(e), this.notifyListeners({\n key: e,\n oldValue: t,\n newValue: null\n }));\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n const r = this.getItem(e);\n this.store.set(e, t), this.notifyListeners({ key: e, oldValue: r, newValue: t });\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n return this.listeners.add(e), () => this.listeners.delete(e);\n }\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n notifyListeners(e) {\n a() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {\n try {\n t(e);\n } catch (r) {\n console.error(\"Error in storage change listener:\", r);\n }\n });\n }\n}\nclass o {\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(e) {\n this.storage = e;\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.storage.length;\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n const t = (r) => {\n r.storageArea === this.storage && e(r);\n };\n return window.addEventListener(i, t), () => window.removeEventListener(i, t);\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.storage.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n return this.storage.getItem(e);\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return this.storage.key(e);\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n this.storage.removeItem(e);\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n this.storage.setItem(e, t);\n }\n}\nconst i = \"storage\", h = () => a() ? new o(window.localStorage) : new n();\nclass l {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(e) {\n return JSON.stringify(e);\n }\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize(e) {\n return JSON.parse(e);\n }\n}\nclass c {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(e) {\n return e;\n }\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(e) {\n return e;\n }\n}\nconst d = new l(), u = new c();\nfunction g() {\n return u;\n}\nclass w {\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(e) {\n this.cacheValue = null, this.refreshCacheListener = (t) => {\n this.cacheValue = null, t.newValue && this.refreshCache(t.newValue);\n }, this.key = e.key, this.serializer = e.serializer ?? g(), this.storage = e.storage ?? h(), this.addListener(this.refreshCacheListener);\n }\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n refreshCache(e) {\n this.cacheValue = this.serializer.deserialize(e);\n }\n addListener(e) {\n const t = (r) => {\n r.key === this.key && e(r);\n };\n return this.storage.addListener(t);\n }\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get() {\n if (this.cacheValue)\n return this.cacheValue;\n const e = this.storage.getItem(this.key);\n return e ? (this.refreshCache(e), this.cacheValue) : null;\n }\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(e) {\n const t = this.serializer.serialize(e);\n this.storage.setItem(this.key, t), this.cacheValue = e;\n }\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove() {\n this.storage.removeItem(this.key), this.cacheValue = null;\n }\n}\nexport {\n o as BrowserListenableStorage,\n c as IdentitySerializer,\n n as InMemoryListenableStorage,\n l as JsonSerializer,\n w as KeyStorage,\n i as STORAGE_EVENT_TYPE,\n h as createListenableStorage,\n u as identitySerializer,\n a as isBrowser,\n d as jsonSerializer,\n g as typedIdentitySerializer\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, IdentitySerializer, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload | null;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload | null;\n\n /**\n * Creates a new JwtToken instance\n */\n constructor(\n public readonly token: string,\n public readonly earlyPeriod: number = 0,\n ) {\n this.payload = parseJwtPayload<Payload>(token);\n }\n\n /**\n * Checks if the token is expired\n * @returns true if the token is expired, false otherwise\n */\n get isExpired(): boolean {\n if (!this.payload) {\n return true;\n }\n return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { TokenStorage } from './tokenStorage';\n\n/**\n * Configuration options for resource attribution\n */\nexport interface ResourceAttributionOptions {\n /**\n * The path parameter key used for tenant ID in URL templates\n */\n tenantId?: string;\n /**\n * The path parameter key used for owner ID in URL templates\n */\n ownerId?: string;\n /**\n * Storage mechanism for retrieving current authentication tokens\n */\n tokenStorage: TokenStorage;\n}\n\n/**\n * Name identifier for the ResourceAttributionRequestInterceptor\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME = 'ResourceAttributionRequestInterceptor';\n/**\n * Order priority for the ResourceAttributionRequestInterceptor, set to maximum safe integer to ensure it runs last\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER;\n\n/**\n * Request interceptor that automatically adds tenant and owner ID path parameters to requests\n * based on the current authentication token. This is useful for multi-tenant applications where\n * requests need to include tenant-specific information in the URL path.\n */\nexport class ResourceAttributionRequestInterceptor implements RequestInterceptor {\n\n readonly name = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME;\n readonly order = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER;\n private readonly tenantIdPathKey: string;\n private readonly ownerIdPathKey: string;\n private readonly tokenStorage: TokenStorage;\n\n /**\n * Creates a new ResourceAttributionRequestInterceptor\n * @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage\n */\n constructor({ tenantId = 'tenantId', ownerId = 'ownerId', tokenStorage }: ResourceAttributionOptions) {\n this.tenantIdPathKey = tenantId;\n this.ownerIdPathKey = ownerId;\n this.tokenStorage = tokenStorage;\n }\n\n /**\n * Intercepts outgoing requests and automatically adds tenant and owner ID path parameters\n * if they are defined in the URL template but not provided in the request.\n * @param exchange - The fetch exchange containing the request information\n */\n intercept(exchange: FetchExchange): void {\n const currentToken = this.tokenStorage.get();\n if (!currentToken) {\n return;\n }\n const principal = currentToken.access.payload;\n if (!principal) {\n return;\n }\n if (!principal.tenantId && !principal.sub) {\n return;\n }\n\n // Extract path parameters from the URL template\n const extractedPathParams = exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(exchange.request.url);\n const tenantIdPathKey = this.tenantIdPathKey;\n const requestPathParams = exchange.ensureRequestUrlParams().path;\n const tenantId = principal.tenantId;\n\n // Add tenant ID to path parameters if it's part of the URL template and not already provided\n if (tenantId && extractedPathParams.includes(tenantIdPathKey) && !requestPathParams[tenantIdPathKey]) {\n requestPathParams[tenantIdPathKey] = tenantId;\n }\n\n const ownerIdPathKey = this.ownerIdPathKey;\n const ownerId = principal.sub;\n\n // Add owner ID to path parameters if it's part of the URL template and not already provided\n if (ownerId && extractedPathParams.includes(ownerIdPathKey) && !requestPathParams[ownerIdPathKey]) {\n requestPathParams[ownerIdPathKey] = ownerId;\n }\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\nimport { createListenableStorage, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","a","n","o","i","h","c","u","g","w","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":";;AAmBO,MAAMA,IAAN,MAAMA,EAAa;AAK1B;AAJEA,EAAgB,YAAY,mBAC5BA,EAAgB,SAAS,gBACzBA,EAAgB,gBAAgB,iBAChCA,EAAgB,aAAa;AAJxB,IAAMC,IAAND;AAOA,MAAME,IAAN,MAAMA,EAAc;AAE3B;AADEA,EAAgB,eAAe;AAD1B,IAAMC,IAAND;AAqCA,MAAME,IAAmB;AAAA,EAC9B,OAAO,EAAE,YAAY,IAAM,QAAQ,QAAA;AAAA,EACnC,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,mBAAmB,EAAE,YAAY,IAAO,QAAQ,oBAAA;AAClD;AC9CO,MAAMC,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,aAAqB;AACnB,WAAOC,EAAA;AAAA,EACT;AACF;AAEO,MAAMC,IAAc,IAAIF,EAAA,GCPlBG,IAAiC,2BAMjCC,IACXC,IAAiC,KAEtBC,IAAqC;AAkB3C,MAAMC,EAAsD;AAAA;AAAA;AAAA;AAAA;AAA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AAA,UAAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAQ8B,GAAgD;AAItD,WAAO,KAAK,QAAQ,QAAQ;AAAA,MAAqB,KAAK,QAAQ;AAAA,MAC5D;AAAA,QACE,MAAMA;AAAA,MAAA;AAAA,MACL;AAAA,QACD,iBAAiB+B,EAAiB;AAAA,QAClC,gCAAgB,IAAI,CAAC,CAAC/D,GAAoC,EAAI,CAAC,CAAC;AAAA,MAAA;AAAA,IAClE;AAAA,EAEJ;AACF;ACxEO,MAAMgE,IAA0B;AAKhC,MAAMC,WAAqBtC,EAA4D;AAAA,EAE5F,YACEC,IAAcoC,GACE1B,IAAsB,GACtC;AACA,UAAM;AAAA,MACJ,KAAAV;AAAA,MACA,SAASE,EAAA;AAAA,MACT,YAAY,IAAIa,EAA4BL,CAAW;AAAA,IAAA,CACxD,GANe,KAAA,cAAAA;AAAA,EAOlB;AAAA,EAEA,kBAAkBO,GAAgC;AAChD,SAAK;AAAA,MACH,IAAIH,EAAkBG,CAAc;AAAA,IAAA;AAAA,EAExC;AACF;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(r,
|
|
1
|
+
(function(r,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@ahoo-wang/fetcher"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid"],a):(r=typeof globalThis<"u"?globalThis:r||self,a(r.FetcherCoSec={},r.Fetcher,r.nanoid))})(this,(function(r,a,V){"use strict";const c=class c{};c.DEVICE_ID="CoSec-Device-Id",c.APP_ID="CoSec-App-Id",c.AUTHORIZATION="Authorization",c.REQUEST_ID="CoSec-Request-Id";let i=c;const g=class g{};g.UNAUTHORIZED=401;let E=g;const K={ALLOW:{authorized:!0,reason:"Allow"},EXPLICIT_DENY:{authorized:!1,reason:"Explicit Deny"},IMPLICIT_DENY:{authorized:!1,reason:"Implicit Deny"},TOKEN_EXPIRED:{authorized:!1,reason:"Token Expired"},TOO_MANY_REQUESTS:{authorized:!1,reason:"Too Many Requests"}};class S{generateId(){return V.nanoid()}}const l=new S,A="CoSecRequestInterceptor",R=a.REQUEST_BODY_INTERCEPTOR_ORDER+1e3,T="Ignore-Refresh-Token";class Q{constructor(e){this.name=A,this.order=R,this.options=e}async intercept(e){const t=l.generateId(),s=this.options.deviceIdStorage.getOrCreate(),o=e.ensureRequestHeaders();o[i.APP_ID]=this.options.appId,o[i.DEVICE_ID]=s,o[i.REQUEST_ID]=t}}const p="AuthorizationRequestInterceptor",C=R+1e3;class H{constructor(e){this.options=e,this.name=p,this.order=C}async intercept(e){let t=this.options.tokenManager.currentToken;const s=e.ensureRequestHeaders();!t||s[i.AUTHORIZATION]||(!e.attributes.has(T)&&t.isRefreshNeeded&&t.isRefreshable&&await this.options.tokenManager.refresh(),t=this.options.tokenManager.currentToken,t&&(s[i.AUTHORIZATION]=`Bearer ${t.access.token}`))}}const k="AuthorizationResponseInterceptor",w=Number.MIN_SAFE_INTEGER+1e3;class J{constructor(e){this.name=k,this.order=w,this.options=e}async intercept(e){const t=e.response;if(t&&t.status===E.UNAUTHORIZED&&this.options.tokenManager.isRefreshable)try{await this.options.tokenManager.refresh(),await e.fetcher.interceptors.exchange(e)}catch(s){throw this.options.tokenManager.tokenStorage.remove(),s}}}function y(){return typeof window<"u"}class Z{constructor(){this.store=new Map,this.listeners=new Set}get length(){return this.store.size}clear(){this.store.clear()}getItem(e){const t=this.store.get(e);return t!==void 0?t:null}key(e){return Array.from(this.store.keys())[e]||null}removeItem(e){const t=this.getItem(e);this.store.has(e)&&(this.store.delete(e),this.notifyListeners({key:e,oldValue:t,newValue:null}))}setItem(e,t){const s=this.getItem(e);this.store.set(e,t),this.notifyListeners({key:e,oldValue:s,newValue:t})}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){y()&&window.location&&(e.url=e.url||window.location.href),e.storageArea=this,this.listeners.forEach(t=>{try{t(e)}catch(s){console.error("Error in storage change listener:",s)}})}}class F{constructor(e){this.storage=e}get length(){return this.storage.length}addListener(e){const t=s=>{s.storageArea===this.storage&&e(s)};return window.addEventListener(P,t),()=>window.removeEventListener(P,t)}clear(){this.storage.clear()}getItem(e){return this.storage.getItem(e)}key(e){return this.storage.key(e)}removeItem(e){this.storage.removeItem(e)}setItem(e,t){this.storage.setItem(e,t)}}const P="storage",I=()=>y()?new F(window.localStorage):new Z;class m{serialize(e){return e}deserialize(e){return e}}const B=new m;function Y(){return B}class U{constructor(e){this.cacheValue=null,this.refreshCacheListener=t=>{this.cacheValue=null,t.newValue&&this.refreshCache(t.newValue)},this.key=e.key,this.serializer=e.serializer??Y(),this.storage=e.storage??I(),this.addListener(this.refreshCacheListener)}refreshCache(e){this.cacheValue=this.serializer.deserialize(e)}addListener(e){const t=s=>{s.key===this.key&&e(s)};return this.storage.addListener(t)}get(){if(this.cacheValue)return this.cacheValue;const e=this.storage.getItem(this.key);return e?(this.refreshCache(e),this.cacheValue):null}set(e){const t=this.serializer.serialize(e);this.storage.setItem(this.key,t),this.cacheValue=e}remove(){this.storage.removeItem(this.key),this.cacheValue=null}}const D="cosec-device-id";class G extends U{constructor(e=D){super({key:e,serializer:new m,storage:I()})}generateDeviceId(){return l.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}}function d(n){try{const e=n.split(".");if(e.length!==3)return null;const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=s.padEnd(s.length+(4-s.length%4)%4,"="),u=decodeURIComponent(atob(o).split("").map(function(h){return"%"+("00"+h.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(u)}catch(e){return console.error("Failed to parse JWT token",e),null}}function z(n,e=0){const t=typeof n=="string"?d(n):n;if(!t)return!0;const s=t.exp;return s?Date.now()/1e3>s-e:!1}class f{constructor(e,t=0){this.token=e,this.earlyPeriod=t,this.payload=d(e)}get isExpired(){return this.payload?z(this.payload,this.earlyPeriod):!0}}class _{constructor(e,t=0){this.token=e,this.earlyPeriod=t,this.access=new f(e.accessToken,t),this.refresh=new f(e.refreshToken,t)}get isRefreshNeeded(){return this.access.isExpired}get isRefreshable(){return!this.refresh.isExpired}}class O{constructor(e=0){this.earlyPeriod=e}deserialize(e){const t=JSON.parse(e);return new _(t,this.earlyPeriod)}serialize(e){return JSON.stringify(e.token)}}const j=new O;class X{constructor(e,t){this.tokenStorage=e,this.tokenRefresher=t}get currentToken(){return this.tokenStorage.get()}async refresh(e){if(!e){const t=this.currentToken;if(!t)throw new Error("No token found");e=t.token}return this.refreshInProgress?this.refreshInProgress:(this.refreshInProgress=this.tokenRefresher.refresh(e).then(t=>{this.tokenStorage.setCompositeToken(t)}).catch(t=>{throw this.tokenStorage.remove(),t}).finally(()=>{this.refreshInProgress=void 0}),this.refreshInProgress)}get isRefreshNeeded(){return this.currentToken?this.currentToken.isRefreshNeeded:!1}get isRefreshable(){return this.currentToken?this.currentToken.isRefreshable:!1}}const M="ResourceAttributionRequestInterceptor",v=Number.MAX_SAFE_INTEGER;class W{constructor({tenantId:e="tenantId",ownerId:t="ownerId",tokenStorage:s}){this.name=M,this.order=v,this.tenantIdPathKey=e,this.ownerIdPathKey=t,this.tokenStorage=s}intercept(e){const t=this.tokenStorage.get();if(!t)return;const s=t.access.payload;if(!s||!s.tenantId&&!s.sub)return;const o=e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url),u=this.tenantIdPathKey,h=e.ensureRequestUrlParams().path,b=s.tenantId;b&&o.includes(u)&&!h[u]&&(h[u]=b);const N=this.ownerIdPathKey,L=s.sub;L&&o.includes(N)&&!h[N]&&(h[N]=L)}}class ${constructor(e){this.options=e}refresh(e){return this.options.fetcher.post(this.options.endpoint,{body:e},{resultExtractor:a.ResultExtractors.Json,attributes:new Map([[T,!0]])})}}const q="cosec-token";class x extends U{constructor(e=q,t=0){super({key:e,storage:I(),serializer:new O(t)}),this.earlyPeriod=t}setCompositeToken(e){this.set(new _(e))}}r.AUTHORIZATION_REQUEST_INTERCEPTOR_NAME=p,r.AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER=C,r.AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME=k,r.AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER=w,r.AuthorizationRequestInterceptor=H,r.AuthorizationResponseInterceptor=J,r.AuthorizeResults=K,r.COSEC_REQUEST_INTERCEPTOR_NAME=A,r.COSEC_REQUEST_INTERCEPTOR_ORDER=R,r.CoSecHeaders=i,r.CoSecRequestInterceptor=Q,r.CoSecTokenRefresher=$,r.DEFAULT_COSEC_DEVICE_ID_KEY=D,r.DEFAULT_COSEC_TOKEN_KEY=q,r.DeviceIdStorage=G,r.IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY=T,r.JwtCompositeToken=_,r.JwtCompositeTokenSerializer=O,r.JwtToken=f,r.JwtTokenManager=X,r.NanoIdGenerator=S,r.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME=M,r.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER=v,r.ResourceAttributionRequestInterceptor=W,r.ResponseCodes=E,r.TokenStorage=x,r.idGenerator=l,r.isTokenExpired=z,r.jwtCompositeTokenSerializer=j,r.parseJwtPayload=d,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../../storage/dist/index.es.js","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts","../src/resourceAttributionRequestInterceptor.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","function a() {\n return typeof window < \"u\";\n}\nclass n {\n constructor() {\n this.store = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set();\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.store.size;\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.store.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n const t = this.store.get(e);\n return t !== void 0 ? t : null;\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return Array.from(this.store.keys())[e] || null;\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n const t = this.getItem(e);\n this.store.has(e) && (this.store.delete(e), this.notifyListeners({\n key: e,\n oldValue: t,\n newValue: null\n }));\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n const r = this.getItem(e);\n this.store.set(e, t), this.notifyListeners({ key: e, oldValue: r, newValue: t });\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n return this.listeners.add(e), () => this.listeners.delete(e);\n }\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n notifyListeners(e) {\n a() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {\n try {\n t(e);\n } catch (r) {\n console.error(\"Error in storage change listener:\", r);\n }\n });\n }\n}\nclass o {\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(e) {\n this.storage = e;\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.storage.length;\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n const t = (r) => {\n r.storageArea === this.storage && e(r);\n };\n return window.addEventListener(i, t), () => window.removeEventListener(i, t);\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.storage.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n return this.storage.getItem(e);\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return this.storage.key(e);\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n this.storage.removeItem(e);\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n this.storage.setItem(e, t);\n }\n}\nconst i = \"storage\", h = () => a() ? new o(window.localStorage) : new n();\nclass l {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(e) {\n return JSON.stringify(e);\n }\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize(e) {\n return JSON.parse(e);\n }\n}\nclass c {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(e) {\n return e;\n }\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(e) {\n return e;\n }\n}\nconst d = new l(), u = new c();\nfunction g() {\n return u;\n}\nclass w {\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(e) {\n this.cacheValue = null, this.refreshCacheListener = (t) => {\n this.cacheValue = null, t.newValue && this.refreshCache(t.newValue);\n }, this.key = e.key, this.serializer = e.serializer ?? g(), this.storage = e.storage ?? h(), this.addListener(this.refreshCacheListener);\n }\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n refreshCache(e) {\n this.cacheValue = this.serializer.deserialize(e);\n }\n addListener(e) {\n const t = (r) => {\n r.key === this.key && e(r);\n };\n return this.storage.addListener(t);\n }\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get() {\n if (this.cacheValue)\n return this.cacheValue;\n const e = this.storage.getItem(this.key);\n return e ? (this.refreshCache(e), this.cacheValue) : null;\n }\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(e) {\n const t = this.serializer.serialize(e);\n this.storage.setItem(this.key, t), this.cacheValue = e;\n }\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove() {\n this.storage.removeItem(this.key), this.cacheValue = null;\n }\n}\nexport {\n o as BrowserListenableStorage,\n c as IdentitySerializer,\n n as InMemoryListenableStorage,\n l as JsonSerializer,\n w as KeyStorage,\n i as STORAGE_EVENT_TYPE,\n h as createListenableStorage,\n u as identitySerializer,\n a as isBrowser,\n d as jsonSerializer,\n g as typedIdentitySerializer\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, IdentitySerializer, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload | null;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload | null;\n\n /**\n * Creates a new JwtToken instance\n */\n constructor(\n public readonly token: string,\n public readonly earlyPeriod: number = 0,\n ) {\n this.payload = parseJwtPayload<Payload>(token);\n }\n\n /**\n * Checks if the token is expired\n * @returns true if the token is expired, false otherwise\n */\n get isExpired(): boolean {\n if (!this.payload) {\n return true;\n }\n return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\nimport { createListenableStorage, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { TokenStorage } from './tokenStorage';\n\n/**\n * Configuration options for resource attribution\n */\nexport interface ResourceAttributionOptions {\n /**\n * The path parameter key used for tenant ID in URL templates\n */\n tenantId?: string;\n /**\n * The path parameter key used for owner ID in URL templates\n */\n ownerId?: string;\n /**\n * Storage mechanism for retrieving current authentication tokens\n */\n tokenStorage: TokenStorage;\n}\n\n/**\n * Name identifier for the ResourceAttributionRequestInterceptor\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME = 'ResourceAttributionRequestInterceptor';\n/**\n * Order priority for the ResourceAttributionRequestInterceptor, set to maximum safe integer to ensure it runs last\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER;\n\n/**\n * Request interceptor that automatically adds tenant and owner ID path parameters to requests\n * based on the current authentication token. This is useful for multi-tenant applications where\n * requests need to include tenant-specific information in the URL path.\n */\nexport class ResourceAttributionRequestInterceptor implements RequestInterceptor {\n\n readonly name = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME;\n readonly order = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER;\n private readonly tenantIdPathKey: string;\n private readonly ownerIdPathKey: string;\n private readonly tokenStorage: TokenStorage;\n\n /**\n * Creates a new ResourceAttributionRequestInterceptor\n * @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage\n */\n constructor({ tenantId = 'tenantId', ownerId = 'ownerId', tokenStorage }: ResourceAttributionOptions) {\n this.tenantIdPathKey = tenantId;\n this.ownerIdPathKey = ownerId;\n this.tokenStorage = tokenStorage;\n }\n\n /**\n * Intercepts outgoing requests and automatically adds tenant and owner ID path parameters\n * if they are defined in the URL template but not provided in the request.\n * @param exchange - The fetch exchange containing the request information\n */\n intercept(exchange: FetchExchange): void {\n const currentToken = this.tokenStorage.get();\n if (!currentToken) {\n return;\n }\n const principal = currentToken.access.payload;\n if (!principal) {\n return;\n }\n if (!principal.tenantId && !principal.sub) {\n return;\n }\n\n // Extract path parameters from the URL template\n const extractedPathParams = exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(exchange.request.url);\n const tenantIdPathKey = this.tenantIdPathKey;\n const requestPathParams = exchange.ensureRequestUrlParams().path;\n const tenantId = principal.tenantId;\n\n // Add tenant ID to path parameters if it's part of the URL template and not already provided\n if (tenantId && extractedPathParams.includes(tenantIdPathKey) && !requestPathParams[tenantIdPathKey]) {\n requestPathParams[tenantIdPathKey] = tenantId;\n }\n\n const ownerIdPathKey = this.ownerIdPathKey;\n const ownerId = principal.sub;\n\n // Add owner ID to path parameters if it's part of the URL template and not already provided\n if (ownerId && extractedPathParams.includes(ownerIdPathKey) && !requestPathParams[ownerIdPathKey]) {\n requestPathParams[ownerIdPathKey] = ownerId;\n }\n }\n\n}"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","error","a","n","r","o","i","h","c","u","g","w","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey"],"mappings":"0UAmBO,MAAMA,EAAN,MAAMA,CAAa,CAK1B,EAJEA,EAAgB,UAAY,kBAC5BA,EAAgB,OAAS,eACzBA,EAAgB,cAAgB,gBAChCA,EAAgB,WAAa,mBAJxB,IAAMC,EAAND,EAOA,MAAME,EAAN,MAAMA,CAAc,CAE3B,EADEA,EAAgB,aAAe,IAD1B,IAAMC,EAAND,EAgCA,MAAME,EAAmB,CAC9B,MAAO,CAAE,WAAY,GAAM,OAAQ,OAAA,EACnC,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,kBAAmB,CAAE,WAAY,GAAO,OAAQ,mBAAA,CAClD,ECzCO,MAAMC,CAAuC,CAMlD,YAAqB,CACnB,OAAOC,SAAA,CACT,CACF,CAEO,MAAMC,EAAc,IAAIF,ECVlBG,EAAiC,0BAMjCC,EACXC,EAAAA,+BAAiC,IAEtBC,EAAqC,uBAmB3C,MAAMC,CAAsD,CASjE,YAAYC,EAAuB,CARnC,KAAS,KAAOL,EAChB,KAAS,MAAQC,EAQf,KAAK,QAAUI,CACjB,CAyBA,MAAM,UAAUC,EAAyB,CAEvC,MAAMC,EAAYR,EAAY,WAAA,EAGxBS,EAAW,KAAK,QAAQ,gBAAgB,YAAA,EAGxCC,EAAiBH,EAAS,qBAAA,EAGhCG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,oBAAoB,kBAAkBA,EAAS,QAAQ,GAAG,EAC5G0D,EAAkB,KAAK,gBACvBC,EAAoB3D,EAAS,uBAAA,EAAyB,KACtDsD,EAAWE,EAAU,SAGvBF,GAAYG,EAAoB,SAASC,CAAe,GAAK,CAACC,EAAkBD,CAAe,IACjGC,EAAkBD,CAAe,EAAIJ,GAGvC,MAAMM,EAAiB,KAAK,eACtBL,EAAUC,EAAU,IAGtBD,GAAWE,EAAoB,SAASG,CAAc,GAAK,CAACD,EAAkBC,CAAc,IAC9FD,EAAkBC,CAAc,EAAIL,EAExC,CAEF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../../storage/dist/index.es.js","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/resourceAttributionRequestInterceptor.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\nexport interface AppIdCapable {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n}\n\nexport interface DeviceIdStorageCapable {\n deviceIdStorage: DeviceIdStorage;\n}\n\nexport interface JwtTokenManagerCapable {\n tokenManager: JwtTokenManager;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions extends AppIdCapable, DeviceIdStorageCapable, JwtTokenManagerCapable {\n\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { AppIdCapable, CoSecHeaders, DeviceIdStorageCapable } from './types';\nimport { idGenerator } from './idGenerator';\n\nexport interface CoSecRequestOptions extends AppIdCapable, DeviceIdStorageCapable {\n}\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecRequestOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecRequestOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { COSEC_REQUEST_INTERCEPTOR_ORDER, IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME = 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER = COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n async intercept(exchange: FetchExchange): Promise<void> {\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\nimport {\n AuthorizationInterceptorOptions,\n} from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME = 'AuthorizationResponseInterceptor';\n\n/**\n * The order of the AuthorizationResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class AuthorizationResponseInterceptor implements ResponseInterceptor {\n readonly name = AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER;\n private options: AuthorizationInterceptorOptions;\n\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: AuthorizationInterceptorOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","function a() {\n return typeof window < \"u\";\n}\nclass n {\n constructor() {\n this.store = /* @__PURE__ */ new Map(), this.listeners = /* @__PURE__ */ new Set();\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.store.size;\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.store.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n const t = this.store.get(e);\n return t !== void 0 ? t : null;\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return Array.from(this.store.keys())[e] || null;\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n const t = this.getItem(e);\n this.store.has(e) && (this.store.delete(e), this.notifyListeners({\n key: e,\n oldValue: t,\n newValue: null\n }));\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n const r = this.getItem(e);\n this.store.set(e, t), this.notifyListeners({ key: e, oldValue: r, newValue: t });\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n return this.listeners.add(e), () => this.listeners.delete(e);\n }\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n notifyListeners(e) {\n a() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {\n try {\n t(e);\n } catch (r) {\n console.error(\"Error in storage change listener:\", r);\n }\n });\n }\n}\nclass o {\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(e) {\n this.storage = e;\n }\n /**\n * Gets the number of items stored in the storage.\n */\n get length() {\n return this.storage.length;\n }\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(e) {\n const t = (r) => {\n r.storageArea === this.storage && e(r);\n };\n return window.addEventListener(i, t), () => window.removeEventListener(i, t);\n }\n /**\n * Clears all items from the storage.\n */\n clear() {\n this.storage.clear();\n }\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(e) {\n return this.storage.getItem(e);\n }\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(e) {\n return this.storage.key(e);\n }\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(e) {\n this.storage.removeItem(e);\n }\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(e, t) {\n this.storage.setItem(e, t);\n }\n}\nconst i = \"storage\", h = () => a() ? new o(window.localStorage) : new n();\nclass l {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(e) {\n return JSON.stringify(e);\n }\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize(e) {\n return JSON.parse(e);\n }\n}\nclass c {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(e) {\n return e;\n }\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(e) {\n return e;\n }\n}\nconst d = new l(), u = new c();\nfunction g() {\n return u;\n}\nclass w {\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(e) {\n this.cacheValue = null, this.refreshCacheListener = (t) => {\n this.cacheValue = null, t.newValue && this.refreshCache(t.newValue);\n }, this.key = e.key, this.serializer = e.serializer ?? g(), this.storage = e.storage ?? h(), this.addListener(this.refreshCacheListener);\n }\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n refreshCache(e) {\n this.cacheValue = this.serializer.deserialize(e);\n }\n addListener(e) {\n const t = (r) => {\n r.key === this.key && e(r);\n };\n return this.storage.addListener(t);\n }\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get() {\n if (this.cacheValue)\n return this.cacheValue;\n const e = this.storage.getItem(this.key);\n return e ? (this.refreshCache(e), this.cacheValue) : null;\n }\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(e) {\n const t = this.serializer.serialize(e);\n this.storage.setItem(this.key, t), this.cacheValue = e;\n }\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove() {\n this.storage.removeItem(this.key), this.cacheValue = null;\n }\n}\nexport {\n o as BrowserListenableStorage,\n c as IdentitySerializer,\n n as InMemoryListenableStorage,\n l as JsonSerializer,\n w as KeyStorage,\n i as STORAGE_EVENT_TYPE,\n h as createListenableStorage,\n u as identitySerializer,\n a as isBrowser,\n d as jsonSerializer,\n g as typedIdentitySerializer\n};\n//# sourceMappingURL=index.es.js.map\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, IdentitySerializer, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload | null;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload | null;\n\n /**\n * Creates a new JwtToken instance\n */\n constructor(\n public readonly token: string,\n public readonly earlyPeriod: number = 0,\n ) {\n this.payload = parseJwtPayload<Payload>(token);\n }\n\n /**\n * Checks if the token is expired\n * @returns true if the token is expired, false otherwise\n */\n get isExpired(): boolean {\n if (!this.payload) {\n return true;\n }\n return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, RequestInterceptor } from '@ahoo-wang/fetcher';\nimport { TokenStorage } from './tokenStorage';\n\n/**\n * Configuration options for resource attribution\n */\nexport interface ResourceAttributionOptions {\n /**\n * The path parameter key used for tenant ID in URL templates\n */\n tenantId?: string;\n /**\n * The path parameter key used for owner ID in URL templates\n */\n ownerId?: string;\n /**\n * Storage mechanism for retrieving current authentication tokens\n */\n tokenStorage: TokenStorage;\n}\n\n/**\n * Name identifier for the ResourceAttributionRequestInterceptor\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME = 'ResourceAttributionRequestInterceptor';\n/**\n * Order priority for the ResourceAttributionRequestInterceptor, set to maximum safe integer to ensure it runs last\n */\nexport const RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER = Number.MAX_SAFE_INTEGER;\n\n/**\n * Request interceptor that automatically adds tenant and owner ID path parameters to requests\n * based on the current authentication token. This is useful for multi-tenant applications where\n * requests need to include tenant-specific information in the URL path.\n */\nexport class ResourceAttributionRequestInterceptor implements RequestInterceptor {\n\n readonly name = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME;\n readonly order = RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER;\n private readonly tenantIdPathKey: string;\n private readonly ownerIdPathKey: string;\n private readonly tokenStorage: TokenStorage;\n\n /**\n * Creates a new ResourceAttributionRequestInterceptor\n * @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage\n */\n constructor({ tenantId = 'tenantId', ownerId = 'ownerId', tokenStorage }: ResourceAttributionOptions) {\n this.tenantIdPathKey = tenantId;\n this.ownerIdPathKey = ownerId;\n this.tokenStorage = tokenStorage;\n }\n\n /**\n * Intercepts outgoing requests and automatically adds tenant and owner ID path parameters\n * if they are defined in the URL template but not provided in the request.\n * @param exchange - The fetch exchange containing the request information\n */\n intercept(exchange: FetchExchange): void {\n const currentToken = this.tokenStorage.get();\n if (!currentToken) {\n return;\n }\n const principal = currentToken.access.payload;\n if (!principal) {\n return;\n }\n if (!principal.tenantId && !principal.sub) {\n return;\n }\n\n // Extract path parameters from the URL template\n const extractedPathParams = exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(exchange.request.url);\n const tenantIdPathKey = this.tenantIdPathKey;\n const requestPathParams = exchange.ensureRequestUrlParams().path;\n const tenantId = principal.tenantId;\n\n // Add tenant ID to path parameters if it's part of the URL template and not already provided\n if (tenantId && extractedPathParams.includes(tenantIdPathKey) && !requestPathParams[tenantIdPathKey]) {\n requestPathParams[tenantIdPathKey] = tenantId;\n }\n\n const ownerIdPathKey = this.ownerIdPathKey;\n const ownerId = principal.sub;\n\n // Add owner ID to path parameters if it's part of the URL template and not already provided\n if (ownerId && extractedPathParams.includes(ownerIdPathKey) && !requestPathParams[ownerIdPathKey]) {\n requestPathParams[ownerIdPathKey] = ownerId;\n }\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\nimport { createListenableStorage, KeyStorage } from '@ahoo-wang/fetcher-storage';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","a","n","r","o","i","h","c","u","g","w","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":"0UAmBO,MAAMA,EAAN,MAAMA,CAAa,CAK1B,EAJEA,EAAgB,UAAY,kBAC5BA,EAAgB,OAAS,eACzBA,EAAgB,cAAgB,gBAChCA,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,EAA4BL,CAAW,CAAA,CACxD,EANe,KAAA,YAAAA,CAOlB,CAEA,kBAAkBO,EAAgC,CAChD,KAAK,IACH,IAAIH,EAAkBG,CAAc,CAAA,CAExC,CACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -12,20 +12,23 @@ export declare class CoSecHeaders {
|
|
|
12
12
|
export declare class ResponseCodes {
|
|
13
13
|
static readonly UNAUTHORIZED = 401;
|
|
14
14
|
}
|
|
15
|
-
|
|
16
|
-
* CoSec options interface.
|
|
17
|
-
*/
|
|
18
|
-
export interface CoSecOptions {
|
|
15
|
+
export interface AppIdCapable {
|
|
19
16
|
/**
|
|
20
17
|
* Application ID to be sent in the CoSec-App-Id header.
|
|
21
18
|
*/
|
|
22
19
|
appId: string;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
*/
|
|
20
|
+
}
|
|
21
|
+
export interface DeviceIdStorageCapable {
|
|
26
22
|
deviceIdStorage: DeviceIdStorage;
|
|
23
|
+
}
|
|
24
|
+
export interface JwtTokenManagerCapable {
|
|
27
25
|
tokenManager: JwtTokenManager;
|
|
28
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* CoSec options interface.
|
|
29
|
+
*/
|
|
30
|
+
export interface CoSecOptions extends AppIdCapable, DeviceIdStorageCapable, JwtTokenManagerCapable {
|
|
31
|
+
}
|
|
29
32
|
/**
|
|
30
33
|
* Authorization result interface.
|
|
31
34
|
*/
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;GAEG;AACH,qBAAa,YAAY;IACvB,MAAM,CAAC,QAAQ,CAAC,SAAS,qBAAqB;IAC9C,MAAM,CAAC,QAAQ,CAAC,MAAM,kBAAkB;IACxC,MAAM,CAAC,QAAQ,CAAC,aAAa,mBAAmB;IAChD,MAAM,CAAC,QAAQ,CAAC,UAAU,sBAAsB;CACjD;AAED,qBAAa,aAAa;IACxB,MAAM,CAAC,QAAQ,CAAC,YAAY,OAAO;CACpC;AAED
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEpD;;GAEG;AACH,qBAAa,YAAY;IACvB,MAAM,CAAC,QAAQ,CAAC,SAAS,qBAAqB;IAC9C,MAAM,CAAC,QAAQ,CAAC,MAAM,kBAAkB;IACxC,MAAM,CAAC,QAAQ,CAAC,aAAa,mBAAmB;IAChD,MAAM,CAAC,QAAQ,CAAC,UAAU,sBAAsB;CACjD;AAED,qBAAa,aAAa;IACxB,MAAM,CAAC,QAAQ,CAAC,YAAY,OAAO;CACpC;AAED,MAAM,WAAW,YAAY;IAC3B;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,sBAAsB;IACrC,eAAe,EAAE,eAAe,CAAC;CAClC;AAED,MAAM,WAAW,sBAAsB;IACrC,YAAY,EAAE,eAAe,CAAC;CAC/B;AAED;;GAEG;AACH,MAAM,WAAW,YAAa,SAAQ,YAAY,EAAE,sBAAsB,EAAE,sBAAsB;CAEjG;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,OAAO,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;CAM5B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-cosec",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.3",
|
|
4
4
|
"description": "CoSec authentication integration for Fetcher HTTP client with enterprise-grade security features. Provides automatic token management, device ID persistence, and request tracking.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"fetch",
|
|
@@ -40,8 +40,8 @@
|
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"nanoid": "^5.1.5",
|
|
43
|
-
"@ahoo-wang/fetcher": "1.8.
|
|
44
|
-
"@ahoo-wang/fetcher-storage": "1.8.
|
|
43
|
+
"@ahoo-wang/fetcher": "1.8.3",
|
|
44
|
+
"@ahoo-wang/fetcher-storage": "1.8.3"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
47
|
"@vitest/coverage-v8": "^3.2.4",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cosecResponseInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecResponseInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,KAAK,YAAY,EAAiB,MAAM,SAAS,CAAC;AAC3D,OAAO,EAAE,aAAa,EAAE,KAAK,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE7E;;GAEG;AACH,eAAO,MAAM,+BAA+B,6BAA6B,CAAC;AAE1E;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAiC,CAAC;AAE/E;;;;;;;;;GASG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAClE,QAAQ,CAAC,IAAI,8BAAmC;IAChD,QAAQ,CAAC,KAAK,SAAoC;IAClD,OAAO,CAAC,OAAO,CAAe;IAE9B;;;OAGG;gBACS,OAAO,EAAE,YAAY;IAIjC;;;OAGG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CAyBxD"}
|