@ahoo-wang/fetcher-cosec 3.0.0 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ import { JwtTokenManagerCapable } from './types';
3
3
  export interface AuthorizationInterceptorOptions extends JwtTokenManagerCapable {
4
4
  }
5
5
  export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_NAME = "AuthorizationRequestInterceptor";
6
- export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER: any;
6
+ export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER: number;
7
7
  /**
8
8
  * Request interceptor that automatically adds Authorization header to requests.
9
9
  *
@@ -17,7 +17,7 @@ export declare const AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER: any;
17
17
  export declare class AuthorizationRequestInterceptor implements RequestInterceptor {
18
18
  private readonly options;
19
19
  readonly name = "AuthorizationRequestInterceptor";
20
- readonly order: any;
20
+ readonly order: number;
21
21
  /**
22
22
  * Creates an AuthorizationRequestInterceptor instance.
23
23
  *
@@ -1 +1 @@
1
- {"version":3,"file":"authorizationRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/authorizationRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAKvE,OAAO,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG/D,MAAM,WAAW,+BACf,SAAQ,sBAAsB;CAC/B;AAED,eAAO,MAAM,sCAAsC,oCAChB,CAAC;AACpC,eAAO,MAAM,uCAAuC,KACZ,CAAC;AAEzC;;;;;;;;;GASG;AACH,qBAAa,+BAAgC,YAAW,kBAAkB;IAS5D,OAAO,CAAC,QAAQ,CAAC,OAAO;IARpC,QAAQ,CAAC,IAAI,qCAA0C;IACvD,QAAQ,CAAC,KAAK,MAA2C;IAEzD;;;;OAIG;gBAC0B,OAAO,EAAE,+BAA+B;IAGrE;;;;;;;;;;OAUG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CA6BxD"}
1
+ {"version":3,"file":"authorizationRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/authorizationRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAKvE,OAAO,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG/D,MAAM,WAAW,+BACf,SAAQ,sBAAsB;CAC/B;AAED,eAAO,MAAM,sCAAsC,oCAChB,CAAC;AACpC,eAAO,MAAM,uCAAuC,QACZ,CAAC;AAEzC;;;;;;;;;GASG;AACH,qBAAa,+BAAgC,YAAW,kBAAkB;IAS5D,OAAO,CAAC,QAAQ,CAAC,OAAO;IARpC,QAAQ,CAAC,IAAI,qCAA0C;IACvD,QAAQ,CAAC,KAAK,SAA2C;IAEzD;;;;OAIG;gBAC0B,OAAO,EAAE,+BAA+B;IAGrE;;;;;;;;;;OAUG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;CA6BxD"}
@@ -10,7 +10,7 @@ export declare const COSEC_REQUEST_INTERCEPTOR_NAME = "CoSecRequestInterceptor";
10
10
  * The order of the CoSecRequestInterceptor.
11
11
  * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.
12
12
  */
13
- export declare const COSEC_REQUEST_INTERCEPTOR_ORDER: any;
13
+ export declare const COSEC_REQUEST_INTERCEPTOR_ORDER: number;
14
14
  export declare const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = "Ignore-Refresh-Token";
15
15
  /**
16
16
  * Interceptor that automatically adds CoSec authentication headers to requests.
@@ -30,7 +30,7 @@ export declare const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = "Ignore-Refresh-Token"
30
30
  */
