@griddo/ax 12.15.1-astro-rc.0 → 12.17.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.
Files changed (93) hide show
  1. package/README.md +1 -0
  2. package/config/__tests__/getCSSModuleLocalIdent.test.js +30 -0
  3. package/config/griddo-config/index.js +3 -2
  4. package/config/webpack/getCSSModuleLocalIdent.js +10 -0
  5. package/config/webpack.config.js +1 -1
  6. package/package.json +8 -6
  7. package/public/img/logos/logoGriddoDxp.svg +22 -0
  8. package/public/img/logos/logoGriddoG.svg +10 -0
  9. package/src/GlobalStore.tsx +32 -25
  10. package/src/__tests__/GlobalStore.session.test.tsx +98 -0
  11. package/src/__tests__/api/global.test.ts +64 -0
  12. package/src/__tests__/api/session.test.ts +311 -0
  13. package/src/__tests__/api/sessionRenewal.test.ts +705 -0
  14. package/src/__tests__/api/utils.test.ts +373 -0
  15. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +33 -6
  16. package/src/__tests__/components/Fields/TranslateButton/TranslateButton.test.tsx +121 -4
  17. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +5 -3
  18. package/src/__tests__/components/Login/BrandPalette.test.tsx +145 -0
  19. package/src/__tests__/components/Login/Login.test.tsx +2 -33
  20. package/src/__tests__/components/Login/LoginCollapsible.test.tsx +271 -0
  21. package/src/__tests__/components/Login/LoginDropdownCard.test.tsx +311 -0
  22. package/src/__tests__/components/Login/LoginFooter.test.tsx +128 -0
  23. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +213 -0
  24. package/src/__tests__/components/Login/LoginInlineError.test.tsx +116 -0
  25. package/src/__tests__/components/Login/RecoveryModal/RecoveryModal.test.tsx +3 -4
  26. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +86 -0
  27. package/src/__tests__/config/webpackAliases.test.ts +18 -0
  28. package/src/__tests__/containers/App/reducer.griddoId.test.ts +18 -0
  29. package/src/__tests__/containers/App/session.test.ts +397 -0
  30. package/src/__tests__/containers/App/signInOut.test.ts +159 -0
  31. package/src/__tests__/helpers/griddoId.test.ts +56 -0
  32. package/src/__tests__/hooks/useShouldBeSaved.test.tsx +78 -0
  33. package/src/__tests__/locales/loginLocale.test.ts +37 -0
  34. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +54 -0
  35. package/src/__tests__/modules/App/Routing/PrivateRoute.test.tsx +64 -0
  36. package/src/__tests__/modules/App/Routing/Routing.startup.test.tsx +79 -0
  37. package/src/__tests__/modules/Login/Login.test.tsx +169 -0
  38. package/src/__tests__/modules/Login/loginError.uc.test.tsx +294 -0
  39. package/src/__tests__/modules/Login/signInOut.test.tsx +125 -0
  40. package/src/__tests__/modules/Redirects/RedirectPanel/RedirectPanel.test.tsx +9 -0
  41. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +19 -0
  42. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +19 -0
  43. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +19 -0
  44. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +30 -0
  45. package/src/__tests__/routes/publicRoutes.test.ts +36 -0
  46. package/src/api/global.tsx +24 -1
  47. package/src/api/session.tsx +197 -0
  48. package/src/api/sessionRenewal.tsx +114 -0
  49. package/src/api/utils.tsx +22 -12
  50. package/src/{helpers/categoryColumns.tsx → components/CategoryCell/buildCategoryColumns.tsx} +3 -2
  51. package/src/components/Circle/index.tsx +1 -1
  52. package/src/components/Circle/style.tsx +4 -2
  53. package/src/components/ErrorPage/index.tsx +1 -1
  54. package/src/components/ErrorPage/style.tsx +11 -9
  55. package/src/components/ErrorToast/index.tsx +2 -0
  56. package/src/components/Fields/TranslateButton/index.tsx +4 -9
  57. package/src/{helpers/fields.tsx → components/FieldsBehavior/getFieldByPath.tsx} +1 -1
  58. package/src/components/FieldsBehavior/index.tsx +3 -1
  59. package/src/components/Login/LoginFooter/index.tsx +16 -0
  60. package/src/components/Login/LoginFooter/style.tsx +17 -0
  61. package/src/components/Login/LoginForm/index.tsx +147 -79
  62. package/src/components/Login/LoginForm/style.tsx +147 -24
  63. package/src/components/Login/LoginGriddoId/index.tsx +56 -0
  64. package/src/components/Login/LoginGriddoId/style.tsx +35 -0
  65. package/src/components/Login/LoginSSO/index.tsx +4 -7
  66. package/src/components/Login/LoginSSO/style.tsx +10 -26
  67. package/src/components/Login/LoginSlider/style.tsx +5 -5
  68. package/src/components/Login/index.tsx +35 -6
  69. package/src/components/Login/style.tsx +40 -24
  70. package/src/components/Notification/index.tsx +3 -1
  71. package/src/components/SsoDenied/index.tsx +46 -0
  72. package/src/components/SsoDenied/style.tsx +37 -0
  73. package/src/components/index.tsx +11 -7
  74. package/src/containers/App/actions.tsx +114 -6
  75. package/src/containers/App/interfaces.tsx +2 -2
  76. package/src/containers/App/reducer.tsx +9 -0
  77. package/src/containers/Users/actions.tsx +28 -24
  78. package/src/helpers/griddoId.ts +28 -0
  79. package/src/helpers/index.tsx +4 -5
  80. package/src/hooks/forms.tsx +8 -5
  81. package/src/locales/en-US.ts +13 -0
  82. package/src/locales/es-ES.ts +13 -0
  83. package/src/locales/index.ts +9 -1
  84. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  85. package/src/modules/Content/PageItem/index.tsx +6 -8
  86. package/src/modules/Login/index.tsx +33 -14
  87. package/src/modules/SsoDenied/index.tsx +9 -0
  88. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +6 -8
  89. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +9 -11
  90. package/src/modules/Users/UserEdit/index.tsx +9 -2
  91. package/src/routes/publicRoutes.tsx +3 -0
  92. package/src/themes/brandPalette.ts +16 -0
  93. package/public/img/logos/logoSQY.svg +0 -3
