@ahoo-wang/fetcher-cosec 3.4.6 → 3.5.1

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.
@@ -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/forbiddenErrorInterceptor.ts","../src/jwtTokenManager.ts","../src/resourceAttributionRequestInterceptor.ts","../src/jwts.ts","../src/jwtToken.ts","../src/tokenStorage.ts","../src/unauthorizedErrorInterceptor.ts","../src/cosecConfigurer.ts","../src/tokenRefresher.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 * 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 * 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\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 * 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 * 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 { KeyStorage, KeyStorageOptions, typedIdentitySerializer } from '@ahoo-wang/fetcher-storage';\nimport {\n BroadcastTypedEventBus,\n SerialTypedEventBus,\n} 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\n extends Partial<KeyStorageOptions<string>> {\n}\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor({\n key = DEFAULT_COSEC_DEVICE_ID_KEY,\n eventBus = new BroadcastTypedEventBus({\n delegate: new SerialTypedEventBus(DEFAULT_COSEC_DEVICE_ID_KEY),\n }),\n ...reset\n }: DeviceIdStorageOptions = {}) {\n super({ key, eventBus, ...reset, serializer: typedIdentitySerializer() });\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\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 * 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","/*\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 * 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\nconst TENANT_ID_PATH_KEY = 'tenantId';\nconst OWNER_ID_PATH_KEY = 'ownerId';\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{\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 = TENANT_ID_PATH_KEY,\n ownerId = OWNER_ID_PATH_KEY,\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/**\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{\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{\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{\n constructor(public readonly earlyPeriod: number = 0) {}\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 { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\nimport { KeyStorage, KeyStorageOptions } from '@ahoo-wang/fetcher-storage';\nimport {\n BroadcastTypedEventBus,\n SerialTypedEventBus,\n} from '@ahoo-wang/fetcher-eventbus';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\nexport interface TokenStorageOptions\n extends Partial<Omit<KeyStorageOptions<JwtCompositeToken>, 'serializer'>>,\n Partial<EarlyPeriodCapable> {}\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable\n{\n public readonly earlyPeriod: number;\n\n constructor({\n key = DEFAULT_COSEC_TOKEN_KEY,\n eventBus = new BroadcastTypedEventBus({\n delegate: new SerialTypedEventBus(DEFAULT_COSEC_TOKEN_KEY),\n }),\n earlyPeriod = 0,\n ...reset\n }: TokenStorageOptions = {}) {\n super({\n key,\n eventBus,\n ...reset,\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n this.earlyPeriod = earlyPeriod;\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(new JwtCompositeToken(compositeToken, this.earlyPeriod));\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 */\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 * 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 { Fetcher, FetcherConfigurer, FetchExchange } from '@ahoo-wang/fetcher';\nimport { AuthorizationRequestInterceptor } from './authorizationRequestInterceptor';\nimport { AuthorizationResponseInterceptor } from './authorizationResponseInterceptor';\nimport { CoSecRequestInterceptor } from './cosecRequestInterceptor';\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { ForbiddenErrorInterceptor } from './forbiddenErrorInterceptor';\nimport { JwtTokenManager } from './jwtTokenManager';\nimport { ResourceAttributionRequestInterceptor } from './resourceAttributionRequestInterceptor';\nimport { TokenRefresher } from './tokenRefresher';\nimport { TokenStorage } from './tokenStorage';\nimport { UnauthorizedErrorInterceptor } from './unauthorizedErrorInterceptor';\nimport { AppIdCapable, DeviceIdStorageCapable } from './types';\n\n/**\n * Simplified configuration interface for CoSec setup.\n * Provides flexible configuration with sensible defaults for optional components.\n */\nexport interface CoSecConfig\n extends AppIdCapable,\n Partial<DeviceIdStorageCapable> {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n * This is required for identifying your application in the CoSec system.\n */\n appId: string;\n\n /**\n * Custom token storage implementation.\n * If not provided, a default TokenStorage instance will be created.\n * Useful for custom storage backends or testing scenarios.\n */\n tokenStorage?: TokenStorage;\n\n /**\n * Custom device ID storage implementation.\n * If not provided, a default DeviceIdStorage instance will be created.\n * Useful for custom device identification strategies or testing scenarios.\n */\n deviceIdStorage?: DeviceIdStorage;\n\n /**\n * Token refresher implementation for handling expired tokens.\n * If not provided, authentication interceptors will not be added.\n * This enables CoSec configuration without full JWT authentication.\n */\n tokenRefresher?: TokenRefresher;\n\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * If not provided, 401 errors will not be intercepted.\n */\n onUnauthorized?: (exchange: FetchExchange) => Promise<void> | void;\n\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * If not provided, 403 errors will not be intercepted.\n */\n onForbidden?: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * CoSecConfigurer provides a flexible way to configure CoSec interceptors\n * and dependencies with a single configuration object.\n *\n * This class implements FetcherConfigurer and supports both full authentication\n * setups and minimal CoSec header injection. It conditionally creates dependencies\n * based on the provided configuration, allowing for different levels of integration.\n *\n * @implements {FetcherConfigurer}\n *\n * @example\n * Full authentication setup with custom storage:\n * ```typescript\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app-001',\n * tokenStorage: new CustomTokenStorage(),\n * deviceIdStorage: new CustomDeviceStorage(),\n * tokenRefresher: {\n * refresh: async (token: CompositeToken) => {\n * const response = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token.refreshToken }),\n * });\n * const newTokens = await response.json();\n * return {\n * accessToken: newTokens.accessToken,\n * refreshToken: newTokens.refreshToken,\n * };\n * },\n * },\n * onUnauthorized: (exchange) => redirectToLogin(),\n * onForbidden: (exchange) => showPermissionError(),\n * });\n *\n * configurer.applyTo(fetcher);\n * ```\n *\n * @example\n * Minimal setup with only CoSec headers (no authentication):\n * ```typescript\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app-001',\n * // No tokenRefresher provided - authentication interceptors won't be added\n * });\n *\n * configurer.applyTo(fetcher);\n * ```\n */\nexport class CoSecConfigurer implements FetcherConfigurer {\n /**\n * Token storage instance, either provided in config or auto-created.\n */\n readonly tokenStorage: TokenStorage;\n\n /**\n * Device ID storage instance, either provided in config or auto-created.\n */\n readonly deviceIdStorage: DeviceIdStorage;\n\n /**\n * JWT token manager instance, only created if tokenRefresher is provided.\n * When undefined, authentication interceptors will not be added.\n */\n readonly tokenManager?: JwtTokenManager;\n\n /**\n * Creates a new CoSecConfigurer instance with the provided configuration.\n *\n * This constructor conditionally creates dependencies based on the configuration:\n * - TokenStorage and DeviceIdStorage are always created (using defaults if not provided)\n * - JwtTokenManager is only created if tokenRefresher is provided\n *\n * @param config - CoSec configuration object\n *\n * @example\n * ```typescript\n * // Full setup with all dependencies\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenRefresher: myTokenRefresher,\n * });\n *\n * // Minimal setup with custom storage\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenStorage: customStorage,\n * deviceIdStorage: customDeviceStorage,\n * });\n * ```\n */\n constructor(public readonly config: CoSecConfig) {\n // Create storage instances with fallbacks to defaults\n this.tokenStorage = config.tokenStorage ?? new TokenStorage();\n this.deviceIdStorage = config.deviceIdStorage ?? new DeviceIdStorage();\n\n // Create token manager only if token refresher is provided\n if (config.tokenRefresher) {\n this.tokenManager = new JwtTokenManager(\n this.tokenStorage,\n config.tokenRefresher,\n );\n }\n }\n\n /**\n * Applies CoSec interceptors to the provided Fetcher instance.\n *\n * This method conditionally configures interceptors based on the provided configuration:\n *\n * Always added:\n * 1. CoSecRequestInterceptor - Adds CoSec headers (appId, deviceId, requestId)\n * 2. ResourceAttributionRequestInterceptor - Adds tenant/owner path parameters\n *\n * Only when `tokenRefresher` is provided:\n * 3. AuthorizationRequestInterceptor - Adds Bearer token authentication\n * 4. AuthorizationResponseInterceptor - Handles token refresh on 401 responses\n *\n * Only when corresponding handlers are provided:\n * 5. UnauthorizedErrorInterceptor - Handles 401 unauthorized errors\n * 6. ForbiddenErrorInterceptor - Handles 403 forbidden errors\n *\n * @param fetcher - The Fetcher instance to configure\n *\n * @example\n * ```typescript\n * const fetcher = new Fetcher({ baseURL: '/api' });\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenRefresher: myTokenRefresher,\n * onUnauthorized: handle401,\n * onForbidden: handle403,\n * });\n *\n * configurer.applyTo(fetcher);\n * // Now fetcher has all CoSec interceptors configured\n * ```\n */\n applyTo(fetcher: Fetcher): void {\n fetcher.interceptors.request.use(\n new CoSecRequestInterceptor({\n appId: this.config.appId,\n deviceIdStorage: this.deviceIdStorage,\n }),\n );\n\n fetcher.interceptors.request.use(\n new ResourceAttributionRequestInterceptor({\n tokenStorage: this.tokenStorage,\n }),\n );\n if (this.tokenManager) {\n fetcher.interceptors.request.use(\n new AuthorizationRequestInterceptor({\n tokenManager: this.tokenManager,\n }),\n );\n\n fetcher.interceptors.response.use(\n new AuthorizationResponseInterceptor({\n tokenManager: this.tokenManager,\n }),\n );\n }\n if (this.config.onUnauthorized) {\n fetcher.interceptors.error.use(\n new UnauthorizedErrorInterceptor({\n onUnauthorized: this.config.onUnauthorized,\n }),\n );\n }\n\n if (this.config.onForbidden) {\n fetcher.interceptors.error.use(\n new ForbiddenErrorInterceptor({\n onForbidden: this.config.onForbidden,\n }),\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 { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface representing an access token used for authentication.\n *\n * This interface defines the structure for access tokens, which are typically\n * short-lived tokens used to authenticate API requests.\n *\n * @interface AccessToken\n * @property {string} accessToken - The access token string used for authentication.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface representing a refresh token used to obtain new access tokens.\n *\n * Refresh tokens are long-lived tokens that can be used to request new access\n * tokens without requiring the user to re-authenticate.\n *\n * @interface RefreshToken\n * @property {string} refreshToken - The refresh token string used to obtain new access tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * This interface combines AccessToken and RefreshToken, ensuring that both\n * tokens are always handled together. In authentication systems, access and\n * refresh tokens are typically issued and refreshed as a pair.\n *\n * @interface CompositeToken\n * @extends AccessToken\n * @extends RefreshToken\n * @property {string} accessToken - The access token string used for authentication.\n * @property {string} refreshToken - The refresh token string used to obtain new access tokens.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {}\n\n/**\n * Interface for token refreshers.\n *\n * This interface defines the contract for classes responsible for refreshing\n * authentication tokens. Implementations should handle the logic of exchanging\n * an expired or soon-to-expire token for a new one.\n *\n * **CRITICAL**: When implementing the `refresh` method, always include the\n * `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])` in the\n * request options to prevent infinite loops. Without this attribute, the request\n * interceptor may attempt to refresh the token recursively, causing a deadlock.\n *\n * @interface TokenRefresher\n */\nexport interface TokenRefresher {\n /**\n * Refreshes the given composite token and returns a new one.\n *\n * This method should send the provided token to the appropriate endpoint\n * and return the refreshed token pair. **IMPORTANT**: The implementation must\n * include `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])`\n * in the request options to prevent recursive refresh attempts that could\n * cause infinite loops.\n *\n * @param {CompositeToken} token - The composite token to refresh, containing both access and refresh tokens.\n * @returns {Promise<CompositeToken>} A promise that resolves to a new CompositeToken with updated access and refresh tokens.\n * @throws {Error} Throws an error if the token refresh fails due to network issues, invalid tokens, or server errors.\n *\n * @example\n * ```typescript\n * const refresher: TokenRefresher = new CoSecTokenRefresher({ fetcher, endpoint: '/auth/refresh' });\n * const newToken = await refresher.refresh(currentToken);\n * console.log('New access token:', newToken.accessToken);\n * ```\n *\n * @warning **Critical**: Failing to set the `IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY`\n * attribute will result in infinite loops during token refresh operations.\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\n/**\n * Configuration options for the CoSecTokenRefresher class.\n *\n * This interface defines the required options to initialize a CoSecTokenRefresher\n * instance, including the HTTP client and the refresh endpoint URL.\n *\n * @interface CoSecTokenRefresherOptions\n * @property {Fetcher} fetcher - The HTTP client instance used to make requests to the refresh endpoint.\n * @property {string} endpoint - The URL endpoint where token refresh requests are sent.\n */\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * Implementation of TokenRefresher for refreshing composite tokens using CoSec authentication.\n *\n * This class provides a concrete implementation of the TokenRefresher interface,\n * using the provided Fetcher instance to send POST requests to a specified endpoint\n * for token refresh operations. It is designed to work with CoSec (Corporate Security)\n * authentication systems.\n *\n * @class CoSecTokenRefresher\n * @implements TokenRefresher\n *\n * @example\n * ```typescript\n * import { Fetcher } from '@ahoo-wang/fetcher';\n * import { CoSecTokenRefresher } from './tokenRefresher';\n *\n * const fetcher = new Fetcher();\n * const refresher = new CoSecTokenRefresher({\n * fetcher,\n * endpoint: 'https://api.example.com/auth/refresh'\n * });\n *\n * const currentToken = { accessToken: 'old-token', refreshToken: 'refresh-token' };\n * const newToken = await refresher.refresh(currentToken);\n * ```\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param {CoSecTokenRefresherOptions} options - The configuration options for the token refresher.\n * @param {Fetcher} options.fetcher - The HTTP client instance used for making refresh requests.\n * @param {string} options.endpoint - The URL endpoint for token refresh operations.\n *\n * @example\n * ```typescript\n * const refresher = new CoSecTokenRefresher({\n * fetcher: myFetcherInstance,\n * endpoint: '/api/v1/auth/refresh'\n * });\n * ```\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {}\n\n /**\n * Refreshes the given composite token by sending a POST request to the configured endpoint.\n *\n * This method sends the current token pair to the refresh endpoint and expects\n * a new CompositeToken in response.\n *\n * **CRITICAL**: The request includes a special\n * attribute `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])`\n * to prevent infinite loops. Without this attribute, the request interceptor\n * may attempt to refresh the token again, causing a recursive loop.\n *\n * @param {CompositeToken} token - The composite token to refresh, containing both access and refresh tokens.\n * @returns {Promise<CompositeToken>} A promise that resolves to a new CompositeToken with refreshed tokens.\n * @throws {Error} Throws an error if the HTTP request fails, the server returns an error status, or the response cannot be parsed as JSON.\n * @throws {NetworkError} Throws a network error if there are connectivity issues.\n * @throws {AuthenticationError} Throws an authentication error if the refresh token is invalid or expired.\n *\n * @example\n * ```typescript\n * const refresher = new CoSecTokenRefresher({ fetcher, endpoint: '/auth/refresh' });\n * const token = { accessToken: 'expired-token', refreshToken: 'valid-refresh-token' };\n *\n * try {\n * const newToken = await refresher.refresh(token);\n * console.log('Refreshed access token:', newToken.accessToken);\n * } catch (error) {\n * console.error('Token refresh failed:', error.message);\n * }\n * ```\n *\n * @warning **Important**: Always include the `IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY` attribute\n * in refresh requests to avoid infinite loops caused by recursive token refresh attempts.\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"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","eventBus","BroadcastTypedEventBus","SerialTypedEventBus","reset","typedIdentitySerializer","FORBIDDEN_ERROR_INTERCEPTOR_NAME","FORBIDDEN_ERROR_INTERCEPTOR_ORDER","ForbiddenErrorInterceptor","RefreshTokenError","FetcherError","token","cause","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","TENANT_ID_PATH_KEY","OWNER_ID_PATH_KEY","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","UNAUTHORIZED_ERROR_INTERCEPTOR_NAME","UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER","UnauthorizedErrorInterceptor","CoSecConfigurer","config","fetcher","CoSecTokenRefresher","ResultExtractors"],"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,EAuCA,MAAME,EAAmB,CAC9B,MAAO,CAAE,WAAY,GAAM,OAAQ,OAAA,EACnC,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,kBAAmB,CAAE,WAAY,GAAO,OAAQ,mBAAA,CAClD,EChDO,MAAMC,CAAuC,CAMlD,YAAqB,CACnB,OAAOC,SAAA,CACT,CACF,CAEO,MAAMC,EAAc,IAAIF,ECNlBG,EAAiC,0BAMjCC,EACXC,E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IAAI,CAAC,CAAC1E,EAAoC,EAAI,CAAC,CAAC,CAAA,CAClE,CAEJ,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/forbiddenErrorInterceptor.ts","../src/jwtTokenManager.ts","../src/resourceAttributionRequestInterceptor.ts","../src/jwts.ts","../src/jwtToken.ts","../src/tokenStorage.ts","../src/unauthorizedErrorInterceptor.ts","../src/cosecConfigurer.ts","../src/tokenRefresher.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 * 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 * 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\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 * 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 * 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 { KeyStorage, KeyStorageOptions, typedIdentitySerializer } from '@ahoo-wang/fetcher-storage';\nimport {\n BroadcastTypedEventBus,\n SerialTypedEventBus,\n} 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\n extends Partial<KeyStorageOptions<string>> {\n}\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor({\n key = DEFAULT_COSEC_DEVICE_ID_KEY,\n eventBus = new BroadcastTypedEventBus({\n delegate: new SerialTypedEventBus(DEFAULT_COSEC_DEVICE_ID_KEY),\n }),\n ...reset\n }: DeviceIdStorageOptions = {}) {\n super({ key, eventBus, ...reset, serializer: typedIdentitySerializer() });\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\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 * 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","/*\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 * 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\nconst TENANT_ID_PATH_KEY = 'tenantId';\nconst OWNER_ID_PATH_KEY = 'ownerId';\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{\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 = TENANT_ID_PATH_KEY,\n ownerId = OWNER_ID_PATH_KEY,\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/**\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 *\n * This interface represents a JWT token that includes the raw token string,\n * a parsed payload of a specific type, and methods to check expiration status.\n * It extends EarlyPeriodCapable to support early expiration checks.\n *\n * @template Payload The type of the JWT payload, must extend JwtPayload\n *\n * @example\n * ```typescript\n * interface CustomPayload extends JwtPayload {\n * userId: string;\n * roles: string[];\n * }\n *\n * const token: IJwtToken<CustomPayload> = new JwtToken<CustomPayload>('jwt.token.here');\n * if (!token.isExpired) {\n * console.log(token.payload?.userId);\n * }\n * ```\n */\nexport interface IJwtToken<\n Payload extends JwtPayload,\n> extends EarlyPeriodCapable {\n /**\n * The raw JWT token string.\n */\n readonly token: string;\n\n /**\n * The parsed JWT payload. Null if the token could not be parsed.\n */\n readonly payload: Payload | null;\n\n /**\n * Indicates whether the token is expired, considering the early period.\n */\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload.\n *\n * This class provides a concrete implementation of IJwtToken, parsing the JWT\n * token string and providing access to the payload and expiration status.\n * It supports early expiration periods for proactive token refresh.\n *\n * @template Payload The type of the JWT payload, must extend JwtPayload\n *\n * @example\n * ```typescript\n * const token = new JwtToken<CoSecJwtPayload>('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', 300000); // 5 min early period\n * console.log(token.isExpired); // false if not expired\n * console.log(token.payload?.sub); // user ID from payload\n * ```\n */\nexport class JwtToken<\n Payload extends JwtPayload,\n> implements IJwtToken<Payload> {\n /**\n * The parsed JWT payload. Null if the token could not be parsed.\n */\n public readonly payload: Payload | null;\n\n /**\n * Creates a new JwtToken instance.\n *\n * Parses the JWT token string to extract the payload and stores the early period\n * for expiration checks.\n *\n * @param token The raw JWT token string to parse\n * @param earlyPeriod The early expiration period in milliseconds (default: 0).\n * Tokens are considered expired this many milliseconds before their actual expiration time.\n *\n * @throws Will not throw but payload will be null if token parsing fails\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 *\n * Considers both the token's expiration time and the early period.\n * Returns true if the payload is null (parsing failed) or if the token is expired.\n *\n * @returns true if the token is expired or invalid, 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\n/**\n * Interface for checking refresh token status capabilities.\n *\n * This interface defines methods to check if token refresh is needed and possible.\n */\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed.\n *\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token.\n *\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 *\n * This class manages both access and refresh JWT tokens together, providing\n * convenient methods to check authentication status, refresh needs, and user information.\n * It implements both EarlyPeriodCapable and RefreshTokenStatusCapable interfaces.\n *\n * @example\n * ```typescript\n * const compositeToken = new JwtCompositeToken({\n * accessToken: 'access.jwt.here',\n * refreshToken: 'refresh.jwt.here'\n * }, 300000); // 5 min early period\n *\n * if (compositeToken.authenticated) {\n * console.log(compositeToken.currentUser?.sub);\n * }\n *\n * if (compositeToken.isRefreshNeeded && compositeToken.isRefreshable) {\n * // Refresh the access token\n * }\n * ```\n */\nexport class JwtCompositeToken\n implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n /**\n * The access JWT token instance.\n */\n public readonly access: JwtToken<CoSecJwtPayload>;\n\n /**\n * The refresh JWT token instance.\n */\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance.\n *\n * Initializes both access and refresh token instances with the provided early period.\n *\n * @param token The composite token containing access and refresh token strings\n * @param earlyPeriod The early expiration period in milliseconds (default: 0)\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 *\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 *\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 * Checks if the user is currently authenticated (access token is valid).\n *\n * @returns true if the access token is not expired, false otherwise\n */\n get authenticated(): boolean {\n return !this.access.isExpired;\n }\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings.\n *\n * This class provides serialization and deserialization functionality for JwtCompositeToken\n * instances, allowing them to be stored and retrieved from persistent storage.\n *\n * @example\n * ```typescript\n * const serializer = new JwtCompositeTokenSerializer(300000);\n * const token = new JwtCompositeToken({ accessToken: '...', refreshToken: '...' });\n *\n * const serialized = serializer.serialize(token);\n * const deserialized = serializer.deserialize(serialized);\n * ```\n */\nexport class JwtCompositeTokenSerializer\n implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n /**\n * Creates a new JwtCompositeTokenSerializer instance.\n *\n * @param earlyPeriod The early expiration period in milliseconds to use for deserialized tokens (default: 0)\n */\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken.\n *\n * Parses the JSON string and creates a new JwtCompositeToken instance with the stored tokens.\n *\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n * @throws SyntaxError if the JSON string is invalid\n * @throws Error if the parsed object doesn't match the expected CompositeToken structure\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 *\n * Converts the composite token to a JSON string for storage.\n *\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\n/**\n * Default instance of JwtCompositeTokenSerializer with no early period.\n *\n * This pre-configured serializer can be used directly for basic serialization needs.\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 { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { CoSecJwtPayload, EarlyPeriodCapable } from './jwts';\nimport { KeyStorage, KeyStorageOptions } from '@ahoo-wang/fetcher-storage';\nimport {\n BroadcastTypedEventBus,\n SerialTypedEventBus,\n} from '@ahoo-wang/fetcher-eventbus';\n\n/**\n * Default key used for storing CoSec tokens in storage.\n */\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Options for configuring TokenStorage.\n * Extends KeyStorageOptions excluding 'serializer' and includes EarlyPeriodCapable properties.\n */\nexport interface TokenStorageOptions\n extends\n Partial<Omit<KeyStorageOptions<JwtCompositeToken>, 'serializer'>>,\n Partial<EarlyPeriodCapable> {}\n\n/**\n * Storage class for managing access and refresh tokens in CoSec authentication.\n * Provides methods to store, retrieve, and manage JWT composite tokens with early period support.\n * Extends KeyStorage to handle persistence and implements EarlyPeriodCapable for token refresh timing.\n */\nexport class TokenStorage\n extends KeyStorage<JwtCompositeToken>\n implements EarlyPeriodCapable\n{\n /**\n * The early period in milliseconds for token refresh timing.\n */\n public readonly earlyPeriod: number;\n\n /**\n * Creates a new TokenStorage instance.\n * @param options - Configuration options for the token storage.\n * @param options.key - The storage key for tokens. Defaults to DEFAULT_COSEC_TOKEN_KEY.\n * @param options.eventBus - Event bus for token change notifications. Defaults to a BroadcastTypedEventBus with SerialTypedEventBus delegate.\n * @param options.earlyPeriod - Early period for token refresh in milliseconds. Defaults to 0.\n * @param reset - Additional options passed to KeyStorage.\n */\n constructor({\n key = DEFAULT_COSEC_TOKEN_KEY,\n eventBus = new BroadcastTypedEventBus({\n delegate: new SerialTypedEventBus(DEFAULT_COSEC_TOKEN_KEY),\n }),\n earlyPeriod = 0,\n ...reset\n }: TokenStorageOptions = {}) {\n super({\n key,\n eventBus,\n ...reset,\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n this.earlyPeriod = earlyPeriod;\n }\n\n /**\n * Sets a composite token in storage.\n * Converts the composite token to a JwtCompositeToken and stores it.\n * @deprecated Use signIn() instead for better semantic clarity.\n * @param compositeToken - The composite token containing access and refresh tokens.\n */\n setCompositeToken(compositeToken: CompositeToken) {\n this.signIn(compositeToken);\n }\n\n /**\n * Signs in by storing the composite token.\n * @param compositeToken - The composite token to store for authentication.\n */\n signIn(compositeToken: CompositeToken): void {\n this.set(new JwtCompositeToken(compositeToken, this.earlyPeriod));\n }\n\n /**\n * Signs out by removing the stored token.\n * Clears the token from storage.\n */\n signOut(): void {\n this.remove();\n }\n\n /**\n * Checks if the user is authenticated.\n * @returns true if a valid token is present and authenticated, false otherwise.\n */\n get authenticated(): boolean {\n return this.get()?.authenticated === true;\n }\n\n /**\n * Gets the current user's JWT payload.\n * @returns The JWT payload of the current user if authenticated, null otherwise.\n */\n get currentUser(): CoSecJwtPayload | null {\n if (!this.authenticated) {\n return null;\n }\n return this.get()?.access.payload ?? null;\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 */\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 * 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 { Fetcher, FetcherConfigurer, FetchExchange } from '@ahoo-wang/fetcher';\nimport { AuthorizationRequestInterceptor } from './authorizationRequestInterceptor';\nimport { AuthorizationResponseInterceptor } from './authorizationResponseInterceptor';\nimport { CoSecRequestInterceptor } from './cosecRequestInterceptor';\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { ForbiddenErrorInterceptor } from './forbiddenErrorInterceptor';\nimport { JwtTokenManager } from './jwtTokenManager';\nimport { ResourceAttributionRequestInterceptor } from './resourceAttributionRequestInterceptor';\nimport { TokenRefresher } from './tokenRefresher';\nimport { TokenStorage } from './tokenStorage';\nimport { UnauthorizedErrorInterceptor } from './unauthorizedErrorInterceptor';\nimport { AppIdCapable, DeviceIdStorageCapable } from './types';\n\n/**\n * Simplified configuration interface for CoSec setup.\n * Provides flexible configuration with sensible defaults for optional components.\n */\nexport interface CoSecConfig\n extends AppIdCapable,\n Partial<DeviceIdStorageCapable> {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n * This is required for identifying your application in the CoSec system.\n */\n appId: string;\n\n /**\n * Custom token storage implementation.\n * If not provided, a default TokenStorage instance will be created.\n * Useful for custom storage backends or testing scenarios.\n */\n tokenStorage?: TokenStorage;\n\n /**\n * Custom device ID storage implementation.\n * If not provided, a default DeviceIdStorage instance will be created.\n * Useful for custom device identification strategies or testing scenarios.\n */\n deviceIdStorage?: DeviceIdStorage;\n\n /**\n * Token refresher implementation for handling expired tokens.\n * If not provided, authentication interceptors will not be added.\n * This enables CoSec configuration without full JWT authentication.\n */\n tokenRefresher?: TokenRefresher;\n\n /**\n * Callback function invoked when an unauthorized (401) response is detected.\n * If not provided, 401 errors will not be intercepted.\n */\n onUnauthorized?: (exchange: FetchExchange) => Promise<void> | void;\n\n /**\n * Callback function invoked when a forbidden (403) response is detected.\n * If not provided, 403 errors will not be intercepted.\n */\n onForbidden?: (exchange: FetchExchange) => Promise<void>;\n}\n\n/**\n * CoSecConfigurer provides a flexible way to configure CoSec interceptors\n * and dependencies with a single configuration object.\n *\n * This class implements FetcherConfigurer and supports both full authentication\n * setups and minimal CoSec header injection. It conditionally creates dependencies\n * based on the provided configuration, allowing for different levels of integration.\n *\n * @implements {FetcherConfigurer}\n *\n * @example\n * Full authentication setup with custom storage:\n * ```typescript\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app-001',\n * tokenStorage: new CustomTokenStorage(),\n * deviceIdStorage: new CustomDeviceStorage(),\n * tokenRefresher: {\n * refresh: async (token: CompositeToken) => {\n * const response = await fetch('/api/auth/refresh', {\n * method: 'POST',\n * body: JSON.stringify({ refreshToken: token.refreshToken }),\n * });\n * const newTokens = await response.json();\n * return {\n * accessToken: newTokens.accessToken,\n * refreshToken: newTokens.refreshToken,\n * };\n * },\n * },\n * onUnauthorized: (exchange) => redirectToLogin(),\n * onForbidden: (exchange) => showPermissionError(),\n * });\n *\n * configurer.applyTo(fetcher);\n * ```\n *\n * @example\n * Minimal setup with only CoSec headers (no authentication):\n * ```typescript\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app-001',\n * // No tokenRefresher provided - authentication interceptors won't be added\n * });\n *\n * configurer.applyTo(fetcher);\n * ```\n */\nexport class CoSecConfigurer implements FetcherConfigurer {\n /**\n * Token storage instance, either provided in config or auto-created.\n */\n readonly tokenStorage: TokenStorage;\n\n /**\n * Device ID storage instance, either provided in config or auto-created.\n */\n readonly deviceIdStorage: DeviceIdStorage;\n\n /**\n * JWT token manager instance, only created if tokenRefresher is provided.\n * When undefined, authentication interceptors will not be added.\n */\n readonly tokenManager?: JwtTokenManager;\n\n /**\n * Creates a new CoSecConfigurer instance with the provided configuration.\n *\n * This constructor conditionally creates dependencies based on the configuration:\n * - TokenStorage and DeviceIdStorage are always created (using defaults if not provided)\n * - JwtTokenManager is only created if tokenRefresher is provided\n *\n * @param config - CoSec configuration object\n *\n * @example\n * ```typescript\n * // Full setup with all dependencies\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenRefresher: myTokenRefresher,\n * });\n *\n * // Minimal setup with custom storage\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenStorage: customStorage,\n * deviceIdStorage: customDeviceStorage,\n * });\n * ```\n */\n constructor(public readonly config: CoSecConfig) {\n // Create storage instances with fallbacks to defaults\n this.tokenStorage = config.tokenStorage ?? new TokenStorage();\n this.deviceIdStorage = config.deviceIdStorage ?? new DeviceIdStorage();\n\n // Create token manager only if token refresher is provided\n if (config.tokenRefresher) {\n this.tokenManager = new JwtTokenManager(\n this.tokenStorage,\n config.tokenRefresher,\n );\n }\n }\n\n /**\n * Applies CoSec interceptors to the provided Fetcher instance.\n *\n * This method conditionally configures interceptors based on the provided configuration:\n *\n * Always added:\n * 1. CoSecRequestInterceptor - Adds CoSec headers (appId, deviceId, requestId)\n * 2. ResourceAttributionRequestInterceptor - Adds tenant/owner path parameters\n *\n * Only when `tokenRefresher` is provided:\n * 3. AuthorizationRequestInterceptor - Adds Bearer token authentication\n * 4. AuthorizationResponseInterceptor - Handles token refresh on 401 responses\n *\n * Only when corresponding handlers are provided:\n * 5. UnauthorizedErrorInterceptor - Handles 401 unauthorized errors\n * 6. ForbiddenErrorInterceptor - Handles 403 forbidden errors\n *\n * @param fetcher - The Fetcher instance to configure\n *\n * @example\n * ```typescript\n * const fetcher = new Fetcher({ baseURL: '/api' });\n * const configurer = new CoSecConfigurer({\n * appId: 'my-app',\n * tokenRefresher: myTokenRefresher,\n * onUnauthorized: handle401,\n * onForbidden: handle403,\n * });\n *\n * configurer.applyTo(fetcher);\n * // Now fetcher has all CoSec interceptors configured\n * ```\n */\n applyTo(fetcher: Fetcher): void {\n fetcher.interceptors.request.use(\n new CoSecRequestInterceptor({\n appId: this.config.appId,\n deviceIdStorage: this.deviceIdStorage,\n }),\n );\n\n fetcher.interceptors.request.use(\n new ResourceAttributionRequestInterceptor({\n tokenStorage: this.tokenStorage,\n }),\n );\n if (this.tokenManager) {\n fetcher.interceptors.request.use(\n new AuthorizationRequestInterceptor({\n tokenManager: this.tokenManager,\n }),\n );\n\n fetcher.interceptors.response.use(\n new AuthorizationResponseInterceptor({\n tokenManager: this.tokenManager,\n }),\n );\n }\n if (this.config.onUnauthorized) {\n fetcher.interceptors.error.use(\n new UnauthorizedErrorInterceptor({\n onUnauthorized: this.config.onUnauthorized,\n }),\n );\n }\n\n if (this.config.onForbidden) {\n fetcher.interceptors.error.use(\n new ForbiddenErrorInterceptor({\n onForbidden: this.config.onForbidden,\n }),\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 { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface representing an access token used for authentication.\n *\n * This interface defines the structure for access tokens, which are typically\n * short-lived tokens used to authenticate API requests.\n *\n * @interface AccessToken\n * @property {string} accessToken - The access token string used for authentication.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface representing a refresh token used to obtain new access tokens.\n *\n * Refresh tokens are long-lived tokens that can be used to request new access\n * tokens without requiring the user to re-authenticate.\n *\n * @interface RefreshToken\n * @property {string} refreshToken - The refresh token string used to obtain new access tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * This interface combines AccessToken and RefreshToken, ensuring that both\n * tokens are always handled together. In authentication systems, access and\n * refresh tokens are typically issued and refreshed as a pair.\n *\n * @interface CompositeToken\n * @extends AccessToken\n * @extends RefreshToken\n * @property {string} accessToken - The access token string used for authentication.\n * @property {string} refreshToken - The refresh token string used to obtain new access tokens.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {}\n\n/**\n * Interface for token refreshers.\n *\n * This interface defines the contract for classes responsible for refreshing\n * authentication tokens. Implementations should handle the logic of exchanging\n * an expired or soon-to-expire token for a new one.\n *\n * **CRITICAL**: When implementing the `refresh` method, always include the\n * `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])` in the\n * request options to prevent infinite loops. Without this attribute, the request\n * interceptor may attempt to refresh the token recursively, causing a deadlock.\n *\n * @interface TokenRefresher\n */\nexport interface TokenRefresher {\n /**\n * Refreshes the given composite token and returns a new one.\n *\n * This method should send the provided token to the appropriate endpoint\n * and return the refreshed token pair. **IMPORTANT**: The implementation must\n * include `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])`\n * in the request options to prevent recursive refresh attempts that could\n * cause infinite loops.\n *\n * @param {CompositeToken} token - The composite token to refresh, containing both access and refresh tokens.\n * @returns {Promise<CompositeToken>} A promise that resolves to a new CompositeToken with updated access and refresh tokens.\n * @throws {Error} Throws an error if the token refresh fails due to network issues, invalid tokens, or server errors.\n *\n * @example\n * ```typescript\n * const refresher: TokenRefresher = new CoSecTokenRefresher({ fetcher, endpoint: '/auth/refresh' });\n * const newToken = await refresher.refresh(currentToken);\n * console.log('New access token:', newToken.accessToken);\n * ```\n *\n * @warning **Critical**: Failing to set the `IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY`\n * attribute will result in infinite loops during token refresh operations.\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\n/**\n * Configuration options for the CoSecTokenRefresher class.\n *\n * This interface defines the required options to initialize a CoSecTokenRefresher\n * instance, including the HTTP client and the refresh endpoint URL.\n *\n * @interface CoSecTokenRefresherOptions\n * @property {Fetcher} fetcher - The HTTP client instance used to make requests to the refresh endpoint.\n * @property {string} endpoint - The URL endpoint where token refresh requests are sent.\n */\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * Implementation of TokenRefresher for refreshing composite tokens using CoSec authentication.\n *\n * This class provides a concrete implementation of the TokenRefresher interface,\n * using the provided Fetcher instance to send POST requests to a specified endpoint\n * for token refresh operations. It is designed to work with CoSec (Corporate Security)\n * authentication systems.\n *\n * @class CoSecTokenRefresher\n * @implements TokenRefresher\n *\n * @example\n * ```typescript\n * import { Fetcher } from '@ahoo-wang/fetcher';\n * import { CoSecTokenRefresher } from './tokenRefresher';\n *\n * const fetcher = new Fetcher();\n * const refresher = new CoSecTokenRefresher({\n * fetcher,\n * endpoint: 'https://api.example.com/auth/refresh'\n * });\n *\n * const currentToken = { accessToken: 'old-token', refreshToken: 'refresh-token' };\n * const newToken = await refresher.refresh(currentToken);\n * ```\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param {CoSecTokenRefresherOptions} options - The configuration options for the token refresher.\n * @param {Fetcher} options.fetcher - The HTTP client instance used for making refresh requests.\n * @param {string} options.endpoint - The URL endpoint for token refresh operations.\n *\n * @example\n * ```typescript\n * const refresher = new CoSecTokenRefresher({\n * fetcher: myFetcherInstance,\n * endpoint: '/api/v1/auth/refresh'\n * });\n * ```\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {}\n\n /**\n * Refreshes the given composite token by sending a POST request to the configured endpoint.\n *\n * This method sends the current token pair to the refresh endpoint and expects\n * a new CompositeToken in response.\n *\n * **CRITICAL**: The request includes a special\n * attribute `attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]])`\n * to prevent infinite loops. Without this attribute, the request interceptor\n * may attempt to refresh the token again, causing a recursive loop.\n *\n * @param {CompositeToken} token - The composite token to refresh, containing both access and refresh tokens.\n * @returns {Promise<CompositeToken>} A promise that resolves to a new CompositeToken with refreshed tokens.\n * @throws {Error} Throws an error if the HTTP request fails, the server returns an error status, or the response cannot be parsed as JSON.\n * @throws {NetworkError} Throws a network error if there are connectivity issues.\n * @throws {AuthenticationError} Throws an authentication error if the refresh token is invalid or expired.\n *\n * @example\n * ```typescript\n * const refresher = new CoSecTokenRefresher({ fetcher, endpoint: '/auth/refresh' });\n * const token = { accessToken: 'expired-token', refreshToken: 'valid-refresh-token' };\n *\n * try {\n * const newToken = await refresher.refresh(token);\n * console.log('Refreshed access token:', newToken.accessToken);\n * } catch (error) {\n * console.error('Token refresh failed:', error.message);\n * }\n * ```\n *\n * @warning **Important**: Always include the `IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY` attribute\n * in refresh requests to avoid infinite loops caused by recursive token refresh attempts.\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"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY","CoSecRequestInterceptor","options","exchange","requestId","deviceId","requestHeaders","AUTHORIZATION_REQUEST_INTERCEPTOR_NAME","AUTHORIZATION_REQUEST_INTERCEPTOR_ORDER","AuthorizationRequestInterceptor","currentToken","AUTHORIZATION_RESPONSE_INTERCEPTOR_NAME","AUTHORIZATION_RESPONSE_INTERCEPTOR_ORDER","AuthorizationResponseInterceptor","response","error","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","KeyStorage","key","eventBus","BroadcastTypedEventBus","SerialTypedEventBus","reset","typedIdentitySerializer","FORBIDDEN_ERROR_INTERCEPTOR_NAME","FORBIDDEN_ERROR_INTERCEPTOR_ORDER","ForbiddenErrorInterceptor","RefreshTokenError","FetcherError","token","cause","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","TENANT_ID_PATH_KEY","OWNER_ID_PATH_KEY","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_NAME","RESOURCE_ATTRIBUTION_REQUEST_INTERCEPTOR_ORDER","ResourceAttributionRequestInterceptor","tenantId","ownerId","principal","extractedPathParams","tenantIdPathKey","requestPathParams","ownerIdPathKey","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","value","compositeToken","jwtCompositeTokenSerializer","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","UNAUTHORIZED_ERROR_INTERCEPTOR_NAME","UNAUTHORIZED_ERROR_INTERCEPTOR_ORDER","UnauthorizedErrorInterceptor","CoSecConfigurer","config","fetcher","CoSecTokenRefresher","ResultExt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GjDsD,EAAO,iBACT,KAAK,aAAe,IAAIvC,EACtB,KAAK,aACLuC,EAAO,cAAA,EAGb,CAmCA,QAAQC,EAAwB,CAC9BA,EAAQ,aAAa,QAAQ,IAC3B,IAAIvE,EAAwB,CAC1B,MAAO,KAAK,OAAO,MACnB,gBAAiB,KAAK,eAAA,CACvB,CAAA,EAGHuE,EAAQ,aAAa,QAAQ,IAC3B,IAAI/B,EAAsC,CACxC,aAAc,KAAK,YAAA,CACpB,CAAA,EAEC,KAAK,eACP+B,EAAQ,aAAa,QAAQ,IAC3B,IAAI/D,EAAgC,CAClC,aAAc,KAAK,YAAA,CACpB,CAAA,EAGH+D,EAAQ,aAAa,SAAS,IAC5B,IAAI3D,EAAiC,CACnC,aAAc,KAAK,YAAA,CACpB,CAAA,GAGD,KAAK,OAAO,gBACd2D,EAAQ,aAAa,MAAM,IACzB,IAAIH,EAA6B,CAC/B,eAAgB,KAAK,OAAO,cAAA,CAC7B,CAAA,EAID,KAAK,OAAO,aACdG,EAAQ,aAAa,MAAM,IACzB,IAAI7C,EAA0B,CAC5B,YAAa,KAAK,OAAO,WAAA,CAC1B,CAAA,CAGP,CACF,CCjHO,MAAM8C,EAA8C,CAgBzD,YAA4BvE,EAAqC,CAArC,KAAA,QAAAA,CAAsC,CAmClE,QAAQ4B,EAAgD,CAItD,OAAO,KAAK,QAAQ,QAAQ,KAC1B,KAAK,QAAQ,SACb,CACE,KAAMA,CAAA,EAER,CACE,gBAAiB4C,EAAAA,iBAAiB,KAClC,eAAgB,IAAI,CAAC,CAAC1E,EAAoC,EAAI,CAAC,CAAC,CAAA,CAClE,CAEJ,CACF"}
@@ -2,85 +2,216 @@ import { CoSecJwtPayload, EarlyPeriodCapable, JwtPayload } from './jwts';
2
2
  import { CompositeToken } from './tokenRefresher';
3
3
  import { Serializer } from '@ahoo-wang/fetcher-storage';
4
4
  /**
5
- * Interface for JWT token with typed payload
6
- * @template Payload The type of the JWT payload
5
+ * Interface for JWT token with typed payload.
6
+ *
7
+ * This interface represents a JWT token that includes the raw token string,
8
+ * a parsed payload of a specific type, and methods to check expiration status.
9
+ * It extends EarlyPeriodCapable to support early expiration checks.
10
+ *
11
+ * @template Payload The type of the JWT payload, must extend JwtPayload
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * interface CustomPayload extends JwtPayload {
16
+ * userId: string;
17
+ * roles: string[];
18
+ * }
19
+ *
20
+ * const token: IJwtToken<CustomPayload> = new JwtToken<CustomPayload>('jwt.token.here');
21
+ * if (!token.isExpired) {
22
+ * console.log(token.payload?.userId);
23
+ * }
24
+ * ```
7
25
  */
8
26
  export interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {
27
+ /**
28
+ * The raw JWT token string.
29
+ */
9
30
  readonly token: string;
31
+ /**
32
+ * The parsed JWT payload. Null if the token could not be parsed.
33
+ */
10
34
  readonly payload: Payload | null;
35
+ /**
36
+ * Indicates whether the token is expired, considering the early period.
37
+ */
11
38
  isExpired: boolean;
12
39
  }
13
40
  /**
14
- * Class representing a JWT token with typed payload
15
- * @template Payload The type of the JWT payload
41
+ * Class representing a JWT token with typed payload.
42
+ *
43
+ * This class provides a concrete implementation of IJwtToken, parsing the JWT
44
+ * token string and providing access to the payload and expiration status.
45
+ * It supports early expiration periods for proactive token refresh.
46
+ *
47
+ * @template Payload The type of the JWT payload, must extend JwtPayload
48
+ *
49
+ * @example
50
+ * ```typescript
51
+ * const token = new JwtToken<CoSecJwtPayload>('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', 300000); // 5 min early period
52
+ * console.log(token.isExpired); // false if not expired
53
+ * console.log(token.payload?.sub); // user ID from payload
54
+ * ```
16
55
  */
17
56
  export declare class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {
18
57
  readonly token: string;
19
58
  readonly earlyPeriod: number;
59
+ /**
60
+ * The parsed JWT payload. Null if the token could not be parsed.
61
+ */
20
62
  readonly payload: Payload | null;
21
63
  /**
22
- * Creates a new JwtToken instance
64
+ * Creates a new JwtToken instance.
65
+ *
66
+ * Parses the JWT token string to extract the payload and stores the early period
67
+ * for expiration checks.
68
+ *
69
+ * @param token The raw JWT token string to parse
70
+ * @param earlyPeriod The early expiration period in milliseconds (default: 0).
71
+ * Tokens are considered expired this many milliseconds before their actual expiration time.
72
+ *
73
+ * @throws Will not throw but payload will be null if token parsing fails
23
74
  */
24
75
  constructor(token: string, earlyPeriod?: number);
25
76
  /**
26
- * Checks if the token is expired
27
- * @returns true if the token is expired, false otherwise
77
+ * Checks if the token is expired.
78
+ *
79
+ * Considers both the token's expiration time and the early period.
80
+ * Returns true if the payload is null (parsing failed) or if the token is expired.
81
+ *
82
+ * @returns true if the token is expired or invalid, false otherwise
28
83
  */
29
84
  get isExpired(): boolean;
30
85
  }
86
+ /**
87
+ * Interface for checking refresh token status capabilities.
88
+ *
89
+ * This interface defines methods to check if token refresh is needed and possible.
90
+ */
31
91
  export interface RefreshTokenStatusCapable {
32
92
  /**
33
- * Checks if the access token needs to be refreshed
93
+ * Checks if the access token needs to be refreshed.
94
+ *
34
95
  * @returns true if the access token is expired, false otherwise
35
96
  */
36
97
  readonly isRefreshNeeded: boolean;
37
98
  /**
38
- * Checks if the refresh token is still valid and can be used to refresh the access token
99
+ * Checks if the refresh token is still valid and can be used to refresh the access token.
100
+ *
39
101
  * @returns true if the refresh token is not expired, false otherwise
40
102
  */
41
103
  readonly isRefreshable: boolean;
42
104
  }
43
105
  /**
44
- * Class representing a composite token containing both access and refresh tokens
106
+ * Class representing a composite token containing both access and refresh tokens.
107
+ *
108
+ * This class manages both access and refresh JWT tokens together, providing
109
+ * convenient methods to check authentication status, refresh needs, and user information.
110
+ * It implements both EarlyPeriodCapable and RefreshTokenStatusCapable interfaces.
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * const compositeToken = new JwtCompositeToken({
115
+ * accessToken: 'access.jwt.here',
116
+ * refreshToken: 'refresh.jwt.here'
117
+ * }, 300000); // 5 min early period
118
+ *
119
+ * if (compositeToken.authenticated) {
120
+ * console.log(compositeToken.currentUser?.sub);
121
+ * }
122
+ *
123
+ * if (compositeToken.isRefreshNeeded && compositeToken.isRefreshable) {
124
+ * // Refresh the access token
125
+ * }
126
+ * ```
45
127
  */
46
128
  export declare class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {
47
129
  readonly token: CompositeToken;
48
130
  readonly earlyPeriod: number;
131
+ /**
132
+ * The access JWT token instance.
133
+ */
49
134
  readonly access: JwtToken<CoSecJwtPayload>;
135
+ /**
136
+ * The refresh JWT token instance.
137
+ */
50
138
  readonly refresh: JwtToken<JwtPayload>;
51
139
  /**
52
- * Creates a new JwtCompositeToken instance
140
+ * Creates a new JwtCompositeToken instance.
141
+ *
142
+ * Initializes both access and refresh token instances with the provided early period.
143
+ *
144
+ * @param token The composite token containing access and refresh token strings
145
+ * @param earlyPeriod The early expiration period in milliseconds (default: 0)
53
146
  */
54
147
  constructor(token: CompositeToken, earlyPeriod?: number);
55
148
  /**
56
- * Checks if the access token needs to be refreshed
149
+ * Checks if the access token needs to be refreshed.
150
+ *
57
151
  * @returns true if the access token is expired, false otherwise
58
152
  */
59
153
  get isRefreshNeeded(): boolean;
60
154
  /**
61
- * Checks if the refresh token is still valid and can be used to refresh the access token
155
+ * Checks if the refresh token is still valid and can be used to refresh the access token.
156
+ *
62
157
  * @returns true if the refresh token is not expired, false otherwise
63
158
  */
64
159
  get isRefreshable(): boolean;
160
+ /**
161
+ * Checks if the user is currently authenticated (access token is valid).
162
+ *
163
+ * @returns true if the access token is not expired, false otherwise
164
+ */
165
+ get authenticated(): boolean;
65
166
  }
66
167
  /**
67
- * Serializer for JwtCompositeToken that handles conversion to and from JSON strings
168
+ * Serializer for JwtCompositeToken that handles conversion to and from JSON strings.
169
+ *
170
+ * This class provides serialization and deserialization functionality for JwtCompositeToken
171
+ * instances, allowing them to be stored and retrieved from persistent storage.
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const serializer = new JwtCompositeTokenSerializer(300000);
176
+ * const token = new JwtCompositeToken({ accessToken: '...', refreshToken: '...' });
177
+ *
178
+ * const serialized = serializer.serialize(token);
179
+ * const deserialized = serializer.deserialize(serialized);
180
+ * ```
68
181
  */
69
182
  export declare class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {
70
183
  readonly earlyPeriod: number;
184
+ /**
185
+ * Creates a new JwtCompositeTokenSerializer instance.
186
+ *
187
+ * @param earlyPeriod The early expiration period in milliseconds to use for deserialized tokens (default: 0)
188
+ */
71
189
  constructor(earlyPeriod?: number);
72
190
  /**
73
- * Deserializes a JSON string to a JwtCompositeToken
191
+ * Deserializes a JSON string to a JwtCompositeToken.
192
+ *
193
+ * Parses the JSON string and creates a new JwtCompositeToken instance with the stored tokens.
194
+ *
74
195
  * @param value The JSON string representation of a composite token
75
196
  * @returns A JwtCompositeToken instance
197
+ * @throws SyntaxError if the JSON string is invalid
198
+ * @throws Error if the parsed object doesn't match the expected CompositeToken structure
76
199
  */
77
200
  deserialize(value: string): JwtCompositeToken;
78
201
  /**
79
- * Serializes a JwtCompositeToken to a JSON string
202
+ * Serializes a JwtCompositeToken to a JSON string.
203
+ *
204
+ * Converts the composite token to a JSON string for storage.
205
+ *
80
206
  * @param value The JwtCompositeToken to serialize
81
207
  * @returns A JSON string representation of the composite token
82
208
  */
83
209
  serialize(value: JwtCompositeToken): string;
84
210
  }
211
+ /**
212
+ * Default instance of JwtCompositeTokenSerializer with no early period.
213
+ *
214
+ * This pre-configured serializer can be used directly for basic serialization needs.
215
+ */
85
216
  export declare const jwtCompositeTokenSerializer: JwtCompositeTokenSerializer;
86
217
  //# sourceMappingURL=jwtToken.d.ts.map