@ahoo-wang/fetcher-cosec 1.2.3 → 1.2.6
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/cosecRequestInterceptor.d.ts.map +1 -1
- package/dist/index.es.js +30 -35
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/package.json +4 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,
|
|
1
|
+
{"version":3,"file":"cosecRequestInterceptor.d.ts","sourceRoot":"","sources":["../src/cosecRequestInterceptor.ts"],"names":[],"mappings":"AAaA,OAAO,EACL,aAAa,EAEb,kBAAkB,EACnB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAgB,YAAY,EAAE,MAAM,SAAS,CAAC;AAGrD;;GAEG;AACH,eAAO,MAAM,8BAA8B,4BAA4B,CAAC;AAExE;;;GAGG;AACH,eAAO,MAAM,+BAA+B,QACL,CAAC;AAExC;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,uBAAwB,YAAW,kBAAkB;IAChE,QAAQ,CAAC,IAAI,6BAAkC;IAC/C,QAAQ,CAAC,KAAK,SAAmC;IACjD,OAAO,CAAC,OAAO,CAAe;gBAElB,OAAO,EAAE,YAAY;IAIjC;;;;;;;;;;;;;;;;;;;OAmBG;IACH,SAAS,CAAC,QAAQ,EAAE,aAAa;CAYlC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { REQUEST_BODY_INTERCEPTOR_ORDER as
|
|
1
|
+
import { REQUEST_BODY_INTERCEPTOR_ORDER as u } from "@ahoo-wang/fetcher";
|
|
2
2
|
import { nanoid as d } from "nanoid";
|
|
3
3
|
const a = class a {
|
|
4
4
|
};
|
|
5
5
|
a.DEVICE_ID = "CoSec-Device-Id", a.APP_ID = "CoSec-App-Id", a.AUTHORIZATION = "Authorization", a.REQUEST_ID = "CoSec-Request-Id";
|
|
6
6
|
let i = a;
|
|
7
|
-
const
|
|
7
|
+
const I = class I {
|
|
8
8
|
};
|
|
9
|
-
|
|
10
|
-
let
|
|
11
|
-
const
|
|
9
|
+
I.UNAUTHORIZED = 401;
|
|
10
|
+
let c = I;
|
|
11
|
+
const N = {
|
|
12
12
|
ALLOW: { authorized: !0, reason: "Allow" },
|
|
13
13
|
EXPLICIT_DENY: { authorized: !1, reason: "Explicit Deny" },
|
|
14
14
|
IMPLICIT_DENY: { authorized: !1, reason: "Implicit Deny" },
|
|
@@ -25,10 +25,10 @@ class p {
|
|
|
25
25
|
return d();
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
|
-
const
|
|
29
|
-
class
|
|
28
|
+
const h = new p(), g = "CoSecRequestInterceptor", T = u + 1e3;
|
|
29
|
+
class m {
|
|
30
30
|
constructor(e) {
|
|
31
|
-
this.name = g, this.order =
|
|
31
|
+
this.name = g, this.order = T, this.options = e;
|
|
32
32
|
}
|
|
33
33
|
/**
|
|
34
34
|
* Intercept requests to add CoSec authentication headers.
|
|
@@ -51,23 +51,18 @@ class N {
|
|
|
51
51
|
* subsequent request processing interceptors.
|
|
52
52
|
*/
|
|
53
53
|
intercept(e) {
|
|
54
|
-
const t =
|
|
55
|
-
|
|
56
|
-
headers: {
|
|
57
|
-
...e.request.headers
|
|
58
|
-
}
|
|
59
|
-
}, n = c.headers;
|
|
60
|
-
n[i.APP_ID] = this.options.appId, n[i.DEVICE_ID] = s, n[i.REQUEST_ID] = t, o && (n[i.AUTHORIZATION] = `Bearer ${o.accessToken}`), e.request = c;
|
|
54
|
+
const t = h.generateId(), s = this.options.deviceIdStorage.getOrCreate(), o = this.options.tokenStorage.get(), n = e.ensureRequestHeaders();
|
|
55
|
+
n[i.APP_ID] = this.options.appId, n[i.DEVICE_ID] = s, n[i.REQUEST_ID] = t, o && !n[i.AUTHORIZATION] && (n[i.AUTHORIZATION] = `Bearer ${o.accessToken}`);
|
|
61
56
|
}
|
|
62
57
|
}
|
|
63
|
-
const
|
|
64
|
-
class
|
|
58
|
+
const R = "CoSecResponseInterceptor", S = Number.MIN_SAFE_INTEGER + 1e3;
|
|
59
|
+
class A {
|
|
65
60
|
/**
|
|
66
61
|
* Creates a new CoSecResponseInterceptor instance.
|
|
67
62
|
* @param options - The CoSec configuration options including token storage and refresher
|
|
68
63
|
*/
|
|
69
64
|
constructor(e) {
|
|
70
|
-
this.name =
|
|
65
|
+
this.name = R, this.order = S, this.options = e;
|
|
71
66
|
}
|
|
72
67
|
/**
|
|
73
68
|
* Intercepts the response and handles unauthorized responses by refreshing tokens.
|
|
@@ -75,7 +70,7 @@ class k {
|
|
|
75
70
|
*/
|
|
76
71
|
async intercept(e) {
|
|
77
72
|
const t = e.response;
|
|
78
|
-
if (!t || t.status !==
|
|
73
|
+
if (!t || t.status !== c.UNAUTHORIZED)
|
|
79
74
|
return;
|
|
80
75
|
const s = this.options.tokenStorage.get();
|
|
81
76
|
if (s)
|
|
@@ -115,7 +110,7 @@ function E() {
|
|
|
115
110
|
return typeof window < "u" && window.localStorage ? window.localStorage : new O();
|
|
116
111
|
}
|
|
117
112
|
const f = "cosec-device-id";
|
|
118
|
-
class
|
|
113
|
+
class k {
|
|
119
114
|
constructor(e = f, t = E()) {
|
|
120
115
|
this.deviceIdKey = e, this.storage = t;
|
|
121
116
|
}
|
|
@@ -141,7 +136,7 @@ class A {
|
|
|
141
136
|
* @returns A newly generated device ID
|
|
142
137
|
*/
|
|
143
138
|
generateDeviceId() {
|
|
144
|
-
return
|
|
139
|
+
return h.generateId();
|
|
145
140
|
}
|
|
146
141
|
/**
|
|
147
142
|
* Get or create a device ID.
|
|
@@ -167,12 +162,12 @@ function _(r) {
|
|
|
167
162
|
const s = e[1].replace(/-/g, "+").replace(/_/g, "/"), o = s.padEnd(
|
|
168
163
|
s.length + (4 - s.length % 4) % 4,
|
|
169
164
|
"="
|
|
170
|
-
),
|
|
171
|
-
atob(o).split("").map(function(
|
|
172
|
-
return "%" + ("00" +
|
|
165
|
+
), n = decodeURIComponent(
|
|
166
|
+
atob(o).split("").map(function(l) {
|
|
167
|
+
return "%" + ("00" + l.charCodeAt(0).toString(16)).slice(-2);
|
|
173
168
|
}).join("")
|
|
174
169
|
);
|
|
175
|
-
return JSON.parse(
|
|
170
|
+
return JSON.parse(n);
|
|
176
171
|
} catch (e) {
|
|
177
172
|
return console.error("Failed to parse JWT token", e), null;
|
|
178
173
|
}
|
|
@@ -185,7 +180,7 @@ function w(r, e = 0) {
|
|
|
185
180
|
return s ? Date.now() / 1e3 > s - e : !1;
|
|
186
181
|
}
|
|
187
182
|
const D = "cosec-token";
|
|
188
|
-
class
|
|
183
|
+
class U {
|
|
189
184
|
constructor(e = D, t = E()) {
|
|
190
185
|
this.tokenKey = e, this.storage = t;
|
|
191
186
|
}
|
|
@@ -221,23 +216,23 @@ class v {
|
|
|
221
216
|
}
|
|
222
217
|
}
|
|
223
218
|
export {
|
|
224
|
-
|
|
219
|
+
N as AuthorizeResults,
|
|
225
220
|
g as COSEC_REQUEST_INTERCEPTOR_NAME,
|
|
226
|
-
|
|
227
|
-
|
|
221
|
+
T as COSEC_REQUEST_INTERCEPTOR_ORDER,
|
|
222
|
+
R as COSEC_RESPONSE_INTERCEPTOR_NAME,
|
|
228
223
|
S as COSEC_RESPONSE_INTERCEPTOR_ORDER,
|
|
229
224
|
i as CoSecHeaders,
|
|
230
|
-
|
|
231
|
-
|
|
225
|
+
m as CoSecRequestInterceptor,
|
|
226
|
+
A as CoSecResponseInterceptor,
|
|
232
227
|
f as DEFAULT_COSEC_DEVICE_ID_KEY,
|
|
233
228
|
D as DEFAULT_COSEC_TOKEN_KEY,
|
|
234
|
-
|
|
229
|
+
k as DeviceIdStorage,
|
|
235
230
|
O as InMemoryStorage,
|
|
236
231
|
p as NanoIdGenerator,
|
|
237
|
-
|
|
238
|
-
|
|
232
|
+
c as ResponseCodes,
|
|
233
|
+
U as TokenStorage,
|
|
239
234
|
E as getStorage,
|
|
240
|
-
|
|
235
|
+
h as idGenerator,
|
|
241
236
|
w as isTokenExpired,
|
|
242
237
|
_ as parseJwtPayload
|
|
243
238
|
};
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { TokenStorage } from './tokenStorage';\nimport { TokenRefresher } from './tokenRefresher';\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 /**\n * Token storage instance.\n */\n tokenStorage: TokenStorage;\n\n /**\n * Token refresher function.\n *\n * Takes a CompositeToken and returns a Promise that resolves to a new CompositeToken.\n */\n tokenRefresher: TokenRefresher;\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 FetchRequest,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n 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\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 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 intercept(exchange: FetchExchange) {\n const requestId = idGenerator.generateId();\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n const token = this.options.tokenStorage.get();\n\n // Clone the request to avoid modifying the original\n const newRequest: FetchRequest = {\n ...exchange.request,\n headers: {\n ...exchange.request.headers,\n },\n };\n\n const requestHeaders = newRequest.headers as Record<string, string>;\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n if (token) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] =\n `Bearer ${token.accessToken}`;\n }\n exchange.request = newRequest;\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 { CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, 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 // Get the current token from storage\n const currentToken = this.options.tokenStorage.get();\n // If there's no current token, we can't refresh it\n if (!currentToken) {\n return;\n }\n\n try {\n // Attempt to refresh the token\n const newToken = await this.options.tokenRefresher.refresh(currentToken);\n // Store the refreshed token\n this.options.tokenStorage.set(newToken);\n // Retry the original request with the new token\n await exchange.fetcher.request(exchange.request);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenStorage.clear();\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\n/**\n * In-memory storage fallback for environments without localStorage.\n */\nexport class InMemoryStorage implements Storage {\n private store: Map<string, string> = new Map();\n\n get length(): number {\n return this.store.size;\n }\n\n clear(): void {\n this.store.clear();\n }\n\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n removeItem(key: string): void {\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n }\n\n setItem(key: string, value: string): void {\n this.store.set(key, value);\n }\n}\n\nexport function getStorage(): Storage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n } else {\n // Use in-memory storage as fallback\n return new InMemoryStorage();\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 { getStorage } from './inMemoryStorage';\nimport { idGenerator } from './idGenerator';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage {\n private readonly deviceIdKey: string;\n private storage: Storage;\n\n constructor(\n deviceIdKey: string = DEFAULT_COSEC_DEVICE_ID_KEY,\n storage: Storage = getStorage(),\n ) {\n this.deviceIdKey = deviceIdKey;\n this.storage = storage;\n }\n\n /**\n * Get the current device ID.\n *\n * @returns The current device ID or null if not set\n */\n get(): string | null {\n return this.storage.getItem(this.deviceIdKey);\n }\n\n /**\n * Set a device ID.\n *\n * @param deviceId - The device ID to set\n */\n set(deviceId: string): void {\n this.storage.setItem(this.deviceIdKey, deviceId);\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 * Clear the stored device ID.\n */\n clear(): void {\n this.storage.removeItem(this.deviceIdKey);\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\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 { getStorage } from './inMemoryStorage';\nimport { CompositeToken } from './tokenRefresher';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage {\n private readonly tokenKey: string;\n private storage: Storage;\n\n constructor(\n tokenKey: string = DEFAULT_COSEC_TOKEN_KEY,\n storage: Storage = getStorage(),\n ) {\n this.tokenKey = tokenKey;\n this.storage = storage;\n }\n\n /**\n * Get the current access token.\n *\n * @returns The current composite token or null if not set\n */\n get(): CompositeToken | null {\n const tokenStr = this.storage.getItem(this.tokenKey);\n if (!tokenStr) {\n return null;\n }\n\n try {\n return JSON.parse(tokenStr);\n } catch (error) {\n console.warn('Failed to get token from storage:', error);\n this.clear();\n return null;\n }\n }\n\n /**\n * Store a composite token.\n *\n * @param token - The composite token to store\n */\n set(token: CompositeToken): void {\n const tokenStr = JSON.stringify(token);\n this.storage.setItem(this.tokenKey, tokenStr);\n }\n\n /**\n * Clear all tokens.\n */\n clear(): void {\n this.storage.removeItem(this.tokenKey);\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","CoSecRequestInterceptor","options","exchange","requestId","deviceId","token","newRequest","requestHeaders","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","currentToken","newToken","error","InMemoryStorage","key","value","index","getStorage","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","deviceIdKey","storage","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","tokenKey","tokenStr"],"mappings":";;AAoBO,MAAMA,IAAN,MAAMA,EAAa;AAK1B;AAJEA,EAAgB,YAAY,mBAC5BA,EAAgB,SAAS,gBACzBA,EAAgB,gBAAgB,iBAChCA,EAAgB,aAAa;AAJxB,IAAMC,IAAND;AAOA,MAAME,IAAN,MAAMA,EAAc;AAE3B;AADEA,EAAgB,eAAe;AAD1B,IAAMC,IAAND;AA0CA,MAAME,IAAmB;AAAA,EAC9B,OAAO,EAAE,YAAY,IAAM,QAAQ,QAAA;AAAA,EACnC,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,eAAe,EAAE,YAAY,IAAO,QAAQ,gBAAA;AAAA,EAC5C,mBAAmB,EAAE,YAAY,IAAO,QAAQ,oBAAA;AAClD;ACpDO,MAAMC,EAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMlD,aAAqB;AACnB,WAAOC,EAAA;AAAA,EACT;AACF;AAEO,MAAMC,IAAc,IAAIF,EAAA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MG,IAA0B;AAKhC,MAAMC,EAAa;AAAA,EAIxB,YACEC,IAAmBF,GACnBX,IAAmBJ,KACnB;AACA,SAAK,WAAWiB,GAChB,KAAK,UAAUb;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAA6B;AAC3B,UAAMc,IAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ;AACnD,QAAI,CAACA;AACH,aAAO;AAGT,QAAI;AACF,aAAO,KAAK,MAAMA,CAAQ;AAAA,IAC5B,SAASvB,GAAO;AACd,qBAAQ,KAAK,qCAAqCA,CAAK,GACvD,KAAK,MAAA,GACE;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAIT,GAA6B;AAC/B,UAAMgC,IAAW,KAAK,UAAUhC,CAAK;AACrC,SAAK,QAAQ,QAAQ,KAAK,UAAUgC,CAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,QAAQ,WAAW,KAAK,QAAQ;AAAA,EACvC;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { TokenStorage } from './tokenStorage';\nimport { TokenRefresher } from './tokenRefresher';\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 /**\n * Token storage instance.\n */\n tokenStorage: TokenStorage;\n\n /**\n * Token refresher function.\n *\n * Takes a CompositeToken and returns a Promise that resolves to a new CompositeToken.\n */\n tokenRefresher: TokenRefresher;\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 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\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 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 intercept(exchange: FetchExchange) {\n const requestId = idGenerator.generateId();\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n const token = this.options.tokenStorage.get();\n const requestHeaders = exchange.ensureRequestHeaders();\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n if (token && !requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${token.accessToken}`;\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 { CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, 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 // Get the current token from storage\n const currentToken = this.options.tokenStorage.get();\n // If there's no current token, we can't refresh it\n if (!currentToken) {\n return;\n }\n\n try {\n // Attempt to refresh the token\n const newToken = await this.options.tokenRefresher.refresh(currentToken);\n // Store the refreshed token\n this.options.tokenStorage.set(newToken);\n // Retry the original request with the new token\n await exchange.fetcher.request(exchange.request);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenStorage.clear();\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\n/**\n * In-memory storage fallback for environments without localStorage.\n */\nexport class InMemoryStorage implements Storage {\n private store: Map<string, string> = new Map();\n\n get length(): number {\n return this.store.size;\n }\n\n clear(): void {\n this.store.clear();\n }\n\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n removeItem(key: string): void {\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n }\n\n setItem(key: string, value: string): void {\n this.store.set(key, value);\n }\n}\n\nexport function getStorage(): Storage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n } else {\n // Use in-memory storage as fallback\n return new InMemoryStorage();\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 { getStorage } from './inMemoryStorage';\nimport { idGenerator } from './idGenerator';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage {\n private readonly deviceIdKey: string;\n private storage: Storage;\n\n constructor(\n deviceIdKey: string = DEFAULT_COSEC_DEVICE_ID_KEY,\n storage: Storage = getStorage(),\n ) {\n this.deviceIdKey = deviceIdKey;\n this.storage = storage;\n }\n\n /**\n * Get the current device ID.\n *\n * @returns The current device ID or null if not set\n */\n get(): string | null {\n return this.storage.getItem(this.deviceIdKey);\n }\n\n /**\n * Set a device ID.\n *\n * @param deviceId - The device ID to set\n */\n set(deviceId: string): void {\n this.storage.setItem(this.deviceIdKey, deviceId);\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 * Clear the stored device ID.\n */\n clear(): void {\n this.storage.removeItem(this.deviceIdKey);\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\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 { getStorage } from './inMemoryStorage';\nimport { CompositeToken } from './tokenRefresher';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage {\n private readonly tokenKey: string;\n private storage: Storage;\n\n constructor(\n tokenKey: string = DEFAULT_COSEC_TOKEN_KEY,\n storage: Storage = getStorage(),\n ) {\n this.tokenKey = tokenKey;\n this.storage = storage;\n }\n\n /**\n * Get the current access token.\n *\n * @returns The current composite token or null if not set\n */\n get(): CompositeToken | null {\n const tokenStr = this.storage.getItem(this.tokenKey);\n if (!tokenStr) {\n return null;\n }\n\n try {\n return JSON.parse(tokenStr);\n } catch (error) {\n console.warn('Failed to get token from storage:', error);\n this.clear();\n return null;\n }\n }\n\n /**\n * Store a composite token.\n *\n * @param token - The composite token to store\n */\n set(token: CompositeToken): void {\n const tokenStr = JSON.stringify(token);\n this.storage.setItem(this.tokenKey, tokenStr);\n }\n\n /**\n * Clear all tokens.\n */\n clear(): void {\n this.storage.removeItem(this.tokenKey);\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","CoSecRequestInterceptor","options","exchange","requestId","deviceId","token","requestHeaders","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","currentToken","newToken","error","InMemoryStorage","key","value","index","getStorage","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","deviceIdKey","storage","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","tokenKey","tokenStr"],"mappings":";;AAoBO,MAAMA,IAAN,MAAMA,EAAa;AAK1B;AAJEA,EAAgB,YAAY,mBAC5BA,EAAgB,SAAS,gBACzBA,EAAgB,gBAAgB,iBAChCA,EAAgB,aAAa;AAJxB,IAAMC,IAAND;AAOA,MAAME,IAAN,MAAMA,EAAc;AAE3B;AADEA,EAAgB,eAAe;AAD1B,IAAMC,IAAND;AA0CA,MAAME,IAAmB;AAAA,EAC9B,OAAO,EAAE,YAAY,IAAM,QA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A,CAAK,GACzC;AAAA,EACT;AACF;AAkBO,SAASgB,EACdxB,GACAyB,IAAsB,GACb;AACT,QAAMC,IAAU,OAAO1B,KAAU,WAAWkB,EAAgBlB,CAAK,IAAIA;AACrE,MAAI,CAAC0B;AACH,WAAO;AAGT,QAAMC,IAAQD,EAAQ;AACtB,SAAKC,IAIO,KAAK,IAAA,IAAQ,MACZA,IAAQF,IAJZ;AAKX;AC1IO,MAAMG,IAA0B;AAKhC,MAAMC,EAAa;AAAA,EAIxB,YACEC,IAAmBF,GACnBX,IAAmBJ,KACnB;AACA,SAAK,WAAWiB,GAChB,KAAK,UAAUb;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAA6B;AAC3B,UAAMc,IAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ;AACnD,QAAI,CAACA;AACH,aAAO;AAGT,QAAI;AACF,aAAO,KAAK,MAAMA,CAAQ;AAAA,IAC5B,SAASvB,GAAO;AACd,qBAAQ,KAAK,qCAAqCA,CAAK,GACvD,KAAK,MAAA,GACE;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAIR,GAA6B;AAC/B,UAAM+B,IAAW,KAAK,UAAU/B,CAAK;AACrC,SAAK,QAAQ,QAAQ,KAAK,UAAU+B,CAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,QAAQ,WAAW,KAAK,QAAQ;AAAA,EACvC;AACF;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(t,E){typeof exports=="object"&&typeof module<"u"?E(exports,require("@ahoo-wang/fetcher"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid"],E):(t=typeof globalThis<"u"?globalThis:t||self,E(t.FetcherCoSec={},t.Fetcher,t.nanoid))})(this,(function(t,E,
|
|
1
|
+
(function(t,E){typeof exports=="object"&&typeof module<"u"?E(exports,require("@ahoo-wang/fetcher"),require("nanoid")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher","nanoid"],E):(t=typeof globalThis<"u"?globalThis:t||self,E(t.FetcherCoSec={},t.Fetcher,t.nanoid))})(this,(function(t,E,p){"use strict";const c=class c{};c.DEVICE_ID="CoSec-Device-Id",c.APP_ID="CoSec-App-Id",c.AUTHORIZATION="Authorization",c.REQUEST_ID="CoSec-Request-Id";let i=c;const h=class h{};h.UNAUTHORIZED=401;let I=h;const N={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 l{generateId(){return p.nanoid()}}const u=new l,R="CoSecRequestInterceptor",S=E.REQUEST_BODY_INTERCEPTOR_ORDER+1e3;class D{constructor(e){this.name=R,this.order=S,this.options=e}intercept(e){const o=u.generateId(),s=this.options.deviceIdStorage.getOrCreate(),n=this.options.tokenStorage.get(),a=e.ensureRequestHeaders();a[i.APP_ID]=this.options.appId,a[i.DEVICE_ID]=s,a[i.REQUEST_ID]=o,n&&!a[i.AUTHORIZATION]&&(a[i.AUTHORIZATION]=`Bearer ${n.accessToken}`)}}const T="CoSecResponseInterceptor",g=Number.MIN_SAFE_INTEGER+1e3;class y{constructor(e){this.name=T,this.order=g,this.options=e}async intercept(e){const o=e.response;if(!o||o.status!==I.UNAUTHORIZED)return;const s=this.options.tokenStorage.get();if(s)try{const n=await this.options.tokenRefresher.refresh(s);this.options.tokenStorage.set(n),await e.fetcher.request(e.request)}catch(n){throw this.options.tokenStorage.clear(),n}}}class O{constructor(){this.store=new Map}get length(){return this.store.size}clear(){this.store.clear()}getItem(e){const o=this.store.get(e);return o!==void 0?o:null}key(e){return Array.from(this.store.keys())[e]||null}removeItem(e){this.store.has(e)&&this.store.delete(e)}setItem(e,o){this.store.set(e,o)}}function d(){return typeof window<"u"&&window.localStorage?window.localStorage:new O}const _="cosec-device-id";class A{constructor(e=_,o=d()){this.deviceIdKey=e,this.storage=o}get(){return this.storage.getItem(this.deviceIdKey)}set(e){this.storage.setItem(this.deviceIdKey,e)}generateDeviceId(){return u.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}clear(){this.storage.removeItem(this.deviceIdKey)}}function C(r){try{const e=r.split(".");if(e.length!==3)return null;const s=e[1].replace(/-/g,"+").replace(/_/g,"/"),n=s.padEnd(s.length+(4-s.length%4)%4,"="),a=decodeURIComponent(atob(n).split("").map(function(P){return"%"+("00"+P.charCodeAt(0).toString(16)).slice(-2)}).join(""));return JSON.parse(a)}catch(e){return console.error("Failed to parse JWT token",e),null}}function m(r,e=0){const o=typeof r=="string"?C(r):r;if(!o)return!0;const s=o.exp;return s?Date.now()/1e3>s-e:!1}const f="cosec-token";class k{constructor(e=f,o=d()){this.tokenKey=e,this.storage=o}get(){const e=this.storage.getItem(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch(o){return console.warn("Failed to get token from storage:",o),this.clear(),null}}set(e){const o=JSON.stringify(e);this.storage.setItem(this.tokenKey,o)}clear(){this.storage.removeItem(this.tokenKey)}}t.AuthorizeResults=N,t.COSEC_REQUEST_INTERCEPTOR_NAME=R,t.COSEC_REQUEST_INTERCEPTOR_ORDER=S,t.COSEC_RESPONSE_INTERCEPTOR_NAME=T,t.COSEC_RESPONSE_INTERCEPTOR_ORDER=g,t.CoSecHeaders=i,t.CoSecRequestInterceptor=D,t.CoSecResponseInterceptor=y,t.DEFAULT_COSEC_DEVICE_ID_KEY=_,t.DEFAULT_COSEC_TOKEN_KEY=f,t.DeviceIdStorage=A,t.InMemoryStorage=O,t.NanoIdGenerator=l,t.ResponseCodes=I,t.TokenStorage=k,t.getStorage=d,t.idGenerator=u,t.isTokenExpired=m,t.parseJwtPayload=C,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { TokenStorage } from './tokenStorage';\nimport { TokenRefresher } from './tokenRefresher';\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 /**\n * Token storage instance.\n */\n tokenStorage: TokenStorage;\n\n /**\n * Token refresher function.\n *\n * Takes a CompositeToken and returns a Promise that resolves to a new CompositeToken.\n */\n tokenRefresher: TokenRefresher;\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 FetchRequest,\n REQUEST_BODY_INTERCEPTOR_ORDER,\n 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\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 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 intercept(exchange: FetchExchange) {\n const requestId = idGenerator.generateId();\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n const token = this.options.tokenStorage.get();\n\n // Clone the request to avoid modifying the original\n const newRequest: FetchRequest = {\n ...exchange.request,\n headers: {\n ...exchange.request.headers,\n },\n };\n\n const requestHeaders = newRequest.headers as Record<string, string>;\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n if (token) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] =\n `Bearer ${token.accessToken}`;\n }\n exchange.request = newRequest;\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 { CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, 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 // Get the current token from storage\n const currentToken = this.options.tokenStorage.get();\n // If there's no current token, we can't refresh it\n if (!currentToken) {\n return;\n }\n\n try {\n // Attempt to refresh the token\n const newToken = await this.options.tokenRefresher.refresh(currentToken);\n // Store the refreshed token\n this.options.tokenStorage.set(newToken);\n // Retry the original request with the new token\n await exchange.fetcher.request(exchange.request);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenStorage.clear();\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\n/**\n * In-memory storage fallback for environments without localStorage.\n */\nexport class InMemoryStorage implements Storage {\n private store: Map<string, string> = new Map();\n\n get length(): number {\n return this.store.size;\n }\n\n clear(): void {\n this.store.clear();\n }\n\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n removeItem(key: string): void {\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n }\n\n setItem(key: string, value: string): void {\n this.store.set(key, value);\n }\n}\n\nexport function getStorage(): Storage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n } else {\n // Use in-memory storage as fallback\n return new InMemoryStorage();\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 { getStorage } from './inMemoryStorage';\nimport { idGenerator } from './idGenerator';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage {\n private readonly deviceIdKey: string;\n private storage: Storage;\n\n constructor(\n deviceIdKey: string = DEFAULT_COSEC_DEVICE_ID_KEY,\n storage: Storage = getStorage(),\n ) {\n this.deviceIdKey = deviceIdKey;\n this.storage = storage;\n }\n\n /**\n * Get the current device ID.\n *\n * @returns The current device ID or null if not set\n */\n get(): string | null {\n return this.storage.getItem(this.deviceIdKey);\n }\n\n /**\n * Set a device ID.\n *\n * @param deviceId - The device ID to set\n */\n set(deviceId: string): void {\n this.storage.setItem(this.deviceIdKey, deviceId);\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 * Clear the stored device ID.\n */\n clear(): void {\n this.storage.removeItem(this.deviceIdKey);\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\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 { getStorage } from './inMemoryStorage';\nimport { CompositeToken } from './tokenRefresher';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage {\n private readonly tokenKey: string;\n private storage: Storage;\n\n constructor(\n tokenKey: string = DEFAULT_COSEC_TOKEN_KEY,\n storage: Storage = getStorage(),\n ) {\n this.tokenKey = tokenKey;\n this.storage = storage;\n }\n\n /**\n * Get the current access token.\n *\n * @returns The current composite token or null if not set\n */\n get(): CompositeToken | null {\n const tokenStr = this.storage.getItem(this.tokenKey);\n if (!tokenStr) {\n return null;\n }\n\n try {\n return JSON.parse(tokenStr);\n } catch (error) {\n console.warn('Failed to get token from storage:', error);\n this.clear();\n return null;\n }\n }\n\n /**\n * Store a composite token.\n *\n * @param token - The composite token to store\n */\n set(token: CompositeToken): void {\n const tokenStr = JSON.stringify(token);\n this.storage.setItem(this.tokenKey, tokenStr);\n }\n\n /**\n * Clear all tokens.\n */\n clear(): void {\n this.storage.removeItem(this.tokenKey);\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","CoSecRequestInterceptor","options","exchange","requestId","deviceId","token","newRequest","requestHeaders","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","currentToken","newToken","error","InMemoryStorage","key","value","index","getStorage","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","deviceIdKey","storage","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","isTokenExpired","earlyPeriod","payload","expAt","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","tokenKey","tokenStr"],"mappings":"0UAoBO,MAAMA,EAAN,MAAMA,CAAa,CAK1B,EAJEA,EAAgB,UAAY,kBAC5BA,EAAgB,OAAS,eACzBA,EAAgB,cAAgB,gBAChCA,EAAgB,WAAa,mBAJxB,IAAMC,EAAND,EAOA,MAAME,EAAN,MAAMA,CAAc,CAE3B,EADEA,EAAgB,aAAe,IAD1B,IAAMC,EAAND,EA0CA,MAAME,EAAmB,CAC9B,MAAO,CAAE,WAAY,GAAM,OAAQ,OAAA,EACnC,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,cAAe,CAAE,WAAY,GAAO,OAAQ,eAAA,EAC5C,kBAAmB,CAAE,WAAY,GAAO,OAAQ,mBAAA,CAClD,ECpDO,MAAMC,CAAuC,CAMlD,YAAqB,CACnB,OAAOC,SAAA,CACT,CACF,CAEO,MAAMC,EAAc,IAAIF,ECTlBG,EAAiC,0BAMjCC,EACXC,EAAAA,+BAAiC,IAmB5B,MAAMC,CAAsD,CAKjE,YAAYC,EAAuB,CAJnC,KAAS,KAAOJ,EAChB,KAAS,MAAQC,EAIf,KAAK,QAAUG,CACjB,CAsBA,UAAUC,EAAyB,CACjC,MAAMC,EAA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EAAE,SAAS,EAAE,GAAG,MAAM,EAAE,CAC7D,CAAC,EACA,KAAK,EAAE,CAAA,EAEZ,OAAO,KAAK,MAAMC,CAAW,CAC/B,OAASd,EAAO,CAEd,eAAQ,MAAM,4BAA6BA,CAAK,EACzC,IACT,CACF,CAkBO,SAASe,EACdxB,EACAyB,EAAsB,EACb,CACT,MAAMC,EAAU,OAAO1B,GAAU,SAAWmB,EAAgBnB,CAAK,EAAIA,EACrE,GAAI,CAAC0B,EACH,MAAO,GAGT,MAAMC,EAAQD,EAAQ,IACtB,OAAKC,EAIO,KAAK,IAAA,EAAQ,IACZA,EAAQF,EAJZ,EAKX,CC1IO,MAAMG,EAA0B,cAKhC,MAAMC,CAAa,CAIxB,YACEC,EAAmBF,EACnBV,EAAmBJ,IACnB,CACA,KAAK,SAAWgB,EAChB,KAAK,QAAUZ,CACjB,CAOA,KAA6B,CAC3B,MAAMa,EAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ,EACnD,GAAI,CAACA,EACH,OAAO,KAGT,GAAI,CACF,OAAO,KAAK,MAAMA,CAAQ,CAC5B,OAAStB,EAAO,CACd,eAAQ,KAAK,oCAAqCA,CAAK,EACvD,KAAK,MAAA,EACE,IACT,CACF,CAOA,IAAIT,EAA6B,CAC/B,MAAM+B,EAAW,KAAK,UAAU/B,CAAK,EACrC,KAAK,QAAQ,QAAQ,KAAK,SAAU+B,CAAQ,CAC9C,CAKA,OAAc,CACZ,KAAK,QAAQ,WAAW,KAAK,QAAQ,CACvC,CACF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.ts","../src/jwts.ts","../src/tokenStorage.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DeviceIdStorage } from './deviceIdStorage';\nimport { TokenStorage } from './tokenStorage';\nimport { TokenRefresher } from './tokenRefresher';\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 /**\n * Token storage instance.\n */\n tokenStorage: TokenStorage;\n\n /**\n * Token refresher function.\n *\n * Takes a CompositeToken and returns a Promise that resolves to a new CompositeToken.\n */\n tokenRefresher: TokenRefresher;\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 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\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 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 intercept(exchange: FetchExchange) {\n const requestId = idGenerator.generateId();\n const deviceId = this.options.deviceIdStorage.getOrCreate();\n const token = this.options.tokenStorage.get();\n const requestHeaders = exchange.ensureRequestHeaders();\n requestHeaders[CoSecHeaders.APP_ID] = this.options.appId;\n requestHeaders[CoSecHeaders.DEVICE_ID] = deviceId;\n requestHeaders[CoSecHeaders.REQUEST_ID] = requestId;\n if (token && !requestHeaders[CoSecHeaders.AUTHORIZATION]) {\n requestHeaders[CoSecHeaders.AUTHORIZATION] = `Bearer ${token.accessToken}`;\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 { CoSecOptions, ResponseCodes } from './types';\nimport { FetchExchange, 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 // Get the current token from storage\n const currentToken = this.options.tokenStorage.get();\n // If there's no current token, we can't refresh it\n if (!currentToken) {\n return;\n }\n\n try {\n // Attempt to refresh the token\n const newToken = await this.options.tokenRefresher.refresh(currentToken);\n // Store the refreshed token\n this.options.tokenStorage.set(newToken);\n // Retry the original request with the new token\n await exchange.fetcher.request(exchange.request);\n } catch (error) {\n // If token refresh fails, clear stored tokens and re-throw the error\n this.options.tokenStorage.clear();\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\n/**\n * In-memory storage fallback for environments without localStorage.\n */\nexport class InMemoryStorage implements Storage {\n private store: Map<string, string> = new Map();\n\n get length(): number {\n return this.store.size;\n }\n\n clear(): void {\n this.store.clear();\n }\n\n getItem(key: string): string | null {\n const value = this.store.get(key);\n return value !== undefined ? value : null;\n }\n\n key(index: number): string | null {\n const keys = Array.from(this.store.keys());\n return keys[index] || null;\n }\n\n removeItem(key: string): void {\n if (this.store.has(key)) {\n this.store.delete(key);\n }\n }\n\n setItem(key: string, value: string): void {\n this.store.set(key, value);\n }\n}\n\nexport function getStorage(): Storage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n } else {\n // Use in-memory storage as fallback\n return new InMemoryStorage();\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 { getStorage } from './inMemoryStorage';\nimport { idGenerator } from './idGenerator';\n\nexport const DEFAULT_COSEC_DEVICE_ID_KEY = 'cosec-device-id';\n\n/**\n * Storage class for managing device identifiers.\n */\nexport class DeviceIdStorage {\n private readonly deviceIdKey: string;\n private storage: Storage;\n\n constructor(\n deviceIdKey: string = DEFAULT_COSEC_DEVICE_ID_KEY,\n storage: Storage = getStorage(),\n ) {\n this.deviceIdKey = deviceIdKey;\n this.storage = storage;\n }\n\n /**\n * Get the current device ID.\n *\n * @returns The current device ID or null if not set\n */\n get(): string | null {\n return this.storage.getItem(this.deviceIdKey);\n }\n\n /**\n * Set a device ID.\n *\n * @param deviceId - The device ID to set\n */\n set(deviceId: string): void {\n this.storage.setItem(this.deviceIdKey, deviceId);\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 * Clear the stored device ID.\n */\n clear(): void {\n this.storage.removeItem(this.deviceIdKey);\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\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 { getStorage } from './inMemoryStorage';\nimport { CompositeToken } from './tokenRefresher';\n\nexport const DEFAULT_COSEC_TOKEN_KEY = 'cosec-token';\n\n/**\n * Storage class for managing access and refresh tokens.\n */\nexport class TokenStorage {\n private readonly tokenKey: string;\n private storage: Storage;\n\n constructor(\n tokenKey: string = DEFAULT_COSEC_TOKEN_KEY,\n storage: Storage = getStorage(),\n ) {\n this.tokenKey = tokenKey;\n this.storage = storage;\n }\n\n /**\n * Get the current access token.\n *\n * @returns The current composite token or null if not set\n */\n get(): CompositeToken | null {\n const tokenStr = this.storage.getItem(this.tokenKey);\n if (!tokenStr) {\n return null;\n }\n\n try {\n return JSON.parse(tokenStr);\n } catch (error) {\n console.warn('Failed to get token from storage:', error);\n this.clear();\n return null;\n }\n }\n\n /**\n * Store a composite token.\n *\n * @param token - The composite token to store\n */\n set(token: CompositeToken): void {\n const tokenStr = JSON.stringify(token);\n this.storage.setItem(this.tokenKey, tokenStr);\n }\n\n /**\n * Clear all tokens.\n */\n clear(): void {\n this.storage.removeItem(this.tokenKey);\n }\n}\n"],"names":["_CoSecHeaders","CoSecHeaders","_ResponseCodes","ResponseCodes","AuthorizeResults","NanoIdGenerator","nanoid","idGenerator","COSEC_REQUEST_INTERCEPTOR_NAME","COSEC_REQUEST_INTERCEPTOR_ORDER","REQUEST_BODY_INTERCEPTOR_ORDER","CoSecRequestInterceptor","options","exchange","requestId","deviceId","token","requestHeaders","COSEC_RESPONSE_INTERCEPTOR_NAME","COSEC_RESPONSE_INTERCEPTOR_ORDER","CoSecResponseInterceptor","response","currentToken","newToken","error","InMemoryStorage","key","value","index","getStorage","DEFAULT_COSEC_DEVICE_ID_KEY","DeviceIdStorage","deviceIdKey","storage","parseJwtPayload","parts","base64","paddedBase64","jsonPayload","c","isTokenExpired","earlyPeriod","payload","expAt","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","tokenKey","tokenStr"],"mappings":"0UAoBO,MAAMA,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A6B,CAC3B,MAAMc,EAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ,EACnD,GAAI,CAACA,EACH,OAAO,KAGT,GAAI,CACF,OAAO,KAAK,MAAMA,CAAQ,CAC5B,OAASvB,EAAO,CACd,eAAQ,KAAK,oCAAqCA,CAAK,EACvD,KAAK,MAAA,EACE,IACT,CACF,CAOA,IAAIR,EAA6B,CAC/B,MAAM+B,EAAW,KAAK,UAAU/B,CAAK,EACrC,KAAK,QAAQ,QAAQ,KAAK,SAAU+B,CAAQ,CAC9C,CAKA,OAAc,CACZ,KAAK,QAAQ,WAAW,KAAK,QAAQ,CACvC,CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ahoo-wang/fetcher-cosec",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.6",
|
|
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.2.
|
|
43
|
+
"@ahoo-wang/fetcher": "1.2.6"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@vitest/coverage-v8": "^3.2.4",
|
|
@@ -55,6 +55,7 @@
|
|
|
55
55
|
"build": "vite build",
|
|
56
56
|
"test": "vitest run --coverage",
|
|
57
57
|
"lint": "eslint . --fix",
|
|
58
|
-
"clean": "rm -rf dist"
|
|
58
|
+
"clean": "rm -rf dist",
|
|
59
|
+
"analyze": "npx vite-bundle-analyzer -p auto"
|
|
59
60
|
}
|
|
60
61
|
}
|