@@ -0,0 +1,30 @@
1
+ import { cleanup, render, screen } from "@testing-library/react";
2
+ import { ThemeProvider } from "styled-components";
3
+ import "@testing-library/jest-dom";
4
+
5
+ import { parseTheme } from "@ax/helpers";
6
+ import SsoDeniedModule from "@ax/modules/SsoDenied";
7
+ import globalTheme from "@ax/themes/theme.json";
8
+
9
+ afterEach(() => {
10
+ cleanup();
11
+ vi.unstubAllEnvs();
12
+ });
13
+
14
+ describe("módulo SsoDenied", () => {
15
+ it("enlaza «Sign in with another account» a /sso/switch-account de la API configurada", () => {
16
+ vi.stubEnv("GRIDDO_API_URL", "https://api.uni.es");
17
+ vi.spyOn(window.navigator, "language", "get").mockReturnValue("es-ES");
18
+
19
+ render(
20
+ <ThemeProvider theme={parseTheme(globalTheme)}>
21
+ <SsoDeniedModule />
22
+ </ThemeProvider>,
23
+ );
24
+
25
+ expect(screen.getByRole("link", { name: "Sign in with another account" })).toHaveAttribute(
26
+ "href",
27
+ "https://api.uni.es/sso/switch-account",
28
+ );
29
+ });
30
+ });
@@ -0,0 +1,36 @@
1
+ import { matchPath } from "react-router-dom";
2
+
3
+ import publicRoutes from "@ax/routes/publicRoutes";
4
+
5
+ // Solo se comprueba la tabla de rutas: los módulos se sustituyen para no arrastrar el grafo de contenedores.
6
+ vi.mock("@ax/modules/CreatePass", () => ({ default: () => null }));
7
+ vi.mock("@ax/modules/Login", () => ({ default: () => null }));
8
+ vi.mock("@ax/modules/PublicPreview", () => ({ default: () => null }));
9
+ vi.mock("@ax/modules/ResetPass", () => ({ default: () => null }));
10
+ vi.mock("@ax/modules/SsoDenied", () => ({ default: () => null }));
11
+
12
+ describe("publicRoutes", () => {
13
+ const sso = publicRoutes.find((route) => route.path === "/sso-denied");
14
+
15
+ it("declara /sso-denied sin menú de navegación", () => {
16
+ expect(sso).toMatchObject({ path: "/sso-denied", hideNav: true });
17
+ });
18
+
19
+ it("/sso-denied no la captura /login/:petitionId (se montaría Login y canjearía «sso-denied» como uuid)", () => {
20
+ expect(matchPath("/sso-denied", { path: "/login/:petitionId", exact: true })).toBeNull();
21
+ expect(matchPath("/sso-denied", { path: "/login", exact: true })).toBeNull();
22
+ });
23
+
24
+ it("un uuid de petición sigue llegando a Login y no a la pantalla de acceso denegado", () => {
25
+ expect(
26
+ matchPath("/login/0b6f4b52-5d2a-4c7e-9a38-1c5f6a2e7d10", { path: "/login/:petitionId", exact: true }),
27
+ ).not.toBeNull();
28
+ expect(matchPath("/login/0b6f4b52-5d2a-4c7e-9a38-1c5f6a2e7d10", { path: "/sso-denied", exact: true })).toBeNull();
29
+ });
30
+
31
+ it("ninguna otra ruta pública coincide con /sso-denied", () => {
32
+ const matching = publicRoutes.filter((route) => matchPath("/sso-denied", { path: route.path, exact: true }));
33
+
34
+ expect(matching).toHaveLength(1);
35
+ });
36
+ });
@@ -1,6 +1,7 @@
1
1
  import type { ICreatePasswordParams } from "@ax/types";
