@innertia-solutions/innertia-nuxt 0.1.84 → 0.1.86
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/CHANGELOG.md +4 -0
- package/components/App/Versions.vue +9 -2
- package/components/Forms/Select.vue +9 -7
- package/components/Kanban/Standard.vue +32 -2
- package/components/Table/Standard.vue +4 -1
- package/components/Table/index.vue +2 -1
- package/components/TableExportable.vue +9 -1
- package/components/Tree/Standard.vue +6 -1
- package/composables/__tests__/useForm.test.ts +45 -0
- package/composables/internal/__tests__/apiUnauthorized.test.ts +29 -0
- package/composables/internal/apiUnauthorized.js +21 -0
- package/composables/useApi.js +30 -2
- package/composables/useForm.js +10 -0
- package/nuxt.config.ts +8 -0
- package/package.json +1 -1
- package/server/middleware/auth-session.ts +11 -2
- package/server/routes/_auth/context.put.ts +3 -1
- package/server/routes/_auth/logout.post.ts +3 -1
- package/server/routes/api/[...path].ts +11 -6
- package/server/utils/__tests__/tokenRefresh.test.ts +95 -0
- package/server/utils/sessionToken.ts +83 -0
- package/server/utils/tokenRefresh.ts +129 -0
package/CHANGELOG.md
CHANGED
|
@@ -11,6 +11,10 @@ All notable changes to `@innertia-solutions/innertia-nuxt` are documented here.
|
|
|
11
11
|
|
|
12
12
|
### Fixed
|
|
13
13
|
|
|
14
|
+
- Sesión: renovación deslizante del JWT en el BFF. Cuando al token le quedan menos de 10 min (o menos de 1/3 de su vida), `/api/**` y el SSR lo renuevan contra `POST auth/refresh` y reescriben la cookie sellada; refrescos concurrentes se deduplican y los requests tardíos con el token viejo reciben el nuevo; un refresh fallido no se reintenta con ese token por 30 s (timeout de 5 s). Con uso activo la sesión ya no muere a los 60 min fijos. No aplica a tokens de plataforma. Configurable con `runtimeConfig.authRefresh` (`NUXT_AUTH_REFRESH_ENABLED`, `NUXT_AUTH_REFRESH_PATH`).
|
|
15
|
+
- `useApi`: ante un 401, las mutaciones del cliente (POST/PUT/PATCH/DELETE) ahora **lanzan** un error `{ status: 401, data: { message } }` en vez de devolver `null` (antes `useMutation` lo tomaba como éxito y mostraba "Guardado" sin guardar). GET y las llamadas SSR siguen devolviendo `null`. Override por llamada con `{ throwOnUnauthorized: true|false }`. Además muestra un aviso "Tu sesión expiró" (una vez) y, al lanzar, no espera la navegación al login para que el llamador muestre el error antes de las guardas de "cambios sin guardar".
|
|
16
|
+
- `useForm`: el error de un campo se borra al cambiar su valor (antes quedaba "Este campo es obligatorio" bajo un campo ya completado hasta el siguiente envío).
|
|
17
|
+
- `Forms.Select`: el placeholder por defecto es "Selecciona…" y siempre se pasa a Preline (antes, con `clearable`, se veía "Select..."). En modo `clearable` se activa `optionAllowEmptyOption` para que la opción vacía siga siendo seleccionable.
|
|
14
18
|
- `Forms.Select`: el dropdown ahora usa `dropdownScope:'window'` (Preline lo teletransporta al `<body>` y lo posiciona con floating-ui). Deja de recortarse dentro de contenedores con scroll —modales, paneles— y flota por encima (`z-[10000]`). Se expone `window.FloatingUIDOM` en el plugin de Preline y se agrega `@floating-ui/dom` como dependencia.
|
|
15
19
|
- `Kanban.Standard`: en modo `bordered=false`, el `ring` de highlight al arrastrar sobre una columna se recortaba por arriba (el contenedor `overflow-x-auto` sin padding clippeaba los 2px del ring). Se agrega `p-1` al scroll container en ese modo.
|
|
16
20
|
|
|
@@ -16,7 +16,14 @@ const props = defineProps({
|
|
|
16
16
|
title: { type: String, default: 'Versiones' },
|
|
17
17
|
})
|
|
18
18
|
|
|
19
|
-
const { data, error, pending, refresh } = useFetch(props.endpoint, { server: false, key: `innertia-versions:${props.endpoint}` })
|
|
19
|
+
const { data, error, pending, status, refresh } = useFetch(props.endpoint, { server: false, key: `innertia-versions:${props.endpoint}` })
|
|
20
|
+
|
|
21
|
+
// Con `server: false` el servidor deja el fetch en 'idle' (pending=false) y el cliente
|
|
22
|
+
// lo lanza en onBeforeMount (pending=true) antes de hidratar: si el estado de carga
|
|
23
|
+
// dependiera solo de `pending`, el HTML del servidor (grilla vacía) no coincidiría con
|
|
24
|
+
// el primer render del cliente ("Cargando…") → error de hidratación. 'idle' sin datos
|
|
25
|
+
// también cuenta como cargando, así ambos lados renderizan lo mismo.
|
|
26
|
+
const loading = computed(() => !data.value && !error.value && (pending.value || status.value === 'idle'))
|
|
20
27
|
|
|
21
28
|
function fmtDate(iso) {
|
|
22
29
|
if (!iso) return '—'
|
|
@@ -67,7 +74,7 @@ const sides = computed(() => {
|
|
|
67
74
|
</button>
|
|
68
75
|
</header>
|
|
69
76
|
|
|
70
|
-
<div v-if="
|
|
77
|
+
<div v-if="loading" class="p-4 text-sm text-muted-foreground">Cargando…</div>
|
|
71
78
|
<div v-else-if="error" class="p-4 text-sm text-red-600 dark:text-red-400">
|
|
72
79
|
No se pudieron cargar las versiones ({{ error.statusCode ?? 'error' }}).
|
|
73
80
|
</div>
|
|
@@ -11,7 +11,7 @@ const props = withDefaults(defineProps<{
|
|
|
11
11
|
loading?: boolean
|
|
12
12
|
/** Falló la carga de opciones: muestra mensaje + botón Reintentar (emite 'retry'). */
|
|
13
13
|
loadError?: boolean | string
|
|
14
|
-
/** Permite volver a "
|
|
14
|
+
/** Permite volver a "Selecciona…" (blanquear la selección). Default true. */
|
|
15
15
|
clearable?: boolean
|
|
16
16
|
}>(), {
|
|
17
17
|
clearable: true,
|
|
@@ -27,16 +27,18 @@ const loadErrorMessage = computed(() =>
|
|
|
27
27
|
typeof props.loadError === 'string' && props.loadError ? props.loadError : 'No se pudieron cargar las opciones.'
|
|
28
28
|
)
|
|
29
29
|
|
|
30
|
-
const emptyLabel = computed(() => props.placeholder
|
|
30
|
+
const emptyLabel = computed(() => props.placeholder || 'Selecciona…')
|
|
31
31
|
|
|
32
32
|
/**
|
|
33
|
-
* Config de HSSelect.
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
* la
|
|
33
|
+
* Config de HSSelect. El `placeholder` se pasa SIEMPRE: si falta, Preline muestra su
|
|
34
|
+
* default en inglés ("Select..."). Si `clearable`, además `optionAllowEmptyOption`:
|
|
35
|
+
* la opción vacía ("Selecciona…") queda como opción normal (re-seleccionable) y el
|
|
36
|
+
* usuario puede blanquear la selección; sin eso Preline la filtra del dropdown. Si
|
|
37
|
+
* no es clearable, la vacía solo actúa de placeholder.
|
|
37
38
|
*/
|
|
38
39
|
const hsConfig = computed(() => JSON.stringify({
|
|
39
|
-
|
|
40
|
+
placeholder: emptyLabel.value,
|
|
41
|
+
...(props.clearable ? { optionAllowEmptyOption: true } : {}),
|
|
40
42
|
dropdownScope: 'window',
|
|
41
43
|
toggleTag: '<button type="button" aria-expanded="false"></button>',
|
|
42
44
|
toggleClasses: 'innertia-field hs-select-disabled:pointer-events-none hs-select-disabled:opacity-50 relative pe-9 flex gap-x-2 items-center text-nowrap cursor-pointer text-start',
|
|
@@ -56,11 +56,19 @@ const props = defineProps({
|
|
|
56
56
|
states: { type: Array, required: true },
|
|
57
57
|
moveMutation: { type: Function, default: null },
|
|
58
58
|
|
|
59
|
+
// Bloquea un arrastre ANTES de soltar: (row, fromState, toState) => boolean, síncrona.
|
|
60
|
+
// Si retorna false la columna no se resalta, el cursor indica "no permitido" y el drop
|
|
61
|
+
// no hace nada (no hay optimistic update, ni emit('move'), ni llamada al backend).
|
|
62
|
+
// Solo se consulta al cambiar de columna; reordenar dentro de la misma no pasa por acá.
|
|
63
|
+
canDrop: { type: Function, default: null },
|
|
64
|
+
|
|
59
65
|
// Endpoint para persistir reorden (POST). Si null → solo cross-column, sin placeholder.
|
|
60
66
|
reorderEndpoint: { type: String, default: null },
|
|
61
67
|
|
|
62
68
|
// Toolbar visibility
|
|
63
69
|
showSearch: { type: Boolean, default: true },
|
|
70
|
+
// Término con el que parte el buscador. Solo se lee al montar.
|
|
71
|
+
initialSearch: { type: String, default: '' },
|
|
64
72
|
searchPlaceholder:{ type: String, default: 'Buscar...' },
|
|
65
73
|
showColumns: { type: Boolean, default: true },
|
|
66
74
|
showReloadButton: { type: Boolean, default: true },
|
|
@@ -139,7 +147,7 @@ const rows = ref([])
|
|
|
139
147
|
const meta = ref(null)
|
|
140
148
|
const loading = ref(false)
|
|
141
149
|
const isFetching = ref(false)
|
|
142
|
-
const search = ref('')
|
|
150
|
+
const search = ref(props.initialSearch ?? '')
|
|
143
151
|
const isDataFromCache = ref(false)
|
|
144
152
|
|
|
145
153
|
// Visibilidad de columnas (estados) — { [stateKey]: boolean }
|
|
@@ -408,6 +416,8 @@ const loadFromCache = () => {
|
|
|
408
416
|
sessionStorage.removeItem(cacheKey.value)
|
|
409
417
|
return false
|
|
410
418
|
}
|
|
419
|
+
// Con búsqueda inicial, un caché de otro término no sirve: se pide de nuevo.
|
|
420
|
+
if (props.initialSearch && (cached.search ?? '') !== props.initialSearch) return false
|
|
411
421
|
rows.value = cached.rows ?? []
|
|
412
422
|
meta.value = cached.meta ?? null
|
|
413
423
|
stateVisibility.value = cached.stateVisibility ?? stateVisibility.value
|
|
@@ -457,7 +467,24 @@ const onDragStart = (row, state) => {
|
|
|
457
467
|
draggedId.value = row.id
|
|
458
468
|
draggedFrom.value = state
|
|
459
469
|
}
|
|
470
|
+
// ¿Se puede soltar la tarjeta arrastrada en `state`? Sin prop `canDrop` siempre sí.
|
|
471
|
+
// Sin preventDefault en dragover el navegador rechaza el drop y muestra "no permitido".
|
|
472
|
+
const isDropAllowed = (state) => {
|
|
473
|
+
if (!props.canDrop || !draggedId.value || draggedFrom.value === state) return true
|
|
474
|
+
const row = rows.value.find(r => r.id === draggedId.value)
|
|
475
|
+
if (!row) return true
|
|
476
|
+
try {
|
|
477
|
+
return props.canDrop(row, draggedFrom.value, state) !== false
|
|
478
|
+
} catch (e) {
|
|
479
|
+
console.error('[KanbanStandard] canDrop falló, se bloquea el arrastre:', e)
|
|
480
|
+
return false
|
|
481
|
+
}
|
|
482
|
+
}
|
|
460
483
|
const onDragOver = (e, state) => {
|
|
484
|
+
if (!isDropAllowed(state)) {
|
|
485
|
+
if (dragOverState.value === state) { dragOverState.value = null; dragOverIndex.value = null }
|
|
486
|
+
return
|
|
487
|
+
}
|
|
461
488
|
e.preventDefault()
|
|
462
489
|
if (dragOverState.value !== state) dragOverState.value = state
|
|
463
490
|
if (!props.reorderEndpoint) return
|
|
@@ -483,6 +510,7 @@ const onDragEnd = () => {
|
|
|
483
510
|
// Solo escribe el índice si cambió (evita reactividad redundante = menos re-render/parpadeo).
|
|
484
511
|
const onCardDragOver = (e, state, index) => {
|
|
485
512
|
if (!props.reorderEndpoint) return
|
|
513
|
+
if (!isDropAllowed(state)) return // burbujea a la columna, que tampoco acepta el drop
|
|
486
514
|
e.preventDefault()
|
|
487
515
|
e.stopPropagation()
|
|
488
516
|
if (dragOverState.value !== state) dragOverState.value = state
|
|
@@ -493,6 +521,8 @@ const onCardDragOver = (e, state, index) => {
|
|
|
493
521
|
}
|
|
494
522
|
|
|
495
523
|
const onDrop = async (targetState) => {
|
|
524
|
+
// Defensa: el navegador ya no dispara drop si dragover no lo aceptó, pero se revalida.
|
|
525
|
+
const allowed = isDropAllowed(targetState)
|
|
496
526
|
const id = draggedId.value
|
|
497
527
|
const fromState = draggedFrom.value
|
|
498
528
|
const dropIndex = dragOverIndex.value
|
|
@@ -500,7 +530,7 @@ const onDrop = async (targetState) => {
|
|
|
500
530
|
dragOverIndex.value = null
|
|
501
531
|
draggedId.value = null
|
|
502
532
|
draggedFrom.value = null
|
|
503
|
-
if (!id) return
|
|
533
|
+
if (!id || !allowed) return
|
|
504
534
|
|
|
505
535
|
// Modo reorden (prop seteada): calcula vecinos y persiste posición.
|
|
506
536
|
if (props.reorderEndpoint) {
|
|
@@ -14,6 +14,9 @@ const props = defineProps({
|
|
|
14
14
|
clickRowToOpen: { type: Boolean, default: false },
|
|
15
15
|
searchPlaceholder: { type: String, default: 'Buscar...' },
|
|
16
16
|
showSearch: { type: Boolean, default: true },
|
|
17
|
+
// Término con el que parte el buscador (ej. al llegar desde la búsqueda global).
|
|
18
|
+
// Solo se lee al montar; después manda lo que escriba el usuario.
|
|
19
|
+
initialSearch: { type: String, default: '' },
|
|
17
20
|
showFilters: { type: Boolean, default: true },
|
|
18
21
|
// Realtime: auto-suscripción a los canales que el backend expone en meta.channels
|
|
19
22
|
// (`entity.{tabla}.changed` → reload()). realtimeChannel queda como override manual
|
|
@@ -151,7 +154,7 @@ const forwardedSlots = computed(() => {
|
|
|
151
154
|
return Object.fromEntries(Object.entries(slots).filter(([k]) => !excluded.has(k)))
|
|
152
155
|
})
|
|
153
156
|
|
|
154
|
-
const search = ref('')
|
|
157
|
+
const search = ref(props.initialSearch ?? '')
|
|
155
158
|
const activeFilters = ref({})
|
|
156
159
|
const tableRef = ref(null)
|
|
157
160
|
const prefsLoaded = ref(false)
|
|
@@ -764,7 +764,8 @@ defineExpose({
|
|
|
764
764
|
{{ pagination.pageIndex + 1 }}
|
|
765
765
|
</span>
|
|
766
766
|
<span class="text-[10px] font-bold text-muted-foreground uppercase mx-1">de</span>
|
|
767
|
-
|
|
767
|
+
<!-- Sin registros getPageCount() da 0: se muestra "1 de 1", no "1 de 0". -->
|
|
768
|
+
<span class="text-[10px] font-bold text-muted-foreground">{{ Math.max(1, table.getPageCount()) }}</span>
|
|
768
769
|
</div>
|
|
769
770
|
<button
|
|
770
771
|
type="button"
|
|
@@ -38,7 +38,11 @@ const formats = [
|
|
|
38
38
|
{ value: 'json', label: 'JSON' },
|
|
39
39
|
]
|
|
40
40
|
|
|
41
|
+
// Con columnas para elegir, exportar exige al menos una marcada.
|
|
42
|
+
const noColumnsSelected = computed(() => props.columns.length > 0 && selectedColumns.value.length === 0)
|
|
43
|
+
|
|
41
44
|
const doExport = () => {
|
|
45
|
+
if (noColumnsSelected.value) return
|
|
42
46
|
props.tableRef?.exportTable(format.value, true, true, selectedColumns.value)
|
|
43
47
|
isOpen.value = false
|
|
44
48
|
}
|
|
@@ -158,10 +162,14 @@ defineExpose({ open: () => { isOpen.value = true } })
|
|
|
158
162
|
</div>
|
|
159
163
|
|
|
160
164
|
<!-- Export button -->
|
|
165
|
+
<p v-if="noColumnsSelected" class="mb-2 px-1 text-xs text-muted-foreground" role="alert">
|
|
166
|
+
Selecciona al menos una columna para exportar.
|
|
167
|
+
</p>
|
|
161
168
|
<button
|
|
162
169
|
type="button"
|
|
170
|
+
:disabled="noColumnsSelected"
|
|
163
171
|
@click="doExport"
|
|
164
|
-
class="w-full py-1.5 px-3 rounded-control bg-primary hover:bg-primary/90 text-white text-sm font-medium transition-colors inline-flex items-center justify-center gap-2"
|
|
172
|
+
class="w-full py-1.5 px-3 rounded-control bg-primary hover:bg-primary/90 text-white text-sm font-medium transition-colors inline-flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-primary"
|
|
165
173
|
>
|
|
166
174
|
<IconDownload class="size-4" stroke="1.5" />
|
|
167
175
|
Exportar
|
|
@@ -48,6 +48,11 @@ const props = defineProps({
|
|
|
48
48
|
// Empty state.
|
|
49
49
|
emptyMessage: { type: String, default: 'No hay registros.' },
|
|
50
50
|
|
|
51
|
+
// Nombre de lo que cuenta el pie ("12 elementos"). El producto puede poner el suyo
|
|
52
|
+
// (ej. item-label="objetivo" item-label-plural="objetivos").
|
|
53
|
+
itemLabel: { type: String, default: 'elemento' },
|
|
54
|
+
itemLabelPlural: { type: String, default: 'elementos' },
|
|
55
|
+
|
|
51
56
|
// Variante visual:
|
|
52
57
|
// 'table' — clásico con filas, columnas y bordes (default)
|
|
53
58
|
// 'list' — compacto tipo file-tree explorer (sin tabla, sin bordes de fila)
|
|
@@ -969,7 +974,7 @@ defineExpose({
|
|
|
969
974
|
|
|
970
975
|
<!-- Total nodes -->
|
|
971
976
|
<p class="text-sm text-foreground font-medium">
|
|
972
|
-
{{ totalRendered }} {{ totalRendered === 1 ?
|
|
977
|
+
{{ totalRendered }} {{ totalRendered === 1 ? itemLabel : itemLabelPlural }}
|
|
973
978
|
</p>
|
|
974
979
|
|
|
975
980
|
<!-- Cache badge (instant) -->
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { describe, it, expect, beforeAll } from 'vitest'
|
|
2
|
+
import * as vue from 'vue'
|
|
3
|
+
|
|
4
|
+
// useForm usa auto-imports de Nuxt (reactive, watch, toRefs): se exponen como globales.
|
|
5
|
+
let useForm: any
|
|
6
|
+
beforeAll(async () => {
|
|
7
|
+
Object.assign(globalThis, { reactive: vue.reactive, watch: vue.watch, toRefs: vue.toRefs })
|
|
8
|
+
;({ useForm } = await import('../useForm.js'))
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
describe('useForm: limpieza de errores al cambiar el valor', () => {
|
|
12
|
+
it('borra el error de "obligatorio" al elegir un valor', () => {
|
|
13
|
+
const { values, errors, validate } = useForm({ subject_id: { value: null, rules: ['required'] } })
|
|
14
|
+
expect(validate()).toBe(false)
|
|
15
|
+
expect(errors.subject_id).toEqual(['Este campo es obligatorio'])
|
|
16
|
+
values.subject_id = 'abc'
|
|
17
|
+
expect(errors.subject_id).toEqual([])
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
it('borra el error del backend (addError) al editar el campo', () => {
|
|
21
|
+
const { values, errors, addError } = useForm({ email: { value: 'a@b.cl' } })
|
|
22
|
+
addError('email', 'validation.unique')
|
|
23
|
+
expect(errors.email).toEqual(['Ya está registrado'])
|
|
24
|
+
values.email = 'c@d.cl'
|
|
25
|
+
expect(errors.email).toEqual([])
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('no pierde un error agregado justo después de asignar el valor', () => {
|
|
29
|
+
const { values, errors, addError } = useForm({ password: { value: 'x' } })
|
|
30
|
+
values.password = ''
|
|
31
|
+
addError('password', 'La contraseña no es válida')
|
|
32
|
+
expect(errors.password).toEqual(['La contraseña no es válida'])
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('no toca los errores de otros campos', () => {
|
|
36
|
+
const { values, errors, validate } = useForm({
|
|
37
|
+
a: { value: '', rules: ['required'] },
|
|
38
|
+
b: { value: '', rules: ['required'] },
|
|
39
|
+
})
|
|
40
|
+
validate()
|
|
41
|
+
values.a = 'x'
|
|
42
|
+
expect(errors.a).toEqual([])
|
|
43
|
+
expect(errors.b).toEqual(['Este campo es obligatorio'])
|
|
44
|
+
})
|
|
45
|
+
})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { shouldThrowOnUnauthorized, unauthorizedError, SESSION_EXPIRED_MESSAGE } from '../apiUnauthorized.js'
|
|
3
|
+
|
|
4
|
+
describe('shouldThrowOnUnauthorized (contrato de useApi ante 401)', () => {
|
|
5
|
+
it('en el cliente, las mutaciones lanzan (no se confunden con éxito)', () => {
|
|
6
|
+
for (const m of ['POST', 'PUT', 'PATCH', 'DELETE', 'post']) {
|
|
7
|
+
expect(shouldThrowOnUnauthorized(m, {}, true)).toBe(true)
|
|
8
|
+
}
|
|
9
|
+
})
|
|
10
|
+
it('GET devuelve null (fetchMe/auth-init/queries dependen de eso)', () => {
|
|
11
|
+
expect(shouldThrowOnUnauthorized('GET', {}, true)).toBe(false)
|
|
12
|
+
})
|
|
13
|
+
it('en SSR nunca lanza por defecto (evita 500 en vez del redirect)', () => {
|
|
14
|
+
expect(shouldThrowOnUnauthorized('POST', {}, false)).toBe(false)
|
|
15
|
+
})
|
|
16
|
+
it('options.throwOnUnauthorized manda sobre el default', () => {
|
|
17
|
+
expect(shouldThrowOnUnauthorized('GET', { throwOnUnauthorized: true }, true)).toBe(true)
|
|
18
|
+
expect(shouldThrowOnUnauthorized('POST', { throwOnUnauthorized: false }, true)).toBe(false)
|
|
19
|
+
})
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
describe('unauthorizedError', () => {
|
|
23
|
+
it('tiene la forma de los errores HTTP de useApi', () => {
|
|
24
|
+
const e: any = unauthorizedError()
|
|
25
|
+
expect(e).toBeInstanceOf(Error)
|
|
26
|
+
expect(e.status).toBe(401)
|
|
27
|
+
expect(e.data.message).toBe(SESSION_EXPIRED_MESSAGE)
|
|
28
|
+
})
|
|
29
|
+
})
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Contrato de useApi ante un 401. Fuera del auto-import de Nuxt (subcarpeta sin
|
|
2
|
+
// index): son helpers internos, testeables sin el runtime de Nuxt.
|
|
3
|
+
|
|
4
|
+
export const SESSION_EXPIRED_MESSAGE = 'Tu sesión expiró. Vuelve a ingresar; los cambios no se guardaron.'
|
|
5
|
+
|
|
6
|
+
const MUTATING_METHODS = ['POST', 'PUT', 'PATCH', 'DELETE']
|
|
7
|
+
|
|
8
|
+
/** ¿Un 401 debe lanzar (true) o devolver null (false)? Ver contrato en makeRequest. */
|
|
9
|
+
export function shouldThrowOnUnauthorized(method, options = {}, isClient = import.meta.client) {
|
|
10
|
+
if (typeof options?.throwOnUnauthorized === 'boolean') return options.throwOnUnauthorized
|
|
11
|
+
return !!isClient && MUTATING_METHODS.includes(String(method).toUpperCase())
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Error de sesión expirada con la forma de los errores HTTP de useApi (status + data.message). */
|
|
15
|
+
export function unauthorizedError() {
|
|
16
|
+
const err = new Error('Unauthenticated')
|
|
17
|
+
err.status = 401
|
|
18
|
+
err.data = { message: SESSION_EXPIRED_MESSAGE }
|
|
19
|
+
return err
|
|
20
|
+
}
|
|
21
|
+
|
package/composables/useApi.js
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
// useRequestInterceptors auto-imported from nuxt-core
|
|
2
2
|
import { deleteCookie } from 'h3'
|
|
3
3
|
// useAuthStore auto-imported from this package
|
|
4
|
+
import { shouldThrowOnUnauthorized, unauthorizedError } from './internal/apiUnauthorized.js'
|
|
5
|
+
|
|
6
|
+
// Un solo aviso aunque fallen varias requests en paralelo.
|
|
7
|
+
let lastExpiredNoticeAt = 0
|
|
8
|
+
function notifySessionExpired() {
|
|
9
|
+
const now = Date.now()
|
|
10
|
+
if (now - lastExpiredNoticeAt < 5000) return
|
|
11
|
+
lastExpiredNoticeAt = now
|
|
12
|
+
try {
|
|
13
|
+
useToast().warning('Tu sesión expiró. Vuelve a ingresar.')
|
|
14
|
+
} catch { /* sin pinia/toast disponible: el redirect basta */ }
|
|
15
|
+
}
|
|
4
16
|
|
|
5
17
|
export function useApi() {
|
|
6
18
|
const config = useRuntimeConfig()
|
|
@@ -69,6 +81,13 @@ export function useApi() {
|
|
|
69
81
|
const response = await fetch(url, fetchOptions)
|
|
70
82
|
|
|
71
83
|
if (response.status === 401) {
|
|
84
|
+
// Contrato ante 401:
|
|
85
|
+
// - GET (y cualquier llamada SSR): devuelve null (fetchMe, auth-init y las
|
|
86
|
+
// queries dependen de eso; en SSR lanzar daría un 500 en vez del redirect).
|
|
87
|
+
// - Mutaciones en el cliente (POST/PUT/PATCH/DELETE): LANZA un error con
|
|
88
|
+
// status 401. Devolver null hacía que useMutation/try-catch lo tomaran como
|
|
89
|
+
// éxito ("Guardado" sin guardar nada). Override: options.throwOnUnauthorized.
|
|
90
|
+
const shouldThrow = shouldThrowOnUnauthorized(method, options)
|
|
72
91
|
const authStore = useAuthStore()
|
|
73
92
|
authStore.logout()
|
|
74
93
|
// La sesión sellada quedó inválida (token revocado, usuario borrado, BD
|
|
@@ -83,8 +102,17 @@ export function useApi() {
|
|
|
83
102
|
}
|
|
84
103
|
const current = requestEvent ? requestEvent.path?.split('?')[0] : router?.currentRoute.value.path
|
|
85
104
|
// Ya en una página de login (la del producto o /platform/login): no redirigir.
|
|
86
|
-
|
|
87
|
-
|
|
105
|
+
const onLoginPage = current === loginPath || !!current?.endsWith('/login')
|
|
106
|
+
if (import.meta.client && !onLoginPage) notifySessionExpired()
|
|
107
|
+
if (!shouldThrow) {
|
|
108
|
+
if (!onLoginPage) await navigateTo(loginPath)
|
|
109
|
+
return null
|
|
110
|
+
}
|
|
111
|
+
// Al lanzar NO se espera la navegación: así el catch del llamador muestra el
|
|
112
|
+
// error (y conserva lo escrito) antes de que una guarda de "cambios sin
|
|
113
|
+
// guardar" pregunte si descartarlos.
|
|
114
|
+
if (!onLoginPage) Promise.resolve(navigateTo(loginPath)).catch(() => { /* navegación cancelada */ })
|
|
115
|
+
throw unauthorizedError()
|
|
88
116
|
}
|
|
89
117
|
|
|
90
118
|
const contentType = response.headers.get('content-type') ?? ''
|
package/composables/useForm.js
CHANGED
|
@@ -44,6 +44,16 @@ export function useForm(formDefinition, options = {}) {
|
|
|
44
44
|
errors[field] = []
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
+
// Al cambiar el valor de un campo se borra su error (de validación local o del
|
|
48
|
+
// 422 del backend): el mensaje no debe quedar pegado bajo un campo ya corregido
|
|
49
|
+
// hasta el próximo envío. Se vuelve a validar al enviar. flush 'sync': se limpia
|
|
50
|
+
// en el acto, así un `values.x = …; addError('x', …)` seguido no pierde el error nuevo.
|
|
51
|
+
for (const field in formDefinition) {
|
|
52
|
+
watch(() => form[field], () => {
|
|
53
|
+
if (errors[field]?.length) errors[field] = []
|
|
54
|
+
}, { deep: true, flush: 'sync' })
|
|
55
|
+
}
|
|
56
|
+
|
|
47
57
|
const reset = () => {
|
|
48
58
|
for (const field in formDefinition) {
|
|
49
59
|
form[field] = formDefinition[field]?.value !== undefined ? formDefinition[field].value : ''
|
package/nuxt.config.ts
CHANGED
|
@@ -52,6 +52,14 @@ export default defineNuxtConfig({
|
|
|
52
52
|
packages: {},
|
|
53
53
|
detailsPath: 'platform/version',
|
|
54
54
|
},
|
|
55
|
+
// Privado. Renovación deslizante del JWT en el BFF (server/utils/sessionToken.ts):
|
|
56
|
+
// renueva contra Laravel POST {path} cuando al token le quedan < 10 min (o < 1/3
|
|
57
|
+
// de su vida). NUXT_AUTH_REFRESH_ENABLED=false la apaga; NUXT_AUTH_REFRESH_PATH
|
|
58
|
+
// cambia el endpoint si el producto montó sessionRoutes con otro prefijo.
|
|
59
|
+
authRefresh: {
|
|
60
|
+
enabled: true,
|
|
61
|
+
path: 'auth/refresh',
|
|
62
|
+
},
|
|
55
63
|
public: {
|
|
56
64
|
loginPath: '/backoffice/login',
|
|
57
65
|
homePath: '/backoffice',
|
package/package.json
CHANGED
|
@@ -1,12 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { resolveSessionToken, persistRotatedSession } from '../utils/sessionToken'
|
|
2
2
|
|
|
3
3
|
// Lee la sesión sellada una vez por request y deja el token en event.context
|
|
4
4
|
// para que useApi (SSR) adjunte el Bearer en llamadas directas a Laravel.
|
|
5
|
+
// Si al token le queda poco, lo renueva (renovación deslizante): una sesión con
|
|
6
|
+
// uso activo ya no expira a los 60 min fijos del JWT.
|
|
5
7
|
// Defensivo: si no hay secret/sesión, sigue sin token (no revienta el request).
|
|
6
8
|
export default defineEventHandler(async (event) => {
|
|
9
|
+
const path = event.path || ''
|
|
10
|
+
// Las rutas /_auth/** escriben/borran la sesión por su cuenta (login, logout,
|
|
11
|
+
// contexto): no se mezclan con una renovación. Los assets no necesitan sesión.
|
|
12
|
+
if (path.startsWith('/_auth/') || path.startsWith('/_nuxt/') || path.startsWith('/_version')) return
|
|
7
13
|
try {
|
|
8
|
-
const
|
|
14
|
+
const token = await resolveSessionToken(event)
|
|
9
15
|
if (token) event.context.authToken = token
|
|
16
|
+
// El BFF (/api/**) escribe la cookie renovada después de copiar los headers de
|
|
17
|
+
// Laravel (que pisarían el Set-Cookie); el resto (SSR de páginas), acá.
|
|
18
|
+
if (!path.startsWith('/api/')) await persistRotatedSession(event)
|
|
10
19
|
} catch {
|
|
11
20
|
// sin NUXT_SESSION_PASSWORD o sin sesión válida → seguir sin token
|
|
12
21
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { defineEventHandler, readBody, createError } from 'h3'
|
|
2
2
|
import { readSession, writeSession } from '../../utils/session'
|
|
3
|
+
import { latestSessionToken } from '../../utils/sessionToken'
|
|
3
4
|
|
|
4
5
|
// Cambia el contexto activo en la sesión (el modal "¿seguro?" es UX de front).
|
|
5
6
|
export default defineEventHandler(async (event) => {
|
|
6
7
|
const { context } = await readBody(event)
|
|
7
8
|
const current = await readSession(event)
|
|
8
9
|
if (!current.token) throw createError({ statusCode: 401, statusMessage: 'no_session' })
|
|
9
|
-
|
|
10
|
+
// Con el token vigente: si se renovó hace poco, no reescribir la cookie con el viejo.
|
|
11
|
+
await writeSession(event, { ...current, token: latestSessionToken(current.token), currentContext: context })
|
|
10
12
|
return { ok: true, currentContext: context }
|
|
11
13
|
})
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { defineEventHandler } from 'h3'
|
|
2
2
|
import { readSession, clearSession } from '../../utils/session'
|
|
3
3
|
import { buildAuthHeaders } from '../../utils/bff'
|
|
4
|
+
import { latestSessionToken } from '../../utils/sessionToken'
|
|
4
5
|
|
|
5
6
|
// Best-effort: avisa a Laravel con el Bearer de la sesión, luego limpia la sesión.
|
|
6
7
|
export default defineEventHandler(async (event) => {
|
|
7
8
|
const config = useRuntimeConfig(event)
|
|
8
|
-
|
|
9
|
+
// Si el token se renovó hace poco y el browser aún manda el viejo, cerrar el nuevo.
|
|
10
|
+
const token = latestSessionToken((await readSession(event)).token)
|
|
9
11
|
if (token) {
|
|
10
12
|
try {
|
|
11
13
|
await $fetch(`${config.apiInternalUrl}/auth/logout`, {
|
|
@@ -1,22 +1,27 @@
|
|
|
1
1
|
import { defineEventHandler, proxyRequest, getRequestURL } from 'h3'
|
|
2
|
-
import {
|
|
2
|
+
import { clearSession } from '../../utils/session'
|
|
3
3
|
import { resolveApiTarget, buildAuthHeaders } from '../../utils/bff'
|
|
4
|
+
import { resolveSessionToken, persistRotatedSession } from '../../utils/sessionToken'
|
|
4
5
|
|
|
5
6
|
// BFF: reenvía /api/** a Laravel inyectando el Bearer desde la sesión sellada.
|
|
6
7
|
// proxyRequest hace passthrough de método/body/headers y STREAMEA la respuesta
|
|
7
8
|
// (crítico para el SSE del asistente). No se reenvía la cookie de sesión.
|
|
9
|
+
// El token se renueva si está por vencer (ver server/utils/sessionToken.ts).
|
|
8
10
|
export default defineEventHandler(async (event) => {
|
|
9
11
|
const config = useRuntimeConfig(event)
|
|
10
|
-
const
|
|
12
|
+
const token = await resolveSessionToken(event)
|
|
11
13
|
const path = (event.context.params?.path ?? '') as string
|
|
12
14
|
const search = getRequestURL(event).search
|
|
13
15
|
const target = resolveApiTarget(config.apiInternalUrl, path, search)
|
|
14
16
|
return proxyRequest(event, target, {
|
|
15
17
|
headers: buildAuthHeaders(token),
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (token && response.status === 401) clearSession(ev)
|
|
18
|
+
onResponse: async (ev, response) => {
|
|
19
|
+
// Token rechazado por Laravel → la sesión sellada no sirve: borrarla para que
|
|
20
|
+
// /_auth/session deje de reportar authenticated (evita loops de redirección).
|
|
21
|
+
if (token && response.status === 401) return clearSession(ev)
|
|
22
|
+
// Token renovado en este request → reescribir la cookie (después de copiar
|
|
23
|
+
// los headers de Laravel, que pisarían nuestro Set-Cookie).
|
|
24
|
+
await persistRotatedSession(ev)
|
|
20
25
|
},
|
|
21
26
|
})
|
|
22
27
|
})
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { decodeJwtPayload, shouldRefreshToken, createTokenRotator } from '../tokenRefresh'
|
|
3
|
+
|
|
4
|
+
function jwt(payload: Record<string, unknown>): string {
|
|
5
|
+
const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString('base64url')
|
|
6
|
+
return `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64(payload)}.firma`
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
describe('decodeJwtPayload', () => {
|
|
10
|
+
it('lee el payload sin verificar la firma', () => {
|
|
11
|
+
expect(decodeJwtPayload(jwt({ sub: '7', exp: 100 }))).toEqual({ sub: '7', exp: 100 })
|
|
12
|
+
})
|
|
13
|
+
it('devuelve null con basura', () => {
|
|
14
|
+
expect(decodeJwtPayload('no-es-jwt')).toBeNull()
|
|
15
|
+
expect(decodeJwtPayload(undefined)).toBeNull()
|
|
16
|
+
expect(decodeJwtPayload('a.%%%.c')).toBeNull()
|
|
17
|
+
})
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
describe('shouldRefreshToken', () => {
|
|
21
|
+
const iat = 1_000_000
|
|
22
|
+
const ttl60 = (extra = {}) => jwt({ iat, exp: iat + 3600, ...extra })
|
|
23
|
+
|
|
24
|
+
it('no renueva con mucho tiempo por delante', () => {
|
|
25
|
+
expect(shouldRefreshToken(ttl60(), iat + 60)).toBe(false)
|
|
26
|
+
})
|
|
27
|
+
it('renueva cuando quedan menos de 10 minutos', () => {
|
|
28
|
+
expect(shouldRefreshToken(ttl60(), iat + 3600 - 599)).toBe(true)
|
|
29
|
+
})
|
|
30
|
+
it('no renueva un token ya vencido (Laravel no lo acepta)', () => {
|
|
31
|
+
expect(shouldRefreshToken(ttl60(), iat + 3601)).toBe(false)
|
|
32
|
+
})
|
|
33
|
+
it('no renueva tokens de plataforma (identidad separada)', () => {
|
|
34
|
+
expect(shouldRefreshToken(ttl60({ platform: true }), iat + 3500)).toBe(false)
|
|
35
|
+
})
|
|
36
|
+
it('con TTL corto usa 1/3 de la vida como ventana (no renueva en cada request)', () => {
|
|
37
|
+
const short = jwt({ iat, exp: iat + 300 }) // 5 min
|
|
38
|
+
expect(shouldRefreshToken(short, iat + 60)).toBe(false)
|
|
39
|
+
expect(shouldRefreshToken(short, iat + 250)).toBe(true)
|
|
40
|
+
})
|
|
41
|
+
it('sin exp no renueva', () => {
|
|
42
|
+
expect(shouldRefreshToken(jwt({ iat }), iat)).toBe(false)
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
describe('createTokenRotator', () => {
|
|
47
|
+
it('requests en paralelo con el mismo token comparten un solo refresh', async () => {
|
|
48
|
+
let resolve!: (v: string) => void
|
|
49
|
+
const refresh = vi.fn(() => new Promise<string>(r => { resolve = r }))
|
|
50
|
+
const r = createTokenRotator({ refresh })
|
|
51
|
+
const a = r.rotate('viejo')
|
|
52
|
+
const b = r.rotate('viejo')
|
|
53
|
+
resolve('nuevo')
|
|
54
|
+
expect(await a).toBe('nuevo')
|
|
55
|
+
expect(await b).toBe('nuevo')
|
|
56
|
+
expect(refresh).toHaveBeenCalledTimes(1)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('un request tardío con el token viejo recibe el nuevo desde la caché', async () => {
|
|
60
|
+
const refresh = vi.fn(async () => 'nuevo')
|
|
61
|
+
let t = 0
|
|
62
|
+
const r = createTokenRotator({ refresh, graceMs: 1000, now: () => t })
|
|
63
|
+
await r.rotate('viejo')
|
|
64
|
+
expect(r.rotatedFrom('viejo')).toBe('nuevo')
|
|
65
|
+
expect(await r.rotate('viejo')).toBe('nuevo')
|
|
66
|
+
expect(refresh).toHaveBeenCalledTimes(1)
|
|
67
|
+
t = 5000
|
|
68
|
+
expect(r.rotatedFrom('viejo')).toBeNull()
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('si el refresh falla devuelve null (se sigue con el token actual)', async () => {
|
|
72
|
+
const r = createTokenRotator({ refresh: async () => { throw new Error('401') } })
|
|
73
|
+
expect(await r.rotate('viejo')).toBeNull()
|
|
74
|
+
expect(r.rotatedFrom('viejo')).toBeNull()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
it('tras un refresh fallido no reintenta con el mismo token hasta que pase el backoff', async () => {
|
|
78
|
+
let t = 0
|
|
79
|
+
const refresh = vi.fn(async () => { throw new Error('404') })
|
|
80
|
+
const r = createTokenRotator({ refresh, failureBackoffMs: 30_000, now: () => t })
|
|
81
|
+
expect(await r.rotate('viejo')).toBeNull()
|
|
82
|
+
t = 10_000
|
|
83
|
+
expect(await r.rotate('viejo')).toBeNull()
|
|
84
|
+
expect(refresh).toHaveBeenCalledTimes(1)
|
|
85
|
+
t = 31_000
|
|
86
|
+
await r.rotate('viejo')
|
|
87
|
+
expect(refresh).toHaveBeenCalledTimes(2)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('pasa el contexto al refresh', async () => {
|
|
91
|
+
const refresh = vi.fn(async (_t: string, ctx?: string) => `nuevo-${ctx}`)
|
|
92
|
+
const r = createTokenRotator<string>({ refresh })
|
|
93
|
+
expect(await r.rotate('viejo', 'evento')).toBe('nuevo-evento')
|
|
94
|
+
})
|
|
95
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { getRequestHeader } from 'h3'
|
|
2
|
+
import type { H3Event } from 'h3'
|
|
3
|
+
import { readSession, writeSession } from './session'
|
|
4
|
+
import type { SessionData } from './session'
|
|
5
|
+
import { buildAuthHeaders, forwardClientHeaders } from './bff'
|
|
6
|
+
import { createTokenRotator, shouldRefreshToken } from './tokenRefresh'
|
|
7
|
+
|
|
8
|
+
// Token de la sesión sellada con renovación deslizante (ver tokenRefresh.ts).
|
|
9
|
+
// Un rotador por proceso Nitro: deduplica refrescos concurrentes del mismo token.
|
|
10
|
+
let rotator: ReturnType<typeof createTokenRotator<H3Event>> | null = null
|
|
11
|
+
|
|
12
|
+
function getRotator() {
|
|
13
|
+
if (!rotator) {
|
|
14
|
+
rotator = createTokenRotator<H3Event>({
|
|
15
|
+
refresh: async (token, ev) => {
|
|
16
|
+
if (!ev) return null
|
|
17
|
+
const config = useRuntimeConfig(ev)
|
|
18
|
+
const path = String((config as any).authRefresh?.path || 'auth/refresh').replace(/^\/+/, '')
|
|
19
|
+
const res: any = await $fetch(`${String(config.apiInternalUrl).replace(/\/+$/, '')}/${path}`, {
|
|
20
|
+
method: 'POST',
|
|
21
|
+
// Un refresh colgado no debe bloquear el request del usuario: se sigue con el token actual.
|
|
22
|
+
timeout: 5000,
|
|
23
|
+
headers: {
|
|
24
|
+
...buildAuthHeaders(token),
|
|
25
|
+
Accept: 'application/json',
|
|
26
|
+
...forwardClientHeaders(n => getRequestHeader(ev, n)),
|
|
27
|
+
},
|
|
28
|
+
})
|
|
29
|
+
return typeof res?.token === 'string' ? res.token : null
|
|
30
|
+
},
|
|
31
|
+
})
|
|
32
|
+
}
|
|
33
|
+
return rotator
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Devuelve el token vigente de la sesión del request, renovándolo si está por
|
|
38
|
+
* vencer. Si se renovó, deja la sesión nueva pendiente en event.context para que
|
|
39
|
+
* se escriba la cookie con `persistRotatedSession` (en el momento adecuado: el
|
|
40
|
+
* proxy la escribe después de copiar los headers de Laravel, que pisarían el
|
|
41
|
+
* Set-Cookie). Se resuelve una sola vez por request.
|
|
42
|
+
*/
|
|
43
|
+
export async function resolveSessionToken(event: H3Event): Promise<string | undefined> {
|
|
44
|
+
const ctx = event.context as any
|
|
45
|
+
if (ctx.innertiaTokenResolved) return ctx.innertiaToken
|
|
46
|
+
ctx.innertiaTokenResolved = true
|
|
47
|
+
|
|
48
|
+
const session: SessionData = await readSession(event)
|
|
49
|
+
let token = session.token
|
|
50
|
+
if (!token) return (ctx.innertiaToken = undefined)
|
|
51
|
+
|
|
52
|
+
const r = getRotator()
|
|
53
|
+
// Token recién rotado por otro request en paralelo → usar el nuevo.
|
|
54
|
+
let fresh = r.rotatedFrom(token)
|
|
55
|
+
const enabled = (useRuntimeConfig(event) as any).authRefresh?.enabled !== false
|
|
56
|
+
if (!fresh && enabled && shouldRefreshToken(token, Math.floor(Date.now() / 1000))) {
|
|
57
|
+
try { fresh = await r.rotate(token, event) } catch { fresh = null }
|
|
58
|
+
}
|
|
59
|
+
if (fresh && fresh !== token) {
|
|
60
|
+
token = fresh
|
|
61
|
+
ctx.innertiaPendingSession = { ...session, token: fresh }
|
|
62
|
+
}
|
|
63
|
+
return (ctx.innertiaToken = token)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Escribe la cookie sellada con el token renovado, si hubo renovación en este request. */
|
|
67
|
+
export async function persistRotatedSession(event: H3Event): Promise<void> {
|
|
68
|
+
const ctx = event.context as any
|
|
69
|
+
const pending: SessionData | undefined = ctx.innertiaPendingSession
|
|
70
|
+
if (!pending) return
|
|
71
|
+
ctx.innertiaPendingSession = undefined
|
|
72
|
+
try { await writeSession(event, pending) } catch { /* sin secret: seguir sin reescribir */ }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Token más reciente para un token de cookie: si fue rotado hace poco (el browser
|
|
77
|
+
* todavía manda la cookie vieja), devuelve el nuevo. Lo usan logout/contexto para
|
|
78
|
+
* no operar sobre un token que Laravel ya invalidó al refrescar.
|
|
79
|
+
*/
|
|
80
|
+
export function latestSessionToken(token?: string): string | undefined {
|
|
81
|
+
if (!token || !rotator) return token
|
|
82
|
+
return rotator.rotatedFrom(token) ?? token
|
|
83
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// Renovación deslizante del JWT de la sesión sellada (lógica pura, sin h3).
|
|
2
|
+
//
|
|
3
|
+
// Laravel emite el JWT con un TTL fijo (config/jwt.php, default 60 min) y solo deja
|
|
4
|
+
// refrescarlo mientras siga vigente (POST auth/refresh invalida el token viejo y
|
|
5
|
+
// devuelve uno nuevo). Sin renovación, una sesión con uso activo moría al minuto 60
|
|
6
|
+
// y el siguiente "Guardar" terminaba en 401 → login, perdiendo lo escrito.
|
|
7
|
+
// El BFF renueva el token cuando le queda poco, mientras el usuario sigue activo.
|
|
8
|
+
|
|
9
|
+
export interface JwtPayload {
|
|
10
|
+
exp?: number
|
|
11
|
+
iat?: number
|
|
12
|
+
nbf?: number
|
|
13
|
+
platform?: boolean
|
|
14
|
+
[key: string]: unknown
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Decodifica el payload del JWT SIN verificar la firma (solo para leer exp/iat). */
|
|
18
|
+
export function decodeJwtPayload(token?: string | null): JwtPayload | null {
|
|
19
|
+
if (!token || typeof token !== 'string') return null
|
|
20
|
+
const parts = token.split('.')
|
|
21
|
+
if (parts.length !== 3) return null
|
|
22
|
+
try {
|
|
23
|
+
const b64 = parts[1].replace(/-/g, '+').replace(/_/g, '/')
|
|
24
|
+
const padded = b64 + '='.repeat((4 - (b64.length % 4)) % 4)
|
|
25
|
+
const json = typeof atob === 'function'
|
|
26
|
+
? new TextDecoder().decode(Uint8Array.from(atob(padded), c => c.charCodeAt(0)))
|
|
27
|
+
: Buffer.from(padded, 'base64').toString('utf8')
|
|
28
|
+
const payload = JSON.parse(json)
|
|
29
|
+
return payload && typeof payload === 'object' ? payload : null
|
|
30
|
+
} catch {
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Ventana máxima (segundos) antes del vencimiento en que se renueva. */
|
|
36
|
+
export const REFRESH_WINDOW_SECONDS = 10 * 60
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* ¿Conviene renovar ahora? Sí cuando el token sigue vigente y le queda menos de
|
|
40
|
+
* min(10 min, 1/3 de su vida). El tope por vida evita renovar en cada request si
|
|
41
|
+
* el TTL configurado es corto. Los tokens de plataforma (claim `platform`) NO se
|
|
42
|
+
* renuevan: auth/refresh de Laravel resuelve el usuario con el modelo de usuarios
|
|
43
|
+
* del producto y no conserva el claim, así que emitiría un token de otra identidad.
|
|
44
|
+
*/
|
|
45
|
+
export function shouldRefreshToken(token: string | null | undefined, nowSeconds: number, windowSeconds = REFRESH_WINDOW_SECONDS): boolean {
|
|
46
|
+
const payload = decodeJwtPayload(token)
|
|
47
|
+
if (!payload || typeof payload.exp !== 'number') return false
|
|
48
|
+
if (payload.platform) return false
|
|
49
|
+
const remaining = payload.exp - nowSeconds
|
|
50
|
+
if (remaining <= 0) return false
|
|
51
|
+
const issuedAt = typeof payload.iat === 'number' ? payload.iat : (typeof payload.nbf === 'number' ? payload.nbf : null)
|
|
52
|
+
const lifetime = issuedAt !== null ? payload.exp - issuedAt : null
|
|
53
|
+
const threshold = lifetime && lifetime > 0 ? Math.min(windowSeconds, lifetime / 3) : windowSeconds
|
|
54
|
+
return remaining < threshold
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Rotador con deduplicación. Laravel invalida el token viejo al refrescar, así que:
|
|
59
|
+
* - requests en paralelo con el mismo token comparten UNA sola llamada a refresh;
|
|
60
|
+
* - requests que llegan con el token viejo poco después (el browser aún no recibió
|
|
61
|
+
* la cookie nueva) reciben el token nuevo desde una caché corta, en vez de 401.
|
|
62
|
+
*/
|
|
63
|
+
export function createTokenRotator<C = unknown>(opts: {
|
|
64
|
+
refresh: (token: string, ctx?: C) => Promise<string | null>
|
|
65
|
+
graceMs?: number
|
|
66
|
+
/** Tras un refresh fallido, no reintentar con ese token durante este lapso. */
|
|
67
|
+
failureBackoffMs?: number
|
|
68
|
+
now?: () => number
|
|
69
|
+
}) {
|
|
70
|
+
const graceMs = opts.graceMs ?? 2 * 60 * 1000
|
|
71
|
+
const failureBackoffMs = opts.failureBackoffMs ?? 30 * 1000
|
|
72
|
+
const now = opts.now ?? (() => Date.now())
|
|
73
|
+
const inflight = new Map<string, Promise<string | null>>()
|
|
74
|
+
const rotated = new Map<string, { token: string, at: number }>()
|
|
75
|
+
// Refrescos fallidos recientes (endpoint inexistente, sesión revocada, Laravel
|
|
76
|
+
// caído): sin esto, CADA request de la ventana final repetiría la llamada.
|
|
77
|
+
const failed = new Map<string, number>()
|
|
78
|
+
|
|
79
|
+
function prune() {
|
|
80
|
+
const limit = now() - graceMs
|
|
81
|
+
for (const [old, entry] of rotated) {
|
|
82
|
+
if (entry.at < limit) rotated.delete(old)
|
|
83
|
+
}
|
|
84
|
+
const failLimit = now() - failureBackoffMs
|
|
85
|
+
for (const [tok, at] of failed) {
|
|
86
|
+
if (at < failLimit) failed.delete(tok)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Token nuevo si este ya fue rotado hace poco (si no, null). */
|
|
91
|
+
function rotatedFrom(token: string): string | null {
|
|
92
|
+
const entry = rotated.get(token)
|
|
93
|
+
if (!entry) return null
|
|
94
|
+
if (entry.at < now() - graceMs) { rotated.delete(token); return null }
|
|
95
|
+
return entry.token
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Renueva (o reutiliza la renovación en curso/reciente). Null si no se pudo. */
|
|
99
|
+
async function rotate(token: string, ctx?: C): Promise<string | null> {
|
|
100
|
+
const done = rotatedFrom(token)
|
|
101
|
+
if (done) return done
|
|
102
|
+
const running = inflight.get(token)
|
|
103
|
+
if (running) return running
|
|
104
|
+
const failedAt = failed.get(token)
|
|
105
|
+
if (failedAt !== undefined && failedAt >= now() - failureBackoffMs) return null
|
|
106
|
+
const p = (async () => {
|
|
107
|
+
try {
|
|
108
|
+
const fresh = await opts.refresh(token, ctx)
|
|
109
|
+
prune()
|
|
110
|
+
if (fresh && fresh !== token) {
|
|
111
|
+
rotated.set(token, { token: fresh, at: now() })
|
|
112
|
+
return fresh
|
|
113
|
+
}
|
|
114
|
+
failed.set(token, now())
|
|
115
|
+
return null
|
|
116
|
+
} catch {
|
|
117
|
+
prune()
|
|
118
|
+
failed.set(token, now())
|
|
119
|
+
return null
|
|
120
|
+
} finally {
|
|
121
|
+
inflight.delete(token)
|
|
122
|
+
}
|
|
123
|
+
})()
|
|
124
|
+
inflight.set(token, p)
|
|
125
|
+
return p
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { rotate, rotatedFrom }
|
|
129
|
+
}
|