@webority/web-core 0.95.0 → 0.96.0
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/README.md
CHANGED
|
@@ -104,6 +104,7 @@ export const store = configureStore({
|
|
|
104
104
|
initUserAuth(store, {
|
|
105
105
|
logout: resetState,
|
|
106
106
|
refresh: { path: "/api/account/refresh", headers: () => ({ "Installation-Id": getInstallationId() }) },
|
|
107
|
+
endSessionOn: ["account_locked"],
|
|
107
108
|
legacyKeys: { accessToken: "app.accessToken", refreshToken: "app.refreshToken" },
|
|
108
109
|
});
|
|
109
110
|
setupApiListeners(store.dispatch);
|
|
@@ -117,6 +118,14 @@ other 401 takes the refresh path. Either way the library then dispatches `logout
|
|
|
117
118
|
code of a terminated session; for a rejected refresh it is the same code when the refusal carried one,
|
|
118
119
|
else `null`. Another tab's sign-out and an app's own `clearSession()` give `null`.
|
|
119
120
|
|
|
121
|
+
`endSessionOn` lists the problem codes that end the session on any response, at any status, the
|
|
122
|
+
refresh call included (for example an account locked by an administrator). A listed code clears the
|
|
123
|
+
session as `terminated` with that code; an unlisted one leaves the session alone.
|
|
124
|
+
|
|
125
|
+
A failure the caller handles itself (a 404 the screen turns into "not found") still rejects, but the
|
|
126
|
+
library logs it at debug instead of error when the status is listed:
|
|
127
|
+
`userClient.get(url, { expectedStatuses: [404] })`.
|
|
128
|
+
|
|
120
129
|
A request never runs in a workspace other than the one it was made in. `initUserAuth`'s `accountId`
|
|
121
130
|
provider is read once, when a request is made, and sent as `Account-Id`; a retry, a replay after a
|
|
122
131
|
refresh and a replay after a session replacement send that same id and never read the provider again.
|
package/dist/api/publicClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyRequestDefaults as e}from"./requestDefaults.js";import{Logger as t}from"../logger/logger.js";import{applyConfiguredBaseUrl as n}from"./baseUrl.js";import{applyClientHeaders as r}from"./clientHeaders.js";import{applyDesignSample as i}from"./designSample.js";import{readMinAppVersion as a}from"./minAppVersion.js";import{sendFormDataAsMultipart as o}from"./multipart.js";import{responseBodyText as s}from"./responseBodyText.js";import{attachRetry as c}from"./retry.js";import l from"axios";var u=l.create({headers:{"Content-Type":`application/json`,Accept:`application/json`}});n(u),e(u),o(u),a(u),c(u),u.interceptors.request.use(e=>(t.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),e),e=>{let n=e instanceof Error?e.message:String(e);return t.error(`Request error:`,n),Promise.reject(e)}),r(u),i(u),u.interceptors.response.use(e=>(t.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(l.isCancel(e))return Promise.reject(e);if(l.isAxiosError(e)){let n=e.config;if(n?.skipErrorLog)return Promise.reject(e);e.response
|
|
1
|
+
import{applyRequestDefaults as e}from"./requestDefaults.js";import{Logger as t}from"../logger/logger.js";import{applyConfiguredBaseUrl as n}from"./baseUrl.js";import{applyClientHeaders as r}from"./clientHeaders.js";import{applyDesignSample as i}from"./designSample.js";import{readMinAppVersion as a}from"./minAppVersion.js";import{sendFormDataAsMultipart as o}from"./multipart.js";import{responseBodyText as s}from"./responseBodyText.js";import{attachRetry as c}from"./retry.js";import l from"axios";var u=l.create({headers:{"Content-Type":`application/json`,Accept:`application/json`}});n(u),e(u),o(u),a(u),c(u),u.interceptors.request.use(e=>(t.info(`Request: ${e.method?.toUpperCase()} ${e.url}`),e),e=>{let n=e instanceof Error?e.message:String(e);return t.error(`Request error:`,n),Promise.reject(e)}),r(u),i(u),u.interceptors.response.use(e=>(t.info(`Response: ${e.status} from ${e.config.url}`),e),e=>{if(l.isCancel(e))return Promise.reject(e);if(l.isAxiosError(e)){let n=e.config;if(n?.skipErrorLog)return Promise.reject(e);if(!e.response)t.error(`Network error or no response from server: ${e.message}, URL: ${n?.url}`);else{let r=`Response error: ${s(e.response.data,e.message)}, URL: ${n?.url}, Status: ${e.response.status}`;n?.expectedStatuses?.includes(e.response.status)?t.debug(r):t.error(r)}}else{let n=e instanceof Error?e.message:String(e);t.error(`Unknown response error: ${n}`)}return Promise.reject(e)});export{u as default};
|
package/dist/api/tokenRefresh.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Logger as e}from"../logger/logger.js";import{ACCESS_TOKEN_KEY as t,REFRESH_TOKEN_KEY as n,clearSession as r,getToken as i,storeToken as a}from"../auth/authStore.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d,f,p=e=>{d=e},m=e=>{f=e},h=null,g=[],_=(e,t=null)=>{g.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),g=[]},v=()=>{h=null,_(Error(`[@webority/web-core] Session ended`))},y=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,b=()=>{if(!d||!f)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:d,auth:f}},x=()=>f?.accountId,S=()=>f?.refresh.path,C=async()=>{let e=b();await e.store.dispatch(e.auth.logout())},w=async(e,t)=>{await r(e,{code:t}),await C()},T=e=>{let t=e&&typeof e==`object`?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},E=()=>h!==null,
|
|
1
|
+
import{Logger as e}from"../logger/logger.js";import{ACCESS_TOKEN_KEY as t,REFRESH_TOKEN_KEY as n,clearSession as r,getToken as i,storeToken as a}from"../auth/authStore.js";import{withCrossTabRefreshLock as o}from"./crossTabRefreshLock.js";import s from"./publicClient.js";import c from"axios";var l=`session_revoked`,u=`session_expired`,d,f,p=e=>{d=e},m=e=>{f=e},h=null,g=[],_=(e,t=null)=>{g.forEach(({resolve:n,reject:r})=>{e?r(e):t!==null&&n(t)}),g=[]},v=()=>{h=null,_(Error(`[@webority/web-core] Session ended`))},y=e=>e instanceof Error?e.message:typeof e==`string`?e:`Unknown error`,b=()=>{if(!d||!f)throw Error(`User package store is not initialized. Call initUserAuth first.`);return{store:d,auth:f}},x=()=>f?.accountId,S=()=>f?.refresh.path,C=async()=>{let e=b();await e.store.dispatch(e.auth.logout())},w=async(e,t)=>{await r(e,{code:t}),await C()},T=e=>{let t=e&&typeof e==`object`?e.code:void 0;return t===`session_revoked`||t===`session_expired`?t:null},E=e=>{if(!c.isAxiosError(e)||!e.response)return null;let t=e.response.data,n=t&&typeof t==`object`?t.code:void 0;return typeof n==`string`&&f?.endSessionOn?.includes(n)?n:null},D=()=>h!==null,O=0,k=Promise.resolve(),A=null,j=()=>{O===0&&(k=new Promise(e=>{A=e})),O+=1;let e=!1;return()=>{e||(e=!0,--O,O===0&&(A?.(),A=null))}},M=()=>O===0?Promise.resolve():k,N=async r=>{let i;try{i=(f?.refresh.readTokens??B)(r)}catch(t){e.error(`A session-replacing response carried no tokens:`,y(t));return}await a(t,i.accessToken,i.accessTokenExpiry),await a(n,i.refreshToken,i.refreshTokenExpiry)},P=async e=>{let t=(await i(`accessToken`))?.token??null;return t!==null&&t!==e?t:null},F=()=>new Promise((e,t)=>{g.push({resolve:e,reject:t})}),I=class e extends Error{constructor(t){super(t),this.name=`SessionEndedError`,Object.setPrototypeOf(this,e.prototype)}},L=e=>e instanceof I||c.isAxiosError(e)&&(e.response?.status===400||e.response?.status===401),R=e=>!c.isAxiosError(e)||e.response?.status!==401?null:T(e.response.data),z=(e,t)=>{if(typeof e!=`string`||e===``)throw Error(`The refresh response has no "${t}".`);return e},B=e=>{let t=e??{};return{accessToken:z(t.accessToken,`accessToken`),accessTokenExpiry:z(t.accessTokenExpiration,`accessTokenExpiration`),refreshToken:z(t.refreshToken,`refreshToken`),refreshTokenExpiry:z(t.refreshTokenExpiration,`refreshTokenExpiration`)}},V=async r=>{await M();let o=await i(n);if(!o?.token)throw new I(`No refresh token available`);if(Date.parse(o.expiry)<=Date.now())throw new I(`Refresh token expired`);let c={accessToken:(await i(`accessToken`))?.token??null,refreshToken:o.token},l=r.body?await r.body(c):c,u=r.headers?await r.headers():void 0;e.info(`Refreshing the access token`);let{data:d}=await s.post(r.path,l,u?{headers:u}:void 0),f=(r.readTokens??B)(d);await M();let p=(await i(`refreshToken`))?.token===o.token?null:await i(t);return p?.token?(e.info(`Keeping the session that replaced this one during the refresh`),p.token):(await a(t,f.accessToken,f.accessTokenExpiry),await a(n,f.refreshToken,f.refreshTokenExpiry),e.info(`Access token refreshed`),f.accessToken)},H=30*1e3,U=async(n,r)=>{let a=await i(t);return a?.token&&a.token!==r&&Date.parse(a.expiry)>Date.now()+H?(e.info(`Adopting the access token another tab refreshed`),a.token):V(n)},W=()=>{if(h)return h;let t=(async()=>{let t=null;try{let{refresh:e}=b().auth;t=(await i(`accessToken`))?.token??null;let n=await o(()=>U(e,t));return _(null,n),n}catch(n){if(L(n)){await M();let n=await P(t);if(n)return e.info(`The session was replaced during the refresh; continuing with the new one`),_(null,n),n}let r=E(n);if(r!==null)throw _(n,null),await w(`terminated`,r),n;let i=c.isAxiosError(n)?n.response?.data:void 0;throw e.error(`Token refresh failed:`,i??y(n)),_(n,null),L(n)&&await w(`rejected`,R(n)),n}})().finally(()=>{h===t&&(h=null)});return h=t,t};export{u as SESSION_EXPIRED_CODE,l as SESSION_REVOKED_CODE,j as beginSessionReplacement,P as currentTokenIfReplaced,C as dispatchLogout,w as endSessionAndLogout,E as endSessionCodeOf,x as getAccountIdProvider,y as getErrorMessage,S as getRefreshPath,p as injectStore,m as injectUserAuth,D as isRefreshInFlight,F as queueBehindRefresh,W as refreshAccessToken,v as resetRefreshState,T as sessionCodeOf,N as storeReplacementSession,M as waitForSessionReplacement};
|
package/dist/api/userClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyRequestDefaults as e}from"./requestDefaults.js";import{Logger as t}from"../logger/logger.js";import{ACCESS_TOKEN_KEY as n,getToken as r}from"../auth/authStore.js";import{getLastKnownNetworkStatus as i}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as a}from"./baseUrl.js";import{applyClientHeaders as o,readAccountId as s,stampAccountId as c}from"./clientHeaders.js";import{applyDesignSample as l}from"./designSample.js";import{readMinAppVersion as u}from"./minAppVersion.js";import{sendFormDataAsMultipart as d}from"./multipart.js";import{responseBodyText as f}from"./responseBodyText.js";import{WorkspaceChangedError as p,isWorkspaceChangedResponse as m,workspaceChangedFromResponse as h}from"./workspaceChanged.js";import{attachRetry as g}from"./retry.js";import{SESSION_EXPIRED_CODE as _,SESSION_REVOKED_CODE as v,beginSessionReplacement as y,currentTokenIfReplaced as b,endSessionAndLogout as x,
|
|
1
|
+
import{applyRequestDefaults as e}from"./requestDefaults.js";import{Logger as t}from"../logger/logger.js";import{ACCESS_TOKEN_KEY as n,getToken as r}from"../auth/authStore.js";import{getLastKnownNetworkStatus as i}from"../network/networkStatus.js";import{applyConfiguredBaseUrl as a}from"./baseUrl.js";import{applyClientHeaders as o,readAccountId as s,stampAccountId as c}from"./clientHeaders.js";import{applyDesignSample as l}from"./designSample.js";import{readMinAppVersion as u}from"./minAppVersion.js";import{sendFormDataAsMultipart as d}from"./multipart.js";import{responseBodyText as f}from"./responseBodyText.js";import{WorkspaceChangedError as p,isWorkspaceChangedResponse as m,workspaceChangedFromResponse as h}from"./workspaceChanged.js";import{attachRetry as g}from"./retry.js";import{SESSION_EXPIRED_CODE as _,SESSION_REVOKED_CODE as v,beginSessionReplacement as y,currentTokenIfReplaced as b,endSessionAndLogout as x,endSessionCodeOf as S,getAccountIdProvider as C,getErrorMessage as w,getRefreshPath as T,injectStore as E,injectUserAuth as D,isRefreshInFlight as O,queueBehindRefresh as k,refreshAccessToken as A,resetRefreshState as j,sessionCodeOf as M,storeReplacementSession as N,waitForSessionReplacement as P}from"./tokenRefresh.js";import F,{AxiosHeaders as I}from"axios";var L=class e extends Error{constructor(t=`Request blocked: device is offline`){super(t),this.name=`RequestOfflineError`,Object.setPrototypeOf(this,e.prototype)}},R=class e extends Error{constructor(){super(`No access token available`),this.name=`NoAccessTokenError`,Object.setPrototypeOf(this,e.prototype)}},z=e=>{e?._endReplacement?.(),e&&(e._endReplacement=void 0)},B=e=>{let t=e.headers instanceof I?e.headers.get(`Authorization`):void 0;return typeof t==`string`&&t.startsWith(`Bearer `)?t.slice(7):null},V=F.create({headers:{"Content-Type":`application/json`}});u(V),g(V);var H=(e,t)=>{e.headers instanceof I?e.headers.set(`Authorization`,`Bearer ${t}`):e.headers=I.from({...e.headers,Authorization:`Bearer ${t}`})},U=e=>{let t=T();return!!t&&!!e?.includes(t)};a(V),e(V),d(V),o(V),l(V),V.interceptors.request.use(async e=>{if(z(e),(await i()).isConnected===!1)return t.warn(`Request blocked: browser is offline. URL: ${e.url}`),Promise.reject(new L);try{if(U(e.url))return e;await c(e,C());let i=await r(n);if(!i?.token)throw new R;let a=Date.now();return Date.parse(i.expiry)<=a+30*1e3?(t.info(`Access token expired or about to expire, refreshing before request`),H(e,await A())):H(e,i.token),e.replacesSession&&(e._endReplacement=y()),e}catch(n){return n instanceof R?t.info(`Request not sent: signed out. URL: ${e.url}`):t.error(`Failed to attach token:`,w(n)),Promise.reject(n)}},e=>(t.error(`Request error:`,w(e)),Promise.reject(e))),V.interceptors.response.use(async e=>{let t=e.config;if(t._endReplacement)try{await N(e.data)}finally{z(t)}return e},async e=>{if(z(e?.config),F.isCancel(e)||e instanceof L||e instanceof R||e instanceof p)return Promise.reject(e);if(!F.isAxiosError(e))return t.error(`Non-axios error in response interceptor: ${w(e)}`),Promise.reject(e);let n=e,r=n.config;if(!n.response)return r?.skipErrorLog||t.error(`Network error or no response from server: ${n.message}, URL: ${r?.url}`),Promise.reject(e);if(m(n))return t.info(`Request refused: the workspace changed after it was made. URL: ${r?.url}`),Promise.reject(h(n));if(n.response.status===401&&r&&!r._replayedWithCurrentToken&&!r.replacesSession&&!U(r.url)&&(await P(),await b(B(r))))return(r._accountId??null)===await s(C())?(t.info(`Session changed while the request was in flight; sending it again. URL: ${r.url}`),r._replayedWithCurrentToken=!0,V(r)):(t.info(`Session moved to another workspace while the request was in flight; not sending it again. URL: ${r.url}`),Promise.reject(new p(void 0,{config:r,cause:e})));let i=U(r?.url)?null:S(n);if(i!==null)return t.warn(`Session ended by ${i}, logging out. URL: ${r?.url}`),j(),await x(`terminated`,i),Promise.reject(e);if(n.response.status===401&&r&&!r._retry){if(U(r.url))return Promise.reject(e);let i=M(n.response.data);if(i!==null)return t.warn(`Session ${i}, logging out without refresh. URL: ${r.url}`),j(),await x(`terminated`,i),Promise.reject(e);if(t.warn(`Unauthorized URL: ${r.url}`),r._retry=!0,O())return k().then(e=>(t.info(`Retrying request after token refresh:`,r.url),H(r,e),V(r))).catch(e=>(e instanceof p||t.error(`Failed to retry request after token refresh:`,w(e)),Promise.reject(e)));try{return H(r,await A()),V(r)}catch(e){return Promise.reject(e)}}if(!r?.skipErrorLog){let e=`Response error: ${f(n.response?.data,n.message)}, URL: ${r?.url}, Status: ${n.response.status}`;r?.expectedStatuses?.includes(n.response.status)?t.debug(e):t.error(e)}return Promise.reject(e)});export{L as RequestOfflineError,_ as SESSION_EXPIRED_CODE,v as SESSION_REVOKED_CODE,V as default,E as injectStore,D as injectUserAuth,j as resetRefreshState};
|
|
@@ -45,6 +45,8 @@ export declare const dispatchLogout: () => Promise<void>;
|
|
|
45
45
|
export declare const endSessionAndLogout: (reason: SessionEndReason, code: string | null) => Promise<void>;
|
|
46
46
|
/** The server's session code in a 401 body (`session_revoked`, `session_expired`), or null. */
|
|
47
47
|
export declare const sessionCodeOf: (data: unknown) => string | null;
|
|
48
|
+
/** The server's problem-body code when it is one the app ends the session on (`endSessionOn`), at any status, or null. */
|
|
49
|
+
export declare const endSessionCodeOf: (error: unknown) => string | null;
|
|
48
50
|
export declare const isRefreshInFlight: () => boolean;
|
|
49
51
|
/** Opens the replacement window for one flagged request; call the returned function once it settles. */
|
|
50
52
|
export declare const beginSessionReplacement: () => (() => void);
|
|
@@ -45,6 +45,8 @@ export interface UserAuthOptions {
|
|
|
45
45
|
* token alone.
|
|
46
46
|
*/
|
|
47
47
|
accountId?: AccountIdProvider;
|
|
48
|
+
/** Problem codes that end the session on any response, the refresh call included: tokens are cleared and session-ended listeners get reason `terminated` with the code. */
|
|
49
|
+
endSessionOn?: readonly string[];
|
|
48
50
|
/**
|
|
49
51
|
* The keys the app kept its session under before this library. The first token read that
|
|
50
52
|
* finds the library's keys empty moves a session found there and deletes the old keys, so
|
|
@@ -11,5 +11,7 @@ declare module "axios" {
|
|
|
11
11
|
* new session is in another workspace: then it rejects with `WorkspaceChangedError`.
|
|
12
12
|
*/
|
|
13
13
|
replacesSession?: boolean;
|
|
14
|
+
/** Statuses the caller handles itself: a failure with one still rejects, but the library logs it at debug instead of error. */
|
|
15
|
+
expectedStatuses?: readonly number[];
|
|
14
16
|
}
|
|
15
17
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webority/web-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.96.0",
|
|
4
4
|
"description": "Platform layer for Webority React web portals: HTTP clients with single-flight token refresh, auth store, API error extraction, RTK Query base query, logger, formatters, storage, version check and route guards. No UI.",
|
|
5
5
|
"license": "SEE LICENSE IN LICENSE",
|
|
6
6
|
"type": "module",
|