@robosophy/auth 1.0.0 → 1.2.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 +135 -141
- package/dist/index.d.ts +5 -2
- package/dist/index.js +16 -25
- package/package.json +35 -35
package/README.md
CHANGED
|
@@ -1,141 +1,135 @@
|
|
|
1
|
-
# @robosophy/auth
|
|
2
|
-
|
|
3
|
-
Sesión de los fronts de Mi Cuenta contra el Landing: access token RS256 de 15 minutos en `localStorage["token"]`, refresh opaco en cookie HttpOnly y datos del usuario desde `GET /api/usuario/self`.
|
|
4
|
-
|
|
5
|
-
No depende de ningún framework. Necesita `axios` (peer dependency) y `fetch`.
|
|
6
|
-
|
|
7
|
-
## Instalación
|
|
8
|
-
|
|
9
|
-
```sh
|
|
10
|
-
npm install @robosophy/auth
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
## Configuración
|
|
14
|
-
|
|
15
|
-
Se llama una sola vez, al arrancar la app:
|
|
16
|
-
|
|
17
|
-
```js
|
|
18
|
-
import { configureAuth } from "@robosophy/auth";
|
|
19
|
-
|
|
20
|
-
configureAuth({
|
|
21
|
-
landingUrl: import.meta.env.VITE_LANDING_URL, // origin del Landing (front y back comparten origin)
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
| `
|
|
33
|
-
| `
|
|
34
|
-
| `
|
|
35
|
-
| `
|
|
36
|
-
| `
|
|
37
|
-
| `
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
- En
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
return
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
## Desarrollo local
|
|
137
|
-
|
|
138
|
-
- La variable con la URL del Landing (`landingUrl`) apunta al **Landing back** en `http://localhost:8184`, no al Vite del front de Landing: ahí están `/api/usuario/self` y `/dev/token`.
|
|
139
|
-
- `VITE_DEV_EMAIL=usuario@basf.com` va en `.env.local`, que no se commitea.
|
|
140
|
-
- Con el Landing back en perfil `local`, el front pide el token solo en el primer 401: no hace falta loguearse ni copiar tokens.
|
|
141
|
-
- Para entrar con otro usuario se cambia el email y se recarga. `configureAuth` detecta el cambio (lo guarda en `localStorage["auth-dev-email"]`) y borra la sesión del usuario anterior.
|
|
1
|
+
# @robosophy/auth
|
|
2
|
+
|
|
3
|
+
Sesión de los fronts de Mi Cuenta contra el Landing: access token RS256 de 15 minutos en `localStorage["token"]`, refresh opaco en cookie HttpOnly y datos del usuario desde `GET /api/usuario/self`.
|
|
4
|
+
|
|
5
|
+
No depende de ningún framework. Necesita `axios` (peer dependency) y `fetch`.
|
|
6
|
+
|
|
7
|
+
## Instalación
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @robosophy/auth
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Configuración
|
|
14
|
+
|
|
15
|
+
Se llama una sola vez, al arrancar la app:
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
import { configureAuth } from "@robosophy/auth";
|
|
19
|
+
|
|
20
|
+
configureAuth({
|
|
21
|
+
landingUrl: import.meta.env.VITE_LANDING_URL, // origin del Landing (front y back comparten origin)
|
|
22
|
+
isDev: import.meta.env.DEV,
|
|
23
|
+
});
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`hostsLogin: true` solo en Landing, que es el que tiene el login: redirige a su propio `/login` (`window.location.origin`) y lo hace también en DEV. Los módulos no lo pasan: van a `{landingUrl}/login` y en DEV no redirigen.
|
|
27
|
+
|
|
28
|
+
## API
|
|
29
|
+
|
|
30
|
+
| Función | Qué hace |
|
|
31
|
+
|---|---|
|
|
32
|
+
| `configureAuth(opts)` | Guarda `landingUrl`, `isDev` y `hostsLogin`. |
|
|
33
|
+
| `getToken()` | Devuelve `localStorage["token"]` o `null`. |
|
|
34
|
+
| `attachAuthRefresh(api)` | Agrega el Bearer a cada request y ante un 401 renueva el token y reintenta una vez. |
|
|
35
|
+
| `getCurrentUser()` | `GET {landingUrl}/api/usuario/self`, cacheado en memoria. Si falla, el cache se descarta. |
|
|
36
|
+
| `setSession(token)` | Guarda el token nuevo e invalida el cache del usuario. |
|
|
37
|
+
| `logout()` | `POST {landingUrl}/api/auth/logout`, limpia la sesión y va al login (ver `hostsLogin`). |
|
|
38
|
+
| `clearSession()` | Borra `token`, `user-id`, `originalToken` y `token-landing` de `localStorage`. |
|
|
39
|
+
|
|
40
|
+
## Cómo se renueva el token
|
|
41
|
+
|
|
42
|
+
Ante un 401 de un request que todavía no se reintentó:
|
|
43
|
+
|
|
44
|
+
1. Se toma el lock `basf-auth-refresh` con `navigator.locks`, compartido entre pestañas. Si el navegador no lo soporta, se deduplica solo dentro de la pestaña.
|
|
45
|
+
2. Si `localStorage["token"]` ya cambió, otra pestaña renovó primero y se usa ese token.
|
|
46
|
+
3. Si no, se pide uno nuevo: `POST {landingUrl}/api/auth/refresh` con `credentials: "include"`, que rota la cookie de refresh.
|
|
47
|
+
4. Con token nuevo se reintenta el request original. Si no hay token:
|
|
48
|
+
- En DEV: `console.warn('[auth] sin sesión: copiá el token de dev en localStorage (key "token") y recargá')` y el error sigue. No redirige (salvo con `hostsLogin`).
|
|
49
|
+
- En prod, o con `hostsLogin`: `clearSession()` y redirect al login, salvo que ya esté en esa página.
|
|
50
|
+
|
|
51
|
+
Los 401 de `/api/auth/login`, `/api/auth/verify-2fa`, `/api/auth/resend-2fa`, `/api/auth/refresh` y `/api/auth/logout` no disparan el refresh: ahí el 401 es la respuesta (credenciales, código 2FA, refresh vencido). El resto de `/api/auth/*`, como `request-2fa-challenge`, sí renueva y reintenta.
|
|
52
|
+
|
|
53
|
+
## Uso en Vue
|
|
54
|
+
|
|
55
|
+
```js
|
|
56
|
+
// main.js
|
|
57
|
+
import { configureAuth } from "@robosophy/auth";
|
|
58
|
+
|
|
59
|
+
configureAuth({
|
|
60
|
+
landingUrl: import.meta.env.VITE_LANDING_URL,
|
|
61
|
+
isDev: import.meta.env.DEV,
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
// axiosClient.js
|
|
67
|
+
import axios from "axios";
|
|
68
|
+
import { attachAuthRefresh } from "@robosophy/auth";
|
|
69
|
+
|
|
70
|
+
const api = axios.create({ baseURL: import.meta.env.VITE_URL });
|
|
71
|
+
attachAuthRefresh(api);
|
|
72
|
+
export default api;
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
// router/index.js
|
|
77
|
+
import { getCurrentUser } from "@robosophy/auth";
|
|
78
|
+
|
|
79
|
+
router.beforeEach(async (to) => {
|
|
80
|
+
if (!to.meta.requiresAuth) return true;
|
|
81
|
+
try {
|
|
82
|
+
const user = await getCurrentUser();
|
|
83
|
+
return Boolean(user?.rolCYO?.rol);
|
|
84
|
+
} catch {
|
|
85
|
+
return false; // attachAuthRefresh ya redirigió al login (prod) o avisó por consola (DEV)
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
```vue
|
|
91
|
+
<!-- Botón de salir -->
|
|
92
|
+
<script setup>
|
|
93
|
+
import { logout } from "@robosophy/auth";
|
|
94
|
+
</script>
|
|
95
|
+
|
|
96
|
+
<template>
|
|
97
|
+
<button @click="logout">Salir</button>
|
|
98
|
+
</template>
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
## Uso en React
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
// main.tsx
|
|
105
|
+
import { configureAuth } from "@robosophy/auth";
|
|
106
|
+
|
|
107
|
+
configureAuth({
|
|
108
|
+
landingUrl: import.meta.env.VITE_LANDING_URL,
|
|
109
|
+
isDev: import.meta.env.DEV,
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
// useCurrentUser.ts
|
|
115
|
+
import { useEffect, useState } from "react";
|
|
116
|
+
import { getCurrentUser } from "@robosophy/auth";
|
|
117
|
+
|
|
118
|
+
export function useCurrentUser<T>() {
|
|
119
|
+
const [user, setUser] = useState<T | null>(null);
|
|
120
|
+
useEffect(() => {
|
|
121
|
+
getCurrentUser<T>().then(setUser).catch(() => setUser(null));
|
|
122
|
+
}, []);
|
|
123
|
+
return user;
|
|
124
|
+
}
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
```tsx
|
|
128
|
+
import { logout } from "@robosophy/auth";
|
|
129
|
+
|
|
130
|
+
<button onClick={() => logout()}>Salir</button>;
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## Desarrollo local
|
|
134
|
+
|
|
135
|
+
En dev el access token dura 24 h. Para trabajar con un front local: loguearse en `https://dev.micuenta.basf.com.ar`, copiar `token` del `localStorage` y pegarlo en el `localStorage` del front local (`localhost:<puerto>`), con la misma key. Con `isDev` el paquete no redirige al login: si el token vence, avisa en la consola y hay que pegar uno nuevo.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
interface AuthOptions {
|
|
2
2
|
/** Origin del Landing (front y back comparten origin): ej. import.meta.env.VITE_LANDING_URL */
|
|
3
3
|
landingUrl: string;
|
|
4
|
-
/** Solo DEV: email para pedir el token a POST /dev/token del Landing back local. */
|
|
5
|
-
devEmail?: string;
|
|
6
4
|
/** import.meta.env.DEV */
|
|
7
5
|
isDev?: boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Solo Landing, que es el que tiene el login: redirige a su propio /login (window.location.origin,
|
|
8
|
+
* no landingUrl, que en local es el back) y lo hace también en DEV.
|
|
9
|
+
*/
|
|
10
|
+
hostsLogin?: boolean;
|
|
8
11
|
}
|
|
9
12
|
/**
|
|
10
13
|
* Lo único que se usa de la instancia. Estructural para no atar los tipos a la versión de axios
|
package/dist/index.js
CHANGED
|
@@ -4,17 +4,14 @@ var TOKEN_KEY = "token";
|
|
|
4
4
|
var SESSION_KEYS = [TOKEN_KEY, "user-id", "originalToken", "token-landing"];
|
|
5
5
|
var LOCK_NAME = "basf-auth-refresh";
|
|
6
6
|
var REFRESH_PATH = "/api/auth/refresh";
|
|
7
|
-
var DEV_TOKEN_PATH = "/dev/token";
|
|
8
7
|
var LOGOUT_PATH = "/api/auth/logout";
|
|
9
8
|
var SELF_PATH = "/api/usuario/self";
|
|
10
|
-
var DEV_EMAIL_KEY = "auth-dev-email";
|
|
11
9
|
var NO_RETRY_PATHS = [
|
|
12
10
|
"/api/auth/login",
|
|
13
11
|
"/api/auth/verify-2fa",
|
|
14
12
|
"/api/auth/resend-2fa",
|
|
15
13
|
REFRESH_PATH,
|
|
16
|
-
LOGOUT_PATH
|
|
17
|
-
DEV_TOKEN_PATH
|
|
14
|
+
LOGOUT_PATH
|
|
18
15
|
];
|
|
19
16
|
var options = null;
|
|
20
17
|
var landingApi = null;
|
|
@@ -23,15 +20,11 @@ var inFlightRefresh = null;
|
|
|
23
20
|
function configureAuth(opts) {
|
|
24
21
|
options = {
|
|
25
22
|
landingUrl: opts.landingUrl.replace(/\/+$/, ""),
|
|
26
|
-
|
|
27
|
-
|
|
23
|
+
isDev: opts.isDev ?? false,
|
|
24
|
+
hostsLogin: opts.hostsLogin ?? false
|
|
28
25
|
};
|
|
29
26
|
landingApi = null;
|
|
30
27
|
currentUser = null;
|
|
31
|
-
if (options.isDev && options.devEmail !== "" && localStorage.getItem(DEV_EMAIL_KEY) !== options.devEmail) {
|
|
32
|
-
clearSession();
|
|
33
|
-
localStorage.setItem(DEV_EMAIL_KEY, options.devEmail);
|
|
34
|
-
}
|
|
35
28
|
}
|
|
36
29
|
function getToken() {
|
|
37
30
|
return localStorage.getItem(TOKEN_KEY);
|
|
@@ -91,7 +84,7 @@ async function logout() {
|
|
|
91
84
|
} catch {
|
|
92
85
|
}
|
|
93
86
|
clearSession();
|
|
94
|
-
window.location.href =
|
|
87
|
+
window.location.href = loginUrl();
|
|
95
88
|
}
|
|
96
89
|
function requireOptions() {
|
|
97
90
|
if (!options) {
|
|
@@ -99,6 +92,10 @@ function requireOptions() {
|
|
|
99
92
|
}
|
|
100
93
|
return options;
|
|
101
94
|
}
|
|
95
|
+
function loginUrl() {
|
|
96
|
+
const { landingUrl, hostsLogin } = requireOptions();
|
|
97
|
+
return `${hostsLogin ? window.location.origin : landingUrl}/login`;
|
|
98
|
+
}
|
|
102
99
|
function getLandingApi() {
|
|
103
100
|
if (!landingApi) {
|
|
104
101
|
landingApi = axios.create({ baseURL: requireOptions().landingUrl });
|
|
@@ -141,15 +138,9 @@ function withRefreshLock(task) {
|
|
|
141
138
|
return locks ? locks.request(LOCK_NAME, task) : task();
|
|
142
139
|
}
|
|
143
140
|
async function requestNewToken() {
|
|
144
|
-
const { landingUrl
|
|
145
|
-
const useDevToken = isDev && devEmail !== "";
|
|
141
|
+
const { landingUrl } = requireOptions();
|
|
146
142
|
try {
|
|
147
|
-
const response = await fetch(landingUrl +
|
|
148
|
-
method: "POST",
|
|
149
|
-
credentials: "include",
|
|
150
|
-
headers: useDevToken ? { "Content-Type": "application/json" } : void 0,
|
|
151
|
-
body: useDevToken ? JSON.stringify({ email: devEmail }) : void 0
|
|
152
|
-
});
|
|
143
|
+
const response = await fetch(landingUrl + REFRESH_PATH, { method: "POST", credentials: "include" });
|
|
153
144
|
if (!response.ok) {
|
|
154
145
|
return null;
|
|
155
146
|
}
|
|
@@ -160,15 +151,15 @@ async function requestNewToken() {
|
|
|
160
151
|
}
|
|
161
152
|
}
|
|
162
153
|
function onSessionLost() {
|
|
163
|
-
const {
|
|
164
|
-
if (isDev) {
|
|
165
|
-
console.warn(
|
|
154
|
+
const { isDev, hostsLogin } = requireOptions();
|
|
155
|
+
if (isDev && !hostsLogin) {
|
|
156
|
+
console.warn('[auth] sin sesi\xF3n: copi\xE1 el token de dev en localStorage (key "token") y recarg\xE1');
|
|
166
157
|
return;
|
|
167
158
|
}
|
|
168
159
|
clearSession();
|
|
169
|
-
const
|
|
170
|
-
if (!window.location.href.startsWith(
|
|
171
|
-
window.location.href =
|
|
160
|
+
const target = loginUrl();
|
|
161
|
+
if (!window.location.href.startsWith(target)) {
|
|
162
|
+
window.location.href = target;
|
|
172
163
|
}
|
|
173
164
|
}
|
|
174
165
|
export {
|
package/package.json
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@robosophy/auth",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"private": false,
|
|
5
|
-
"license": "UNLICENSED",
|
|
6
|
-
"type": "module",
|
|
7
|
-
"main": "./dist/index.js",
|
|
8
|
-
"types": "./dist/index.d.ts",
|
|
9
|
-
"exports": {
|
|
10
|
-
".": {
|
|
11
|
-
"types": "./dist/index.d.ts",
|
|
12
|
-
"default": "./dist/index.js"
|
|
13
|
-
}
|
|
14
|
-
},
|
|
15
|
-
"files": [
|
|
16
|
-
"dist",
|
|
17
|
-
"README.md",
|
|
18
|
-
"package.json"
|
|
19
|
-
],
|
|
20
|
-
"sideEffects": false,
|
|
21
|
-
"scripts": {
|
|
22
|
-
"prepublishOnly": "npm run build",
|
|
23
|
-
"build": "tsup src/index.ts --format esm --dts --clean --external axios",
|
|
24
|
-
"test": "vitest run"
|
|
25
|
-
},
|
|
26
|
-
"peerDependencies": {
|
|
27
|
-
"axios": ">=0.19.0"
|
|
28
|
-
},
|
|
29
|
-
"devDependencies": {
|
|
30
|
-
"axios": "^1.7.0",
|
|
31
|
-
"tsup": "^8.5.0",
|
|
32
|
-
"typescript": "^5.9.3",
|
|
33
|
-
"vitest": "^4.0.0"
|
|
34
|
-
}
|
|
35
|
-
}
|
|
1
|
+
{
|
|
2
|
+
"name": "@robosophy/auth",
|
|
3
|
+
"version": "1.2.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"license": "UNLICENSED",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"package.json"
|
|
19
|
+
],
|
|
20
|
+
"sideEffects": false,
|
|
21
|
+
"scripts": {
|
|
22
|
+
"prepublishOnly": "npm run build",
|
|
23
|
+
"build": "tsup src/index.ts --format esm --dts --clean --external axios",
|
|
24
|
+
"test": "vitest run"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"axios": ">=0.19.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"axios": "^1.7.0",
|
|
31
|
+
"tsup": "^8.5.0",
|
|
32
|
+
"typescript": "^5.9.3",
|
|
33
|
+
"vitest": "^4.0.0"
|
|
34
|
+
}
|
|
35
|
+
}
|