@ahoo-wang/fetcher-cosec 0.11.0 → 0.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -212,3 +212,4 @@ export {
212
212
  E as getStorage,
213
213
  I as idGenerator
214
214
  };
215
+ //# sourceMappingURL=index.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.es.js","sources":["../src/types.ts","../../../node_modules/.pnpm/nanoid@5.1.5/node_modules/nanoid/url-alphabet/index.js","../../../node_modules/.pnpm/nanoid@5.1.5/node_modules/nanoid/index.browser.js","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.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 enum CoSecHeaders {\n DEVICE_ID = 'CoSec-Device-Id',\n APP_ID = 'CoSec-App-Id',\n AUTHORIZATION = 'Authorization',\n REQUEST_ID = 'CoSec-Request-Id',\n}\n\nexport enum ResponseCodes {\n 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","export const urlAlphabet =\n 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\n","/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\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\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","ResponseCodes","AuthorizeResults","urlAlphabet","nanoid","size","id","bytes","scopedUrlAlphabet","NanoIdGenerator","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","deviceId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EAKA,QAAc;AACZ,SAAK,QAAQ,WAAW,KAAK,WAAW;AAAA,EAC1C;AACF;ACnEO,MAAMoB,IAA0B;AAKhC,MAAMC,EAAa;AAAA,EAIxB,YACEC,IAAmBF,GACnBD,IAAmBJ,KACnB;AACA,SAAK,WAAWO,GAChB,KAAK,UAAUH;AAAA,EACjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAA6B;AAC3B,UAAMI,IAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ;AACnD,QAAI,CAACA;AACH,aAAO;AAGT,QAAI;AACF,aAAO,KAAK,MAAMA,CAAQ;AAAA,IAC5B,SAASb,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,UAAMsB,IAAW,KAAK,UAAUtB,CAAK;AACrC,SAAK,QAAQ,QAAQ,KAAK,UAAUsB,CAAQ;AAAA,EAC9C;AAAA;AAAA;AAAA;AAAA,EAKA,QAAc;AACZ,SAAK,QAAQ,WAAW,KAAK,QAAQ;AAAA,EACvC;AACF;","x_google_ignoreList":[1,2]}
package/dist/index.umd.js CHANGED
@@ -1 +1,2 @@
1
1
  (function(t,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],i):(t=typeof globalThis<"u"?globalThis:t||self,i(t.FetcherCoSec={},t.Fetcher))})(this,(function(t,i){"use strict";var s=(o=>(o.DEVICE_ID="CoSec-Device-Id",o.APP_ID="CoSec-App-Id",o.AUTHORIZATION="Authorization",o.REQUEST_ID="CoSec-Request-Id",o))(s||{}),E=(o=>(o[o.UNAUTHORIZED=401]="UNAUTHORIZED",o))(E||{});const g={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"}},f="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let D=(o=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(o|=0));for(;o--;)e+=f[r[o]&63];return e};class h{generateId(){return D()}}const I=new h,d="CoSecRequestInterceptor",R=i.REQUEST_BODY_INTERCEPTOR_ORDER+1e3;class N{constructor(e){this.name=d,this.order=R,this.options=e}intercept(e){const r=I.generateId(),a=this.options.deviceIdStorage.getOrCreate(),n=this.options.tokenStorage.get(),O={...e.request,headers:{...e.request.headers}},c=O.headers;c[s.APP_ID]=this.options.appId,c[s.DEVICE_ID]=a,c[s.REQUEST_ID]=r,n&&(c[s.AUTHORIZATION]=`Bearer ${n.accessToken}`),e.request=O}}const S="CoSecResponseInterceptor",T=Number.MIN_SAFE_INTEGER+1e3;class y{constructor(e){this.name=S,this.order=T,this.options=e}async intercept(e){const r=e.response;if(!r||r.status!==E.UNAUTHORIZED)return;const a=this.options.tokenStorage.get();if(a)try{const n=await this.options.tokenRefresher.refresh(a);this.options.tokenStorage.set(n),await e.fetcher.request(e.request)}catch(n){throw this.options.tokenStorage.clear(),n}}}class _{constructor(){this.store=new Map}get length(){return this.store.size}clear(){this.store.clear()}getItem(e){const r=this.store.get(e);return r!==void 0?r:null}key(e){return Array.from(this.store.keys())[e]||null}removeItem(e){this.store.has(e)&&this.store.delete(e)}setItem(e,r){this.store.set(e,r)}}function u(){return typeof window<"u"&&window.localStorage?window.localStorage:new _}const l="cosec-device-id";class A{constructor(e=l,r=u()){this.deviceIdKey=e,this.storage=r}get(){return this.storage.getItem(this.deviceIdKey)}set(e){this.storage.setItem(this.deviceIdKey,e)}generateDeviceId(){return I.generateId()}getOrCreate(){let e=this.get();return e||(e=this.generateDeviceId(),this.set(e)),e}clear(){this.storage.removeItem(this.deviceIdKey)}}const C="cosec-token";class p{constructor(e=C,r=u()){this.tokenKey=e,this.storage=r}get(){const e=this.storage.getItem(this.tokenKey);if(!e)return null;try{return JSON.parse(e)}catch(r){return console.warn("Failed to get token from storage:",r),this.clear(),null}}set(e){const r=JSON.stringify(e);this.storage.setItem(this.tokenKey,r)}clear(){this.storage.removeItem(this.tokenKey)}}t.AuthorizeResults=g,t.COSEC_REQUEST_INTERCEPTOR_NAME=d,t.COSEC_REQUEST_INTERCEPTOR_ORDER=R,t.COSEC_RESPONSE_INTERCEPTOR_NAME=S,t.COSEC_RESPONSE_INTERCEPTOR_ORDER=T,t.CoSecHeaders=s,t.CoSecRequestInterceptor=N,t.CoSecResponseInterceptor=y,t.DEFAULT_COSEC_DEVICE_ID_KEY=l,t.DEFAULT_COSEC_TOKEN_KEY=C,t.DeviceIdStorage=A,t.InMemoryStorage=_,t.NanoIdGenerator=h,t.ResponseCodes=E,t.TokenStorage=p,t.getStorage=u,t.idGenerator=I,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})}));
