@griddo/ax 12.14.3 → 12.15.0-beta.1

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 (53) hide show
  1. package/README.md +1 -0
  2. package/package.json +7 -4
  3. package/src/GlobalStore.tsx +32 -25
  4. package/src/__tests__/GlobalStore.session.test.tsx +98 -0
  5. package/src/__tests__/api/global.test.ts +64 -0
  6. package/src/__tests__/api/session.test.ts +311 -0
  7. package/src/__tests__/api/sessionRenewal.test.ts +705 -0
  8. package/src/__tests__/api/utils.test.ts +373 -0
  9. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +33 -6
  10. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +5 -3
  11. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +195 -0
  12. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +86 -0
  13. package/src/__tests__/containers/App/reducer.griddoId.test.ts +18 -0
  14. package/src/__tests__/containers/App/session.test.ts +397 -0
  15. package/src/__tests__/helpers/griddoId.test.ts +56 -0
  16. package/src/__tests__/locales/loginLocale.test.ts +52 -0
  17. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +54 -0
  18. package/src/__tests__/modules/Login/Login.test.tsx +151 -0
  19. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +19 -0
  20. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +19 -0
  21. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +19 -0
  22. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +30 -0
  23. package/src/__tests__/routes/publicRoutes.test.ts +36 -0
  24. package/src/api/global.tsx +24 -1
  25. package/src/api/session.tsx +197 -0
  26. package/src/api/sessionRenewal.tsx +114 -0
  27. package/src/api/utils.tsx +22 -12
  28. package/src/{helpers/categoryColumns.tsx → components/CategoryCell/buildCategoryColumns.tsx} +3 -2
  29. package/src/{helpers/fields.tsx → components/FieldsBehavior/getFieldByPath.tsx} +1 -1
  30. package/src/components/FieldsBehavior/index.tsx +3 -1
  31. package/src/components/Login/LoginForm/index.tsx +7 -2
  32. package/src/components/Login/LoginGriddoId/index.tsx +46 -0
  33. package/src/components/Login/LoginGriddoId/style.tsx +35 -0
  34. package/src/components/Login/index.tsx +13 -1
  35. package/src/components/SsoDenied/index.tsx +46 -0
  36. package/src/components/SsoDenied/style.tsx +37 -0
  37. package/src/components/index.tsx +11 -7
  38. package/src/containers/App/actions.tsx +110 -5
  39. package/src/containers/App/interfaces.tsx +2 -2
  40. package/src/containers/App/reducer.tsx +9 -0
  41. package/src/containers/Users/actions.tsx +28 -24
  42. package/src/helpers/griddoId.ts +28 -0
  43. package/src/helpers/index.tsx +4 -5
  44. package/src/locales/en-US.ts +7 -0
  45. package/src/locales/es-ES.ts +7 -0
  46. package/src/locales/index.ts +10 -0
  47. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  48. package/src/modules/Content/PageItem/index.tsx +6 -8
  49. package/src/modules/Login/index.tsx +12 -2
  50. package/src/modules/SsoDenied/index.tsx +9 -0
  51. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +6 -8
  52. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +9 -11
  53. package/src/routes/publicRoutes.tsx +3 -0
