@ahoo-wang/fetcher-cosec 1.6.0 → 1.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.es.js +11 -11
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/tokenRefresher.d.ts.map +1 -1
- package/package.json +2 -2
package/dist/index.es.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { REQUEST_BODY_INTERCEPTOR_ORDER as k, ResultExtractors as y } from "@ahoo-wang/fetcher";
|
|
2
2
|
import { nanoid as m } from "nanoid";
|
|
3
|
-
function
|
|
3
|
+
function E() {
|
|
4
4
|
return typeof window < "u";
|
|
5
5
|
}
|
|
6
6
|
class O {
|
|
@@ -70,7 +70,7 @@ class O {
|
|
|
70
70
|
* @param eventInit - The initialization object for the StorageEvent
|
|
71
71
|
*/
|
|
72
72
|
notifyListeners(e) {
|
|
73
|
-
|
|
73
|
+
E() && window.location && (e.url = e.url || window.location.href), e.storageArea = this, this.listeners.forEach((t) => {
|
|
74
74
|
try {
|
|
75
75
|
t(e);
|
|
76
76
|
} catch (s) {
|
|
@@ -142,7 +142,7 @@ class _ {
|
|
|
142
142
|
this.storage.setItem(e, t);
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
const u = "storage", h = () =>
|
|
145
|
+
const u = "storage", h = () => E() ? new _(window.localStorage) : new O();
|
|
146
146
|
class N {
|
|
147
147
|
/**
|
|
148
148
|
* Serializes a value to a JSON string
|
|
@@ -172,7 +172,7 @@ class N {
|
|
|
172
172
|
return JSON.parse(e);
|
|
173
173
|
}
|
|
174
174
|
}
|
|
175
|
-
class
|
|
175
|
+
class g {
|
|
176
176
|
/**
|
|
177
177
|
* Returns the value as-is without serialization
|
|
178
178
|
* @param value The value to pass through
|
|
@@ -201,7 +201,7 @@ class E {
|
|
|
201
201
|
return e;
|
|
202
202
|
}
|
|
203
203
|
}
|
|
204
|
-
const x = new N(), C = new
|
|
204
|
+
const x = new N(), C = new g();
|
|
205
205
|
function z() {
|
|
206
206
|
return C;
|
|
207
207
|
}
|
|
@@ -311,7 +311,7 @@ class q {
|
|
|
311
311
|
const t = I.generateId(), s = this.options.deviceIdStorage.getOrCreate(), i = e.ensureRequestHeaders();
|
|
312
312
|
i[n.APP_ID] = this.options.appId, i[n.DEVICE_ID] = s, i[n.REQUEST_ID] = t;
|
|
313
313
|
let o = this.options.tokenManager.currentToken;
|
|
314
|
-
!o || i[n.AUTHORIZATION] || (!e.attributes
|
|
314
|
+
!o || i[n.AUTHORIZATION] || (!e.attributes.has(p) && o.isRefreshNeeded && o.isRefreshable && await this.options.tokenManager.refresh(), o = this.options.tokenManager.currentToken, o && (i[n.AUTHORIZATION] = `Bearer ${o.access.token}`));
|
|
315
315
|
}
|
|
316
316
|
}
|
|
317
317
|
const U = "CoSecResponseInterceptor", V = Number.MIN_SAFE_INTEGER + 1e3;
|
|
@@ -342,7 +342,7 @@ class B extends f {
|
|
|
342
342
|
constructor(e = L) {
|
|
343
343
|
super({
|
|
344
344
|
key: e,
|
|
345
|
-
serializer: new
|
|
345
|
+
serializer: new g(),
|
|
346
346
|
storage: h()
|
|
347
347
|
});
|
|
348
348
|
}
|
|
@@ -522,9 +522,9 @@ class F {
|
|
|
522
522
|
{
|
|
523
523
|
body: e
|
|
524
524
|
},
|
|
525
|
-
y.Json,
|
|
526
525
|
{
|
|
527
|
-
|
|
526
|
+
resultExtractor: y.Json,
|
|
527
|
+
attributes: /* @__PURE__ */ new Map([[p, !0]])
|
|
528
528
|
}
|
|
529
529
|
);
|
|
530
530
|
}
|
|
@@ -559,7 +559,7 @@ export {
|
|
|
559
559
|
M as DEFAULT_COSEC_TOKEN_KEY,
|
|
560
560
|
B as DeviceIdStorage,
|
|
561
561
|
p as IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY,
|
|
562
|
-
|
|
562
|
+
g as IdentitySerializer,
|
|
563
563
|
O as InMemoryListenableStorage,
|
|
564
564
|
N as JsonSerializer,
|
|
565
565
|
R as JwtCompositeToken,
|
|
@@ -574,7 +574,7 @@ export {
|
|
|
574
574
|
h as createListenableStorage,
|
|
575
575
|
I as idGenerator,
|
|
576
576
|
C as identitySerializer,
|
|
577
|
-
|
|
577
|
+
E as isBrowser,
|
|
578
578
|
b as isTokenExpired,
|
|
579
579
|
x as jsonSerializer,
|
|
580
580
|
Q as jwtCompositeTokenSerializer,
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/env.ts","../src/storage/inMemoryListenableStorage.ts","../src/storage/browserListenableStorage.ts","../src/storage/listenableStorage.ts","../src/serializer.ts","../src/storage/keyStorage.ts","../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\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 { ListenableStorage, RemoveStorageListener, StorageListener } from './listenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * An in-memory implementation of ListenableStorage that works in any environment.\n * This implementation stores data in a Map and manually fires storage events when data changes.\n */\nexport class InMemoryListenableStorage implements ListenableStorage {\n private readonly store: Map<string, string> = new Map();\n private readonly listeners: Set<StorageListener> = new Set();\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.store.size;\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n const oldValue = this.getItem(key);\n if (this.store.has(key)) {\n this.store.delete(key);\n this.notifyListeners({\n key,\n oldValue,\n newValue: null,\n });\n }\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n const oldValue = this.getItem(key);\n this.store.set(key, value);\n this.notifyListeners({ key, oldValue, newValue: value });\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n private notifyListeners(\n eventInit: StorageEventInit,\n ): void {\n if (isBrowser() && window.location) {\n eventInit.url = eventInit.url || window.location.href;\n }\n eventInit.storageArea = this;\n this.listeners.forEach(listener => {\n try {\n listener(eventInit);\n } catch (error) {\n console.error('Error in storage change listener:', 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 { ListenableStorage, RemoveStorageListener, STORAGE_EVENT_TYPE, StorageListener } from './listenableStorage';\n\n/**\n * A wrapper around the browser's native Storage (localStorage or sessionStorage)\n * that implements the ListenableStorage interface by using the browser's native storage events.\n */\nexport class BrowserListenableStorage implements ListenableStorage {\n\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(private readonly storage: Storage) {\n }\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.storage.length;\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n const wrapper: StorageListener = (event: StorageEventInit) => {\n if (event.storageArea === this.storage) {\n listener(event);\n }\n };\n window.addEventListener(STORAGE_EVENT_TYPE, wrapper);\n return () => window.removeEventListener(STORAGE_EVENT_TYPE, wrapper);\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.storage.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n return this.storage.getItem(key);\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n return this.storage.key(index);\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n this.storage.removeItem(key);\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n this.storage.setItem(key, value);\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 { InMemoryListenableStorage } from './inMemoryListenableStorage';\nimport { BrowserListenableStorage } from './browserListenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * The type of storage event used for listening to storage changes.\n */\nexport const STORAGE_EVENT_TYPE = 'storage';\n\n/**\n * A function that handles storage change events.\n */\nexport type StorageListener = (event: StorageEventInit) => void;\n\n/**\n * A function that removes a storage listener when called.\n */\nexport type RemoveStorageListener = () => void;\n\nexport interface StorageListenable {\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener;\n}\n\n/**\n * An interface that extends the native Storage interface with the ability to listen for storage changes.\n */\nexport interface ListenableStorage extends Storage, StorageListenable {\n\n}\n\n/**\n * Factory function to get an appropriate ListenableStorage implementation based on the environment.\n * In a browser environment, it returns a BrowserListenableStorage wrapping localStorage.\n * In other environments, it returns an InMemoryListenableStorage.\n * @returns A ListenableStorage instance suitable for the current environment\n */\nexport const createListenableStorage = (): ListenableStorage => {\n if (isBrowser()) {\n return new BrowserListenableStorage(window.localStorage);\n }\n return new InMemoryListenableStorage();\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/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n */\n/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n * @template Deserialized The type of the deserialized value\n */\nexport interface Serializer<Serialized, Deserialized> {\n /**\n * Serializes a value to the specified format\n * @param value The value to serialize\n * @returns The serialized value\n */\n serialize(value: any): Serialized;\n\n /**\n * Deserializes a value from the specified format\n * @template Deserialized The type of the deserialized value\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a value from the specified format\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n deserialize(value: Serialized): Deserialized;\n}\n\n/**\n * Implementation of Serializer that uses JSON for serialization\n */\nexport class JsonSerializer implements Serializer<string, any> {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(value: any): string {\n return JSON.stringify(value);\n }\n\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize<V>(value: string): V {\n return JSON.parse(value);\n }\n}\n\n/**\n * Implementation of Serializer that performs no actual serialization\n * @template T The type of the value to pass through\n */\nexport class IdentitySerializer<T> implements Serializer<T, T> {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(value: T): T {\n return value;\n }\n\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(value: T): T {\n return value;\n }\n}\n\n/**\n * Global instance of JsonSerializer\n */\nexport const jsonSerializer = new JsonSerializer();\n/**\n * Global instance of IdentitySerializer\n */\nexport const identitySerializer = new IdentitySerializer<any>();\n\nexport function typedIdentitySerializer<T>(): IdentitySerializer<T> {\n return identitySerializer as IdentitySerializer<T>;\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 { createListenableStorage, ListenableStorage, StorageListener } from './listenableStorage';\nimport { Serializer, typedIdentitySerializer } from '../serializer';\n\n/**\n * Options for configuring KeyStorage\n */\nexport interface KeyStorageOptions<Deserialized> {\n /**\n * The key used to store and retrieve values from storage\n */\n key: string;\n\n /**\n * Optional serializer for converting values to and from storage format\n * Defaults to IdentitySerializer if not provided\n */\n serializer?: Serializer<string, Deserialized>;\n\n /**\n * Optional storage implementation\n * Defaults to the result of createListenableStorage() if not provided\n */\n storage?: ListenableStorage;\n}\n\n/**\n * A storage wrapper that manages a single value associated with a specific key\n * Provides caching and automatic cache invalidation when the storage value changes\n * @template Deserialized The type of the value being stored\n */\nexport class KeyStorage<Deserialized> {\n private readonly key: string;\n private readonly serializer: Serializer<string, Deserialized>;\n private readonly storage: ListenableStorage;\n private cacheValue: Deserialized | null = null;\n\n /**\n * Listener for storage change events\n * Invalidates the cache when the relevant key is modified\n */\n private readonly listener: StorageListener = (event) => {\n if (event.key !== this.key) {\n return;\n }\n this.cacheValue = null;\n if (event.newValue) {\n this.refreshCache(event.newValue);\n }\n };\n\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n private refreshCache(value: string) {\n this.cacheValue = this.serializer.deserialize(value);\n }\n\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(options: KeyStorageOptions<Deserialized>) {\n this.key = options.key;\n this.serializer = options.serializer ?? typedIdentitySerializer();\n this.storage = options.storage ?? createListenableStorage();\n this.storage.addListener(this.listener);\n }\n\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get(): Deserialized | null {\n if (this.cacheValue) {\n return this.cacheValue;\n }\n const value = this.storage.getItem(this.key);\n if (!value) {\n return null;\n }\n this.refreshCache(value);\n return this.cacheValue;\n }\n\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(value: Deserialized): void {\n const serialized = this.serializer.serialize(value);\n this.storage.setItem(this.key, serialized);\n this.cacheValue = value;\n }\n\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove(): void {\n this.storage.removeItem(this.key);\n this.cacheValue = null;\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 { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY] && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { IdentitySerializer } from './serializer';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { Serializer } from './serializer';\nimport { CompositeToken } from './tokenRefresher';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload;\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(token) as Payload;\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 return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, ResultExtractors.Json,\n {\n [IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY]: true,\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 { createListenableStorage, KeyStorage } from './storage';\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["isBrowser","InMemoryListenableStorage","key","value","index","oldValue","listener","eventInit","error","BrowserListenableStorage","storage","wrapper","event","STORAGE_EVENT_TYPE","createListenableStorage","JsonSerializer","IdentitySerializer","jsonSerializer","identitySerializer","typedIdentitySerializer","KeyStorage","options","serialized","_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","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":";;AAaO,SAASA,IAAqB;AACnC,SAAO,OAAO,SAAW;AAC3B;ACKO,MAAMC,EAAuD;AAAA,EAA7D,cAAA;AACL,SAAiB,4BAAiC,IAAA,GAClD,KAAiB,gCAAsC,IAAA;AAAA,EAAI;AAAA;AAAA;AAAA;AAAA,EAK3D,IAAI,SAAiB;AACnB,WAAO,KAAK,MAAM;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,MAAM,MAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAQC,GAA4B;AAClC,UAAMC,IAAQ,KAAK,MAAM,IAAID,CAAG;AAChC,WAAOC,MAAU,SAAYA,IAAQ;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAIC,GAA8B;AAEhC,WADa,MAAM,KAAK,KAAK,MAAM,MAAM,EAC7BA,CAAK,KAAK;AAAA,EACx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AA,EAExC;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/env.ts","../src/storage/inMemoryListenableStorage.ts","../src/storage/browserListenableStorage.ts","../src/storage/listenableStorage.ts","../src/serializer.ts","../src/storage/keyStorage.ts","../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\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 { ListenableStorage, RemoveStorageListener, StorageListener } from './listenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * An in-memory implementation of ListenableStorage that works in any environment.\n * This implementation stores data in a Map and manually fires storage events when data changes.\n */\nexport class InMemoryListenableStorage implements ListenableStorage {\n private readonly store: Map<string, string> = new Map();\n private readonly listeners: Set<StorageListener> = new Set();\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.store.size;\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n const oldValue = this.getItem(key);\n if (this.store.has(key)) {\n this.store.delete(key);\n this.notifyListeners({\n key,\n oldValue,\n newValue: null,\n });\n }\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n const oldValue = this.getItem(key);\n this.store.set(key, value);\n this.notifyListeners({ key, oldValue, newValue: value });\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n private notifyListeners(\n eventInit: StorageEventInit,\n ): void {\n if (isBrowser() && window.location) {\n eventInit.url = eventInit.url || window.location.href;\n }\n eventInit.storageArea = this;\n this.listeners.forEach(listener => {\n try {\n listener(eventInit);\n } catch (error) {\n console.error('Error in storage change listener:', 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 { ListenableStorage, RemoveStorageListener, STORAGE_EVENT_TYPE, StorageListener } from './listenableStorage';\n\n/**\n * A wrapper around the browser's native Storage (localStorage or sessionStorage)\n * that implements the ListenableStorage interface by using the browser's native storage events.\n */\nexport class BrowserListenableStorage implements ListenableStorage {\n\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(private readonly storage: Storage) {\n }\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.storage.length;\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n const wrapper: StorageListener = (event: StorageEventInit) => {\n if (event.storageArea === this.storage) {\n listener(event);\n }\n };\n window.addEventListener(STORAGE_EVENT_TYPE, wrapper);\n return () => window.removeEventListener(STORAGE_EVENT_TYPE, wrapper);\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.storage.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n return this.storage.getItem(key);\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n return this.storage.key(index);\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n this.storage.removeItem(key);\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n this.storage.setItem(key, value);\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 { InMemoryListenableStorage } from './inMemoryListenableStorage';\nimport { BrowserListenableStorage } from './browserListenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * The type of storage event used for listening to storage changes.\n */\nexport const STORAGE_EVENT_TYPE = 'storage';\n\n/**\n * A function that handles storage change events.\n */\nexport type StorageListener = (event: StorageEventInit) => void;\n\n/**\n * A function that removes a storage listener when called.\n */\nexport type RemoveStorageListener = () => void;\n\nexport interface StorageListenable {\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener;\n}\n\n/**\n * An interface that extends the native Storage interface with the ability to listen for storage changes.\n */\nexport interface ListenableStorage extends Storage, StorageListenable {\n\n}\n\n/**\n * Factory function to get an appropriate ListenableStorage implementation based on the environment.\n * In a browser environment, it returns a BrowserListenableStorage wrapping localStorage.\n * In other environments, it returns an InMemoryListenableStorage.\n * @returns A ListenableStorage instance suitable for the current environment\n */\nexport const createListenableStorage = (): ListenableStorage => {\n if (isBrowser()) {\n return new BrowserListenableStorage(window.localStorage);\n }\n return new InMemoryListenableStorage();\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/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n */\n/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n * @template Deserialized The type of the deserialized value\n */\nexport interface Serializer<Serialized, Deserialized> {\n /**\n * Serializes a value to the specified format\n * @param value The value to serialize\n * @returns The serialized value\n */\n serialize(value: any): Serialized;\n\n /**\n * Deserializes a value from the specified format\n * @template Deserialized The type of the deserialized value\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a value from the specified format\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n deserialize(value: Serialized): Deserialized;\n}\n\n/**\n * Implementation of Serializer that uses JSON for serialization\n */\nexport class JsonSerializer implements Serializer<string, any> {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(value: any): string {\n return JSON.stringify(value);\n }\n\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize<V>(value: string): V {\n return JSON.parse(value);\n }\n}\n\n/**\n * Implementation of Serializer that performs no actual serialization\n * @template T The type of the value to pass through\n */\nexport class IdentitySerializer<T> implements Serializer<T, T> {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(value: T): T {\n return value;\n }\n\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(value: T): T {\n return value;\n }\n}\n\n/**\n * Global instance of JsonSerializer\n */\nexport const jsonSerializer = new JsonSerializer();\n/**\n * Global instance of IdentitySerializer\n */\nexport const identitySerializer = new IdentitySerializer<any>();\n\nexport function typedIdentitySerializer<T>(): IdentitySerializer<T> {\n return identitySerializer as IdentitySerializer<T>;\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 { createListenableStorage, ListenableStorage, StorageListener } from './listenableStorage';\nimport { Serializer, typedIdentitySerializer } from '../serializer';\n\n/**\n * Options for configuring KeyStorage\n */\nexport interface KeyStorageOptions<Deserialized> {\n /**\n * The key used to store and retrieve values from storage\n */\n key: string;\n\n /**\n * Optional serializer for converting values to and from storage format\n * Defaults to IdentitySerializer if not provided\n */\n serializer?: Serializer<string, Deserialized>;\n\n /**\n * Optional storage implementation\n * Defaults to the result of createListenableStorage() if not provided\n */\n storage?: ListenableStorage;\n}\n\n/**\n * A storage wrapper that manages a single value associated with a specific key\n * Provides caching and automatic cache invalidation when the storage value changes\n * @template Deserialized The type of the value being stored\n */\nexport class KeyStorage<Deserialized> {\n private readonly key: string;\n private readonly serializer: Serializer<string, Deserialized>;\n private readonly storage: ListenableStorage;\n private cacheValue: Deserialized | null = null;\n\n /**\n * Listener for storage change events\n * Invalidates the cache when the relevant key is modified\n */\n private readonly listener: StorageListener = (event) => {\n if (event.key !== this.key) {\n return;\n }\n this.cacheValue = null;\n if (event.newValue) {\n this.refreshCache(event.newValue);\n }\n };\n\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n private refreshCache(value: string) {\n this.cacheValue = this.serializer.deserialize(value);\n }\n\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(options: KeyStorageOptions<Deserialized>) {\n this.key = options.key;\n this.serializer = options.serializer ?? typedIdentitySerializer();\n this.storage = options.storage ?? createListenableStorage();\n this.storage.addListener(this.listener);\n }\n\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get(): Deserialized | null {\n if (this.cacheValue) {\n return this.cacheValue;\n }\n const value = this.storage.getItem(this.key);\n if (!value) {\n return null;\n }\n this.refreshCache(value);\n return this.cacheValue;\n }\n\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(value: Deserialized): void {\n const serialized = this.serializer.serialize(value);\n this.storage.setItem(this.key, serialized);\n this.cacheValue = value;\n }\n\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove(): void {\n this.storage.removeItem(this.key);\n this.cacheValue = null;\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 { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { IdentitySerializer } from './serializer';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { Serializer } from './serializer';\nimport { CompositeToken } from './tokenRefresher';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload;\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(token) as Payload;\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 return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["isBrowser","InMemoryListenableStorage","key","value","index","oldValue","listener","eventInit","error","BrowserListenableStorage","storage","wrapper","event","STORAGE_EVENT_TYPE","createListenableStorage","JsonSerializer","IdentitySerializer","jsonSerializer","identitySerializer","typedIdentitySerializer","KeyStorage","options","serialized","_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","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":";;AAaO,SAASA,IAAqB;AACnC,SAAO,OAAO,SAAW;AAC3B;ACKO,MAAMC,EAAuD;AAAA,EAA7D,cAAA;AACL,SAAiB,4BAAiC,IAAA,GAClD,KAAiB,gCAAsC,IAAA;AAAA,EAAI;AAAA;AAAA;AAAA;AAAA,EAK3D,IAAI,SAAiB;AACnB,WAAO,KAAK,MAAM;AAAA,EACpB;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,MAAM,MAAA;AAAA,EACb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,QAAQC,GAA4B;AAClC,UAAMC,IAAQ,KAAK,MAAM,IAAID,CAAG;AAChC,WAAOC,MAAU,SAAYA,IAAQ;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAIC,GAA8B;AAEhC,WADa,MAAM,KAAK,KAAK,MAAM,MAAM,EAC7BA,CAAK,KAAK;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAWF,GAAmB;AAC5B,UAAMG,IAAW,KAAK,QAAQH,CAAG;AACjC,IAAI,KAAK,MAAM,IAAIA,CAAG,MACpB,KAAK,MAAM,OAAOA,CAAG,GACrB,KAAK,gBAAgB;AAAA,MACnB,KAAAA;AAAA,MACA,UAAAG;AAAA,MACA,UAAU;AAAA,IAAA,CACX;AAAA,EAEL;AAAA;AAAA;AAAA;AAAA;AAAA;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;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,kBAA2B;AAC7B,WAAK,KAAK,eAGH,KAAK,aAAa,kBAFhB;AAAA,EAGX;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,gBAAyB;AAC3B,WAAK,KAAK,eAGH,KAAK,aAAa,gBAFhB;AAAA,EAGX;AAEF;ACpCO,MAAM4D,EAA8C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMzD,YAA4B/C,GAAqC;AAArC,SAAA,UAAAA;AAAA,EAC5B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAQ2B,GAAgD;AAItD,WAAO,KAAK,QAAQ,QAAQ;AAAA,MAAqB,KAAK,QAAQ;AAAA,MAC5D;AAAA,QACE,MAAMA;AAAA,MAAA;AAAA,MACL;AAAA,QACD,iBAAiBqB,EAAiB;AAAA,QAClC,gCAAgB,IAAI,CAAC,CAACnC,GAAoC,EAAI,CAAC,CAAC;AAAA,MAAA;AAAA,IAClE;AAAA,EAEJ;AACF;ACxEO,MAAMoC,IAA0B;AAKhC,MAAMC,UAAqBnD,EAA4D;AAAA,EAE5F,YACElB,IAAcoE,GACEf,IAAsB,GACtC;AACA,UAAM;AAAA,MACJ,KAAArD;AAAA,MACA,SAASY,EAAA;AAAA,MACT,YAAY,IAAI8C,EAA4BL,CAAW;AAAA,IAAA,CACxD,GANe,KAAA,cAAAA;AAAA,EAOlB;AAAA,EAEA,kBAAkBM,GAAgC;AAChD,SAAK;AAAA,MACH,IAAIF,EAAkBE,CAAc;AAAA,IAAA;AAAA,EAExC;AACF;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(r,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@ahoo-wang/fetcher"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid"],c):(r=typeof globalThis<"u"?globalThis:r||self,c(r.FetcherCoSec={},r.Fetcher,r.nanoid))})(this,(function(r,c,
|
|
1
|
+
(function(r,c){typeof exports=="object"&&typeof module<"u"?c(exports,require("@ahoo-wang/fetcher"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid"],c):(r=typeof globalThis<"u"?globalThis:r||self,c(r.FetcherCoSec={},r.Fetcher,r.nanoid))})(this,(function(r,c,b){"use strict";function E(){return typeof window<"u"}class O{constructor(){this.store=new Map,this.listeners=new Set}get length(){return this.store.size}clear(){this.store.clear()}getItem(e){const t=this.store.get(e);return t!==void 0?t:null}key(e){return Array.from(this.store.keys())[e]||null}removeItem(e){const t=this.getItem(e);this.store.has(e)&&(this.store.delete(e),this.notifyListeners({key:e,oldValue:t,newValue:null}))}setItem(e,t){const i=this.getItem(e);this.store.set(e,t),this.notifyListeners({key:e,oldValue:i,newValue:t})}addListener(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(e){E()&&window.location&&(e.url=e.url||window.location.href),e.storageArea=this,this.listeners.forEach(t=>{try{t(e)}catch(i){console.error("Error in storage change listener:",i)}})}}class k{constructor(e){this.storage=e}get length(){return this.storage.length}addListener(e){const t=i=>{i.storageArea===this.storage&&e(i)};return window.addEventListener(d,t),()=>window.removeEventListener(d,t)}clear(){this.storage.clear()}getItem(e){return this.storage.getItem(e)}key(e){return this.storage.key(e)}removeItem(e){this.storage.removeItem(e)}setItem(e,t){this.storage.setItem(e,t)}}const d="storage",l=()=>E()?new k(window.localStorage):new O;class y{serialize(e){return JSON.stringify(e)}deserialize(e){return JSON.parse(e)}}class T{serialize(e){return e}deserialize(e){return e}}const V=new y,p=new T;function N(){return p}class f{constructor(e){this.cacheValue=null,this.listener=t=>{t.key===this.key&&(this.cacheValue=null,t.newValue&&this.refreshCache(t.newValue))},this.key=e.key,this.serializer=e.serializer??N(),this.storage=e.storage??l(),this.storage.addListener(this.listener)}refreshCache(e){this.cacheValue=this.serializer.deserialize(e)}get(){if(this.cacheValue)return this.cacheValue;const e=this.storage.getItem(this.key);return e?(this.refreshCache(e),this.cacheValue):null}set(e){const t=this.serializer.serialize(e);this.storage.setItem(this.key,t),this.cacheValue=e}remove(){this.storage.removeItem(this.key),this.cacheValue=null}}const h=class h{};h.DEVICE_ID="CoSec-Device-Id",h.APP_ID="CoSec-App-Id",h.AUTHORIZATION="Authorization",h.REQUEST_ID="CoSec-Request-Id";let n=h;const C=class C{};C.UNAUTHORIZED=401;let u=C;const J={ALLOW:{authorized:!0,reason:"Allow"},EXPLICIT_DENY:{authorized:!1,reason:"Explicit Deny"},IMPLICIT_DENY:{authorized:!1,reason:"Implicit Deny"},TOKEN_EXPIRED:{authorized:!1,reason:"Token Expired"},TOO_MANY_REQUESTS:{authorized:!1,reason:"Too Many Requests"}};class m{generateId(){return b.nanoid()}}const g=new m,z="CoSecRequestInterceptor",A=c.REQUEST_BODY_INTERCEPTOR_ORDER+1e3,I="Ignore-Refresh-Token";class v{constructor(e){this.name=z,this.order=A,this.options=e}async intercept(e){const t=g.generateId(),i=this.options.deviceIdStorage.getOrCreate(),o=e.ensureRequestHeaders();o[n.APP_ID]=this.options.appId,o[n.DEVICE_ID]=i,o[n.REQUEST_ID]=t;let a=this.options.tokenManager.currentToken;!a||o[n.AUTHORIZATION]||(!e.attributes.has(I)&&a.isRefreshNeeded&&a.isRefreshable&&await this.options.tokenManager.refresh(),a=this.options.tokenManager.currentToken,a&&(o[n.AUTHORIZATION]=`Bearer ${a.access.token}`))}}const D="CoSecResponseInterceptor",P=Number.MIN_SAFE_INTEGER+1e3;class K{constructor(e){this.name=D,this.order=P,this.options=e}async intercept(e){const t=e.response;if(t&&t.status===u.UNAUTHORIZED&&this.options.tokenManager.isRefreshable)try{await this.options.tokenManager.refresh(),await e.fetcher.interceptors.exchange(e)}catch(i){throw this.options.tokenManager.tokenStorage.remove(),i}}}const U="cosec-device-id";class Y extends f{constructor(e=U){super({key:e,serializer:new T,storage:l()})}generateDeviceId(){return g.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}}function S(s){try{const e=s.split(".");if(e.length!==3)return null;const i=e[1].replace(/-/g,"+").replace(/_/g,"/"),o=i.padEnd(i.length+(4-i.length%4)%4,"="),a=decodeURIComponent(atob(o).split("").map(function(G){return"%"+("00"+G.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(a)}catch(e){return console.error("Failed to parse JWT token",e),null}}function L(s,e=0){const t=typeof s=="string"?S(s):s;if(!t)return!0;const i=t.exp;return i?Date.now()/1e3>i-e:!1}class R{constructor(e,t=0){this.token=e,this.earlyPeriod=t,this.payload=S(e)}get isExpired(){return L(this.payload,this.earlyPeriod)}}class w{constructor(e,t=0){this.token=e,this.earlyPeriod=t,this.access=new R(e.accessToken,t),this.refresh=new R(e.refreshToken,t)}get isRefreshNeeded(){return this.access.isExpired}get isRefreshable(){return!this.refresh.isExpired}}class _{constructor(e=0){this.earlyPeriod=e}deserialize(e){const t=JSON.parse(e);return new w(t,this.earlyPeriod)}serialize(e){return JSON.stringify(e.token)}}const q=new _;class F{constructor(e,t){this.tokenStorage=e,this.tokenRefresher=t}get currentToken(){return this.tokenStorage.get()}async refresh(e){if(!e){const t=this.currentToken;if(!t)throw new Error("No token found");e=t.token}return this.refreshInProgress?this.refreshInProgress:(this.refreshInProgress=this.tokenRefresher.refresh(e).then(t=>{this.tokenStorage.setCompositeToken(t)}).catch(t=>{throw this.tokenStorage.remove(),t}).finally(()=>{this.refreshInProgress=void 0}),this.refreshInProgress)}get isRefreshNeeded(){return this.currentToken?this.currentToken.isRefreshNeeded:!1}get isRefreshable(){return this.currentToken?this.currentToken.isRefreshable:!1}}class j{constructor(e){this.options=e}refresh(e){return this.options.fetcher.post(this.options.endpoint,{body:e},{resultExtractor:c.ResultExtractors.Json,attributes:new Map([[I,!0]])})}}const M="cosec-token";class B extends f{constructor(e=M,t=0){super({key:e,storage:l(),serializer:new _(t)}),this.earlyPeriod=t}setCompositeToken(e){this.set(new w(e))}}r.AuthorizeResults=J,r.BrowserListenableStorage=k,r.COSEC_REQUEST_INTERCEPTOR_NAME=z,r.COSEC_REQUEST_INTERCEPTOR_ORDER=A,r.COSEC_RESPONSE_INTERCEPTOR_NAME=D,r.COSEC_RESPONSE_INTERCEPTOR_ORDER=P,r.CoSecHeaders=n,r.CoSecRequestInterceptor=v,r.CoSecResponseInterceptor=K,r.CoSecTokenRefresher=j,r.DEFAULT_COSEC_DEVICE_ID_KEY=U,r.DEFAULT_COSEC_TOKEN_KEY=M,r.DeviceIdStorage=Y,r.IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY=I,r.IdentitySerializer=T,r.InMemoryListenableStorage=O,r.JsonSerializer=y,r.JwtCompositeToken=w,r.JwtCompositeTokenSerializer=_,r.JwtToken=R,r.JwtTokenManager=F,r.KeyStorage=f,r.NanoIdGenerator=m,r.ResponseCodes=u,r.STORAGE_EVENT_TYPE=d,r.TokenStorage=B,r.createListenableStorage=l,r.idGenerator=g,r.identitySerializer=p,r.isBrowser=E,r.isTokenExpired=L,r.jsonSerializer=V,r.jwtCompositeTokenSerializer=q,r.parseJwtPayload=S,r.typedIdentitySerializer=N,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/env.ts","../src/storage/inMemoryListenableStorage.ts","../src/storage/browserListenableStorage.ts","../src/storage/listenableStorage.ts","../src/serializer.ts","../src/storage/keyStorage.ts","../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\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 { ListenableStorage, RemoveStorageListener, StorageListener } from './listenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * An in-memory implementation of ListenableStorage that works in any environment.\n * This implementation stores data in a Map and manually fires storage events when data changes.\n */\nexport class InMemoryListenableStorage implements ListenableStorage {\n private readonly store: Map<string, string> = new Map();\n private readonly listeners: Set<StorageListener> = new Set();\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.store.size;\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n const oldValue = this.getItem(key);\n if (this.store.has(key)) {\n this.store.delete(key);\n this.notifyListeners({\n key,\n oldValue,\n newValue: null,\n });\n }\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n const oldValue = this.getItem(key);\n this.store.set(key, value);\n this.notifyListeners({ key, oldValue, newValue: value });\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n private notifyListeners(\n eventInit: StorageEventInit,\n ): void {\n if (isBrowser() && window.location) {\n eventInit.url = eventInit.url || window.location.href;\n }\n eventInit.storageArea = this;\n this.listeners.forEach(listener => {\n try {\n listener(eventInit);\n } catch (error) {\n console.error('Error in storage change listener:', 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 { ListenableStorage, RemoveStorageListener, STORAGE_EVENT_TYPE, StorageListener } from './listenableStorage';\n\n/**\n * A wrapper around the browser's native Storage (localStorage or sessionStorage)\n * that implements the ListenableStorage interface by using the browser's native storage events.\n */\nexport class BrowserListenableStorage implements ListenableStorage {\n\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(private readonly storage: Storage) {\n }\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.storage.length;\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n const wrapper: StorageListener = (event: StorageEventInit) => {\n if (event.storageArea === this.storage) {\n listener(event);\n }\n };\n window.addEventListener(STORAGE_EVENT_TYPE, wrapper);\n return () => window.removeEventListener(STORAGE_EVENT_TYPE, wrapper);\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.storage.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n return this.storage.getItem(key);\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n return this.storage.key(index);\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n this.storage.removeItem(key);\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n this.storage.setItem(key, value);\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 { InMemoryListenableStorage } from './inMemoryListenableStorage';\nimport { BrowserListenableStorage } from './browserListenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * The type of storage event used for listening to storage changes.\n */\nexport const STORAGE_EVENT_TYPE = 'storage';\n\n/**\n * A function that handles storage change events.\n */\nexport type StorageListener = (event: StorageEventInit) => void;\n\n/**\n * A function that removes a storage listener when called.\n */\nexport type RemoveStorageListener = () => void;\n\nexport interface StorageListenable {\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener;\n}\n\n/**\n * An interface that extends the native Storage interface with the ability to listen for storage changes.\n */\nexport interface ListenableStorage extends Storage, StorageListenable {\n\n}\n\n/**\n * Factory function to get an appropriate ListenableStorage implementation based on the environment.\n * In a browser environment, it returns a BrowserListenableStorage wrapping localStorage.\n * In other environments, it returns an InMemoryListenableStorage.\n * @returns A ListenableStorage instance suitable for the current environment\n */\nexport const createListenableStorage = (): ListenableStorage => {\n if (isBrowser()) {\n return new BrowserListenableStorage(window.localStorage);\n }\n return new InMemoryListenableStorage();\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/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n */\n/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n * @template Deserialized The type of the deserialized value\n */\nexport interface Serializer<Serialized, Deserialized> {\n /**\n * Serializes a value to the specified format\n * @param value The value to serialize\n * @returns The serialized value\n */\n serialize(value: any): Serialized;\n\n /**\n * Deserializes a value from the specified format\n * @template Deserialized The type of the deserialized value\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a value from the specified format\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n deserialize(value: Serialized): Deserialized;\n}\n\n/**\n * Implementation of Serializer that uses JSON for serialization\n */\nexport class JsonSerializer implements Serializer<string, any> {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(value: any): string {\n return JSON.stringify(value);\n }\n\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize<V>(value: string): V {\n return JSON.parse(value);\n }\n}\n\n/**\n * Implementation of Serializer that performs no actual serialization\n * @template T The type of the value to pass through\n */\nexport class IdentitySerializer<T> implements Serializer<T, T> {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(value: T): T {\n return value;\n }\n\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(value: T): T {\n return value;\n }\n}\n\n/**\n * Global instance of JsonSerializer\n */\nexport const jsonSerializer = new JsonSerializer();\n/**\n * Global instance of IdentitySerializer\n */\nexport const identitySerializer = new IdentitySerializer<any>();\n\nexport function typedIdentitySerializer<T>(): IdentitySerializer<T> {\n return identitySerializer as IdentitySerializer<T>;\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 { createListenableStorage, ListenableStorage, StorageListener } from './listenableStorage';\nimport { Serializer, typedIdentitySerializer } from '../serializer';\n\n/**\n * Options for configuring KeyStorage\n */\nexport interface KeyStorageOptions<Deserialized> {\n /**\n * The key used to store and retrieve values from storage\n */\n key: string;\n\n /**\n * Optional serializer for converting values to and from storage format\n * Defaults to IdentitySerializer if not provided\n */\n serializer?: Serializer<string, Deserialized>;\n\n /**\n * Optional storage implementation\n * Defaults to the result of createListenableStorage() if not provided\n */\n storage?: ListenableStorage;\n}\n\n/**\n * A storage wrapper that manages a single value associated with a specific key\n * Provides caching and automatic cache invalidation when the storage value changes\n * @template Deserialized The type of the value being stored\n */\nexport class KeyStorage<Deserialized> {\n private readonly key: string;\n private readonly serializer: Serializer<string, Deserialized>;\n private readonly storage: ListenableStorage;\n private cacheValue: Deserialized | null = null;\n\n /**\n * Listener for storage change events\n * Invalidates the cache when the relevant key is modified\n */\n private readonly listener: StorageListener = (event) => {\n if (event.key !== this.key) {\n return;\n }\n this.cacheValue = null;\n if (event.newValue) {\n this.refreshCache(event.newValue);\n }\n };\n\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n private refreshCache(value: string) {\n this.cacheValue = this.serializer.deserialize(value);\n }\n\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(options: KeyStorageOptions<Deserialized>) {\n this.key = options.key;\n this.serializer = options.serializer ?? typedIdentitySerializer();\n this.storage = options.storage ?? createListenableStorage();\n this.storage.addListener(this.listener);\n }\n\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get(): Deserialized | null {\n if (this.cacheValue) {\n return this.cacheValue;\n }\n const value = this.storage.getItem(this.key);\n if (!value) {\n return null;\n }\n this.refreshCache(value);\n return this.cacheValue;\n }\n\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(value: Deserialized): void {\n const serialized = this.serializer.serialize(value);\n this.storage.setItem(this.key, serialized);\n this.cacheValue = value;\n }\n\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove(): void {\n this.storage.removeItem(this.key);\n this.cacheValue = null;\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 { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY] && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { IdentitySerializer } from './serializer';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { Serializer } from './serializer';\nimport { CompositeToken } from './tokenRefresher';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload;\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(token) as Payload;\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 return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, ResultExtractors.Json,\n {\n [IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY]: true,\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 { createListenableStorage, KeyStorage } from './storage';\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["isBrowser","InMemoryListenableStorage","key","value","index","oldValue","listener","eventInit","error","BrowserListenableStorage","storage","wrapper","event","STORAGE_EVENT_TYPE","createListenableStorage","JsonSerializer","IdentitySerializer","jsonSerializer","identitySerializer","typedIdentitySerializer","KeyStorage","options","serialized","_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","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":"0UAaO,SAASA,GAAqB,CACnC,OAAO,OAAO,OAAW,GAC3B,CCKO,MAAMC,CAAuD,CAA7D,aAAA,CACL,KAAiB,U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A,CAC5B,CAQA,QAAQ2B,EAAgD,CAGtD,OAAO,KAAK,QAAQ,QAAQ,KAAqB,KAAK,QAAQ,SAC5D,CACE,KAAMA,CAAA,EACLqB,EAAAA,iBAAiB,KACpB,CACE,CAACnC,CAAkC,EAAG,EAAA,CACxC,CACJ,CACF,CCtEO,MAAMoC,EAA0B,cAKhC,MAAMC,UAAqBnD,CAA4D,CAE5F,YACElB,EAAcoE,EACEf,EAAsB,EACtC,CACA,MAAM,CACJ,IAAArD,EACA,QAASY,EAAA,EACT,WAAY,IAAI8C,EAA4BL,CAAW,CAAA,CACxD,EANe,KAAA,YAAAA,CAOlB,CAEA,kBAAkBM,EAAgC,CAChD,KAAK,IACH,IAAIF,EAAkBE,CAAc,CAAA,CAExC,CACF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/env.ts","../src/storage/inMemoryListenableStorage.ts","../src/storage/browserListenableStorage.ts","../src/storage/listenableStorage.ts","../src/serializer.ts","../src/storage/keyStorage.ts","../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/jwtToken.ts","../src/jwtTokenManager.ts","../src/tokenRefresher.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isBrowser(): boolean {\n return typeof window !== 'undefined';\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 { ListenableStorage, RemoveStorageListener, StorageListener } from './listenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * An in-memory implementation of ListenableStorage that works in any environment.\n * This implementation stores data in a Map and manually fires storage events when data changes.\n */\nexport class InMemoryListenableStorage implements ListenableStorage {\n private readonly store: Map<string, string> = new Map();\n private readonly listeners: Set<StorageListener> = new Set();\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.store.size;\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n const oldValue = this.getItem(key);\n if (this.store.has(key)) {\n this.store.delete(key);\n this.notifyListeners({\n key,\n oldValue,\n newValue: null,\n });\n }\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n const oldValue = this.getItem(key);\n this.store.set(key, value);\n this.notifyListeners({ key, oldValue, newValue: value });\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n /**\n * Notifies all listeners of a storage change by creating and dispatching a StorageEvent.\n * @param eventInit - The initialization object for the StorageEvent\n */\n private notifyListeners(\n eventInit: StorageEventInit,\n ): void {\n if (isBrowser() && window.location) {\n eventInit.url = eventInit.url || window.location.href;\n }\n eventInit.storageArea = this;\n this.listeners.forEach(listener => {\n try {\n listener(eventInit);\n } catch (error) {\n console.error('Error in storage change listener:', 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 { ListenableStorage, RemoveStorageListener, STORAGE_EVENT_TYPE, StorageListener } from './listenableStorage';\n\n/**\n * A wrapper around the browser's native Storage (localStorage or sessionStorage)\n * that implements the ListenableStorage interface by using the browser's native storage events.\n */\nexport class BrowserListenableStorage implements ListenableStorage {\n\n /**\n * Creates a new BrowserListenableStorage instance.\n * @param storage - The native Storage object to wrap (e.g., localStorage or sessionStorage)\n */\n constructor(private readonly storage: Storage) {\n }\n\n /**\n * Gets the number of items stored in the storage.\n */\n get length(): number {\n return this.storage.length;\n }\n\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener {\n const wrapper: StorageListener = (event: StorageEventInit) => {\n if (event.storageArea === this.storage) {\n listener(event);\n }\n };\n window.addEventListener(STORAGE_EVENT_TYPE, wrapper);\n return () => window.removeEventListener(STORAGE_EVENT_TYPE, wrapper);\n }\n\n /**\n * Clears all items from the storage.\n */\n clear(): void {\n this.storage.clear();\n }\n\n /**\n * Gets an item from the storage.\n * @param key - The key of the item to retrieve\n * @returns The value of the item, or null if the item does not exist\n */\n getItem(key: string): string | null {\n return this.storage.getItem(key);\n }\n\n /**\n * Gets the key at the specified index.\n * @param index - The index of the key to retrieve\n * @returns The key at the specified index, or null if the index is out of bounds\n */\n key(index: number): string | null {\n return this.storage.key(index);\n }\n\n /**\n * Removes an item from the storage.\n * @param key - The key of the item to remove\n */\n removeItem(key: string): void {\n this.storage.removeItem(key);\n }\n\n /**\n * Sets an item in the storage.\n * @param key - The key of the item to set\n * @param value - The value to set\n */\n setItem(key: string, value: string): void {\n this.storage.setItem(key, value);\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 { InMemoryListenableStorage } from './inMemoryListenableStorage';\nimport { BrowserListenableStorage } from './browserListenableStorage';\nimport { isBrowser } from '../env';\n\n/**\n * The type of storage event used for listening to storage changes.\n */\nexport const STORAGE_EVENT_TYPE = 'storage';\n\n/**\n * A function that handles storage change events.\n */\nexport type StorageListener = (event: StorageEventInit) => void;\n\n/**\n * A function that removes a storage listener when called.\n */\nexport type RemoveStorageListener = () => void;\n\nexport interface StorageListenable {\n /**\n * Adds a listener for storage changes.\n * @param listener - The listener function to be called when storage changes\n * @returns A function that can be called to remove the listener\n */\n addListener(listener: StorageListener): RemoveStorageListener;\n}\n\n/**\n * An interface that extends the native Storage interface with the ability to listen for storage changes.\n */\nexport interface ListenableStorage extends Storage, StorageListenable {\n\n}\n\n/**\n * Factory function to get an appropriate ListenableStorage implementation based on the environment.\n * In a browser environment, it returns a BrowserListenableStorage wrapping localStorage.\n * In other environments, it returns an InMemoryListenableStorage.\n * @returns A ListenableStorage instance suitable for the current environment\n */\nexport const createListenableStorage = (): ListenableStorage => {\n if (isBrowser()) {\n return new BrowserListenableStorage(window.localStorage);\n }\n return new InMemoryListenableStorage();\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/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n */\n/**\n * Interface for serializing and deserializing values\n * @template Serialized The type of the serialized value\n * @template Deserialized The type of the deserialized value\n */\nexport interface Serializer<Serialized, Deserialized> {\n /**\n * Serializes a value to the specified format\n * @param value The value to serialize\n * @returns The serialized value\n */\n serialize(value: any): Serialized;\n\n /**\n * Deserializes a value from the specified format\n * @template Deserialized The type of the deserialized value\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a value from the specified format\n * @param value The value to deserialize\n * @returns The deserialized value\n */\n deserialize(value: Serialized): Deserialized;\n}\n\n/**\n * Implementation of Serializer that uses JSON for serialization\n */\nexport class JsonSerializer implements Serializer<string, any> {\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n /**\n * Serializes a value to a JSON string\n * @param value The value to serialize\n * @returns The JSON string representation of the value\n */\n serialize(value: any): string {\n return JSON.stringify(value);\n }\n\n /**\n * Deserializes a JSON string to a value\n * @template V The type of the deserialized value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n /**\n * Deserializes a JSON string to a value\n * @param value The JSON string to deserialize\n * @returns The deserialized value\n */\n deserialize<V>(value: string): V {\n return JSON.parse(value);\n }\n}\n\n/**\n * Implementation of Serializer that performs no actual serialization\n * @template T The type of the value to pass through\n */\nexport class IdentitySerializer<T> implements Serializer<T, T> {\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n /**\n * Returns the value as-is without serialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n serialize(value: T): T {\n return value;\n }\n\n /**\n * Returns the value as-is without deserialization\n * @template Deserialized The type of the deserialized value\n * @param value The value to pass through\n * @returns The same value that was passed in, cast to the target type\n */\n /**\n * Returns the value as-is without deserialization\n * @param value The value to pass through\n * @returns The same value that was passed in\n */\n deserialize(value: T): T {\n return value;\n }\n}\n\n/**\n * Global instance of JsonSerializer\n */\nexport const jsonSerializer = new JsonSerializer();\n/**\n * Global instance of IdentitySerializer\n */\nexport const identitySerializer = new IdentitySerializer<any>();\n\nexport function typedIdentitySerializer<T>(): IdentitySerializer<T> {\n return identitySerializer as IdentitySerializer<T>;\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 { createListenableStorage, ListenableStorage, StorageListener } from './listenableStorage';\nimport { Serializer, typedIdentitySerializer } from '../serializer';\n\n/**\n * Options for configuring KeyStorage\n */\nexport interface KeyStorageOptions<Deserialized> {\n /**\n * The key used to store and retrieve values from storage\n */\n key: string;\n\n /**\n * Optional serializer for converting values to and from storage format\n * Defaults to IdentitySerializer if not provided\n */\n serializer?: Serializer<string, Deserialized>;\n\n /**\n * Optional storage implementation\n * Defaults to the result of createListenableStorage() if not provided\n */\n storage?: ListenableStorage;\n}\n\n/**\n * A storage wrapper that manages a single value associated with a specific key\n * Provides caching and automatic cache invalidation when the storage value changes\n * @template Deserialized The type of the value being stored\n */\nexport class KeyStorage<Deserialized> {\n private readonly key: string;\n private readonly serializer: Serializer<string, Deserialized>;\n private readonly storage: ListenableStorage;\n private cacheValue: Deserialized | null = null;\n\n /**\n * Listener for storage change events\n * Invalidates the cache when the relevant key is modified\n */\n private readonly listener: StorageListener = (event) => {\n if (event.key !== this.key) {\n return;\n }\n this.cacheValue = null;\n if (event.newValue) {\n this.refreshCache(event.newValue);\n }\n };\n\n /**\n * Refreshes the cached value by deserializing the provided string\n * @param value The serialized value to deserialize and cache\n */\n private refreshCache(value: string) {\n this.cacheValue = this.serializer.deserialize(value);\n }\n\n /**\n * Creates a new KeyStorage instance\n * @param options Configuration options for the storage\n */\n constructor(options: KeyStorageOptions<Deserialized>) {\n this.key = options.key;\n this.serializer = options.serializer ?? typedIdentitySerializer();\n this.storage = options.storage ?? createListenableStorage();\n this.storage.addListener(this.listener);\n }\n\n /**\n * Gets the value associated with the key from storage\n * Uses cached value if available, otherwise retrieves from storage and caches it\n * @returns The deserialized value or null if no value is found\n */\n get(): Deserialized | null {\n if (this.cacheValue) {\n return this.cacheValue;\n }\n const value = this.storage.getItem(this.key);\n if (!value) {\n return null;\n }\n this.refreshCache(value);\n return this.cacheValue;\n }\n\n /**\n * Sets the value associated with the key in storage\n * Also updates the cached value\n * @param value The value to serialize and store\n */\n set(value: Deserialized): void {\n const serialized = this.serializer.serialize(value);\n this.storage.setItem(this.key, serialized);\n this.cacheValue = value;\n }\n\n /**\n * Removes the value associated with the key from storage\n * Also clears the cached value\n */\n remove(): void {\n this.storage.removeItem(this.key);\n this.cacheValue = null;\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 { DeviceIdStorage } from './deviceIdStorage';\nimport { JwtTokenManager } from './jwtTokenManager';\n\n/**\n * CoSec HTTP headers enumeration.\n */\nexport class CoSecHeaders {\n static readonly DEVICE_ID = 'CoSec-Device-Id';\n static readonly APP_ID = 'CoSec-App-Id';\n static readonly AUTHORIZATION = 'Authorization';\n static readonly REQUEST_ID = 'CoSec-Request-Id';\n}\n\nexport class ResponseCodes {\n static readonly UNAUTHORIZED = 401;\n}\n\n/**\n * CoSec options interface.\n */\nexport interface CoSecOptions {\n /**\n * Application ID to be sent in the CoSec-App-Id header.\n */\n appId: string;\n\n /**\n * Device ID storage instance.\n */\n deviceIdStorage: DeviceIdStorage;\n\n tokenManager: JwtTokenManager;\n}\n\n/**\n * Authorization result interface.\n */\nexport interface AuthorizeResult {\n authorized: boolean;\n reason: string;\n}\n\n/**\n * Authorization result constants.\n */\nexport const AuthorizeResults = {\n ALLOW: { authorized: true, reason: 'Allow' },\n EXPLICIT_DENY: { authorized: false, reason: 'Explicit Deny' },\n IMPLICIT_DENY: { authorized: false, reason: 'Implicit Deny' },\n TOKEN_EXPIRED: { authorized: false, reason: 'Token Expired' },\n TOO_MANY_REQUESTS: { authorized: false, reason: 'Too Many Requests' },\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { nanoid } from 'nanoid';\n\nexport interface IdGenerator {\n generateId(): string;\n}\n\n/**\n * Nano ID implementation of IdGenerator.\n * Generates unique request IDs using Nano ID.\n */\nexport class NanoIdGenerator implements IdGenerator {\n /**\n * Generate a unique request ID.\n *\n * @returns A unique request ID\n */\n generateId(): string {\n return nanoid();\n }\n}\n\nexport const idGenerator = new NanoIdGenerator();\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FetchExchange,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n type RequestInterceptor,\n} from '@ahoo-wang/fetcher';\nimport { CoSecHeaders, CoSecOptions } from './types';\nimport { idGenerator } from './idGenerator';\n\n/**\n * The name of the CoSecRequestInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_NAME = 'CoSecRequestInterceptor';\n\n/**\n * The order of the CoSecRequestInterceptor.\n * Set to REQUEST_BODY_INTERCEPTOR_ORDER + 1000 to ensure it runs after RequestBodyInterceptor.\n */\nexport const COSEC_REQUEST_INTERCEPTOR_ORDER =\n REQUEST_BODY_INTERCEPTOR_ORDER + 1000;\n\nexport const IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY = 'Ignore-Refresh-Token';\n\n/**\n * Interceptor that automatically adds CoSec authentication headers to requests.\n *\n * This interceptor adds the following headers to each request:\n * - CoSec-Device-Id: Device identifier (stored in localStorage or generated)\n * - CoSec-App-Id: Application identifier\n * - Authorization: Bearer token\n * - CoSec-Request-Id: Unique request identifier for each request\n *\n * @remarks\n * This interceptor runs after RequestBodyInterceptor but before FetchInterceptor.\n * The order is set to COSEC_REQUEST_INTERCEPTOR_ORDER to ensure it runs after\n * request body processing but before the actual HTTP request is made. This positioning\n * allows for proper authentication header addition after all request body transformations\n * are complete, ensuring that the final request is properly authenticated before\n * being sent over the network.\n */\nexport class CoSecRequestInterceptor implements RequestInterceptor {\n readonly name = COSEC_REQUEST_INTERCEPTOR_NAME;\n readonly order = COSEC_REQUEST_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecRequestInterceptor instance.\n * @param options - The CoSec configuration options including appId, deviceIdStorage, and tokenManager\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercept requests to add CoSec authentication headers.\n *\n * This method adds the following headers to each request:\n * - CoSec-App-Id: The application identifier from the CoSec options\n * - CoSec-Device-Id: A unique device identifier, either retrieved from storage or generated\n * - CoSec-Request-Id: A unique identifier for this specific request\n * - Authorization: Bearer token if available in token storage\n *\n * @param exchange - The fetch exchange containing the request to process\n *\n * @remarks\n * This method runs after RequestBodyInterceptor but before FetchInterceptor.\n * It ensures that authentication headers are added to the request after all\n * body processing is complete. The positioning allows for proper authentication\n * header addition after all request body transformations are finished, ensuring\n * that the final request is properly authenticated before being sent over the network.\n * This execution order prevents authentication headers from being overwritten by\n * subsequent request processing interceptors.\n *\n * The method also handles token refreshing when the current token is expired but still refreshable.\n * It will attempt to refresh the token before adding the Authorization header to the request.\n */\n async intercept(exchange: FetchExchange) {\n // Generate a unique request ID for this request\n const requestId = idGenerator.generateId();\n\n // Get or create a device ID\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n\n // Ensure request headers object exists\n const requestHeaders = exchange.ensureRequestHeaders();\n\n // Add CoSec headers to the request\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n\n // Get the current token from token manager\n let currentToken = this.options.tokenManager.currentToken;\n\n // Skip if no token exists or Authorization header is already set\n if (!currentToken || requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n return;\n }\n\n // Refresh token if needed and refreshable\n if (!exchange.attributes.has(IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY) && currentToken.isRefreshNeeded && currentToken.isRefreshable) {\n await this.options.tokenManager.refresh();\n }\n\n // Get the current token again (might have been refreshed)\n currentToken = this.options.tokenManager.currentToken;\n\n // Add Authorization header if we have a token\n if (currentToken) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${currentToken.access.token}`;\n }\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, type ResponseInterceptor } from '@ahoo-wang/fetcher';\n\n/**\n * The name of the CoSecResponseInterceptor.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_NAME = 'CoSecResponseInterceptor';\n\n/**\n * The order of the CoSecResponseInterceptor.\n * Set to a high negative value to ensure it runs early in the interceptor chain.\n */\nexport const COSEC_RESPONSE_INTERCEPTOR_ORDER = Number.MIN_SAFE_INTEGER + 1000;\n\n/**\n * CoSecResponseInterceptor is responsible for handling unauthorized responses (401)\n * by attempting to refresh the authentication token and retrying the original request.\n *\n * This interceptor:\n * 1. Checks if the response status is 401 (UNAUTHORIZED)\n * 2. If so, and if there's a current token, attempts to refresh it\n * 3. On successful refresh, stores the new token and retries the original request\n * 4. On refresh failure, clears stored tokens and propagates the error\n */\nexport class CoSecResponseInterceptor implements ResponseInterceptor {\n readonly name = COSEC_RESPONSE_INTERCEPTOR_NAME;\n readonly order = COSEC_RESPONSE_INTERCEPTOR_ORDER;\n private options: CoSecOptions;\n\n /**\n * Creates a new CoSecResponseInterceptor instance.\n * @param options - The CoSec configuration options including token storage and refresher\n */\n constructor(options: CoSecOptions) {\n this.options = options;\n }\n\n /**\n * Intercepts the response and handles unauthorized responses by refreshing tokens.\n * @param exchange - The fetch exchange containing request and response information\n */\n async intercept(exchange: FetchExchange): Promise<void> {\n const response = exchange.response;\n // If there's no response, nothing to intercept\n if (!response) {\n return;\n }\n\n // Only handle unauthorized responses (401)\n if (response.status !== ResponseCodes.UNAUTHORIZED) {\n return;\n }\n\n if (!this.options.tokenManager.isRefreshable) {\n return;\n }\n try {\n await this.options.tokenManager.refresh();\n // Retry the original request with the new token\n await exchange.fetcher.interceptors.exchange(exchange);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenManager.tokenStorage.remove();\n throw error;\n }\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { idGenerator } from './idGenerator';\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { IdentitySerializer } from './serializer';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage extends KeyStorage<string> {\n constructor(key: string = DEFAULT_COSEC_DEVICE_ID_KEY) {\n super({\n key,\n serializer: new IdentitySerializer<string>(),\n storage: createListenableStorage(),\n });\n }\n\n /**\n * Generate a new device ID.\n *\n * @returns A newly generated device ID\n */\n generateDeviceId(): string {\n return idGenerator.generateId();\n }\n\n /**\n * Get or create a device ID.\n *\n * @returns The existing device ID if available, otherwise a newly generated one\n */\n getOrCreate(): string {\n // Try to get existing device ID from storage\n let deviceId = this.get();\n if (!deviceId) {\n // Generate a new device ID and store it\n deviceId = this.generateDeviceId();\n this.set(deviceId);\n }\n\n return deviceId;\n }\n\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Interface representing a JWT payload as defined in RFC 7519.\n * Contains standard JWT claims as well as custom properties.\n */\nexport interface JwtPayload {\n /**\n * JWT ID - provides a unique identifier for the JWT.\n */\n jti?: string;\n /**\n * Subject - identifies the principal that is the subject of the JWT.\n */\n sub?: string;\n /**\n * Issuer - identifies the principal that issued the JWT.\n */\n iss?: string;\n /**\n * Audience - identifies the recipients that the JWT is intended for.\n * Can be a single string or an array of strings.\n */\n aud?: string | string[];\n /**\n * Expiration Time - identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n exp?: number;\n /**\n * Not Before - identifies the time before which the JWT MUST NOT be accepted for processing.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n nbf?: number;\n /**\n * Issued At - identifies the time at which the JWT was issued.\n * Represented as NumericDate (seconds since Unix epoch).\n */\n iat?: number;\n\n /**\n * Allows additional custom properties to be included in the payload.\n */\n [key: string]: any;\n}\n\n/**\n * Interface representing a JWT payload with CoSec-specific extensions.\n * Extends the standard JwtPayload interface with additional CoSec-specific properties.\n */\nexport interface CoSecJwtPayload extends JwtPayload {\n /**\n * Tenant identifier - identifies the tenant scope for the JWT.\n */\n tenantId?: string;\n /**\n * Policies - array of policy identifiers associated with the JWT.\n * These are security policies defined internally by Cosec.\n */\n policies?: string[];\n /**\n * Roles - array of role identifiers associated with the JWT.\n * Role IDs indicate what roles the token belongs to.\n */\n roles?: string[];\n /**\n * Attributes - custom key-value pairs providing additional information about the JWT.\n */\n attributes?: Record<string, any>;\n}\n\n/**\n * Parses a JWT token and extracts its payload.\n *\n * This function decodes the payload part of a JWT token, handling Base64URL decoding\n * and JSON parsing. It validates the token structure and returns null for invalid tokens.\n *\n * @param token - The JWT token string to parse\n * @returns The parsed JWT payload or null if parsing fails\n */\nexport function parseJwtPayload<T extends JwtPayload>(token: string): T | null {\n try {\n const parts = token.split('.');\n if (parts.length !== 3) {\n return null;\n }\n\n const base64Url = parts[1];\n const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n\n // Add padding if needed\n const paddedBase64 = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n '=',\n );\n\n const jsonPayload = decodeURIComponent(\n atob(paddedBase64)\n .split('')\n .map(function(c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);\n })\n .join(''),\n );\n return JSON.parse(jsonPayload) as T;\n } catch (error) {\n // Avoid exposing sensitive information in error logs\n console.error('Failed to parse JWT token', error);\n return null;\n }\n}\n\nexport interface EarlyPeriodCapable {\n /**\n * The time in seconds before actual expiration when the token should be considered expired (default: 0)\n */\n readonly earlyPeriod: number;\n}\n\n/**\n * Checks if a JWT token is expired based on its expiration time (exp claim).\n *\n * This function determines if a JWT token has expired by comparing its exp claim\n * with the current time. If the token is a string, it will be parsed first.\n * Tokens without an exp claim are considered not expired.\n *\n * The early period parameter allows for early token expiration, which is useful\n * for triggering token refresh before the token actually expires. This helps\n * avoid race conditions where a token expires between the time it is checked and\n * the time it is used.\n *\n * @param token - The JWT token to check, either as a string or as a JwtPayload object\n * @param earlyPeriod - The time in seconds before actual expiration when the token should be considered expired (default: 0)\n * @returns true if the token is expired (or will expire within the early period) or cannot be parsed, false otherwise\n */\nexport function isTokenExpired(\n token: string | CoSecJwtPayload,\n earlyPeriod: number = 0,\n): boolean {\n const payload = typeof token === 'string' ? parseJwtPayload(token) : token;\n if (!payload) {\n return true;\n }\n\n const expAt = payload.exp;\n if (!expAt) {\n return false;\n }\n\n const now = Date.now() / 1000;\n return now > expAt - earlyPeriod;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CoSecJwtPayload, EarlyPeriodCapable, isTokenExpired, JwtPayload, parseJwtPayload } from './jwts';\nimport { Serializer } from './serializer';\nimport { CompositeToken } from './tokenRefresher';\n\n\n/**\n * Interface for JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport interface IJwtToken<Payload extends JwtPayload> extends EarlyPeriodCapable {\n readonly token: string;\n readonly payload: Payload;\n\n isExpired: boolean;\n}\n\n/**\n * Class representing a JWT token with typed payload\n * @template Payload The type of the JWT payload\n */\nexport class JwtToken<Payload extends JwtPayload> implements IJwtToken<Payload> {\n public readonly payload: Payload;\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(token) as Payload;\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 return isTokenExpired(this.payload, this.earlyPeriod);\n }\n}\n\nexport interface RefreshTokenStatusCapable {\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n readonly isRefreshNeeded: boolean;\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n readonly isRefreshable: boolean;\n}\n\n/**\n * Class representing a composite token containing both access and refresh tokens\n */\nexport class JwtCompositeToken implements EarlyPeriodCapable, RefreshTokenStatusCapable {\n public readonly access: JwtToken<CoSecJwtPayload>;\n public readonly refresh: JwtToken<JwtPayload>;\n\n /**\n * Creates a new JwtCompositeToken instance\n */\n constructor(public readonly token: CompositeToken, public readonly earlyPeriod: number = 0) {\n this.access = new JwtToken(token.accessToken, earlyPeriod);\n this.refresh = new JwtToken(token.refreshToken, earlyPeriod);\n }\n\n /**\n * Checks if the access token needs to be refreshed\n * @returns true if the access token is expired, false otherwise\n */\n get isRefreshNeeded(): boolean {\n return this.access.isExpired;\n }\n\n /**\n * Checks if the refresh token is still valid and can be used to refresh the access token\n * @returns true if the refresh token is not expired, false otherwise\n */\n get isRefreshable(): boolean {\n return !this.refresh.isExpired;\n }\n\n}\n\n/**\n * Serializer for JwtCompositeToken that handles conversion to and from JSON strings\n */\nexport class JwtCompositeTokenSerializer implements Serializer<string, JwtCompositeToken>, EarlyPeriodCapable {\n constructor(public readonly earlyPeriod: number = 0) {\n }\n\n /**\n * Deserializes a JSON string to a JwtCompositeToken\n * @param value The JSON string representation of a composite token\n * @returns A JwtCompositeToken instance\n */\n deserialize(value: string): JwtCompositeToken {\n const compositeToken = JSON.parse(value) as CompositeToken;\n return new JwtCompositeToken(compositeToken, this.earlyPeriod);\n }\n\n /**\n * Serializes a JwtCompositeToken to a JSON string\n * @param value The JwtCompositeToken to serialize\n * @returns A JSON string representation of the composite token\n */\n serialize(value: JwtCompositeToken): string {\n return JSON.stringify(value.token);\n }\n}\n\nexport const jwtCompositeTokenSerializer = new JwtCompositeTokenSerializer();","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TokenStorage } from './tokenStorage';\nimport { CompositeToken, TokenRefresher } from './tokenRefresher';\nimport { JwtCompositeToken, RefreshTokenStatusCapable } from './jwtToken';\n\n/**\n * Manages JWT token refreshing operations and provides status information\n */\nexport class JwtTokenManager implements RefreshTokenStatusCapable {\n private refreshInProgress?: Promise<void>;\n\n /**\n * Creates a new JwtTokenManager instance\n * @param tokenStorage The storage used to persist tokens\n * @param tokenRefresher The refresher used to refresh expired tokens\n */\n constructor(\n public readonly tokenStorage: TokenStorage,\n public readonly tokenRefresher: TokenRefresher,\n ) {\n\n }\n\n /**\n * Gets the current JWT composite token from storage\n * @returns The current token or null if none exists\n */\n get currentToken(): JwtCompositeToken | null {\n return this.tokenStorage.get();\n }\n\n /**\n * Refreshes the JWT token\n * @param currentToken Optional current token to refresh. If not provided, uses the stored token.\n * @returns Promise that resolves when refresh is complete\n * @throws Error if no token is found or refresh fails\n */\n async refresh(currentToken?: CompositeToken): Promise<void> {\n if (!currentToken) {\n const jwtToken = this.currentToken;\n if (!jwtToken) {\n throw new Error('No token found');\n }\n currentToken = jwtToken.token;\n }\n if (this.refreshInProgress) {\n return this.refreshInProgress;\n }\n\n this.refreshInProgress = this.tokenRefresher.refresh(currentToken)\n .then(newToken => {\n this.tokenStorage.setCompositeToken(newToken);\n })\n .catch(error => {\n this.tokenStorage.remove();\n throw error;\n })\n .finally(() => {\n this.refreshInProgress = undefined;\n });\n\n return this.refreshInProgress;\n }\n\n /**\n * Indicates if the current token needs to be refreshed\n * @returns true if the access token is expired and needs refresh, false otherwise\n */\n get isRefreshNeeded(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshNeeded;\n }\n\n /**\n * Indicates if the current token can be refreshed\n * @returns true if the refresh token is still valid, false otherwise\n */\n get isRefreshable(): boolean {\n if (!this.currentToken) {\n return false;\n }\n return this.currentToken.isRefreshable;\n }\n\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Fetcher, ResultExtractors } from '@ahoo-wang/fetcher';\nimport { IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY } from './cosecRequestInterceptor';\n\n/**\n * Interface for access tokens.\n */\nexport interface AccessToken {\n accessToken: string;\n}\n\n/**\n * Interface for refresh tokens.\n */\nexport interface RefreshToken {\n refreshToken: string;\n}\n\n/**\n * Composite token interface that contains both access and refresh tokens.\n *\n * accessToken and refreshToken always appear in pairs, no need to split them.\n */\nexport interface CompositeToken extends AccessToken, RefreshToken {\n}\n\n/**\n * Interface for token refreshers.\n *\n * Provides a method to refresh tokens.\n */\nexport interface TokenRefresher {\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken>;\n}\n\nexport interface CoSecTokenRefresherOptions {\n fetcher: Fetcher;\n endpoint: string;\n}\n\n/**\n * CoSecTokenRefresher is a class that implements the TokenRefresher interface\n * for refreshing composite tokens through a configured endpoint.\n */\nexport class CoSecTokenRefresher implements TokenRefresher {\n /**\n * Creates a new instance of CoSecTokenRefresher.\n *\n * @param options The configuration options for the token refresher including fetcher and endpoint\n */\n constructor(public readonly options: CoSecTokenRefresherOptions) {\n }\n\n /**\n * Refresh the given token and return a new CompositeToken.\n *\n * @param token The token to refresh\n * @returns A Promise that resolves to a new CompositeToken\n */\n refresh(token: CompositeToken): Promise<CompositeToken> {\n // Send a POST request to the configured endpoint with the token as body\n // and extract the response as JSON to return a new CompositeToken\n\n return this.options.fetcher.post<CompositeToken>(this.options.endpoint,\n {\n body: token,\n }, {\n resultExtractor: ResultExtractors.Json,\n attributes: new Map([[IGNORE_REFRESH_TOKEN_ATTRIBUTE_KEY, true]]),\n },\n );\n }\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createListenableStorage, KeyStorage } from './storage';\nimport { JwtCompositeToken, JwtCompositeTokenSerializer } from './jwtToken';\nimport { CompositeToken } from './tokenRefresher';\nimport { EarlyPeriodCapable } from './jwts';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage extends KeyStorage<JwtCompositeToken> implements EarlyPeriodCapable {\n\n constructor(\n key: string = DEFAULT_COSEC_TOKEN_KEY,\n public readonly earlyPeriod: number = 0,\n ) {\n super({\n key,\n storage: createListenableStorage(),\n serializer: new JwtCompositeTokenSerializer(earlyPeriod),\n });\n }\n\n setCompositeToken(compositeToken: CompositeToken) {\n this.set(\n new JwtCompositeToken(compositeToken),\n );\n }\n}\n"],"names":["isBrowser","InMemoryListenableStorage","key","value","index","oldValue","listener","eventInit","error","BrowserListenableStorage","storage","wrapper","event","STORAGE_EVENT_TYPE","createListenableStorage","JsonSerializer","IdentitySerializer","jsonSerializer","identitySerializer","typedIdentitySerializer","KeyStorage","options","serialized","_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","exchange","requestId","deviceId","requestHeaders","currentToken","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","parseJwtPayload","token","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","JwtToken","JwtCompositeToken","JwtCompositeTokenSerializer","compositeToken","jwtCompositeTokenSerializer","JwtTokenManager","tokenStorage","tokenRefresher","jwtToken","newToken","CoSecTokenRefresher","ResultExtractors","DEFAULT_COSEC_TOKEN_KEY","TokenStorage"],"mappings":"0UAaO,SAASA,GAAqB,CACnC,OAAO,OAAO,OAAW,GAC3B,CCKO,MAAMC,CAAuD,CAA7D,aAAA,CACL,KAAiB,UAAiC,IAClD,KAAiB,cAAsC,GAAI,CAK3D,IAAI,QAAiB,CACnB,OAAO,KAAK,MAAM,IACpB,CAKA,OAAc,CACZ,KAAK,MAAM,MAAA,CACb,CAOA,QAAQC,EAA4B,CAClC,MAAMC,EAAQ,KAAK,MAAM,IAAID,CAAG,EAChC,OAAOC,IAAU,OAAYA,EAAQ,IACvC,CAOA,IAAIC,EAA8B,CAEhC,OADa,MAAM,KAAK,KAAK,MAAM,MAAM,EAC7BA,CAAK,GAAK,IACxB,CAM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B,EACtC,CACA,MAAM,CACJ,IAAArD,EACA,QAASY,EAAA,EACT,WAAY,IAAI8C,EAA4BL,CAAW,CAAA,CACxD,EANe,KAAA,YAAAA,CAOlB,CAEA,kBAAkBM,EAAgC,CAChD,KAAK,IACH,IAAIF,EAAkBE,CAAc,CAAA,CAExC,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../src/tokenRefresher.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAoB,MAAM,oBAAoB,CAAC;AAG/D;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAe,SAAQ,WAAW,EAAE,YAAY;CAChE;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACzD;AAED,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,mBAAoB,YAAW,cAAc;aAM5B,OAAO,EAAE,0BAA0B;IAL/D;;;;OAIG;gBACyB,OAAO,EAAE,0BAA0B;IAG/D;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"tokenRefresher.d.ts","sourceRoot":"","sources":["../src/tokenRefresher.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAoB,MAAM,oBAAoB,CAAC;AAG/D;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;GAEG;AACH,MAAM,WAAW,YAAY;IAC3B,YAAY,EAAE,MAAM,CAAC;CACtB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAe,SAAQ,WAAW,EAAE,YAAY;CAChE;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;CACzD;AAED,MAAM,WAAW,0BAA0B;IACzC,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,mBAAoB,YAAW,cAAc;aAM5B,OAAO,EAAE,0BAA0B;IAL/D;;;;OAIG;gBACyB,OAAO,EAAE,0BAA0B;IAG/D;;;;;OAKG;IACH,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;CAaxD"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-cosec",
|
|
3
|
-
"version": "1.6.
|
|
3
|
+
"version": "1.6.2",
|
|
4
4
|
"description": "CoSec authentication integration for Fetcher HTTP client with enterprise-grade security features. Provides automatic token management, device ID persistence, and request tracking.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"fetch",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
],
|
|
41
41
|
"dependencies": {
|
|
42
42
|
"nanoid": "^5.1.5",
|
|
43
|
-
"@ahoo-wang/fetcher": "1.6.
|
|
43
|
+
"@ahoo-wang/fetcher": "1.6.2"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@vitest/coverage-v8": "^3.2.4",
|