2
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/types.ts","../../../node_modules/.pnpm/nanoid@5.1.5/node_modules/nanoid/url-alphabet/index.js","../../../node_modules/.pnpm/nanoid@5.1.5/node_modules/nanoid/index.browser.js","../src/idGenerator.ts","../src/cosecRequestInterceptor.ts","../src/cosecResponseInterceptor.ts","../src/inMemoryStorage.ts","../src/deviceIdStorage.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 enum CoSecHeaders {\n DEVICE_ID = 'CoSec-Device-Id',\n APP_ID = 'CoSec-App-Id',\n AUTHORIZATION = 'Authorization',\n REQUEST_ID = 'CoSec-Request-Id',\n}\n\nexport enum ResponseCodes {\n 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","export const urlAlphabet =\n 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'\n","/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\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\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","ResponseCodes","AuthorizeResults","urlAlphabet","nanoid","size","id","bytes","scopedUrlAlphabet","NanoIdGenerator","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","DEFAULT_COSEC_TOKEN_KEY","TokenStorage","tokenKey","tokenStr"],"mappings":"oSAoBO,IAAKA,GAAAA,IACVA,EAAA,UAAY,kBACZA,EAAA,OAAS,eACTA,EAAA,cAAgB,gBAChBA,EAAA,WAAa,mBAJHA,IAAAA,GAAA,CAAA,CAAA,EAOAC,GAAAA,IACVA,EAAAA,EAAA,aAAe,GAAA,EAAf,eADUA,IAAAA,GAAA,CAAA,CAAA,EA0CL,MAAMC,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,EC3EaC,EACX,mECoBK,IAAIC,EAAS,CAACC,EAAO,KAAO,CACjC,IAAIC,EAAK,GACLC,EAAQ,OAAO,gBAAgB,IAAI,WAAYF,GAAQ,CAAC,CAAE,EAC9D,KAAOA,KACLC,GAAME,EAAkBD,EAAMF,CAAI,EAAI,EAAE,EAE1C,OAAOC,CACT,ECLO,MAAMG,CAAuC,CAMlD,YAAqB,CACnB,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,MAAMI,EAAW,KAAK,QAAQ,QAAQ,KAAK,QAAQ,EACnD,GAAI,CAACA,EACH,OAAO,KAGT,GAAI,CACF,OAAO,KAAK,MAAMA,CAAQ,CAC5B,OAASb,EAAO,CACd,eAAQ,KAAK,oCAAqCA,CAAK,EACvD,KAAK,MAAA,EACE,IACT,CACF,CAOA,IAAIT,EAA6B,CAC/B,MAAMsB,EAAW,KAAK,UAAUtB,CAAK,EACrC,KAAK,QAAQ,QAAQ,KAAK,SAAUsB,CAAQ,CAC9C,CAKA,OAAc,CACZ,KAAK,QAAQ,WAAW,KAAK,QAAQ,CACvC,CACF","x_google_ignoreList":[1,2]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-cosec",
3
- "version": "0.11.0",
3
+ "version": "0.11.2",
4
4
  "description": "CoSec authentication integration for Fetcher HTTP client",
5
5
  "keywords": [
6
6
  "fetch",
@@ -36,7 +36,7 @@
36
36
  ],
37
37
  "dependencies": {
38
38
  "nanoid": "^5.1.5",
39
- "@ahoo-wang/fetcher": "0.11.0"
39
+ "@ahoo-wang/fetcher": "0.11.2"
40
40
  },
41
41
  "devDependencies": {
42
42
  "@vitest/coverage-v8": "^3.2.4",