@@ -0,0 +1,151 @@
1
+ import { Provider } from "react-redux";
2
+ import { Router } from "react-router-dom";
3
+
4
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
5
+ import configureStore from "redux-mock-store";
6
+ import { ThemeProvider } from "styled-components";
7
+ import "@testing-library/jest-dom";
8
+
9
+ import { appInitialState } from "@ax/containers/App/reducer";
10
+ import { parseTheme } from "@ax/helpers";
11
+ import LoginModule from "@ax/modules/Login";
12
+ import history from "@ax/routes/history";
13
+ import globalTheme from "@ax/themes/theme.json";
14
+
15
+ vi.mock("@ax/containers/App", async (importOriginal) => ({
16
+ ...(await importOriginal<typeof import("@ax/containers/App")>()),
17
+ appActions: {
18
+ ...(await importOriginal<typeof import("@ax/containers/App")>()).appActions,
19
+ login: () => ({ type: "test/login" }),
20
+ loginSSO: () => ({ type: "test/loginSSO" }),
21
+ resetError: () => ({ type: "test/resetError" }),
22
+ getGlobalSettings: () => ({ type: "test/getGlobalSettings" }),
23
+ setHistoryPush: () => ({ type: "test/setHistoryPush" }),
24
+ },
25
+ }));
26
+
27
+ afterEach(() => {
28
+ cleanup();
29
+ vi.unstubAllGlobals();
30
+ vi.unstubAllEnvs();
31
+ });
32
+
33
+ const renderModule = (globalSettings: Partial<typeof appInitialState.globalSettings>) => {
34
+ const store = configureStore([])({
35
+ app: { isLoggingIn: false, globalSettings: { ...appInitialState.globalSettings, ...globalSettings } },
36
+ });
37
+
38
+ render(
39
+ <Provider store={store}>
40
+ <Router history={history}>
41
+ <ThemeProvider theme={parseTheme(globalTheme)}>
42
+ <LoginModule />
43
+ </ThemeProvider>
44
+ </Router>
45
+ </Provider>,
46
+ );
47
+ };
48
+
49
+ describe("módulo Login con auth.griddo.io", () => {
50
+ beforeEach(() => {
51
+ vi.stubEnv("GRIDDO_API_URL", "https://api.uni.es");
52
+ vi.spyOn(window.navigator, "language", "get").mockReturnValue("es-ES");
53
+ });
54
+
55
+ it("«Entrar con Griddo» navega a /sso/start de la API configurada, una sola vez con doble clic", () => {
56
+ const assign = vi.fn();
57
+
58
+ vi.stubGlobal("location", { ...window.location, assign });
59
+ renderModule({ GriddoIdEnabled: true });
60
+
61
+ const button = screen.getByRole("button", { name: "Entrar con Griddo" });
62
+
63
+ fireEvent.click(button);
64
+ fireEvent.click(button);
65
+
66
+ expect(assign).toHaveBeenCalledTimes(1);
67
+ expect(assign).toHaveBeenCalledWith("https://api.uni.es/sso/start");
68
+ });
69
+
70
+ const typeEmail = (value: string) =>
71
+ fireEvent.change(screen.getByPlaceholderText("Type your email"), { target: { value } });
72
+
73
+ const clickGriddoId = () => {
74
+ const assign = vi.fn();
75
+
76
+ vi.stubGlobal("location", { ...window.location, assign });
77
+ renderModule({ GriddoIdEnabled: true });
78
+
79
+ return { assign, button: screen.getByRole("button", { name: "Entrar con Griddo" }) };
80
+ };
81
+
82
+ it("envía el email escrito como login_hint, recortado y codificado", () => {
83
+ const { assign, button } = clickGriddoId();
84
+
85
+ typeEmail(" ana+x@uni.es ");
86
+ fireEvent.click(button);
87
+
88
+ expect(assign).toHaveBeenCalledWith("https://api.uni.es/sso/start?login_hint=ana%2Bx%40uni.es");
89
+ });
90
+
91
+ it("con el campo vacío o sin arroba navega sin query", () => {
92
+ for (const typed of ["", "ana"]) {
93
+ const { assign, button } = clickGriddoId();
94
+
95
+ typeEmail(typed);
96
+ fireEvent.click(button);
97
+
98
+ expect(assign).toHaveBeenCalledWith("https://api.uni.es/sso/start");
99
+ cleanup();
100
+ }
101
+ });
102
+
103
+ it("la contraseña no viaja en la URL", () => {
104
+ const { assign, button } = clickGriddoId();
105
+ const password = document.querySelector<HTMLInputElement>('input[name="password"]') as HTMLInputElement;
106
+
107
+ typeEmail("ana@uni.es");
108
+ fireEvent.change(password, { target: { value: "s3cr3t-pass" } });
109
+ fireEvent.click(button);
110
+
111
+ const url = assign.mock.calls[0][0] as string;
112
+
113
+ expect(url).toBe("https://api.uni.es/sso/start?login_hint=ana%40uni.es");
114
+ expect(url).not.toContain("s3cr3t");
115
+ });
116
+
117
+ it("con email escrito, un doble clic navega una sola vez", () => {
118
+ const { assign, button } = clickGriddoId();
119
+
120
+ typeEmail("ana@uni.es");
121
+ fireEvent.click(button);
122
+ fireEvent.click(button);
123
+
124
+ expect(assign).toHaveBeenCalledTimes(1);
125
+ });
126
+
127
+ it("sin GRIDDO_API_URL el destino cuelga de REACT_APP_API_ENDPOINT", () => {
128
+ vi.stubEnv("GRIDDO_API_URL", "");
129
+ vi.stubEnv("REACT_APP_API_ENDPOINT", "https://fallback.uni.es");
130
+ const { assign, button } = clickGriddoId();
131
+
132
+ typeEmail("ana@uni.es");
133
+ fireEvent.click(button);
134
+
135
+ expect(assign).toHaveBeenCalledWith("https://fallback.uni.es/sso/start?login_hint=ana%40uni.es");
136
+ });
137
+
138
+ it("con el flag activo el formulario sigue ahí junto al botón", () => {
139
+ renderModule({ GriddoIdEnabled: true });
140
+
141
+ expect(screen.getByPlaceholderText("Type your email")).toBeInTheDocument();
142
+ expect(screen.getByRole("button", { name: "Entrar con Griddo" })).toBeInTheDocument();
143
+ });
144
+
145
+ it("con el flag apagado (o sin settings) muestra el formulario de siempre", () => {
146
+ renderModule({ GriddoIdEnabled: false });
147
+
148
+ expect(screen.queryByText("Entrar con Griddo")).toBeNull();
149
+ expect(screen.getByPlaceholderText("Type your email")).toBeInTheDocument();
150
+ });
151
+ });
@@ -14,6 +14,25 @@ vi.mock("@ax/containers/Redirects", () => ({
14
14
  },
15
15
  }));
