@ahoo-wang/fetcher-cosec 2.8.8 → 2.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/deviceIdStorage.d.ts +4 -2
- package/dist/deviceIdStorage.d.ts.map +1 -1
- package/dist/index.es.js +78 -74
- 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/jwts.d.ts.map +1 -1
- package/dist/tokenStorage.d.ts +5 -2
- package/dist/tokenStorage.d.ts.map +1 -1
- package/package.json +2 -1
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { KeyStorage } from '@ahoo-wang/fetcher-storage';
|
|
1
|
+
import { KeyStorage, KeyStorageOptions } from '@ahoo-wang/fetcher-storage';
|
|
2
2
|
export declare const DEFAULT_COSEC_DEVICE_ID_KEY = "cosec-device-id";
|
|
3
|
+
export interface DeviceIdStorageOptions extends KeyStorageOptions<string> {
|
|
4
|
+
}
|
|
3
5
|
/**
|
|
4
6
|
* Storage class for managing device identifiers.
|
|
5
7
|
*/
|
|
6
8
|
export declare class DeviceIdStorage extends KeyStorage<string> {
|
|
7
|
-
constructor(
|
|
9
|
+
constructor(options?: DeviceIdStorageOptions);
|
|
8
10
|
/**
|
|
9
11
|
* Generate a new device ID.
|
|
10
12
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deviceIdStorage.d.ts","sourceRoot":"","sources":["../src/deviceIdStorage.ts"],"names":[],"mappings":"AAcA,OAAO,
|
|
1
|
+
{"version":3,"file":"deviceIdStorage.d.ts","sourceRoot":"","sources":["../src/deviceIdStorage.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,UAAU,EAAE,iBAAiB,EAC9B,MAAM,4BAA4B,CAAC;AAGpC,eAAO,MAAM,2BAA2B,oBAAoB,CAAC;AAG7D,MAAM,WAAW,sBAAuB,SAAQ,iBAAiB,CAAC,MAAM,CAAC;CACxE;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,UAAU,CAAC,MAAM,CAAC;gBACzC,OAAO,GAAE,sBAGpB;IAID;;;;OAIG;IACH,gBAAgB,IAAI,MAAM;IAI1B;;;;OAIG;IACH,WAAW,IAAI,MAAM;CAWtB"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { REQUEST_BODY_INTERCEPTOR_ORDER as
|
|
2
|
-
import { nanoid as
|
|
3
|
-
import { KeyStorage as
|
|
1
|
+
import { REQUEST_BODY_INTERCEPTOR_ORDER as S, ResultExtractors as y } from "@ahoo-wang/fetcher";
|
|
2
|
+
import { nanoid as w } from "nanoid";
|
|
3
|
+
import { KeyStorage as p } from "@ahoo-wang/fetcher-storage";
|
|
4
|
+
import { BroadcastTypedEventBus as f, SerialTypedEventBus as O } from "@ahoo-wang/fetcher-eventbus";
|
|
4
5
|
const a = class a {
|
|
5
6
|
};
|
|
6
7
|
a.DEVICE_ID = "CoSec-Device-Id", a.APP_ID = "CoSec-App-Id", a.AUTHORIZATION = "Authorization", a.REQUEST_ID = "CoSec-Request-Id";
|
|
@@ -16,24 +17,24 @@ const Q = {
|
|
|
16
17
|
TOKEN_EXPIRED: { authorized: !1, reason: "Token Expired" },
|
|
17
18
|
TOO_MANY_REQUESTS: { authorized: !1, reason: "Too Many Requests" }
|
|
18
19
|
};
|
|
19
|
-
class
|
|
20
|
+
class C {
|
|
20
21
|
/**
|
|
21
22
|
* Generate a unique request ID.
|
|
22
23
|
*
|
|
23
24
|
* @returns A unique request ID
|
|
24
25
|
*/
|
|
25
26
|
generateId() {
|
|
26
|
-
return
|
|
27
|
+
return w();
|
|
27
28
|
}
|
|
28
29
|
}
|
|
29
|
-
const
|
|
30
|
+
const _ = new C(), U = "CoSecRequestInterceptor", N = S + 1e3, g = "Ignore-Refresh-Token";
|
|
30
31
|
class H {
|
|
31
32
|
/**
|
|
32
33
|
* Creates a new CoSecRequestInterceptor instance.
|
|
33
34
|
* @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager
|
|
34
35
|
*/
|
|
35
36
|
constructor(e) {
|
|
36
|
-
this.name =
|
|
37
|
+
this.name = U, this.order = N, this.options = e;
|
|
37
38
|
}
|
|
38
39
|
/**
|
|
39
40
|
* Intercept requests to add CoSec authentication headers.
|
|
@@ -58,11 +59,11 @@ class H {
|
|
|
58
59
|
* It will attempt to refresh the token before adding the Authorization header to the request.
|
|
59
60
|
*/
|
|
60
61
|
async intercept(e) {
|
|
61
|
-
const t =
|
|
62
|
+
const t = _.generateId(), r = this.options.deviceIdStorage.getOrCreate(), n = e.ensureRequestHeaders();
|
|
62
63
|
n[o.APP_ID] = this.options.appId, n[o.DEVICE_ID] = r, n[o.REQUEST_ID] = t;
|
|
63
64
|
}
|
|
64
65
|
}
|
|
65
|
-
const
|
|
66
|
+
const m = "AuthorizationRequestInterceptor", D = N + 1e3;
|
|
66
67
|
class Z {
|
|
67
68
|
/**
|
|
68
69
|
* Creates an AuthorizationRequestInterceptor instance.
|
|
@@ -70,7 +71,7 @@ class Z {
|
|
|
70
71
|
* @param options - Configuration options containing the token manager
|
|
71
72
|
*/
|
|
72
73
|
constructor(e) {
|
|
73
|
-
this.options = e, this.name =
|
|
74
|
+
this.options = e, this.name = m, this.order = D;
|
|
74
75
|
}
|
|
75
76
|
/**
|
|
76
77
|
* Intercepts the request exchange to add authorization headers.
|
|
@@ -86,17 +87,17 @@ class Z {
|
|
|
86
87
|
async intercept(e) {
|
|
87
88
|
let t = this.options.tokenManager.currentToken;
|
|
88
89
|
const r = e.ensureRequestHeaders();
|
|
89
|
-
!t || r[o.AUTHORIZATION] || (!e.attributes.has(
|
|
90
|
+
!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}`));
|
|
90
91
|
}
|
|
91
92
|
}
|
|
92
|
-
const
|
|
93
|
-
class
|
|
93
|
+
const b = "AuthorizationResponseInterceptor", M = Number.MIN_SAFE_INTEGER + 1e3;
|
|
94
|
+
class Y {
|
|
94
95
|
/**
|
|
95
96
|
* Creates a new AuthorizationResponseInterceptor instance.
|
|
96
97
|
* @param options - The CoSec configuration options including token storage and refresher
|
|
97
98
|
*/
|
|
98
99
|
constructor(e) {
|
|
99
|
-
this.name =
|
|
100
|
+
this.name = b, this.order = M, this.options = e;
|
|
100
101
|
}
|
|
101
102
|
/**
|
|
102
103
|
* Intercepts the response and handles unauthorized responses by refreshing tokens.
|
|
@@ -112,14 +113,13 @@ class B {
|
|
|
112
113
|
}
|
|
113
114
|
}
|
|
114
115
|
}
|
|
115
|
-
const
|
|
116
|
-
class
|
|
117
|
-
constructor(e =
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
});
|
|
116
|
+
const T = "cosec-device-id";
|
|
117
|
+
class F extends p {
|
|
118
|
+
constructor(e = {
|
|
119
|
+
key: T,
|
|
120
|
+
eventBus: new f(new O(T))
|
|
121
|
+
}) {
|
|
122
|
+
super(e);
|
|
123
123
|
}
|
|
124
124
|
/**
|
|
125
125
|
* Generate a new device ID.
|
|
@@ -127,7 +127,7 @@ class L extends d {
|
|
|
127
127
|
* @returns A newly generated device ID
|
|
128
128
|
*/
|
|
129
129
|
generateDeviceId() {
|
|
130
|
-
return
|
|
130
|
+
return _.generateId();
|
|
131
131
|
}
|
|
132
132
|
/**
|
|
133
133
|
* Get or create a device ID.
|
|
@@ -139,8 +139,10 @@ class L extends d {
|
|
|
139
139
|
return e || (e = this.generateDeviceId(), this.set(e)), e;
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
-
function
|
|
142
|
+
function A(s) {
|
|
143
143
|
try {
|
|
144
|
+
if (typeof s != "string")
|
|
145
|
+
return null;
|
|
144
146
|
const e = s.split(".");
|
|
145
147
|
if (e.length !== 3)
|
|
146
148
|
return null;
|
|
@@ -157,34 +159,34 @@ function _(s) {
|
|
|
157
159
|
return console.error("Failed to parse JWT token", e), null;
|
|
158
160
|
}
|
|
159
161
|
}
|
|
160
|
-
function
|
|
161
|
-
const t = typeof s == "string" ?
|
|
162
|
+
function q(s, e = 0) {
|
|
163
|
+
const t = typeof s == "string" ? A(s) : s;
|
|
162
164
|
if (!t)
|
|
163
165
|
return !0;
|
|
164
166
|
const r = t.exp;
|
|
165
167
|
return r ? Date.now() / 1e3 > r - e : !1;
|
|
166
168
|
}
|
|
167
|
-
class
|
|
169
|
+
class d {
|
|
168
170
|
/**
|
|
169
171
|
* Creates a new JwtToken instance
|
|
170
172
|
*/
|
|
171
173
|
constructor(e, t = 0) {
|
|
172
|
-
this.token = e, this.earlyPeriod = t, this.payload =
|
|
174
|
+
this.token = e, this.earlyPeriod = t, this.payload = A(e);
|
|
173
175
|
}
|
|
174
176
|
/**
|
|
175
177
|
* Checks if the token is expired
|
|
176
178
|
* @returns true if the token is expired, false otherwise
|
|
177
179
|
*/
|
|
178
180
|
get isExpired() {
|
|
179
|
-
return this.payload ?
|
|
181
|
+
return this.payload ? q(this.payload, this.earlyPeriod) : !0;
|
|
180
182
|
}
|
|
181
183
|
}
|
|
182
|
-
class
|
|
184
|
+
class P {
|
|
183
185
|
/**
|
|
184
186
|
* Creates a new JwtCompositeToken instance
|
|
185
187
|
*/
|
|
186
188
|
constructor(e, t = 0) {
|
|
187
|
-
this.token = e, this.earlyPeriod = t, this.access = new
|
|
189
|
+
this.token = e, this.earlyPeriod = t, this.access = new d(e.accessToken, t), this.refresh = new d(e.refreshToken, t);
|
|
188
190
|
}
|
|
189
191
|
/**
|
|
190
192
|
* Checks if the access token needs to be refreshed
|
|
@@ -201,7 +203,7 @@ class g {
|
|
|
201
203
|
return !this.refresh.isExpired;
|
|
202
204
|
}
|
|
203
205
|
}
|
|
204
|
-
class
|
|
206
|
+
class k {
|
|
205
207
|
constructor(e = 0) {
|
|
206
208
|
this.earlyPeriod = e;
|
|
207
209
|
}
|
|
@@ -212,7 +214,7 @@ class N {
|
|
|
212
214
|
*/
|
|
213
215
|
deserialize(e) {
|
|
214
216
|
const t = JSON.parse(e);
|
|
215
|
-
return new
|
|
217
|
+
return new P(t, this.earlyPeriod);
|
|
216
218
|
}
|
|
217
219
|
/**
|
|
218
220
|
* Serializes a JwtCompositeToken to a JSON string
|
|
@@ -223,8 +225,8 @@ class N {
|
|
|
223
225
|
return JSON.stringify(e.token);
|
|
224
226
|
}
|
|
225
227
|
}
|
|
226
|
-
const
|
|
227
|
-
class
|
|
228
|
+
const L = new k();
|
|
229
|
+
class G {
|
|
228
230
|
/**
|
|
229
231
|
* Creates a new JwtTokenManager instance
|
|
230
232
|
* @param tokenStorage The storage used to persist tokens
|
|
@@ -276,8 +278,8 @@ class F {
|
|
|
276
278
|
return this.currentToken ? this.currentToken.isRefreshable : !1;
|
|
277
279
|
}
|
|
278
280
|
}
|
|
279
|
-
const
|
|
280
|
-
class
|
|
281
|
+
const v = "ResourceAttributionRequestInterceptor", z = Number.MAX_SAFE_INTEGER;
|
|
282
|
+
class j {
|
|
281
283
|
/**
|
|
282
284
|
* Creates a new ResourceAttributionRequestInterceptor
|
|
283
285
|
* @param options - Configuration options for resource attribution including tenantId, ownerId and tokenStorage
|
|
@@ -287,7 +289,7 @@ class G {
|
|
|
287
289
|
ownerId: t = "ownerId",
|
|
288
290
|
tokenStorage: r
|
|
289
291
|
}) {
|
|
290
|
-
this.name =
|
|
292
|
+
this.name = v, this.order = z, this.tenantIdPathKey = e, this.ownerIdPathKey = t, this.tokenStorage = r;
|
|
291
293
|
}
|
|
292
294
|
/**
|
|
293
295
|
* Intercepts outgoing requests and automatically adds tenant and owner ID path parameters
|
|
@@ -309,7 +311,7 @@ class G {
|
|
|
309
311
|
R && n.includes(h) && !i[h] && (i[h] = R);
|
|
310
312
|
}
|
|
311
313
|
}
|
|
312
|
-
class
|
|
314
|
+
class V {
|
|
313
315
|
/**
|
|
314
316
|
* Creates a new instance of CoSecTokenRefresher.
|
|
315
317
|
*
|
|
@@ -331,55 +333,57 @@ class j {
|
|
|
331
333
|
body: e
|
|
332
334
|
},
|
|
333
335
|
{
|
|
334
|
-
resultExtractor:
|
|
335
|
-
attributes: /* @__PURE__ */ new Map([[
|
|
336
|
+
resultExtractor: y.Json,
|
|
337
|
+
attributes: /* @__PURE__ */ new Map([[g, !0]])
|
|
336
338
|
}
|
|
337
339
|
);
|
|
338
340
|
}
|
|
339
341
|
}
|
|
340
|
-
const
|
|
341
|
-
class
|
|
342
|
-
constructor(e =
|
|
342
|
+
const l = "cosec-token";
|
|
343
|
+
class X extends p {
|
|
344
|
+
constructor(e = {
|
|
345
|
+
key: l,
|
|
346
|
+
eventBus: new f(new O(l))
|
|
347
|
+
}) {
|
|
343
348
|
super({
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
}), this.earlyPeriod = t;
|
|
349
|
+
serializer: new k(e.earlyPeriod),
|
|
350
|
+
...e
|
|
351
|
+
}), this.earlyPeriod = e.earlyPeriod ?? 0;
|
|
348
352
|
}
|
|
349
353
|
setCompositeToken(e) {
|
|
350
|
-
this.set(new
|
|
354
|
+
this.set(new P(e));
|
|
351
355
|
}
|
|
352
356
|
}
|
|
353
357
|
export {
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
+
m as AUTHORIZATION_REQUEST_INTERCEPTOR_NAME,
|
|
359
|
+
D as AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER,
|
|
360
|
+
b as AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME,
|
|
361
|
+
M as AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER,
|
|
358
362
|
Z as AuthorizationRequestInterceptor,
|
|
359
|
-
|
|
363
|
+
Y as AuthorizationResponseInterceptor,
|
|
360
364
|
Q as AuthorizeResults,
|
|
361
|
-
|
|
362
|
-
|
|
365
|
+
U as COSEC_REQUEST_INTERCEPTOR_NAME,
|
|
366
|
+
N as COSEC_REQUEST_INTERCEPTOR_ORDER,
|
|
363
367
|
o as CoSecHeaders,
|
|
364
368
|
H as CoSecRequestInterceptor,
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
369
|
+
V as CoSecTokenRefresher,
|
|
370
|
+
T as DEFAULT_COSEC_DEVICE_ID_KEY,
|
|
371
|
+
l as DEFAULT_COSEC_TOKEN_KEY,
|
|
372
|
+
F as DeviceIdStorage,
|
|
373
|
+
g as IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,
|
|
374
|
+
P as JwtCompositeToken,
|
|
375
|
+
k as JwtCompositeTokenSerializer,
|
|
376
|
+
d as JwtToken,
|
|
377
|
+
G as JwtTokenManager,
|
|
378
|
+
C as NanoIdGenerator,
|
|
379
|
+
v as RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME,
|
|
380
|
+
z as RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER,
|
|
381
|
+
j as ResourceAttributionRequestInterceptor,
|
|
378
382
|
u as ResponseCodes,
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
383
|
+
X as TokenStorage,
|
|
384
|
+
_ as idGenerator,
|
|
385
|
+
q as isTokenExpired,
|
|
386
|
+
L as jwtCompositeTokenSerializer,
|
|
387
|
+
A as parseJwtPayload
|
|
384
388
|
};
|
|
385
389
|
//# 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/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../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\n extends AppIdCapable,\n DeviceIdStorageCapable,\n JwtTokenManagerCapable {\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\n extends AppIdCapable,\n 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 {\n COSEC_REQUEST_INTERCEPTOR_ORDER,\n IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,\n} from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions\n extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME =\n 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER =\n COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\n/**\n * Request interceptor that automatically adds Authorization header to requests.\n *\n * This interceptor handles JWT token management by:\n * 1. Adding Authorization header with Bearer token if not already present\n * 2. Refreshing tokens when needed and possible\n * 3. Skipping refresh when explicitly requested via attributes\n *\n * The interceptor runs after CoSecRequestInterceptor but before FetchInterceptor in the chain.\n */\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n /**\n * Creates an AuthorizationRequestInterceptor instance.\n *\n * @param options - Configuration options containing the token manager\n */\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n /**\n * Intercepts the request exchange to add authorization headers.\n *\n * This method performs the following operations:\n * 1. Checks if a token exists and if Authorization header is already set\n * 2. Refreshes the token if needed, possible, and not explicitly ignored\n * 3. Adds the Authorization header with Bearer token if a token is available\n *\n * @param exchange - The fetch exchange containing request information\n * @returns Promise that resolves when the interception is complete\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 (\n !exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) &&\n currentToken.isRefreshNeeded &&\n currentToken.isRefreshable\n ) {\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] =\n `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 { AuthorizationInterceptorOptions } from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME =\n '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 =\n 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","/*\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 {\n createListenableStorage,\n IdentitySerializer,\n KeyStorage,\n} 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 * 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 {\n CoSecJwtPayload,\n EarlyPeriodCapable,\n isTokenExpired,\n JwtPayload,\n parseJwtPayload,\n} from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\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>\n 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>\n 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\n 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(\n public readonly token: CompositeToken,\n public readonly earlyPeriod: number = 0,\n ) {\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 * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer\n 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","/*\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 * 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\n .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 =\n '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 =\n 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\n implements RequestInterceptor {\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({\n tenantId = 'tenantId',\n ownerId = 'ownerId',\n tokenStorage,\n }: 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 =\n exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(\n exchange.request.url,\n );\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 (\n tenantId &&\n extractedPathParams.includes(tenantIdPathKey) &&\n !requestPathParams[tenantIdPathKey]\n ) {\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 (\n ownerId &&\n extractedPathParams.includes(ownerIdPathKey) &&\n !requestPathParams[ownerIdPathKey]\n ) {\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>(\n this.options.endpoint,\n {\n body: token,\n },\n {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\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 {\n createListenableStorage,\n KeyStorage,\n} 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\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable {\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(new JwtCompositeToken(compositeToken));\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","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","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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B,GACtC;AACA,UAAM;AAAA,MACJ,KAAAX;AAAA,MACA,SAASE,EAAA;AAAA,MACT,YAAY,IAAIc,EAA4BL,CAAW;AAAA,IAAA,CACxD,GANe,KAAA,cAAAA;AAAA,EAOlB;AAAA,EAEA,kBAAkBO,GAAgC;AAChD,SAAK,IAAI,IAAIH,EAAkBG,CAAc,CAAC;AAAA,EAChD;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../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\n extends AppIdCapable,\n DeviceIdStorageCapable,\n JwtTokenManagerCapable {\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\n extends AppIdCapable,\n 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 {\n COSEC_REQUEST_INTERCEPTOR_ORDER,\n IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,\n} from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions\n extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME =\n 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER =\n COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\n/**\n * Request interceptor that automatically adds Authorization header to requests.\n *\n * This interceptor handles JWT token management by:\n * 1. Adding Authorization header with Bearer token if not already present\n * 2. Refreshing tokens when needed and possible\n * 3. Skipping refresh when explicitly requested via attributes\n *\n * The interceptor runs after CoSecRequestInterceptor but before FetchInterceptor in the chain.\n */\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n /**\n * Creates an AuthorizationRequestInterceptor instance.\n *\n * @param options - Configuration options containing the token manager\n */\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n /**\n * Intercepts the request exchange to add authorization headers.\n *\n * This method performs the following operations:\n * 1. Checks if a token exists and if Authorization header is already set\n * 2. Refreshes the token if needed, possible, and not explicitly ignored\n * 3. Adds the Authorization header with Bearer token if a token is available\n *\n * @param exchange - The fetch exchange containing request information\n * @returns Promise that resolves when the interception is complete\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 (\n !exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) &&\n currentToken.isRefreshNeeded &&\n currentToken.isRefreshable\n ) {\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] =\n `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 { AuthorizationInterceptorOptions } from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME =\n '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 =\n 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","/*\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 {\n KeyStorage, KeyStorageOptions,\n} from '@ahoo-wang/fetcher-storage';\nimport { BroadcastTypedEventBus, SerialTypedEventBus } from '@ahoo-wang/fetcher-eventbus';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface DeviceIdStorageOptions extends KeyStorageOptions<string> {\n}\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(options: DeviceIdStorageOptions = {\n key: DEFAULT_COSEC_DEVICE_ID_KEY,\n eventBus: new BroadcastTypedEventBus(new SerialTypedEventBus(DEFAULT_COSEC_DEVICE_ID_KEY)),\n }) {\n super(options);\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 * 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 if (typeof token !== 'string') {\n return null;\n }\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 {\n CoSecJwtPayload,\n EarlyPeriodCapable,\n isTokenExpired,\n JwtPayload,\n parseJwtPayload,\n} from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\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>\n 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>\n 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\n 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(\n public readonly token: CompositeToken,\n public readonly earlyPeriod: number = 0,\n ) {\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 * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer\n 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","/*\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 * 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\n .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 =\n '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 =\n 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\n implements RequestInterceptor {\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({\n tenantId = 'tenantId',\n ownerId = 'ownerId',\n tokenStorage,\n }: 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 =\n exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(\n exchange.request.url,\n );\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 (\n tenantId &&\n extractedPathParams.includes(tenantIdPathKey) &&\n !requestPathParams[tenantIdPathKey]\n ) {\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 (\n ownerId &&\n extractedPathParams.includes(ownerIdPathKey) &&\n !requestPathParams[ownerIdPathKey]\n ) {\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>(\n this.options.endpoint,\n {\n body: token,\n },\n {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\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 {\n KeyStorage, KeyStorageOptions,\n} from '@ahoo-wang/fetcher-storage';\nimport { PartialBy } from '@ahoo-wang/fetcher';\nimport { BroadcastTypedEventBus, SerialTypedEventBus } from '@ahoo-wang/fetcher-eventbus';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\nexport interface TokenStorageOptions extends Omit<KeyStorageOptions<JwtCompositeToken>, 'serializer'>, PartialBy<EarlyPeriodCapable, 'earlyPeriod'> {\n\n}\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable {\n public readonly earlyPeriod: number;\n\n constructor(\n options: TokenStorageOptions = {\n key: DEFAULT_COSEC_TOKEN_KEY,\n eventBus: new BroadcastTypedEventBus(new SerialTypedEventBus(DEFAULT_COSEC_TOKEN_KEY)),\n },\n ) {\n super({\n serializer: new JwtCompositeTokenSerializer(options.earlyPeriod),\n ...options,\n });\n this.earlyPeriod = options.earlyPeriod ?? 0;\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(new JwtCompositeToken(compositeToken));\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","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","BroadcastTypedEventBus","SerialTypedEventBus","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","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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EAEA,kBAAkBkC,GAAgC;AAChD,SAAK,IAAI,IAAIH,EAAkBG,CAAc,CAAC;AAAA,EAChD;AACF;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(t,a){typeof exports=="object"&&typeof module<"u"?a(exports,require("@ahoo-wang/fetcher"),require("nanoid"),require("@ahoo-wang/fetcher-storage"),require("@ahoo-wang/fetcher-eventbus")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid","@ahoo-wang/fetcher-storage","@ahoo-wang/fetcher-eventbus"],a):(t=typeof globalThis<"u"?globalThis:t||self,a(t.FetcherCoSec={},t.Fetcher,t.nanoid,t.FetcherStorage,t.FetcherEventBus))})(this,(function(t,a,v,C,R){"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 p=class p{};p.UNAUTHORIZED=401;let h=p;const B={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 P{generateId(){return v.nanoid()}}const u=new P,g="CoSecRequestInterceptor",I=a.REQUEST_BODY_INTERCEPTOR_ORDER+1e3,d="Ignore-Refresh-Token";class K{constructor(e){this.name=g,this.order=I,this.options=e}async intercept(e){const r=u.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]=r}}const k="AuthorizationRequestInterceptor",U=I+1e3;class b{constructor(e){this.options=e,this.name=k,this.order=U}async intercept(e){let r=this.options.tokenManager.currentToken;const s=e.ensureRequestHeaders();!r||s[i.AUTHORIZATION]||(!e.attributes.has(d)&&r.isRefreshNeeded&&r.isRefreshable&&await this.options.tokenManager.refresh(),r=this.options.tokenManager.currentToken,r&&(s[i.AUTHORIZATION]=`Bearer ${r.access.token}`))}}const w="AuthorizationResponseInterceptor",y=Number.MIN_SAFE_INTEGER+1e3;class Q{constructor(e){this.name=w,this.order=y,this.options=e}async intercept(e){const r=e.response;if(r&&r.status===h.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}}}const _="cosec-device-id";class H extends C.KeyStorage{constructor(e={key:_,eventBus:new R.BroadcastTypedEventBus(new R.SerialTypedEventBus(_))}){super(e)}generateDeviceId(){return u.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}}function O(n){try{if(typeof n!="string")return null;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,"="),T=decodeURIComponent(atob(o).split("").map(function(E){return"%"+("00"+E.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(T)}catch(e){return console.error("Failed to parse JWT token",e),null}}function D(n,e=0){const r=typeof n=="string"?O(n):n;if(!r)return!0;const s=r.exp;return s?Date.now()/1e3>s-e:!1}class l{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.payload=O(e)}get isExpired(){return this.payload?D(this.payload,this.earlyPeriod):!0}}class f{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.access=new l(e.accessToken,r),this.refresh=new l(e.refreshToken,r)}get isRefreshNeeded(){return this.access.isExpired}get isRefreshable(){return!this.refresh.isExpired}}class S{constructor(e=0){this.earlyPeriod=e}deserialize(e){const r=JSON.parse(e);return new f(r,this.earlyPeriod)}serialize(e){return JSON.stringify(e.token)}}const J=new S;class F{constructor(e,r){this.tokenStorage=e,this.tokenRefresher=r}get currentToken(){return this.tokenStorage.get()}async refresh(e){if(!e){const r=this.currentToken;if(!r)throw new Error("No token found");e=r.token}return this.refreshInProgress?this.refreshInProgress:(this.refreshInProgress=this.tokenRefresher.refresh(e).then(r=>{this.tokenStorage.setCompositeToken(r)}).catch(r=>{throw this.tokenStorage.remove(),r}).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",q=Number.MAX_SAFE_INTEGER;class Z{constructor({tenantId:e="tenantId",ownerId:r="ownerId",tokenStorage:s}){this.name=m,this.order=q,this.tenantIdPathKey=e,this.ownerIdPathKey=r,this.tokenStorage=s}intercept(e){const r=this.tokenStorage.get();if(!r)return;const s=r.access.payload;if(!s||!s.tenantId&&!s.sub)return;const o=e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url),T=this.tenantIdPathKey,E=e.ensureRequestUrlParams().path,M=s.tenantId;M&&o.includes(T)&&!E[T]&&(E[T]=M);const A=this.ownerIdPathKey,z=s.sub;z&&o.includes(A)&&!E[A]&&(E[A]=z)}}class Y{constructor(e){this.options=e}refresh(e){return this.options.fetcher.post(this.options.endpoint,{body:e},{resultExtractor:a.ResultExtractors.Json,attributes:new Map([[d,!0]])})}}const N="cosec-token";class G extends C.KeyStorage{constructor(e={key:N,eventBus:new R.BroadcastTypedEventBus(new R.SerialTypedEventBus(N))}){super({serializer:new S(e.earlyPeriod),...e}),this.earlyPeriod=e.earlyPeriod??0}setCompositeToken(e){this.set(new f(e))}}t.AUTHORIZATION_REQUEST_INTERCEPTOR_NAME=k,t.AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER=U,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME=w,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER=y,t.AuthorizationRequestInterceptor=b,t.AuthorizationResponseInterceptor=Q,t.AuthorizeResults=B,t.COSEC_REQUEST_INTERCEPTOR_NAME=g,t.COSEC_REQUEST_INTERCEPTOR_ORDER=I,t.CoSecHeaders=i,t.CoSecRequestInterceptor=K,t.CoSecTokenRefresher=Y,t.DEFAULT_COSEC_DEVICE_ID_KEY=_,t.DEFAULT_COSEC_TOKEN_KEY=N,t.DeviceIdStorage=H,t.IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY=d,t.JwtCompositeToken=f,t.JwtCompositeTokenSerializer=S,t.JwtToken=l,t.JwtTokenManager=F,t.NanoIdGenerator=P,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME=m,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER=q,t.ResourceAttributionRequestInterceptor=Z,t.ResponseCodes=h,t.TokenStorage=G,t.idGenerator=u,t.isTokenExpired=D,t.jwtCompositeTokenSerializer=J,t.parseJwtPayload=O,Object.defineProperty(t,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/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../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\n extends AppIdCapable,\n DeviceIdStorageCapable,\n JwtTokenManagerCapable {\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\n extends AppIdCapable,\n 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 {\n COSEC_REQUEST_INTERCEPTOR_ORDER,\n IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,\n} from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions\n extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME =\n 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER =\n COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\n/**\n * Request interceptor that automatically adds Authorization header to requests.\n *\n * This interceptor handles JWT token management by:\n * 1. Adding Authorization header with Bearer token if not already present\n * 2. Refreshing tokens when needed and possible\n * 3. Skipping refresh when explicitly requested via attributes\n *\n * The interceptor runs after CoSecRequestInterceptor but before FetchInterceptor in the chain.\n */\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n /**\n * Creates an AuthorizationRequestInterceptor instance.\n *\n * @param options - Configuration options containing the token manager\n */\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n /**\n * Intercepts the request exchange to add authorization headers.\n *\n * This method performs the following operations:\n * 1. Checks if a token exists and if Authorization header is already set\n * 2. Refreshes the token if needed, possible, and not explicitly ignored\n * 3. Adds the Authorization header with Bearer token if a token is available\n *\n * @param exchange - The fetch exchange containing request information\n * @returns Promise that resolves when the interception is complete\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 (\n !exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) &&\n currentToken.isRefreshNeeded &&\n currentToken.isRefreshable\n ) {\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] =\n `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 { AuthorizationInterceptorOptions } from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME =\n '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 =\n 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","/*\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 {\n createListenableStorage,\n IdentitySerializer,\n KeyStorage,\n} 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 * 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 {\n CoSecJwtPayload,\n EarlyPeriodCapable,\n isTokenExpired,\n JwtPayload,\n parseJwtPayload,\n} from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\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>\n 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>\n 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\n 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(\n public readonly token: CompositeToken,\n public readonly earlyPeriod: number = 0,\n ) {\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 * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer\n 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","/*\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 * 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\n .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 =\n '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 =\n 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\n implements RequestInterceptor {\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({\n tenantId = 'tenantId',\n ownerId = 'ownerId',\n tokenStorage,\n }: 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 =\n exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(\n exchange.request.url,\n );\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 (\n tenantId &&\n extractedPathParams.includes(tenantIdPathKey) &&\n !requestPathParams[tenantIdPathKey]\n ) {\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 (\n ownerId &&\n extractedPathParams.includes(ownerIdPathKey) &&\n !requestPathParams[ownerIdPathKey]\n ) {\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>(\n this.options.endpoint,\n {\n body: token,\n },\n {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\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 {\n createListenableStorage,\n KeyStorage,\n} 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\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable {\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(new JwtCompositeToken(compositeToken));\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","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","IdentitySerializer","createListenableStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","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":"gaAmBO,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,EAuCA,MAAME,EAAmB,CAC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EfgD,EAAkB,KAAK,gBACvBC,EAAoBjD,EAAS,uBAAA,EAAyB,KACtD4C,EAAWE,EAAU,SAIzBF,GACAG,EAAoB,SAASC,CAAe,GAC5C,CAACC,EAAkBD,CAAe,IAElCC,EAAkBD,CAAe,EAAIJ,GAGvC,MAAMM,EAAiB,KAAK,eACtBL,EAAUC,EAAU,IAIxBD,GACAE,EAAoB,SAASG,CAAc,GAC3C,CAACD,EAAkBC,CAAc,IAEjCD,EAAkBC,CAAc,EAAIL,EAExC,CACF,CC1DO,MAAMM,CAA8C,CAMzD,YAA4BpD,EAAqC,CAArC,KAAA,QAAAA,CAC5B,CAQA,QAAQqB,EAAgD,CAItD,OAAO,KAAK,QAAQ,QAAQ,KAC1B,KAAK,QAAQ,SACb,CACE,KAAMA,CAAA,EAER,CACE,gBAAiBgC,EAAAA,iBAAiB,KAClC,eAAgB,IAAI,CAAC,CAACvD,EAAoC,EAAI,CAAC,CAAC,CAAA,CAClE,CAEJ,CACF,CCvEO,MAAMwD,EAA0B,cAKhC,MAAMC,UACHvC,EAAAA,UACsB,CAC9B,YACEC,EAAcqC,EACE1B,EAAsB,EACtC,CACA,MAAM,CACJ,IAAAX,EACA,QAASE,EAAAA,wBAAA,EACT,WAAY,IAAIc,EAA4BL,CAAW,CAAA,CACxD,EANe,KAAA,YAAAA,CAOlB,CAEA,kBAAkBO,EAAgC,CAChD,KAAK,IAAI,IAAIH,EAAkBG,CAAc,CAAC,CAChD,CACF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/authorizationRequestInterceptor.ts","../src/authorizationResponseInterceptor.ts","../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\n extends AppIdCapable,\n DeviceIdStorageCapable,\n JwtTokenManagerCapable {\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\n extends AppIdCapable,\n 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 {\n COSEC_REQUEST_INTERCEPTOR_ORDER,\n IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,\n} from './cosecRequestInterceptor';\nimport { CoSecHeaders, JwtTokenManagerCapable } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface AuthorizationInterceptorOptions\n extends JwtTokenManagerCapable {\n}\n\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME =\n 'AuthorizationRequestInterceptor';\nexport const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER =\n COSEC_REQUEST_INTERCEPTOR_ORDER + 1000;\n\n/**\n * Request interceptor that automatically adds Authorization header to requests.\n *\n * This interceptor handles JWT token management by:\n * 1. Adding Authorization header with Bearer token if not already present\n * 2. Refreshing tokens when needed and possible\n * 3. Skipping refresh when explicitly requested via attributes\n *\n * The interceptor runs after CoSecRequestInterceptor but before FetchInterceptor in the chain.\n */\nexport class AuthorizationRequestInterceptor implements RequestInterceptor {\n readonly name = AUTHORIZATION_REQUEST_INTERCEPTOR_NAME;\n readonly order = AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER;\n\n /**\n * Creates an AuthorizationRequestInterceptor instance.\n *\n * @param options - Configuration options containing the token manager\n */\n constructor(private readonly options: AuthorizationInterceptorOptions) {\n }\n\n /**\n * Intercepts the request exchange to add authorization headers.\n *\n * This method performs the following operations:\n * 1. Checks if a token exists and if Authorization header is already set\n * 2. Refreshes the token if needed, possible, and not explicitly ignored\n * 3. Adds the Authorization header with Bearer token if a token is available\n *\n * @param exchange - The fetch exchange containing request information\n * @returns Promise that resolves when the interception is complete\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 (\n !exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) &&\n currentToken.isRefreshNeeded &&\n currentToken.isRefreshable\n ) {\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] =\n `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 { AuthorizationInterceptorOptions } from './authorizationRequestInterceptor';\n\n/**\n * The name of the AuthorizationResponseInterceptor.\n */\nexport const AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME =\n '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 =\n 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","/*\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 {\n KeyStorage, KeyStorageOptions,\n} from '@ahoo-wang/fetcher-storage';\nimport { BroadcastTypedEventBus, SerialTypedEventBus } from '@ahoo-wang/fetcher-eventbus';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface DeviceIdStorageOptions extends KeyStorageOptions<string> {\n}\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(options: DeviceIdStorageOptions = {\n key: DEFAULT_COSEC_DEVICE_ID_KEY,\n eventBus: new BroadcastTypedEventBus(new SerialTypedEventBus(DEFAULT_COSEC_DEVICE_ID_KEY)),\n }) {\n super(options);\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 * 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 if (typeof token !== 'string') {\n return null;\n }\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 {\n CoSecJwtPayload,\n EarlyPeriodCapable,\n isTokenExpired,\n JwtPayload,\n parseJwtPayload,\n} from './jwts';\nimport { CompositeToken } from './tokenRefresher';\nimport { Serializer } from '@ahoo-wang/fetcher-storage';\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>\n 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>\n 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\n 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(\n public readonly token: CompositeToken,\n public readonly earlyPeriod: number = 0,\n ) {\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 * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer\n 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","/*\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 * 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\n .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 =\n '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 =\n 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\n implements RequestInterceptor {\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({\n tenantId = 'tenantId',\n ownerId = 'ownerId',\n tokenStorage,\n }: 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 =\n exchange.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(\n exchange.request.url,\n );\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 (\n tenantId &&\n extractedPathParams.includes(tenantIdPathKey) &&\n !requestPathParams[tenantIdPathKey]\n ) {\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 (\n ownerId &&\n extractedPathParams.includes(ownerIdPathKey) &&\n !requestPathParams[ownerIdPathKey]\n ) {\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>(\n this.options.endpoint,\n {\n body: token,\n },\n {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\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 {\n KeyStorage, KeyStorageOptions,\n} from '@ahoo-wang/fetcher-storage';\nimport { PartialBy } from '@ahoo-wang/fetcher';\nimport { BroadcastTypedEventBus, SerialTypedEventBus } from '@ahoo-wang/fetcher-eventbus';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\nexport interface TokenStorageOptions extends Omit<KeyStorageOptions<JwtCompositeToken>, 'serializer'>, PartialBy<EarlyPeriodCapable, 'earlyPeriod'> {\n\n}\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable {\n public readonly earlyPeriod: number;\n\n constructor(\n options: TokenStorageOptions = {\n key: DEFAULT_COSEC_TOKEN_KEY,\n eventBus: new BroadcastTypedEventBus(new SerialTypedEventBus(DEFAULT_COSEC_TOKEN_KEY)),\n },\n ) {\n super({\n serializer: new JwtCompositeTokenSerializer(options.earlyPeriod),\n ...options,\n });\n this.earlyPeriod = options.earlyPeriod ?? 0;\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(new JwtCompositeToken(compositeToken));\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","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","BroadcastTypedEventBus","SerialTypedEventBus","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","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":"yfAmBO,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,EAuCA,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,EChDO,MAAMC,CAAuC,CAMlD,YAAqB,CACnB,OAAOC,SAAA,CACT,CACF,CAEO,MAAMC,EAAc,IAAIF,ECLlBG,EAAiC,0BAMjCC,EACXC,EAAAA,+BAAiC,IAEtBC,EAAqC,uBAkB3C,MAAMC,CAAsD,CASjE,YAAYC,EAA8B,CAR1C,KAAS,KAAOL,EAChB,KAAS,MAAQC,EAQf,KAAK,QAAUI,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AAM,GAAG,CAAC,GAAG,IAAI,CAiC7E;AAED,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,MAAM,GAAG,eAAe,EAC/B,WAAW,GAAE,MAAU,GACtB,OAAO,CAaT"}
|
package/dist/tokenStorage.d.ts
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
import { JwtCompositeToken } from './jwtToken';
|
|
2
2
|
import { CompositeToken } from './tokenRefresher';
|
|
3
3
|
import { EarlyPeriodCapable } from './jwts';
|
|
4
|
-
import { KeyStorage } from '@ahoo-wang/fetcher-storage';
|
|
4
|
+
import { KeyStorage, KeyStorageOptions } from '@ahoo-wang/fetcher-storage';
|
|
5
|
+
import { PartialBy } from '@ahoo-wang/fetcher';
|
|
5
6
|
export declare const DEFAULT_COSEC_TOKEN_KEY = "cosec-token";
|
|
7
|
+
export interface TokenStorageOptions extends Omit<KeyStorageOptions<JwtCompositeToken>, 'serializer'>, PartialBy<EarlyPeriodCapable, 'earlyPeriod'> {
|
|
8
|
+
}
|
|
6
9
|
/**
|
|
7
10
|
* Storage class for managing access and refresh tokens.
|
|
8
11
|
*/
|
|
9
12
|
export declare class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {
|
|
10
13
|
readonly earlyPeriod: number;
|
|
11
|
-
constructor(
|
|
14
|
+
constructor(options?: TokenStorageOptions);
|
|
12
15
|
setCompositeToken(compositeToken: CompositeToken): void;
|
|
13
16
|
}
|
|
14
17
|
//# sourceMappingURL=tokenStorage.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenStorage.d.ts","sourceRoot":"","sources":["../src/tokenStorage.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAA+B,MAAM,YAAY,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,
|
|
1
|
+
{"version":3,"file":"tokenStorage.d.ts","sourceRoot":"","sources":["../src/tokenStorage.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAA+B,MAAM,YAAY,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAC5C,OAAO,EACL,UAAU,EAAE,iBAAiB,EAC9B,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C,eAAO,MAAM,uBAAuB,gBAAgB,CAAC;AAErD,MAAM,WAAW,mBAAoB,SAAQ,IAAI,CAAC,iBAAiB,CAAC,iBAAiB,CAAC,EAAE,YAAY,CAAC,EAAE,SAAS,CAAC,kBAAkB,EAAE,aAAa,CAAC;CAElJ;AAED;;GAEG;AACH,qBAAa,YACX,SAAQ,UAAU,CAAC,iBAAiB,CACpC,YAAW,kBAAkB;IAC7B,SAAgB,WAAW,EAAE,MAAM,CAAC;gBAGlC,OAAO,GAAE,mBAGR;IASH,iBAAiB,CAAC,cAAc,EAAE,cAAc;CAGjD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-cosec",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
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,6 +40,7 @@
|
|
|
40
40
|
],
|
|
41
41
|
"peerDependencies": {
|
|
42
42
|
"@ahoo-wang/fetcher": "^2.3.4",
|
|
43
|
+
"@ahoo-wang/fetcher-eventbus": "^2.8.5",
|
|
43
44
|
"@ahoo-wang/fetcher-storage": "^2.3.4"
|
|
44
45
|
},
|
|
45
46
|
"dependencies": {
|