2
+
2
3
  import { template } from "./config";
3
- import { type IServiceConfig, sendRequest } from "./utils";
4
+ import { type IServiceConfig, sendInitialRequest, sendRequest } from "./utils";
4
5
 
5
6
  const SERVICES: { [key: string]: IServiceConfig } = {
6
7
  LOGIN: {
@@ -8,6 +9,14 @@ const SERVICES: { [key: string]: IServiceConfig } = {
8
9
  endpoint: "/login_check",
9
10
  method: "POST",
10
11
  hasToken: false,
12
+ skipAuthRenewal: true,
13
+ },
14
+ LOGOUT: {
15
+ ...template,
16
+ endpoint: "/logout",
17
+ method: "POST",
18
+ hasToken: true,
19
+ skipAuthRenewal: true,
11
20
  },
12
21
  GET_SETTINGS: {
13
22
  ...template,
@@ -32,6 +41,7 @@ const SERVICES: { [key: string]: IServiceConfig } = {
32
41
  endpoint: ["/user/", "/password/init"],
33
42
  method: "POST",
34
43
  hasToken: true,
44
+ skipAuthRenewal: true,
35
45
  },
36
46
  };
37
47
 
@@ -76,8 +86,21 @@ const createPassword = async (userID: number, data: ICreatePasswordParams) => {
76
86
  return sendRequest(SERVICES.CREATE_PASSWORD, { ...data });
77
87
  };
78
88
 
89
+ /**
90
+ * Cierra la sesión en la API (idempotente, 204). Acepta el acceso aunque esté caducado y/o el refresh del
91
+ * cuerpo; no dispara renovación (`skipAuthRenewal`) para no entrar en bucle si responde 401.
92
+ */
93
+ const logout = async (session: { token: string; refreshToken: string | null }) => {
94
+ return sendInitialRequest(
95
+ SERVICES.LOGOUT,
96
+ session.token,
97
+ session.refreshToken ? { refreshToken: session.refreshToken } : {},
98
+ );
99
+ };
100
+
79
101
  export default {
80
102
  login,
103
+ logout,
81
104
  getSettings,
82
105
  forgotPassword,
83
106
  resetPassword,
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Sesión local de AX: par `token` (JWT de acceso, 1 h) + `refreshToken` (30 d, rotatorio).
3
+ *
4
+ * Fuentes del par, de más a menos fresca:
5
+ * - **memoria** de la pestaña, escrita de forma síncrona al renovar (redux-persist escribe en diferido);
6
+ * - **`localStorage["persist:app"]`**, compartido entre pestañas.
7
+ *
8
+ * Cada par lleva una versión creciente (`updatedAt`, ms) que decide cuál es el más nuevo. El par
9
+ * (`token`, `refreshToken`, `sessionUpdatedAt`) se escribe siempre dentro de UNA sola clave, así que
10
+ * una cuota llena nunca lo deja desparejado en disco.
11
+ */
12
+
13
+ const PERSIST_KEY = "persist:app";
14
+
15
+ export interface ISession {
16
+ token: string;
17
+ /** `null` cuando la API no devolvió refresh (API antigua) o la sesión es anterior al despliegue. */
18
+ refreshToken: string | null;
19
+ /** Versión monótona del par; 0 en sesiones anteriores al despliegue. */
20
+ updatedAt: number;
21
+ }
22
+
23
+ /** Puente hacia el store de Redux, registrado al crearlo (evita el ciclo api → containers → api). */
24
+ export interface ISessionBridge {
25
+ /** El par se renovó: el store debe reflejarlo. */
26
+ onRenewed?: (session: ISession) => void;
27
+ /** La sesión murió y no se puede renovar: cerrar y navegar al login. */
28
+ onExpired?: () => void;
29
+ }
30
+
31
+ let memory: ISession | null = null;
32
+ let ended = false;
33
+ let bridge: ISessionBridge = {};
34
+
35
+ /** Registra (sustituye) el puente al store. Idempotente: llamarlo de nuevo reemplaza al anterior. */
36
+ export const registerSessionBridge = (next: ISessionBridge): void => {
37
+ bridge = next;
38
+ };
39
+
40
+ /** Avisa al store de que se renovó el par. */
41
+ export const notifySessionRenewed = (session: ISession): void => {
42
+ bridge.onRenewed?.(session);
43
+ };
44
+
45
+ const parseField = (app: Record<string, string>, key: string): unknown => {
46
+ if (app[key] === undefined) return undefined;
47
+ return JSON.parse(app[key]);
48
+ };
49
+
50
+ /**
51
+ * Lee el par persistido por redux-persist.
52
+ * @returns `null` si no hay sesión, está cerrada (token vacío) o el estado es ilegible.
53
+ */
54
+ export const readPersistedSession = (): ISession | null => {
55
+ const raw = localStorage.getItem(PERSIST_KEY);
56
+ // Stryker disable next-line ConditionalExpression: equivalente, JSON.parse(null) no lanza pero `parseField` sí y se captura
57
+ if (!raw) return null;
58
+
59
+ try {
60
+ const app = JSON.parse(raw);
61
+ const token = parseField(app, "token");
62
+ if (typeof token !== "string" || token === "") return null;
63
+
64
+ const refreshToken = parseField(app, "refreshToken");
65
+ const updatedAt = parseField(app, "sessionUpdatedAt");
66
+
67
+ return {
68
+ token,
69
+ refreshToken: typeof refreshToken === "string" && refreshToken !== "" ? refreshToken : null,
70
+ updatedAt: typeof updatedAt === "number" ? updatedAt : 0,
71
+ };
72
+ } catch {
73
+ return null;
74
+ }
75
+ };
76
+
77
+ /** @returns el par más reciente entre la memoria de la pestaña y el disco, o `null` sin sesión. */
78
+ export const getSession = (): ISession | null => {
79
+ const persisted = readPersistedSession();
80
+ if (!memory) return persisted;
81
+ if (!persisted) return memory;
82
+ return persisted.updatedAt > memory.updatedAt ? persisted : memory;
83
+ };
84
+
85
+ const persistPair = (session: ISession): void => {
86
+ const raw = localStorage.getItem(PERSIST_KEY);
87
+ // Sin estado previo no se crea la clave a mano: redux-persist la escribirá con su formato.
88
+ // Stryker disable next-line ConditionalExpression: equivalente, sin estado `app.token = …` lanza y se captura
89
+ if (!raw) return;
90
+
91
+ try {
92
+ const app = JSON.parse(raw);
93
+ app.token = JSON.stringify(session.token);
94
+ app.refreshToken = JSON.stringify(session.refreshToken ?? "");
95
+ app.sessionUpdatedAt = JSON.stringify(session.updatedAt);
96
+ localStorage.setItem(PERSIST_KEY, JSON.stringify(app));
97
+ } catch {
98
+ // Cuota llena o estado ilegible: la sesión sigue viva en memoria y en el store.
99
+ }
100
+ };
101
+
102
+ /**
103
+ * Guarda un par nuevo (login, renovación, cambio de contraseña): memoria + escritura síncrona en disco.
104
+ * Reabre el cierre de sesión (un nuevo login vuelve a poder cerrarse por 401).
105
+ * @returns la sesión guardada, con su versión.
106
+ */
107
+ export const setSession = (token: string, refreshToken: string | null): ISession => {
108
+ const previous = getSession();
109
+ const updatedAt = Math.max(Date.now(), (previous?.updatedAt ?? 0) + 1);
110
+
111
+ memory = { token, refreshToken, updatedAt };
112
+ ended = false;
113
+ persistPair(memory);
114
+
115
+ return memory;
116
+ };
117
+
118
+ /** Olvida el par en memoria (el disco lo limpia el logout). */
119
+ export const clearSession = (): void => {
120
+ memory = null;
121
+ };
122
+
123
+ /** Restablece memoria y cierre (arranque limpio; lo usan los tests para aislarse). */
124
+ export const resetSessionState = (): void => {
125
+ memory = null;
126
+ ended = false;
127
+ };
128
+
129
+ /**
130
+ * Cierra la sesión por 401 irrecuperable. Solo avisa **una vez** hasta el siguiente login, aunque
131
+ * lleguen varios 401 a la vez.
132
+ */
133
+ export const endSession = (): void => {
134
+ if (ended) return;
135
+ ended = true;
136
+ bridge.onExpired?.();
137
+ };
138
+
139
+ /** Marca la sesión como cerrada sin avisar (cierre manual o recibido por broadcast desde otra pestaña). */
140
+ export const markSessionEnded = (): void => {
141
+ ended = true;
142
+ };
143
+
144
+ /**
145
+ * Combina el estado que va a escribir redux-persist con el del disco: si el disco tiene un par más
146
+ * nuevo (otra pestaña renovó), se conserva ese par y el resto del estado entrante se respeta.
147
+ */
148
+ export const mergeNewestSession = (storedRaw: string | null, incomingRaw: string): string => {
149
+ // Stryker disable next-line ConditionalExpression: equivalente, sin estado previo `parseField` lanza y se captura
150
+ if (!storedRaw) return incomingRaw;
151
+
152
+ try {
153
+ const stored = JSON.parse(storedRaw);
154
+ const incoming = JSON.parse(incomingRaw);
155
+ const storedVersion = parseField(stored, "sessionUpdatedAt");
156
+ const incomingVersion = parseField(incoming, "sessionUpdatedAt");
157
+
158
+ if (
159
+ typeof storedVersion !== "number" ||
160
+ storedVersion <= (typeof incomingVersion === "number" ? incomingVersion : 0)
161
+ ) {
162
+ return incomingRaw;
163
+ }
164
+
165
+ return JSON.stringify({
166
+ ...incoming,
167
+ token: stored.token,
168
+ refreshToken: stored.refreshToken,
169
+ sessionUpdatedAt: stored.sessionUpdatedAt,
170
+ });
171
+ } catch {
172
+ return incomingRaw;
173
+ }
174
+ };
175
+
176
+ interface IAsyncStorage {
177
+ getItem(key: string): Promise<string | null>;
178
+ setItem(key: string, value: string): Promise<unknown>;
179
+ removeItem(key: string): Promise<void>;
180
+ }
181
+
182
+ /**
183
+ * Envuelve el storage de redux-persist para el slice `app`: una pestaña con estado viejo no pisa el
184
+ * par más nuevo y un error de cuota al persistir no se propaga.
185
+ */
186
+ export const createSessionStorage = (base: IAsyncStorage): IAsyncStorage => ({
187
+ getItem: (key) => base.getItem(key),
188
+ removeItem: (key) => base.removeItem(key),
189
+ setItem: async (key, value) => {
190
+ try {
191
+ const next = key === PERSIST_KEY ? mergeNewestSession(localStorage.getItem(key), value) : value;
192
+ return await base.setItem(key, next);
193
+ } catch {
194
+ // Cuota llena al persistir: la sesión sigue en memoria y en el store.
195
+ }
196
+ },
197
+ });
@@ -0,0 +1,114 @@
1
+ import axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
2
+
3
+ import { template } from "./config";
4
+ import { endSession, getSession, notifySessionRenewed, setSession } from "./session";
5
+
6
+ /** Estados del refresh que significan «sesión muerta»: 401 (refresh inválido) y 404/405 (API sin `/login_refresh`). */
7
+ const DEAD_SESSION_STATUSES = [401, 404, 405];
8
+ /** Nombre del candado compartido entre pestañas (`navigator.locks`). */
9
+ const LOCK_NAME = "griddo-ax-session-renewal";
10
+ /** Tope de la llamada de renovación: un cuelgue no debe retener el candado de todas las pestañas. */
11
+ const REFRESH_TIMEOUT_MS = 15000;
12
+
13
+ type RenewalOutcome =
14
+ /** Hay un par vigente distinto del que falló: reintentar con `token`. */
15
+ | { status: "renewed"; token: string }
16
+ /** La sesión no se puede renovar (401/404/405 del refresh, sin refresh guardado o sin sesión): cerrar. */
17
+ | { status: "expired" }
18
+ /** Fallo transitorio (5xx, 429, timeout, red, respuesta inválida): el refresh sigue siendo válido. */
19
+ | { status: "failed" };
20
+
21
+ /** axios 0.19 no tipa `signal` (los navegadores nuevos y axios ≥ 0.22 sí): se admite por si se usa. */
22
+ type RequestConfig = AxiosRequestConfig & { signal?: AbortSignal };
23
+
24
+ let inFlight: Promise<RenewalOutcome> | null = null;
25
+
26
+ const callRefresh = async (refreshToken: string): Promise<RenewalOutcome> => {
27
+ try {
28
+ const response = await axios({
29
+ url: `${template.host}/login_refresh`,
30
+ method: "POST",
31
+ headers: template.headers,
32
+ data: { refreshToken },
33
+ timeout: REFRESH_TIMEOUT_MS,
34
+ });
35
+
36
+ const { token, refreshToken: nextRefreshToken } = response.data ?? {};
37
+ if (typeof token !== "string" || !token || typeof nextRefreshToken !== "string" || !nextRefreshToken) {
38
+ return { status: "failed" };
39
+ }
40
+
41
+ notifySessionRenewed(setSession(token, nextRefreshToken));
42
+ return { status: "renewed", token };
43
+ } catch (error) {
44
+ // Solo 401/404/405 del propio refresh significan «sesión muerta»; cualquier otro fallo no cierra sesión.
45
+ return DEAD_SESSION_STATUSES.includes(error.response?.status) ? { status: "expired" } : { status: "failed" };
46
+ }
47
+ };
48
+
49
+ /**
50
+ * Renueva (o comprueba que otra pestaña ya renovó) a partir del token con el que falló la petición.
51
+ * Se ejecuta dentro del candado, así que el par se relee justo antes de gastar el refresh.
52
+ */
53
+ const renew = async (sentToken: string): Promise<RenewalOutcome> => {
54
+ const session = getSession();
55
+ if (!session) return { status: "expired" };
56
+ // Otra petición u otra pestaña ya rotó el par: basta con reintentar con el vigente.
57
+ if (session.token !== sentToken) return { status: "renewed", token: session.token };
58
+ if (!session.refreshToken) return { status: "expired" };
59
+
60
+ return callRefresh(session.refreshToken);
61
+ };
62
+
63
+ const runExclusive = <T,>(task: () => Promise<T>): Promise<T> => {
64
+ const locks = typeof navigator !== "undefined" ? navigator.locks : undefined;
65
+ // Sin Web Locks se degrada a una renovación por pestaña (la gracia de la API absorbe el solape).
66
+ return locks?.request ? locks.request(LOCK_NAME, task) : task();
67
+ };
68
+
69
+ const renewSession = (sentToken: string): Promise<RenewalOutcome> => {
70
+ if (!inFlight) {
71
+ inFlight = runExclusive(() => renew(sentToken)).finally(() => {
72
+ inFlight = null;
73
+ });
74
+ }
75
+ return inFlight;
76
+ };
77
+
78
+ const getSentToken = (config: AxiosRequestConfig): string | null => {
79
+ const authorization = (config.headers as Record<string, unknown> | undefined)?.Authorization;
80
+ const match = typeof authorization === "string" ? /^bearer\s+(.+)$/i.exec(authorization) : null;
81
+ return match ? match[1] : null;
82
+ };
83
+
84
+ /** La petición se canceló (axios 0.19: `Cancel.__CANCEL__` / `cancelToken.reason`; nuevos: `signal`). */
85
+ const isCancellation = (error: any, config: RequestConfig): boolean =>
86
+ error.__CANCEL__ === true ||
87
+ error.code === "ERR_CANCELED" ||
88
+ error.name === "CanceledError" ||
89
+ !!config.cancelToken?.reason ||
90
+ !!config.signal?.aborted;
91
+
92
+ /**
93
+ * `axios(config)` con renovación de sesión ante 401.
94
+ *
95
+ * Solo reacciona al 401 de una petición que lleva `Authorization: bearer` (login, SSO y similares no lo
96
+ * llevan: su 401 es un error normal). Una renovación compartida, un único reintento con el token nuevo
97
+ * en memoria y el error original propagado si no se puede renovar. No lee `exp` en el cliente.
98
+ */
99
+ export const requestWithRenewal = async (config: RequestConfig): Promise<AxiosResponse> => {
100
+ try {
101
+ return await axios(config);
102
+ } catch (error) {
103
+ const sentToken = getSentToken(config);
104
+ if (error?.response?.status !== 401 || !sentToken || isCancellation(error, config)) throw error;
105
+
106
+ const outcome = await renewSession(sentToken);
107
+
108
+ if (outcome.status === "renewed" && !isCancellation(error, config)) {
109
+ return axios({ ...config, headers: { ...config.headers, Authorization: `bearer ${outcome.token}` } });
110
+ }
111
+ if (outcome.status === "expired") endSession();
112
+ throw error;
113
+ }
114
+ };
package/src/api/utils.tsx CHANGED
@@ -1,6 +1,9 @@
1
1
  import axios, { type AxiosRequestConfig, type AxiosResponse, type Method, type ResponseType } from "axios";
2
+
2
3
  import { SET_ERROR } from "./../containers/App/constants";
3
4
  import { getStore } from "../storeRegistry";
5
+ import { getSession } from "./session";
6
+ import { requestWithRenewal } from "./sessionRenewal";
4
7
 
5
8
  export interface IServiceConfig {
6
9
  host: string | undefined;
@@ -11,19 +14,24 @@ export interface IServiceConfig {
11
14
  dynamicUrl?: string;
12
15
  responseType?: ResponseType;
13
16
  onUploadProgress?: any;
17
+ /**
18
+ * El 401 de este servicio es un error normal: no renueva ni cierra la sesión (login, SSO,
19
+ * `password/init`, logout y la propia renovación).
20
+ */
21
+ skipAuthRenewal?: boolean;
14
22
  }
15
23
 
16
24
  const getToken = (): Record<string, unknown> | null => {
17
- const app = localStorage.getItem("persist:app");
18
- if (!app) return null;
19
-
20
- let { token } = JSON.parse(app);
21
- token = JSON.parse(token);
22
- const authorization = { Authorization: `bearer ${token}` };
25
+ const session = getSession();
26
+ if (!session) return null;
23
27
 
24
- return authorization;
28
+ return { Authorization: `bearer ${session.token}` };
25
29
  };
26
30
 
31
+ /** `axios(config)`, con renovación de sesión ante 401 salvo en los servicios excluidos. */
32
+ const send = (serviceConfig: IServiceConfig, config: AxiosRequestConfig) =>
33
+ serviceConfig.skipAuthRenewal ? axios(config) : requestWithRenewal(config);
34
+
27
35
  const getLang = (): Record<string, unknown> => {
28
36
  const store = getStore();
29
37
  if (store) return { lang: store.getState()?.app?.lang?.id ?? null };
@@ -114,7 +122,7 @@ export const sendInitialRequest = async (
114
122
  method,
115
123
  headers: {
116
124
  ...configHeaders,
117
- Authorization: "bearer " + token,
125
+ Authorization: `bearer ${token}`,
118
126
  },
119
127
  };
120
128
 
@@ -122,10 +130,10 @@ export const sendInitialRequest = async (
122
130
  const isPost = method === "PUT" || method === "POST";
123
131
  if (isPost) {
124
132
  const postConfig = { ...config, data };
125
- const postResponse = await axios(postConfig);
133
+ const postResponse = await send(serviceConfig, postConfig);
126
134
  return postResponse;
127
135
  }
128
- const response = await axios(config);
136
+ const response = await send(serviceConfig, config);
129
137
  return response;
130
138
  } catch (e) {
131
139
  if (e.message !== "Network Error") {
@@ -169,7 +177,7 @@ export const sendRequest = async (
169
177
  // requestCache.save(requestConfig, response);
170
178
 
171
179
  // return response;
172
- return await axios(requestConfig);
180
+ return await send(serviceConfig, requestConfig);
173
181
  } catch (e) {
174
182
  if (e.message !== "Network Error") {
175
183
  return (
@@ -202,7 +210,7 @@ export const sendUploadRequest = async (
202
210
  };
203
211
  }
204
212
 
205
- return await axios(requestConfig);
213
+ return await send(serviceConfig, requestConfig);
206
214
  } catch (e) {
207
215
  if (e.message !== "Network Error") {
208
216
  return (
@@ -235,6 +243,8 @@ export function handleResponse(
235
243
  }
236
244
  }
237
245
 
246
+ export { getToken };
247
+
238
248
  export default {
239
249
  getToken,
240
250
  getHeaders,
@@ -1,11 +1,12 @@
1
1
  import React from "react";
2
2
 
3
- import { CategoryCell } from "@ax/components";
4
- import { Cell } from "@ax/components/TableList/TableItem/style";
5
3
  import type { ISchemaField } from "@ax/types";
6
4
 
7
5
  import styled from "styled-components";
8
6
 
7
+ import { Cell } from "../TableList/TableItem/style";
8
+ import CategoryCell from "./index";
9
+
9
10
  const ColumnCell = styled(Cell)`
10
11
  flex: 0 0 215px;
11
12
  position: relative;
@@ -5,7 +5,7 @@ import * as S from "./style";
5
5
  const Circle = (props: ICircleProps) => {
6
6
  const { animation, size = 400 } = props;
7
7
 
8
- return <S.Circle animation={animation} size={size} />;
8
+ return <S.Circle data-testid="circle" animation={animation} size={size} />;
9
9
  };
10
10
 
11
11
  interface ICircleProps {
@@ -1,3 +1,5 @@
1
+ import { BRAND_PALETTE } from "@ax/themes/brandPalette";
2
+
1
3
  import styled, { keyframes } from "styled-components";
2
4
 
3
5
  const animation1 = keyframes`
@@ -11,7 +13,7 @@ const animation2 = keyframes`
11
13
  `;
12
14
 
13
15
  const animations = [animation1, animation2];
14
- const colors = ["#A950CF", "#FBE15C"];
16
+ const colors = [BRAND_PALETTE.purple, BRAND_PALETTE.cyan];
15
17
 
16
18
  const Circle = styled.div<{ size: number; animation: number }>`
17
19
  position: absolute;
@@ -23,7 +25,7 @@ const Circle = styled.div<{ size: number; animation: number }>`
23
25
  animation: ${(p) => animations[p.animation - 1]} 5s linear infinite alternate;
24
26
  backface-visibility: hidden;
25
27
  transform: translate3d(0, 0, 0);
26
- opacity: 0.6;
28
+ opacity: 0.5;
27
29
  `;
28
30
 
29
31
  export { Circle };
@@ -76,7 +76,7 @@ const ErrorPage = (props: IProps): JSX.Element => {
76
76
  };
77
77
 
78
78
  return (
79
- <S.Wrapper>
79
+ <S.Wrapper data-testid="error-page-wrapper">
80
80
  <S.BackgroundAnimation>
81
81
  <Circle animation={1} />
82
82
  <Circle animation={2} />
@@ -1,3 +1,5 @@
1
+ import { BRAND_PALETTE } from "@ax/themes/brandPalette";
2
+
1
3
  import styled from "styled-components";
2
4
 
3
5
  const Wrapper = styled.div`
@@ -6,7 +8,7 @@ const Wrapper = styled.div`
6
8
  align-items: center;
7
9
  height: 100%;
8
10
  width: 100%;
9
- background-color: ${(p) => p.theme.color.uiBackground04};
11
+ background-color: ${BRAND_PALETTE.navy};
10
12
  `;
11
13
 
12
14
  const BackgroundAnimation = styled.div`
@@ -100,17 +102,17 @@ const IconWrapper = styled.div`
100
102
  `;
101
103
 
102
104
  export {
103
- Wrapper,
105
+ BackgroundAnimation,
104
106
  Content,
107
+ ContentNumber,
108
+ ContentWrong,
109
+ ErrorAction,
110
+ ErrorDescription,
111
+ ErrorDescriptionWrong,
105
112
  ErrorNumber,
106
113
  ErrorTitle,
107
114
  ErrorTitleWrong,
108
- ErrorDescription,
109
- ErrorDescriptionWrong,
110
- Logo,
111
- ErrorAction,
112
- ContentNumber,
113
- ContentWrong,
114
- BackgroundAnimation,
115
115
  IconWrapper,
116
+ Logo,
117
+ Wrapper,
116
118
  };
@@ -10,6 +10,8 @@ export interface IProps {
10
10
  size?: string;
11
11
  ref?: any;
12
12
  fixed?: boolean;
13
+ /** Rol ARIA del contenedor (p. ej. `alert` para que los avisos se anuncien). */
14
+ role?: string;
13
15
  }
14
16
 
15
17
  export default forwardRef(ErrorToast);
@@ -83,12 +83,8 @@ const TranslateButton = (props: ITranslateButtonProps): JSX.Element => {
83
83
  }
84
84
  };
85
85
 
86
- const buttonText = state.error ? "Try againg" : state.isLoading ? "Processing..." : "Translate page with AI";
87
- const updateButtonText = state.error
88
- ? "Try againg"
89
- : state.isLoading
90
- ? "Processing..."
91
- : "Update translation with AI";
86
+ const buttonText = state.error ? "Try again" : state.isLoading ? "Processing..." : "Translate page with AI";
87
+ const updateButtonText = state.error ? "Try again" : state.isLoading ? "Processing..." : "Update translation with AI";
92
88
 
93
89
  return (
94
90
  <>
@@ -132,9 +128,8 @@ const TranslateButton = (props: ITranslateButtonProps): JSX.Element => {
132
128
  height="auto"
133
129
  >
134
130
  <S.ModalContent>
135
- This page <strong>already has a translation</strong>. Updating it{" "}
136
- <strong>will replace all existing text in this language</strong>, including any manual edits made after
137
- the previous translation. This action cannot be undone.
131
+ This will <strong>overwrite</strong> the current translation. All <strong>text and modules</strong> will
132
+ be replaced to match the original page. This can’t be undone.
138
133
  </S.ModalContent>
139
134
  </Modal>
140
135
  )}
@@ -1,4 +1,4 @@
1
- import * as components from "@ax/components/Fields";
1
+ import * as components from "../Fields";
2
2
 
3
3
  const getFieldByPath = (name: string): ((props: any) => JSX.Element) => (components as Record<string, any>)[name];
4
4
 
@@ -2,9 +2,11 @@ import { useCallback, useEffect, useState } from "react";
2
2
 
3
3
  import { IconAction, Tooltip } from "@ax/components";
4
4
  import { getValidity } from "@ax/forms";
5
- import { getFieldByPath, isEmptyContainer, slugify } from "@ax/helpers";
5
+ import { isEmptyContainer, slugify } from "@ax/helpers";
6
6
  import type { IErrorItem } from "@ax/types";
7
7
 
8
+ import { getFieldByPath } from "./getFieldByPath";
9
+
8
10
  import * as S from "./style";
9
11
 
10
12
  const FieldsBehavior = (props: IFieldsBehaviorProps): JSX.Element => {