16
16
 
17
+ // RedirectPanel monta UrlField → PageFinder, que pide páginas y tipos de contenido
18
+ // al montarse y hace setState al resolver. Con la API real esa petición acababa
19
+ // después de que vitest desmontara jsdom y reventaba con "window is not defined".
20
+ vi.mock("@ax/api", async (importOriginal) => {
21
+ const actual = (await importOriginal()) as any;
22
+
23
+ return {
24
+ ...actual,
25
+ sites: {
26
+ ...actual.sites,
27
+ getSitePages: () => Promise.resolve({ status: 200, data: { items: [], totalItems: 0 } }),
28
+ },
29
+ structuredData: {
30
+ ...actual.structuredData,
31
+ getData: () => Promise.resolve({ status: 200, data: { items: [] } }),
32
+ },
33
+ };
34
+ });
35
+
17
36
  import { MemoryRouter } from "react-router-dom";
18
37
 
19
38
  import { parseTheme } from "@ax/helpers";
@@ -10,6 +10,25 @@ vi.mock("@ax/containers/Redirects", () => ({
10
10
  },
11
11
  }));
12
12
 
13
+ // RedirectPanel monta UrlField → PageFinder, que pide páginas y tipos de contenido
14
+ // al montarse y hace setState al resolver. Con la API real esa petición acababa
15
+ // después de que vitest desmontara jsdom y reventaba con "window is not defined".
16
+ vi.mock("@ax/api", async (importOriginal) => {
17
+ const actual = (await importOriginal()) as any;
18
+
19
+ return {
20
+ ...actual,
21
+ sites: {
22
+ ...actual.sites,
23
+ getSitePages: () => Promise.resolve({ status: 200, data: { items: [], totalItems: 0 } }),
24
+ },
25
+ structuredData: {
26
+ ...actual.structuredData,
27
+ getData: () => Promise.resolve({ status: 200, data: { items: [] } }),
28
+ },
29
+ };
30
+ });
31
+
13
32
  import { MemoryRouter } from "react-router-dom";
14
33
 
15
34
  import { parseTheme } from "@ax/helpers";
@@ -14,6 +14,25 @@ vi.mock("@ax/containers/Redirects", () => ({
14
14
  },
15
15
  }));
16
16
 
17
+ // RedirectPanel monta UrlField → PageFinder, que pide páginas y tipos de contenido
18
+ // al montarse y hace setState al resolver. Con la API real esa petición acababa
19
+ // después de que vitest desmontara jsdom y reventaba con "window is not defined".
20
+ vi.mock("@ax/api", async (importOriginal) => {
21
+ const actual = (await importOriginal()) as any;
22
+
23
+ return {
24
+ ...actual,
25
+ sites: {
26
+ ...actual.sites,
27
+ getSitePages: () => Promise.resolve({ status: 200, data: { items: [], totalItems: 0 } }),
28
+ },
29
+ structuredData: {
30
+ ...actual.structuredData,
31
+ getData: () => Promise.resolve({ status: 200, data: { items: [] } }),
32
+ },
33
+ };
34
+ });
35
+
17
36
  import { MemoryRouter } from "react-router-dom";
18
37
 
19
38
  import { parseTheme } from "@ax/helpers";
@@ -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 «Entrar con otra cuenta» 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: "Entrar con otra cuenta" })).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
+ };