31
31
  export declare class CoSecRequestInterceptor implements RequestInterceptor {
32
32
  readonly name = "CoSecRequestInterceptor";
33
- readonly order: any;
33
+ readonly order: number;
34
34
  private options;
35
35
  /**
36
36
  * Creates a new CoSecRequestInterceptor instance.
@@ -1 +1 @@
1
- {"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,EAEb,KAAK,kBAAkB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG7E,MAAM,WAAW,mBACf,SAAQ,YAAY,EAClB,sBAAsB;CACzB;AAED;;GAEG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;GAGG;AACH,eAAO,MAAM,+BAA+B,KACL,CAAC;AAExC,eAAO,MAAM,kCAAkC,yBAAyB,CAAC;AAEzE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,uBAAwB,YAAW,kBAAkB;IAChE,QAAQ,CAAC,IAAI,6BAAkC;IAC/C,QAAQ,CAAC,KAAK,MAAmC;IACjD,OAAO,CAAC,OAAO,CAAsB;IAErC;;;OAGG;gBACS,OAAO,EAAE,mBAAmB;IAIxC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa;CAexC"}
1
+ {"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,EAEb,KAAK,kBAAkB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAgB,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAG7E,MAAM,WAAW,mBACf,SAAQ,YAAY,EAClB,sBAAsB;CACzB;AAED;;GAEG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;GAGG;AACH,eAAO,MAAM,+BAA+B,QACL,CAAC;AAExC,eAAO,MAAM,kCAAkC,yBAAyB,CAAC;AAEzE;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,uBAAwB,YAAW,kBAAkB;IAChE,QAAQ,CAAC,IAAI,6BAAkC;IAC/C,QAAQ,CAAC,KAAK,SAAmC;IACjD,OAAO,CAAC,OAAO,CAAsB;IAErC;;;OAGG;gBACS,OAAO,EAAE,mBAAmB;IAIxC;;;;;;;;;;;;;;;;;;;;;OAqBG;IACG,SAAS,CAAC,QAAQ,EAAE,aAAa;CAexC"}
package/dist/index.es.js CHANGED
@@ -113,11 +113,11 @@ class X {
113
113
  }
114
114
  }
115
115
  }
116
- const T = "cosec-device-id";
116
+ const d = "cosec-device-id";
117
117
  class W extends f {
118
118
  constructor(e = {
119
- key: T,
120
- eventBus: new O({ delegate: new _(T) })
119
+ key: d,
120
+ eventBus: new O({ delegate: new _(d) })
121
121
  }) {
122
122
  super(e);
123
123
  }
@@ -227,11 +227,8 @@ class y {
227
227
  }
228
228
  const $ = new y();
229
229
  class u extends S {
230
- constructor(e) {
231
- super(
232
- "Refresh token failed.",
233
- e
234
- ), this.name = "RefreshTokenError", Object.setPrototypeOf(this, u.prototype);
230
+ constructor(e, t) {
231
+ super("Refresh token failed.", t), this.token = e, this.name = "RefreshTokenError", Object.setPrototypeOf(this, u.prototype);
235
232
  }
236
233
  }
237
234
  class ee {
@@ -252,21 +249,17 @@ class ee {
252
249
  }
253
250
  /**
254
251
  * Refreshes the JWT token
255
- * @param currentToken Optional current token to refresh. If not provided, uses the stored token.
256
252
  * @returns Promise that resolves when refresh is complete
257
253
  * @throws Error if no token is found or refresh fails
258
254
  */
259
- async refresh(e) {
260
- if (!e) {
261
- const t = this.currentToken;
262
- if (!t)
263
- throw new Error("No token found");
264
- e = t.token;
265
- }
266
- return this.refreshInProgress ? this.refreshInProgress : (this.refreshInProgress = this.tokenRefresher.refresh(e).then((t) => {
255
+ async refresh() {
256
+ const e = this.currentToken;
257
+ if (!e)
258
+ throw new Error("No token found");
259
+ return this.refreshInProgress ? this.refreshInProgress : (this.refreshInProgress = this.tokenRefresher.refresh(e.token).then((t) => {
267
260
  this.tokenStorage.setCompositeToken(t);
268
261
  }).catch((t) => {
269
- throw this.tokenStorage.remove(), new u(t);
262
+ throw this.tokenStorage.remove(), new u(e, t);
270
263
  }).finally(() => {
271
264
  this.refreshInProgress = void 0;
272
265
  }), this.refreshInProgress);
@@ -315,8 +308,8 @@ class te {
315
308
  e.request.url
316
309
  ), c = this.tenantIdPathKey, i = e.ensureRequestUrlParams().path, I = r.tenantId;
317
310
  I && o.includes(c) && !i[c] && (i[c] = I);
318
- const R = this.ownerIdPathKey, d = r.sub;
319
- d && o.includes(R) && !i[R] && (i[R] = d);
311
+ const R = this.ownerIdPathKey, T = r.sub;
312
+ T && o.includes(R) && !i[R] && (i[R] = T);
320
313
  }
321
314
  }
322
315
  class re {
@@ -474,7 +467,7 @@ export {
474
467
  n as CoSecHeaders,
475
468
  G as CoSecRequestInterceptor,
476
469
  re as CoSecTokenRefresher,
477
- T as DEFAULT_COSEC_DEVICE_ID_KEY,
470
+ d as DEFAULT_COSEC_DEVICE_ID_KEY,
478
471
  l as DEFAULT_COSEC_TOKEN_KEY,
479
472
  W as DeviceIdStorage,
480
473
  Z as FORBIDDEN_ERROR_INTERCEPTOR_NAME,
@@ -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","../src/unauthorizedErrorInterceptor.ts","../src/forbiddenErrorInterceptor.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 static readonly FORBIDDEN = 403;\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\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(private options: AuthorizationInterceptorOptions) {\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({ delegate: 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';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\nexport class RefreshTokenError extends FetcherError {\n constructor(cause?: Error | any) {\n super(\n `Refresh token failed.`, cause,\n );\n this.name = 'RefreshTokenError';\n Object.setPrototypeOf(this, RefreshTokenError.prototype);\n }\n}\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 new RefreshTokenError(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({ delegate: 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, this.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 */\nimport { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\nimport { RefreshTokenError } from './jwtTokenManager';\n\n/**\n * The name identifier for the UnauthorizedErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_NAME =\n 'UnauthorizedErrorInterceptor';\n\n/**\n * The execution order for the UnauthorizedErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the UnauthorizedErrorInterceptor.\n */\nexport interface UnauthorizedErrorInterceptorOptions {\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * This allows custom handling of authentication failures, such as redirecting to login\n * or triggering token refresh mechanisms.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the unauthorized error\n */\n onUnauthorized: (exchange: FetchExchange) => Promise<void> | void;\n}\n\n/**\n * An error interceptor that handles HTTP 401 Unauthorized responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authentication failures\n * across all HTTP requests. When a response with status code 401 is encountered, it calls\n * the configured `onUnauthorized` callback, allowing applications to implement custom\n * authentication recovery logic such as:\n * - Redirecting users to login pages\n * - Triggering token refresh flows\n * - Clearing stored authentication state\n * - Displaying authentication error messages\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function.\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * console.log('Unauthorized access detected for:', exchange.request.url);\n * // Redirect to login page or refresh token\n * window.location.href = '/login';\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n */\nexport class UnauthorizedErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n */\n readonly name = UNAUTHORIZED_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the chain.\n */\n readonly order = UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new UnauthorizedErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle unauthorized responses\n */\n constructor(private options: UnauthorizedErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle unauthorized (401) responses\n * and RefreshTokenError exceptions.\n *\n * This method checks if the response status is 401 (Unauthorized) or if the exchange\n * contains an error of type `RefreshTokenError`. If either condition is met, it invokes\n * the configured `onUnauthorized` callback with the exchange details. The method\n * does not return a value or throw exceptions - all error handling is delegated\n * to the callback function.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for unauthorized status codes or refresh token errors\n * @returns {void} This method does not return a value\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * // Custom logic here\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n if (\n exchange.response?.status === ResponseCodes.UNAUTHORIZED ||\n exchange.error instanceof RefreshTokenError\n ) {\n await this.options.onUnauthorized(exchange);\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 { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\n\n/**\n * The name identifier for the ForbiddenErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_NAME = 'ForbiddenErrorInterceptor';\n\n/**\n * The execution order for the ForbiddenErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the ForbiddenErrorInterceptor.\n */\nexport interface ForbiddenErrorInterceptorOptions {\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * This allows custom handling of authorization failures, such as displaying\n * permission error messages, redirecting to appropriate pages, or triggering\n * privilege escalation flows.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the forbidden error\n * @returns Promise that resolves when the forbidden error handling is complete\n *\n * @example\n * ```typescript\n * const options: ForbiddenErrorInterceptorOptions = {\n * onForbidden: async (exchange) => {\n * console.log('Access forbidden for:', exchange.request.url);\n * // Show permission error or redirect\n * showPermissionError('You do not have permission to access this resource');\n * }\n * };\n * ```\n */\n onForbidden: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * An error interceptor that handles HTTP 403 Forbidden responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authorization failures\n * across all HTTP requests. When a response with status code 403 is encountered, it calls\n * the configured `onForbidden` callback, allowing applications to implement custom\n * authorization recovery logic such as:\n * - Displaying permission error messages\n * - Redirecting users to access request pages\n * - Triggering privilege escalation workflows\n * - Logging security events\n * - Showing upgrade prompts for premium features\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function. This allows for flexible, application-specific\n * handling of forbidden access scenarios.\n *\n * @example\n * ```typescript\n * // Basic usage with error display\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * console.log('Forbidden access detected for:', exchange.request.url);\n * showErrorToast('You do not have permission to access this resource');\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with role-based handling\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * const userRole = getCurrentUserRole();\n *\n * if (userRole === 'guest') {\n * // Redirect to login for guests\n * redirectToLogin(exchange.request.url);\n * } else if (userRole === 'user') {\n * // Show upgrade prompt for basic users\n * showUpgradePrompt('Upgrade to premium for access to this feature');\n * } else {\n * // Log security event for authenticated users\n * logSecurityEvent('Forbidden access attempt', {\n * url: exchange.request.url,\n * userId: getCurrentUserId(),\n * timestamp: new Date().toISOString()\n * });\n * showErrorToast('Access denied due to insufficient permissions');\n * }\n * }\n * });\n * ```\n */\nexport class ForbiddenErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n * Used for registration, debugging, and interceptor chain management.\n */\n readonly name = FORBIDDEN_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the error interceptor chain.\n * Lower values execute earlier in the chain. Default priority (0) allows other\n * interceptors to run first if needed.\n */\n readonly order = FORBIDDEN_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new ForbiddenErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle forbidden responses.\n * Must include the `onForbidden` callback function.\n *\n * @throws Will throw an error if options are not provided or if `onForbidden` callback is missing.\n *\n * @example\n * ```typescript\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // Handle forbidden access\n * }\n * });\n * ```\n */\n constructor(private options: ForbiddenErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle forbidden (403) responses.\n *\n * This method examines the response status code and invokes the configured `onForbidden`\n * callback when a 403 Forbidden response is detected. The method is asynchronous to\n * allow the callback to perform async operations like API calls, redirects, or UI updates.\n *\n * The interceptor only acts on responses with status code 403. Other error codes are\n * ignored and passed through to other error interceptors in the chain.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for forbidden status codes. The exchange object provides\n * access to the original request, response details, and any error information.\n * @returns Promise that resolves when the forbidden error handling is complete.\n * Returns void - the method does not modify the exchange or return values.\n *\n * @remarks\n * - Only responds to HTTP 403 status codes\n * - Does not retry requests or modify responses\n * - Allows async operations in the callback\n * - Does not throw exceptions - delegates all error handling to the callback\n * - Safe to use with other error interceptors\n *\n * @example\n * ```typescript\n * // The intercept method is called automatically by the fetcher\n * // No manual invocation needed - this is for documentation purposes\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // exchange.response.status === 403\n * // exchange.request contains original request details\n * await handleForbiddenAccess(exchange);\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n // Check if the response status indicates forbidden access (403)\n if (exchange.response?.status === ResponseCodes.FORBIDDEN) {\n // Invoke the custom forbidden error handler\n // Allow the callback to perform async operations\n await this.options.onForbidden(exchange);\n }\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","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","RefreshTokenError","FetcherError","cause","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","UNAUTHORIZED_ERROR_INTERCEPTOR_NAME","UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER","UnauthorizedErrorInterceptor","FORBIDDEN_ERROR_INTERCEPTOR_NAME","FORBIDDEN_ERROR_INTERCEPTOR_ORDER","ForbiddenErrorInterceptor"],"mappings":";;;;AAmBO,MAAMA,IAAN,MAAMA,EAAa;AAK1B;AAJEA,EAAgB,YAAY,mBAC5BA,EAAgB,SAAS,gBACzBA,EAAgB,gBAAgB,iBAChCA,EAAgB,aAAa;AAJxB,IAAMC,IAAND;AAOA,MAAME,IAAN,MAAMA,EAAc;AAG3B;AAFEA,EAAgB,eAAe,KAC/BA,EAAgB,YAAY;AAFvB,IAAMC,IAAND;AAwCA,MAAME,IAAmB;AAAA,EAC9B,OAAO,EAAE,YAAY,IAAM,QAAQ,QAAA;AAAA,EACnC,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,mBAAmB,EAAE,YAAY,IAAO,QAAQ,oBAAA;AAClD;ACjDO,MAAMC,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,aAAqB;AACnB,WAAOC,EAAA;AAAA,EACT;AACF;AAEO,MAAMC,IAAc,IAAIF,EAAA,GCLlBG,IAAiC,2BAMjCC,IACXC,IAAiC,KAEtBC,IAAqC;AAkB3C,MAAMC,EAAsD;AAAA;AAAA;AAAA;AAAA;AAAA,EASjE,YAAYC,GAA8B;AAR1C,SAAS,OAAOL,GAChB,KAAS,QAAQC,GAQf,KAAK,UAAUI;AAAA,EACjB;AAAA;AAAA;AAAA;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C;AACtD,KACEA,EAAS,UAAU,WAAWX,EAAc,gBAC5CW,EAAS,iBAAiBmC,MAE1B,MAAM,KAAK,QAAQ,eAAenC,CAAQ;AAAA,EAE9C;AACF;ACtGO,MAAM4D,IAAmC,6BAMnCC,IAAoC;AAsF1C,MAAMC,GAAsD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA+BjE,YAAoB/D,GAA2C;AAA3C,SAAA,UAAAA,GA1BpB,KAAS,OAAO6D,GAOhB,KAAS,QAAQC;AAAA,EAoBjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsCA,MAAM,UAAU7D,GAAwC;AAEtD,IAAIA,EAAS,UAAU,WAAWX,EAAc,aAG9C,MAAM,KAAK,QAAQ,YAAYW,CAAQ;AAAA,EAE3C;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","../src/unauthorizedErrorInterceptor.ts","../src/forbiddenErrorInterceptor.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 static readonly FORBIDDEN = 403;\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\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(private options: AuthorizationInterceptorOptions) {\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({ delegate: 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 { TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\nexport class RefreshTokenError extends FetcherError {\n constructor(\n public readonly token: JwtCompositeToken,\n cause?: Error | any,\n ) {\n super(`Refresh token failed.`, cause);\n this.name = 'RefreshTokenError';\n Object.setPrototypeOf(this, RefreshTokenError.prototype);\n }\n}\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 * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(): Promise<void> {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher\n .refresh(jwtToken.token)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw new RefreshTokenError(jwtToken, 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({ delegate: 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, this.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 */\nimport { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\nimport { RefreshTokenError } from './jwtTokenManager';\n\n/**\n * The name identifier for the UnauthorizedErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_NAME =\n 'UnauthorizedErrorInterceptor';\n\n/**\n * The execution order for the UnauthorizedErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the UnauthorizedErrorInterceptor.\n */\nexport interface UnauthorizedErrorInterceptorOptions {\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * This allows custom handling of authentication failures, such as redirecting to login\n * or triggering token refresh mechanisms.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the unauthorized error\n */\n onUnauthorized: (exchange: FetchExchange) => Promise<void> | void;\n}\n\n/**\n * An error interceptor that handles HTTP 401 Unauthorized responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authentication failures\n * across all HTTP requests. When a response with status code 401 is encountered, it calls\n * the configured `onUnauthorized` callback, allowing applications to implement custom\n * authentication recovery logic such as:\n * - Redirecting users to login pages\n * - Triggering token refresh flows\n * - Clearing stored authentication state\n * - Displaying authentication error messages\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function.\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * console.log('Unauthorized access detected for:', exchange.request.url);\n * // Redirect to login page or refresh token\n * window.location.href = '/login';\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n */\nexport class UnauthorizedErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n */\n readonly name = UNAUTHORIZED_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the chain.\n */\n readonly order = UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new UnauthorizedErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle unauthorized responses\n */\n constructor(private options: UnauthorizedErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle unauthorized (401) responses\n * and RefreshTokenError exceptions.\n *\n * This method checks if the response status is 401 (Unauthorized) or if the exchange\n * contains an error of type `RefreshTokenError`. If either condition is met, it invokes\n * the configured `onUnauthorized` callback with the exchange details. The method\n * does not return a value or throw exceptions - all error handling is delegated\n * to the callback function.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for unauthorized status codes or refresh token errors\n * @returns {void} This method does not return a value\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * // Custom logic here\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n if (\n exchange.response?.status === ResponseCodes.UNAUTHORIZED ||\n exchange.error instanceof RefreshTokenError\n ) {\n await this.options.onUnauthorized(exchange);\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 { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\n\n/**\n * The name identifier for the ForbiddenErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_NAME = 'ForbiddenErrorInterceptor';\n\n/**\n * The execution order for the ForbiddenErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the ForbiddenErrorInterceptor.\n */\nexport interface ForbiddenErrorInterceptorOptions {\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * This allows custom handling of authorization failures, such as displaying\n * permission error messages, redirecting to appropriate pages, or triggering\n * privilege escalation flows.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the forbidden error\n * @returns Promise that resolves when the forbidden error handling is complete\n *\n * @example\n * ```typescript\n * const options: ForbiddenErrorInterceptorOptions = {\n * onForbidden: async (exchange) => {\n * console.log('Access forbidden for:', exchange.request.url);\n * // Show permission error or redirect\n * showPermissionError('You do not have permission to access this resource');\n * }\n * };\n * ```\n */\n onForbidden: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * An error interceptor that handles HTTP 403 Forbidden responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authorization failures\n * across all HTTP requests. When a response with status code 403 is encountered, it calls\n * the configured `onForbidden` callback, allowing applications to implement custom\n * authorization recovery logic such as:\n * - Displaying permission error messages\n * - Redirecting users to access request pages\n * - Triggering privilege escalation workflows\n * - Logging security events\n * - Showing upgrade prompts for premium features\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function. This allows for flexible, application-specific\n * handling of forbidden access scenarios.\n *\n * @example\n * ```typescript\n * // Basic usage with error display\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * console.log('Forbidden access detected for:', exchange.request.url);\n * showErrorToast('You do not have permission to access this resource');\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with role-based handling\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * const userRole = getCurrentUserRole();\n *\n * if (userRole === 'guest') {\n * // Redirect to login for guests\n * redirectToLogin(exchange.request.url);\n * } else if (userRole === 'user') {\n * // Show upgrade prompt for basic users\n * showUpgradePrompt('Upgrade to premium for access to this feature');\n * } else {\n * // Log security event for authenticated users\n * logSecurityEvent('Forbidden access attempt', {\n * url: exchange.request.url,\n * userId: getCurrentUserId(),\n * timestamp: new Date().toISOString()\n * });\n * showErrorToast('Access denied due to insufficient permissions');\n * }\n * }\n * });\n * ```\n */\nexport class ForbiddenErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n * Used for registration, debugging, and interceptor chain management.\n */\n readonly name = FORBIDDEN_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the error interceptor chain.\n * Lower values execute earlier in the chain. Default priority (0) allows other\n * interceptors to run first if needed.\n */\n readonly order = FORBIDDEN_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new ForbiddenErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle forbidden responses.\n * Must include the `onForbidden` callback function.\n *\n * @throws Will throw an error if options are not provided or if `onForbidden` callback is missing.\n *\n * @example\n * ```typescript\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // Handle forbidden access\n * }\n * });\n * ```\n */\n constructor(private options: ForbiddenErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle forbidden (403) responses.\n *\n * This method examines the response status code and invokes the configured `onForbidden`\n * callback when a 403 Forbidden response is detected. The method is asynchronous to\n * allow the callback to perform async operations like API calls, redirects, or UI updates.\n *\n * The interceptor only acts on responses with status code 403. Other error codes are\n * ignored and passed through to other error interceptors in the chain.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for forbidden status codes. The exchange object provides\n * access to the original request, response details, and any error information.\n * @returns Promise that resolves when the forbidden error handling is complete.\n * Returns void - the method does not modify the exchange or return values.\n *\n * @remarks\n * - Only responds to HTTP 403 status codes\n * - Does not retry requests or modify responses\n * - Allows async operations in the callback\n * - Does not throw exceptions - delegates all error handling to the callback\n * - Safe to use with other error interceptors\n *\n * @example\n * ```typescript\n * // The intercept method is called automatically by the fetcher\n * // No manual invocation needed - this is for documentation purposes\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // exchange.response.status === 403\n * // exchange.request contains original request details\n * await handleForbiddenAccess(exchange);\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n // Check if the response status indicates forbidden access (403)\n if (exchange.response?.status === ResponseCodes.FORBIDDEN) {\n // Invoke the custom forbidden error handler\n // Allow the callback to perform async operations\n await this.options.onForbidden(exchange);\n }\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","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","RefreshTokenError","FetcherError","cause","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","T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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA+BjE,YAAoB/D,GAA2C;AAA3C,SAAA,UAAAA,GA1BpB,KAAS,OAAO6D,GAOhB,KAAS,QAAQC;AAAA,EAoBjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsCA,MAAM,UAAU7D,GAAwC;AAEtD,IAAIA,EAAS,UAAU,WAAWX,EAAc,aAG9C,MAAM,KAAK,QAAQ,YAAYW,CAAQ;AAAA,EAE3C;AACF;"}
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
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,K,P,u){"use strict";const R=class R{};R.DEVICE_ID="CoSec-Device-Id",R.APP_ID="CoSec-App-Id",R.AUTHORIZATION="Authorization",R.REQUEST_ID="CoSec-Request-Id";let i=R;const I=class I{};I.UNAUTHORIZED=401,I.FORBIDDEN=403;let E=I;const Z={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 U{generateId(){return K.nanoid()}}const d=new U,D="CoSecRequestInterceptor",O=a.REQUEST_BODY_INTERCEPTOR_ORDER+1e3,_="Ignore-Refresh-Token";class Q{constructor(e){this.name=D,this.order=O,this.options=e}async intercept(e){const r=d.generateId(),n=this.options.deviceIdStorage.getOrCreate(),o=e.ensureRequestHeaders();o[i.APP_ID]=this.options.appId,o[i.DEVICE_ID]=n,o[i.REQUEST_ID]=r}}const g="AuthorizationRequestInterceptor",k=O+1e3;class J{constructor(e){this.options=e,this.name=g,this.order=k}async intercept(e){let r=this.options.tokenManager.currentToken;const n=e.ensureRequestHeaders();!r||n[i.AUTHORIZATION]||(!e.attributes.has(_)&&r.isRefreshNeeded&&r.isRefreshable&&await this.options.tokenManager.refresh(),r=this.options.tokenManager.currentToken,r&&(n[i.AUTHORIZATION]=`Bearer ${r.access.token}`))}}const y="AuthorizationResponseInterceptor",w=Number.MIN_SAFE_INTEGER+1e3;class Y{constructor(e){this.options=e,this.name=y,this.order=w}async intercept(e){const r=e.response;if(r&&r.status===E.UNAUTHORIZED&&this.options.tokenManager.isRefreshable)try{await this.options.tokenManager.refresh(),await e.fetcher.interceptors.exchange(e)}catch(n){throw this.options.tokenManager.tokenStorage.remove(),n}}}const N="cosec-device-id";class j extends P.KeyStorage{constructor(e={key:N,eventBus:new u.BroadcastTypedEventBus({delegate:new u.SerialTypedEventBus(N)})}){super(e)}generateDeviceId(){return d.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}}function l(s){try{if(typeof s!="string")return null;const e=s.split(".");if(e.length!==3)return null;const n=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(n.length+(4-n.length%4)%4,"="),h=decodeURIComponent(atob(o).split("").map(function(c){return"%"+("00"+c.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(h)}catch(e){return console.error("Failed to parse JWT token",e),null}}function m(s,e=0){const r=typeof s=="string"?l(s):s;if(!r)return!0;const n=r.exp;return n?Date.now()/1e3>n-e:!1}class f{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.payload=l(e)}get isExpired(){return this.payload?m(this.payload,this.earlyPeriod):!0}}class p{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.access=new f(e.accessToken,r),this.refresh=new f(e.refreshToken,r)}get isRefreshNeeded(){return this.access.isExpired}get isRefreshable(){return!this.refresh.isExpired}}class A{constructor(e=0){this.earlyPeriod=e}deserialize(e){const r=JSON.parse(e);return new p(r,this.earlyPeriod)}serialize(e){return JSON.stringify(e.token)}}const G=new A;class T extends a.FetcherError{constructor(e){super("Refresh token failed.",e),this.name="RefreshTokenError",Object.setPrototypeOf(this,T.prototype)}}class L{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(),new T(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",z=Number.MAX_SAFE_INTEGER;class V{constructor({tenantId:e="tenantId",ownerId:r="ownerId",tokenStorage:n}){this.name=M,this.order=z,this.tenantIdPathKey=e,this.ownerIdPathKey=r,this.tokenStorage=n}intercept(e){const r=this.tokenStorage.get();if(!r)return;const n=r.access.payload;if(!n||!n.tenantId&&!n.sub)return;const o=e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url),h=this.tenantIdPathKey,c=e.ensureRequestUrlParams().path,v=n.tenantId;v&&o.includes(h)&&!c[h]&&(c[h]=v);const C=this.ownerIdPathKey,H=n.sub;H&&o.includes(C)&&!c[C]&&(c[C]=H)}}class X{constructor(e){this.options=e}refresh(e){return this.options.fetcher.post(this.options.endpoint,{body:e},{resultExtractor:a.ResultExtractors.Json,attributes:new Map([[_,!0]])})}}const S="cosec-token";class W extends P.KeyStorage{constructor(e={key:S,eventBus:new u.BroadcastTypedEventBus({delegate:new u.SerialTypedEventBus(S)})}){super({serializer:new A(e.earlyPeriod),...e}),this.earlyPeriod=e.earlyPeriod??0}setCompositeToken(e){this.set(new p(e,this.earlyPeriod))}}const B="UnauthorizedErrorInterceptor",F=0;class ${constructor(e){this.options=e,this.name=B,this.order=F}async intercept(e){(e.response?.status===E.UNAUTHORIZED||e.error instanceof T)&&await this.options.onUnauthorized(e)}}const q="ForbiddenErrorInterceptor",b=0;class x{constructor(e){this.options=e,this.name=q,this.order=b}async intercept(e){e.response?.status===E.FORBIDDEN&&await this.options.onForbidden(e)}}t.AUTHORIZATION_REQUEST_INTERCEPTOR_NAME=g,t.AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER=k,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME=y,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER=w,t.AuthorizationRequestInterceptor=J,t.AuthorizationResponseInterceptor=Y,t.AuthorizeResults=Z,t.COSEC_REQUEST_INTERCEPTOR_NAME=D,t.COSEC_REQUEST_INTERCEPTOR_ORDER=O,t.CoSecHeaders=i,t.CoSecRequestInterceptor=Q,t.CoSecTokenRefresher=X,t.DEFAULT_COSEC_DEVICE_ID_KEY=N,t.DEFAULT_COSEC_TOKEN_KEY=S,t.DeviceIdStorage=j,t.FORBIDDEN_ERROR_INTERCEPTOR_NAME=q,t.FORBIDDEN_ERROR_INTERCEPTOR_ORDER=b,t.ForbiddenErrorInterceptor=x,t.IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY=_,t.JwtCompositeToken=p,t.JwtCompositeTokenSerializer=A,t.JwtToken=f,t.JwtTokenManager=L,t.NanoIdGenerator=U,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME=M,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER=z,t.RefreshTokenError=T,t.ResourceAttributionRequestInterceptor=V,t.ResponseCodes=E,t.TokenStorage=W,t.UNAUTHORIZED_ERROR_INTERCEPTOR_NAME=B,t.UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER=F,t.UnauthorizedErrorInterceptor=$,t.idGenerator=d,t.isTokenExpired=m,t.jwtCompositeTokenSerializer=G,t.parseJwtPayload=l,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));
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,K,P,u){"use strict";const R=class R{};R.DEVICE_ID="CoSec-Device-Id",R.APP_ID="CoSec-App-Id",R.AUTHORIZATION="Authorization",R.REQUEST_ID="CoSec-Request-Id";let i=R;const I=class I{};I.UNAUTHORIZED=401,I.FORBIDDEN=403;let E=I;const Z={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 U{generateId(){return K.nanoid()}}const d=new U,D="CoSecRequestInterceptor",O=a.REQUEST_BODY_INTERCEPTOR_ORDER+1e3,_="Ignore-Refresh-Token";class Q{constructor(e){this.name=D,this.order=O,this.options=e}async intercept(e){const r=d.generateId(),n=this.options.deviceIdStorage.getOrCreate(),o=e.ensureRequestHeaders();o[i.APP_ID]=this.options.appId,o[i.DEVICE_ID]=n,o[i.REQUEST_ID]=r}}const k="AuthorizationRequestInterceptor",g=O+1e3;class J{constructor(e){this.options=e,this.name=k,this.order=g}async intercept(e){let r=this.options.tokenManager.currentToken;const n=e.ensureRequestHeaders();!r||n[i.AUTHORIZATION]||(!e.attributes.has(_)&&r.isRefreshNeeded&&r.isRefreshable&&await this.options.tokenManager.refresh(),r=this.options.tokenManager.currentToken,r&&(n[i.AUTHORIZATION]=`Bearer ${r.access.token}`))}}const y="AuthorizationResponseInterceptor",w=Number.MIN_SAFE_INTEGER+1e3;class Y{constructor(e){this.options=e,this.name=y,this.order=w}async intercept(e){const r=e.response;if(r&&r.status===E.UNAUTHORIZED&&this.options.tokenManager.isRefreshable)try{await this.options.tokenManager.refresh(),await e.fetcher.interceptors.exchange(e)}catch(n){throw this.options.tokenManager.tokenStorage.remove(),n}}}const N="cosec-device-id";class j extends P.KeyStorage{constructor(e={key:N,eventBus:new u.BroadcastTypedEventBus({delegate:new u.SerialTypedEventBus(N)})}){super(e)}generateDeviceId(){return d.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}}function l(s){try{if(typeof s!="string")return null;const e=s.split(".");if(e.length!==3)return null;const n=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=n.padEnd(n.length+(4-n.length%4)%4,"="),h=decodeURIComponent(atob(o).split("").map(function(c){return"%"+("00"+c.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(h)}catch(e){return console.error("Failed to parse JWT token",e),null}}function m(s,e=0){const r=typeof s=="string"?l(s):s;if(!r)return!0;const n=r.exp;return n?Date.now()/1e3>n-e:!1}class f{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.payload=l(e)}get isExpired(){return this.payload?m(this.payload,this.earlyPeriod):!0}}class p{constructor(e,r=0){this.token=e,this.earlyPeriod=r,this.access=new f(e.accessToken,r),this.refresh=new f(e.refreshToken,r)}get isRefreshNeeded(){return this.access.isExpired}get isRefreshable(){return!this.refresh.isExpired}}class A{constructor(e=0){this.earlyPeriod=e}deserialize(e){const r=JSON.parse(e);return new p(r,this.earlyPeriod)}serialize(e){return JSON.stringify(e.token)}}const G=new A;class T extends a.FetcherError{constructor(e,r){super("Refresh token failed.",r),this.token=e,this.name="RefreshTokenError",Object.setPrototypeOf(this,T.prototype)}}class L{constructor(e,r){this.tokenStorage=e,this.tokenRefresher=r}get currentToken(){return this.tokenStorage.get()}async refresh(){const e=this.currentToken;if(!e)throw new Error("No token found");return this.refreshInProgress?this.refreshInProgress:(this.refreshInProgress=this.tokenRefresher.refresh(e.token).then(r=>{this.tokenStorage.setCompositeToken(r)}).catch(r=>{throw this.tokenStorage.remove(),new T(e,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",z=Number.MAX_SAFE_INTEGER;class V{constructor({tenantId:e="tenantId",ownerId:r="ownerId",tokenStorage:n}){this.name=M,this.order=z,this.tenantIdPathKey=e,this.ownerIdPathKey=r,this.tokenStorage=n}intercept(e){const r=this.tokenStorage.get();if(!r)return;const n=r.access.payload;if(!n||!n.tenantId&&!n.sub)return;const o=e.fetcher.urlBuilder.urlTemplateResolver.extractPathParams(e.request.url),h=this.tenantIdPathKey,c=e.ensureRequestUrlParams().path,v=n.tenantId;v&&o.includes(h)&&!c[h]&&(c[h]=v);const C=this.ownerIdPathKey,H=n.sub;H&&o.includes(C)&&!c[C]&&(c[C]=H)}}class X{constructor(e){this.options=e}refresh(e){return this.options.fetcher.post(this.options.endpoint,{body:e},{resultExtractor:a.ResultExtractors.Json,attributes:new Map([[_,!0]])})}}const S="cosec-token";class W extends P.KeyStorage{constructor(e={key:S,eventBus:new u.BroadcastTypedEventBus({delegate:new u.SerialTypedEventBus(S)})}){super({serializer:new A(e.earlyPeriod),...e}),this.earlyPeriod=e.earlyPeriod??0}setCompositeToken(e){this.set(new p(e,this.earlyPeriod))}}const B="UnauthorizedErrorInterceptor",F=0;class ${constructor(e){this.options=e,this.name=B,this.order=F}async intercept(e){(e.response?.status===E.UNAUTHORIZED||e.error instanceof T)&&await this.options.onUnauthorized(e)}}const q="ForbiddenErrorInterceptor",b=0;class x{constructor(e){this.options=e,this.name=q,this.order=b}async intercept(e){e.response?.status===E.FORBIDDEN&&await this.options.onForbidden(e)}}t.AUTHORIZATION_REQUEST_INTERCEPTOR_NAME=k,t.AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER=g,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME=y,t.AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER=w,t.AuthorizationRequestInterceptor=J,t.AuthorizationResponseInterceptor=Y,t.AuthorizeResults=Z,t.COSEC_REQUEST_INTERCEPTOR_NAME=D,t.COSEC_REQUEST_INTERCEPTOR_ORDER=O,t.CoSecHeaders=i,t.CoSecRequestInterceptor=Q,t.CoSecTokenRefresher=X,t.DEFAULT_COSEC_DEVICE_ID_KEY=N,t.DEFAULT_COSEC_TOKEN_KEY=S,t.DeviceIdStorage=j,t.FORBIDDEN_ERROR_INTERCEPTOR_NAME=q,t.FORBIDDEN_ERROR_INTERCEPTOR_ORDER=b,t.ForbiddenErrorInterceptor=x,t.IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY=_,t.JwtCompositeToken=p,t.JwtCompositeTokenSerializer=A,t.JwtToken=f,t.JwtTokenManager=L,t.NanoIdGenerator=U,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME=M,t.RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER=z,t.RefreshTokenError=T,t.ResourceAttributionRequestInterceptor=V,t.ResponseCodes=E,t.TokenStorage=W,t.UNAUTHORIZED_ERROR_INTERCEPTOR_NAME=B,t.UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER=F,t.UnauthorizedErrorInterceptor=$,t.idGenerator=d,t.isTokenExpired=m,t.jwtCompositeTokenSerializer=G,t.parseJwtPayload=l,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=index.umd.js.map
@@ -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","../src/unauthorizedErrorInterceptor.ts","../src/forbiddenErrorInterceptor.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 static readonly FORBIDDEN = 403;\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\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(private options: AuthorizationInterceptorOptions) {\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({ delegate: 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';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\nexport class RefreshTokenError extends FetcherError {\n constructor(cause?: Error | any) {\n super(\n `Refresh token failed.`, cause,\n );\n this.name = 'RefreshTokenError';\n Object.setPrototypeOf(this, RefreshTokenError.prototype);\n }\n}\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 new RefreshTokenError(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({ delegate: 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, this.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 */\nimport { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\nimport { RefreshTokenError } from './jwtTokenManager';\n\n/**\n * The name identifier for the UnauthorizedErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_NAME =\n 'UnauthorizedErrorInterceptor';\n\n/**\n * The execution order for the UnauthorizedErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the UnauthorizedErrorInterceptor.\n */\nexport interface UnauthorizedErrorInterceptorOptions {\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * This allows custom handling of authentication failures, such as redirecting to login\n * or triggering token refresh mechanisms.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the unauthorized error\n */\n onUnauthorized: (exchange: FetchExchange) => Promise<void> | void;\n}\n\n/**\n * An error interceptor that handles HTTP 401 Unauthorized responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authentication failures\n * across all HTTP requests. When a response with status code 401 is encountered, it calls\n * the configured `onUnauthorized` callback, allowing applications to implement custom\n * authentication recovery logic such as:\n * - Redirecting users to login pages\n * - Triggering token refresh flows\n * - Clearing stored authentication state\n * - Displaying authentication error messages\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function.\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * console.log('Unauthorized access detected for:', exchange.request.url);\n * // Redirect to login page or refresh token\n * window.location.href = '/login';\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n */\nexport class UnauthorizedErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n */\n readonly name = UNAUTHORIZED_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the chain.\n */\n readonly order = UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new UnauthorizedErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle unauthorized responses\n */\n constructor(private options: UnauthorizedErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle unauthorized (401) responses\n * and RefreshTokenError exceptions.\n *\n * This method checks if the response status is 401 (Unauthorized) or if the exchange\n * contains an error of type `RefreshTokenError`. If either condition is met, it invokes\n * the configured `onUnauthorized` callback with the exchange details. The method\n * does not return a value or throw exceptions - all error handling is delegated\n * to the callback function.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for unauthorized status codes or refresh token errors\n * @returns {void} This method does not return a value\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * // Custom logic here\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n if (\n exchange.response?.status === ResponseCodes.UNAUTHORIZED ||\n exchange.error instanceof RefreshTokenError\n ) {\n await this.options.onUnauthorized(exchange);\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 { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\n\n/**\n * The name identifier for the ForbiddenErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_NAME = 'ForbiddenErrorInterceptor';\n\n/**\n * The execution order for the ForbiddenErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the ForbiddenErrorInterceptor.\n */\nexport interface ForbiddenErrorInterceptorOptions {\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * This allows custom handling of authorization failures, such as displaying\n * permission error messages, redirecting to appropriate pages, or triggering\n * privilege escalation flows.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the forbidden error\n * @returns Promise that resolves when the forbidden error handling is complete\n *\n * @example\n * ```typescript\n * const options: ForbiddenErrorInterceptorOptions = {\n * onForbidden: async (exchange) => {\n * console.log('Access forbidden for:', exchange.request.url);\n * // Show permission error or redirect\n * showPermissionError('You do not have permission to access this resource');\n * }\n * };\n * ```\n */\n onForbidden: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * An error interceptor that handles HTTP 403 Forbidden responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authorization failures\n * across all HTTP requests. When a response with status code 403 is encountered, it calls\n * the configured `onForbidden` callback, allowing applications to implement custom\n * authorization recovery logic such as:\n * - Displaying permission error messages\n * - Redirecting users to access request pages\n * - Triggering privilege escalation workflows\n * - Logging security events\n * - Showing upgrade prompts for premium features\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function. This allows for flexible, application-specific\n * handling of forbidden access scenarios.\n *\n * @example\n * ```typescript\n * // Basic usage with error display\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * console.log('Forbidden access detected for:', exchange.request.url);\n * showErrorToast('You do not have permission to access this resource');\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with role-based handling\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * const userRole = getCurrentUserRole();\n *\n * if (userRole === 'guest') {\n * // Redirect to login for guests\n * redirectToLogin(exchange.request.url);\n * } else if (userRole === 'user') {\n * // Show upgrade prompt for basic users\n * showUpgradePrompt('Upgrade to premium for access to this feature');\n * } else {\n * // Log security event for authenticated users\n * logSecurityEvent('Forbidden access attempt', {\n * url: exchange.request.url,\n * userId: getCurrentUserId(),\n * timestamp: new Date().toISOString()\n * });\n * showErrorToast('Access denied due to insufficient permissions');\n * }\n * }\n * });\n * ```\n */\nexport class ForbiddenErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n * Used for registration, debugging, and interceptor chain management.\n */\n readonly name = FORBIDDEN_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the error interceptor chain.\n * Lower values execute earlier in the chain. Default priority (0) allows other\n * interceptors to run first if needed.\n */\n readonly order = FORBIDDEN_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new ForbiddenErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle forbidden responses.\n * Must include the `onForbidden` callback function.\n *\n * @throws Will throw an error if options are not provided or if `onForbidden` callback is missing.\n *\n * @example\n * ```typescript\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // Handle forbidden access\n * }\n * });\n * ```\n */\n constructor(private options: ForbiddenErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle forbidden (403) responses.\n *\n * This method examines the response status code and invokes the configured `onForbidden`\n * callback when a 403 Forbidden response is detected. The method is asynchronous to\n * allow the callback to perform async operations like API calls, redirects, or UI updates.\n *\n * The interceptor only acts on responses with status code 403. Other error codes are\n * ignored and passed through to other error interceptors in the chain.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for forbidden status codes. The exchange object provides\n * access to the original request, response details, and any error information.\n * @returns Promise that resolves when the forbidden error handling is complete.\n * Returns void - the method does not modify the exchange or return values.\n *\n * @remarks\n * - Only responds to HTTP 403 status codes\n * - Does not retry requests or modify responses\n * - Allows async operations in the callback\n * - Does not throw exceptions - delegates all error handling to the callback\n * - Safe to use with other error interceptors\n *\n * @example\n * ```typescript\n * // The intercept method is called automatically by the fetcher\n * // No manual invocation needed - this is for documentation purposes\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // exchange.response.status === 403\n * // exchange.request contains original request details\n * await handleForbiddenAccess(exchange);\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n // Check if the response status indicates forbidden access (403)\n if (exchange.response?.status === ResponseCodes.FORBIDDEN) {\n // Invoke the custom forbidden error handler\n // Allow the callback to perform async operations\n await this.options.onForbidden(exchange);\n }\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","BroadcastTypedEventBus","SerialTypedEventBus","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","RefreshTokenError","FetcherError","cause","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","UNAUTHORIZED_ERROR_INTERCEPTOR_NAME","UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER","UnauthorizedErrorInterceptor","FORBIDDEN_ERROR_INTERCEPTOR_NAME","FORBIDDEN_ERROR_INTERCEPTOR_ORDER","ForbiddenErrorInterceptor"],"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,CAG3B,EAFEA,EAAgB,aAAe,IAC/BA,EAAgB,UAAY,IAFvB,IAAMC,EAAND,EAwCA,MAAME,EAAmB,CAC9B,MAAO,CAAE,WAA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,CAAC,CAClE,CACF,CChCO,MAAMwB,EACX,+BAMWC,EAAuC,EA6C7C,MAAMC,CAAyD,CAgBpE,YAAoB3D,EAA8C,CAA9C,KAAA,QAAAA,EAZpB,KAAS,KAAOyD,EAKhB,KAAS,MAAQC,CAQjB,CAyBA,MAAM,UAAUzD,EAAwC,EAEpDA,EAAS,UAAU,SAAWX,EAAc,cAC5CW,EAAS,iBAAiBkC,IAE1B,MAAM,KAAK,QAAQ,eAAelC,CAAQ,CAE9C,CACF,CCtGO,MAAM2D,EAAmC,4BAMnCC,EAAoC,EAsF1C,MAAMC,CAAsD,CA+BjE,YAAoB9D,EAA2C,CAA3C,KAAA,QAAAA,EA1BpB,KAAS,KAAO4D,EAOhB,KAAS,MAAQC,CAoBjB,CAsCA,MAAM,UAAU5D,EAAwC,CAElDA,EAAS,UAAU,SAAWX,EAAc,WAG9C,MAAM,KAAK,QAAQ,YAAYW,CAAQ,CAE3C,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","../src/unauthorizedErrorInterceptor.ts","../src/forbiddenErrorInterceptor.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 static readonly FORBIDDEN = 403;\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\n /**\n * Creates a new AuthorizationResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(private options: AuthorizationInterceptorOptions) {\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({ delegate: 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 { TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\nexport class RefreshTokenError extends FetcherError {\n constructor(\n public readonly token: JwtCompositeToken,\n cause?: Error | any,\n ) {\n super(`Refresh token failed.`, cause);\n this.name = 'RefreshTokenError';\n Object.setPrototypeOf(this, RefreshTokenError.prototype);\n }\n}\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 * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(): Promise<void> {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher\n .refresh(jwtToken.token)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw new RefreshTokenError(jwtToken, 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({ delegate: 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, this.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 */\nimport { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\nimport { RefreshTokenError } from './jwtTokenManager';\n\n/**\n * The name identifier for the UnauthorizedErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_NAME =\n 'UnauthorizedErrorInterceptor';\n\n/**\n * The execution order for the UnauthorizedErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the UnauthorizedErrorInterceptor.\n */\nexport interface UnauthorizedErrorInterceptorOptions {\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * This allows custom handling of authentication failures, such as redirecting to login\n * or triggering token refresh mechanisms.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the unauthorized error\n */\n onUnauthorized: (exchange: FetchExchange) => Promise<void> | void;\n}\n\n/**\n * An error interceptor that handles HTTP 401 Unauthorized responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authentication failures\n * across all HTTP requests. When a response with status code 401 is encountered, it calls\n * the configured `onUnauthorized` callback, allowing applications to implement custom\n * authentication recovery logic such as:\n * - Redirecting users to login pages\n * - Triggering token refresh flows\n * - Clearing stored authentication state\n * - Displaying authentication error messages\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function.\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * console.log('Unauthorized access detected for:', exchange.request.url);\n * // Redirect to login page or refresh token\n * window.location.href = '/login';\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n */\nexport class UnauthorizedErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n */\n readonly name = UNAUTHORIZED_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the chain.\n */\n readonly order = UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new UnauthorizedErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle unauthorized responses\n */\n constructor(private options: UnauthorizedErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle unauthorized (401) responses\n * and RefreshTokenError exceptions.\n *\n * This method checks if the response status is 401 (Unauthorized) or if the exchange\n * contains an error of type `RefreshTokenError`. If either condition is met, it invokes\n * the configured `onUnauthorized` callback with the exchange details. The method\n * does not return a value or throw exceptions - all error handling is delegated\n * to the callback function.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for unauthorized status codes or refresh token errors\n * @returns {void} This method does not return a value\n *\n * @example\n * ```typescript\n * const interceptor = new UnauthorizedErrorInterceptor({\n * onUnauthorized: (exchange) => {\n * // Custom logic here\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n if (\n exchange.response?.status === ResponseCodes.UNAUTHORIZED ||\n exchange.error instanceof RefreshTokenError\n ) {\n await this.options.onUnauthorized(exchange);\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 { ErrorInterceptor, FetchExchange } from '@ahoo-wang/fetcher';\nimport { ResponseCodes } from './types';\n\n/**\n * The name identifier for the ForbiddenErrorInterceptor.\n * Used for interceptor registration and identification in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_NAME = 'ForbiddenErrorInterceptor';\n\n/**\n * The execution order for the ForbiddenErrorInterceptor.\n * Set to 0, indicating it runs at default priority in the interceptor chain.\n */\nexport const FORBIDDEN_ERROR_INTERCEPTOR_ORDER = 0;\n\n/**\n * Configuration options for the ForbiddenErrorInterceptor.\n */\nexport interface ForbiddenErrorInterceptorOptions {\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * This allows custom handling of authorization failures, such as displaying\n * permission error messages, redirecting to appropriate pages, or triggering\n * privilege escalation flows.\n *\n * @param exchange - The fetch exchange containing the request and response details\n * that resulted in the forbidden error\n * @returns Promise that resolves when the forbidden error handling is complete\n *\n * @example\n * ```typescript\n * const options: ForbiddenErrorInterceptorOptions = {\n * onForbidden: async (exchange) => {\n * console.log('Access forbidden for:', exchange.request.url);\n * // Show permission error or redirect\n * showPermissionError('You do not have permission to access this resource');\n * }\n * };\n * ```\n */\n onForbidden: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * An error interceptor that handles HTTP 403 Forbidden responses by invoking a custom callback.\n *\n * This interceptor is designed to provide centralized handling of authorization failures\n * across all HTTP requests. When a response with status code 403 is encountered, it calls\n * the configured `onForbidden` callback, allowing applications to implement custom\n * authorization recovery logic such as:\n * - Displaying permission error messages\n * - Redirecting users to access request pages\n * - Triggering privilege escalation workflows\n * - Logging security events\n * - Showing upgrade prompts for premium features\n *\n * The interceptor does not modify the response or retry requests automatically - it delegates\n * all handling to the provided callback function. This allows for flexible, application-specific\n * handling of forbidden access scenarios.\n *\n * @example\n * ```typescript\n * // Basic usage with error display\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * console.log('Forbidden access detected for:', exchange.request.url);\n * showErrorToast('You do not have permission to access this resource');\n * }\n * });\n *\n * fetcher.interceptors.error.use(interceptor);\n * ```\n *\n * @example\n * ```typescript\n * // Advanced usage with role-based handling\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * const userRole = getCurrentUserRole();\n *\n * if (userRole === 'guest') {\n * // Redirect to login for guests\n * redirectToLogin(exchange.request.url);\n * } else if (userRole === 'user') {\n * // Show upgrade prompt for basic users\n * showUpgradePrompt('Upgrade to premium for access to this feature');\n * } else {\n * // Log security event for authenticated users\n * logSecurityEvent('Forbidden access attempt', {\n * url: exchange.request.url,\n * userId: getCurrentUserId(),\n * timestamp: new Date().toISOString()\n * });\n * showErrorToast('Access denied due to insufficient permissions');\n * }\n * }\n * });\n * ```\n */\nexport class ForbiddenErrorInterceptor implements ErrorInterceptor {\n /**\n * The unique name identifier for this interceptor instance.\n * Used for registration, debugging, and interceptor chain management.\n */\n readonly name = FORBIDDEN_ERROR_INTERCEPTOR_NAME;\n\n /**\n * The execution order priority for this interceptor in the error interceptor chain.\n * Lower values execute earlier in the chain. Default priority (0) allows other\n * interceptors to run first if needed.\n */\n readonly order = FORBIDDEN_ERROR_INTERCEPTOR_ORDER;\n\n /**\n * Creates a new ForbiddenErrorInterceptor instance.\n *\n * @param options - Configuration options containing the callback to handle forbidden responses.\n * Must include the `onForbidden` callback function.\n *\n * @throws Will throw an error if options are not provided or if `onForbidden` callback is missing.\n *\n * @example\n * ```typescript\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // Handle forbidden access\n * }\n * });\n * ```\n */\n constructor(private options: ForbiddenErrorInterceptorOptions) {\n }\n\n /**\n * Intercepts fetch exchanges to detect and handle forbidden (403) responses.\n *\n * This method examines the response status code and invokes the configured `onForbidden`\n * callback when a 403 Forbidden response is detected. The method is asynchronous to\n * allow the callback to perform async operations like API calls, redirects, or UI updates.\n *\n * The interceptor only acts on responses with status code 403. Other error codes are\n * ignored and passed through to other error interceptors in the chain.\n *\n * @param exchange - The fetch exchange containing request, response, and error information\n * to be inspected for forbidden status codes. The exchange object provides\n * access to the original request, response details, and any error information.\n * @returns Promise that resolves when the forbidden error handling is complete.\n * Returns void - the method does not modify the exchange or return values.\n *\n * @remarks\n * - Only responds to HTTP 403 status codes\n * - Does not retry requests or modify responses\n * - Allows async operations in the callback\n * - Does not throw exceptions - delegates all error handling to the callback\n * - Safe to use with other error interceptors\n *\n * @example\n * ```typescript\n * // The intercept method is called automatically by the fetcher\n * // No manual invocation needed - this is for documentation purposes\n * const interceptor = new ForbiddenErrorInterceptor({\n * onForbidden: async (exchange) => {\n * // exchange.response.status === 403\n * // exchange.request contains original request details\n * await handleForbiddenAccess(exchange);\n * }\n * });\n * ```\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n // Check if the response status indicates forbidden access (403)\n if (exchange.response?.status === ResponseCodes.FORBIDDEN) {\n // Invoke the custom forbidden error handler\n // Allow the callback to perform async operations\n await this.options.onForbidden(exchange);\n }\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","BroadcastTypedEventBus","SerialTypedEventBus","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","RefreshTokenError","FetcherError","cause","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","UNAUTHORIZED_ERROR_INTERCEPTOR_NAME","UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER","UnauthorizedErrorInterceptor","FORBIDDEN_ERROR_INTERCEPTOR_NAME","FORBIDDEN_ERROR_INTERCEPTOR_ORD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uD,EACL,SAAU,IAAItC,EAAAA,uBAAuB,CAAE,SAAU,IAAIC,EAAAA,oBAAoBqC,CAAuB,CAAA,CAAG,CAAA,EAErG,CACA,MAAM,CACJ,WAAY,IAAIxB,EAA4B/B,EAAQ,WAAW,EAC/D,GAAGA,CAAA,CACJ,EACD,KAAK,YAAcA,EAAQ,aAAe,CAC5C,CAEA,kBAAkBiC,EAAgC,CAChD,KAAK,IAAI,IAAIH,EAAkBG,EAAgB,KAAK,WAAW,CAAC,CAClE,CACF,CChCO,MAAMwB,EACX,+BAMWC,EAAuC,EA6C7C,MAAMC,CAAyD,CAgBpE,YAAoB3D,EAA8C,CAA9C,KAAA,QAAAA,EAZpB,KAAS,KAAOyD,EAKhB,KAAS,MAAQC,CAQjB,CAyBA,MAAM,UAAUzD,EAAwC,EAEpDA,EAAS,UAAU,SAAWX,EAAc,cAC5CW,EAAS,iBAAiBkC,IAE1B,MAAM,KAAK,QAAQ,eAAelC,CAAQ,CAE9C,CACF,CCtGO,MAAM2D,EAAmC,4BAMnCC,EAAoC,EAsF1C,MAAMC,CAAsD,CA+BjE,YAAoB9D,EAA2C,CAA3C,KAAA,QAAAA,EA1BpB,KAAS,KAAO4D,EAOhB,KAAS,MAAQC,CAoBjB,CAsCA,MAAM,UAAU5D,EAAwC,CAElDA,EAAS,UAAU,SAAWX,EAAc,WAG9C,MAAM,KAAK,QAAQ,YAAYW,CAAQ,CAE3C,CACF"}
@@ -1,9 +1,10 @@
1
1
  import { TokenStorage } from './tokenStorage';
2
- import { CompositeToken, TokenRefresher } from './tokenRefresher';
2
+ import { TokenRefresher } from './tokenRefresher';
3
3
  import { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';
4
4
  import { FetcherError } from '@ahoo-wang/fetcher';
5
5
  export declare class RefreshTokenError extends FetcherError {
6
- constructor(cause?: Error | any);
6
+ readonly token: JwtCompositeToken;
7
+ constructor(token: JwtCompositeToken, cause?: Error | any);
7
8
  }
8
9
  /**
9
10
  * Manages JWT token refreshing operations and provides status information
@@ -25,11 +26,10 @@ export declare class JwtTokenManager implements RefreshTokenStatusCapable {
25
26
  get currentToken(): JwtCompositeToken | null;
26
27
  /**
27
28
  * Refreshes the JWT token
28
- * @param currentToken Optional current token to refresh. If not provided, uses the stored token.
29
29
  * @returns Promise that resolves when refresh is complete
30
30
  * @throws Error if no token is found or refresh fails
31
31
  */
32
- refresh(currentToken?: CompositeToken): Promise<void>;
32
+ refresh(): Promise<void>;
33
33
  /**
34
34
  * Indicates if the current token needs to be refreshed
35
35
  * @returns true if the access token is expired and needs refresh, false otherwise
@@ -1 +1 @@
1
- {"version":3,"file":"jwtTokenManager.d.ts","sourceRoot":"","sources":["../src/jwtTokenManager.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,qBAAa,iBAAkB,SAAQ,YAAY;gBACrC,KAAK,CAAC,EAAE,KAAK,GAAG,GAAG;CAOhC;AAED;;GAEG;AACH,qBAAa,eAAgB,YAAW,yBAAyB;aAS7C,YAAY,EAAE,YAAY;aAC1B,cAAc,EAAE,cAAc;IAThD,OAAO,CAAC,iBAAiB,CAAC,CAAgB;IAE1C;;;;OAIG;gBAEe,YAAY,EAAE,YAAY,EAC1B,cAAc,EAAE,cAAc;IAIhD;;;OAGG;IACH,IAAI,YAAY,IAAI,iBAAiB,GAAG,IAAI,CAE3C;IAED;;;;;OAKG;IACG,OAAO,CAAC,YAAY,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA4B3D;;;OAGG;IACH,IAAI,eAAe,IAAI,OAAO,CAK7B;IAED;;;OAGG;IACH,IAAI,aAAa,IAAI,OAAO,CAK3B;CACF"}
1
+ {"version":3,"file":"jwtTokenManager.d.ts","sourceRoot":"","sources":["../src/jwtTokenManager.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,qBAAa,iBAAkB,SAAQ,YAAY;aAE/B,KAAK,EAAE,iBAAiB;gBAAxB,KAAK,EAAE,iBAAiB,EACxC,KAAK,CAAC,EAAE,KAAK,GAAG,GAAG;CAMtB;AAED;;GAEG;AACH,qBAAa,eAAgB,YAAW,yBAAyB;aAS7C,YAAY,EAAE,YAAY;aAC1B,cAAc,EAAE,cAAc;IAThD,OAAO,CAAC,iBAAiB,CAAC,CAAgB;IAE1C;;;;OAIG;gBAEe,YAAY,EAAE,YAAY,EAC1B,cAAc,EAAE,cAAc;IAIhD;;;OAGG;IACH,IAAI,YAAY,IAAI,iBAAiB,GAAG,IAAI,CAE3C;IAED;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAyB9B;;;OAGG;IACH,IAAI,eAAe,IAAI,OAAO,CAK7B;IAED;;;OAGG;IACH,IAAI,aAAa,IAAI,OAAO,CAK3B;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-cosec",
3
- "version": "3.0.0",
3
+ "version": "3.0.2",
4
4
  "description": "Enterprise-grade CoSec authentication integration for the Fetcher HTTP client with comprehensive security features including automatic token management, device tracking, and request attribution.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -39,22 +39,22 @@
39
39
  "dist"
40
40
  ],
41
41
  "peerDependencies": {
42
- "@ahoo-wang/fetcher": "^2.3.4",
43
- "@ahoo-wang/fetcher-eventbus": "^2.8.5",
44
- "@ahoo-wang/fetcher-storage": "^2.3.4"
42
+ "@ahoo-wang/fetcher": "^3.0.0",
43
+ "@ahoo-wang/fetcher-eventbus": "^3.0.0",
44
+ "@ahoo-wang/fetcher-storage": "^3.0.0"
45
45
  },
46
46
  "dependencies": {
47
47
  "nanoid": "^5.1.6"
48
48
  },
49
49
  "devDependencies": {
50
- "@eslint/js": "^9.38.0",
50
+ "@eslint/js": "^9.39.1",
51
51
  "@vitest/coverage-v8": "^3.2.4",
52
52
  "@vitest/ui": "^3.2.4",
53
- "eslint": "^9.38.0",
54
- "globals": "^16.4.0",
53
+ "eslint": "^9.39.1",
54
+ "globals": "^16.5.0",
55
55
  "prettier": "^3.6.2",
56
56
  "typescript": "^5.9.3",
57
- "typescript-eslint": "^8.46.2",
57
+ "typescript-eslint": "^8.46.3",
58
58
  "unplugin-dts": "1.0.0-beta.6",
59
59
  "vite": "^7.1.12",
60
60
  "vite-bundle-analyzer": "^1.2.3",