@innertia-solutions/innertia-nuxt 0.1.83 → 0.1.85

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 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
 
@@ -1,5 +1,5 @@
1
1
  <script setup lang="ts">
2
- import { ref, computed, watch, nextTick } from 'vue'
2
+ import { ref, computed, watch, nextTick, useAttrs } from 'vue'
3
3
 
4
4
  /*
5
5
  * CurrencyInput — input de moneda con formato SOLO visual.
@@ -72,15 +72,29 @@ function onBlur() {
72
72
  const baseClasses = computed(() =>
73
73
  `innertia-field${props.size === 'sm' ? ' innertia-field-sm' : ''}`,
74
74
  )
75
+ // Los atributos no declarados (maxlength, min, max, step, required, inputmode,
76
+ // name, id, aria-*, data-*) y los listeners (@blur, @keydown, @focus…) van al
77
+ // <input>; solo class/style quedan en el <div> raíz para no romper el layout.
78
+ defineOptions({ inheritAttrs: false })
79
+ const attrs = useAttrs()
80
+ // Funciones (no computed): useAttrs() no es reactivo, el render sí se re-ejecuta.
81
+ function rootAttrs() {
82
+ return { class: attrs.class, style: attrs.style }
83
+ }
84
+ function inputAttrs() {
85
+ const { class: _class, style: _style, ...rest } = attrs
86
+ return rest
87
+ }
75
88
  </script>
76
89
 
77
90
  <template>
78
- <div class="w-full">
91
+ <div class="w-full" v-bind="rootAttrs()">
79
92
  <label v-if="label" class="block text-sm font-medium text-foreground mb-1.5">
80
93
  {{ label }}
81
94
  </label>
82
95
 
83
96
  <input
97
+ v-bind="inputAttrs()"
84
98
  ref="inputEl"
85
99
  type="text"
86
100
  inputmode="numeric"
@@ -1,5 +1,5 @@
1
1
  <script setup lang="ts">
2
- import { ref, computed } from 'vue'
2
+ import { ref, computed, useAttrs } from 'vue'
3
3
  import { IconEye, IconEyeOff } from '@tabler/icons-vue'
4
4
 
5
5
  const props = defineProps<{
@@ -27,10 +27,23 @@ const inputType = computed(() => {
27
27
  const baseClasses = computed(() =>
28
28
  `innertia-field${props.size === 'sm' ? ' innertia-field-sm' : ''}`
29
29
  )
30
+ // Los atributos no declarados (maxlength, min, max, step, required, inputmode,
31
+ // name, id, aria-*, data-*) y los listeners (@blur, @keydown, @focus…) van al
32
+ // <input>; solo class/style quedan en el <div> raíz para no romper el layout.
33
+ defineOptions({ inheritAttrs: false })
34
+ const attrs = useAttrs()
35
+ // Funciones (no computed): useAttrs() no es reactivo, el render sí se re-ejecuta.
36
+ function rootAttrs() {
37
+ return { class: attrs.class, style: attrs.style }
38
+ }
39
+ function inputAttrs() {
40
+ const { class: _class, style: _style, ...rest } = attrs
41
+ return rest
42
+ }
30
43
  </script>
31
44
 
32
45
  <template>
33
- <div class="w-full">
46
+ <div class="w-full" v-bind="rootAttrs()">
34
47
  <label v-if="label" class="block text-sm font-medium text-foreground mb-1.5">
35
48
  {{ label }}
36
49
  </label>
@@ -42,6 +55,7 @@ const baseClasses = computed(() =>
42
55
  </div>
43
56
 
44
57
  <input
58
+ v-bind="inputAttrs()"
45
59
  v-model="modelValue"
46
60
  :type="inputType"
47
61
  :placeholder="placeholder"
@@ -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 "Seleccionar…" (blanquear la selección). Default true. */
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 ?? 'Seleccionar...')
30
+ const emptyLabel = computed(() => props.placeholder || 'Selecciona…')
31
31
 
32
32
  /**
33
- * Config de HSSelect. Si `clearable`, NO seteamos `placeholder` en Preline: así la
34
- * opción vacía "Seleccionar…" queda como una opción normal (re-seleccionable) y el
35
- * usuario puede blanquear la selección. Si no, la vacía actúa de placeholder (Preline
36
- * la oculta una vez elegido un valor).
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
- ...(props.clearable ? {} : { placeholder: emptyLabel.value }),
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',
@@ -0,0 +1,137 @@
1
+ import { describe, it, expect, vi } from 'vitest'
2
+ import { createRenderer, h, nextTick, ref } from 'vue'
3
+ import Input from '../Input.vue'
4
+ import CurrencyInput from '../CurrencyInput.vue'
5
+
6
+ /*
7
+ * Renderer mínimo (sin DOM): cada nodo guarda su tag y los props/listeners que
8
+ * Vue le aplica. Basta para verificar a qué elemento llegan los $attrs.
9
+ */
10
+ type TestNode = {
11
+ tag: string
12
+ props: Record<string, any>
13
+ children: TestNode[]
14
+ parent: TestNode | null
15
+ text?: string
16
+ value?: any
17
+ /** vModelText registra listeners nativos; aquí basta con aceptarlos. */
18
+ addEventListener: () => void
19
+ }
20
+
21
+ function makeNode(tag: string): TestNode {
22
+ return { tag, props: {}, children: [], parent: null, addEventListener: () => {} }
23
+ }
24
+
25
+ function remove(child: TestNode) {
26
+ const p = child.parent
27
+ if (!p) return
28
+ const i = p.children.indexOf(child)
29
+ if (i > -1) p.children.splice(i, 1)
30
+ child.parent = null
31
+ }
32
+
33
+ const { createApp } = createRenderer<TestNode, TestNode>({
34
+ createElement: tag => makeNode(tag),
35
+ createText: text => ({ ...makeNode('#text'), text }),
36
+ createComment: text => ({ ...makeNode('#comment'), text }),
37
+ setText: (node, text) => { node.text = text },
38
+ setElementText: (node, text) => { node.children = []; node.text = text },
39
+ insert: (child, parent, anchor) => {
40
+ remove(child)
41
+ const i = anchor ? parent.children.indexOf(anchor) : -1
42
+ if (i > -1) parent.children.splice(i, 0, child)
43
+ else parent.children.push(child)
44
+ child.parent = parent
45
+ },
46
+ remove,
47
+ parentNode: node => node.parent,
48
+ nextSibling: (node) => {
49
+ const p = node.parent
50
+ if (!p) return null
51
+ return p.children[p.children.indexOf(node) + 1] ?? null
52
+ },
53
+ patchProp: (el, key, _prev, next) => {
54
+ if (next == null) delete el.props[key]
55
+ else el.props[key] = next
56
+ },
57
+ })
58
+
59
+ function find(node: TestNode, tag: string): TestNode | undefined {
60
+ if (node.tag === tag) return node
61
+ for (const c of node.children) {
62
+ const hit = find(c, tag)
63
+ if (hit) return hit
64
+ }
65
+ }
66
+
67
+ /**
68
+ /** Sin DOM ni SSR: monta la app sobre el renderer de prueba. */
69
+ function mountApp(render: () => any, root: TestNode) {
70
+ createApp({ render }).mount(root)
71
+ }
72
+
73
+ function mount(component: any, props: Record<string, any>) {
74
+ const root = makeNode('root')
75
+ mountApp(() => h(component, props), root)
76
+ const wrapper = root.children.find(c => c.tag === 'div')!
77
+ const input = find(root, 'input')!
78
+ return { root, wrapper, input }
79
+ }
80
+
81
+ /** Vue puede guardar un listener como función o como array (merge de listeners). */
82
+ function call(listener: any, ...args: any[]) {
83
+ if (Array.isArray(listener)) listener.forEach(fn => fn(...args))
84
+ else listener(...args)
85
+ }
86
+
87
+ describe('Forms.Input reenvía $attrs al <input>', () => {
88
+ it('pone maxlength/required/inputmode en el input y no en el div raíz', () => {
89
+ const { wrapper, input } = mount(Input, { maxlength: 20, required: true, inputmode: 'numeric', name: 'code' })
90
+ expect(input.props.maxlength).toBe(20)
91
+ expect(input.props.required).toBe(true)
92
+ expect(input.props.inputmode).toBe('numeric')
93
+ expect(input.props.name).toBe('code')
94
+ expect(wrapper.props.maxlength).toBeUndefined()
95
+ })
96
+
97
+ it('ejecuta @blur y @keydown del consumidor sobre el input', () => {
98
+ const onBlur = vi.fn()
99
+ const onKeydown = vi.fn()
100
+ const { wrapper, input } = mount(Input, { onBlur, onKeydown })
101
+ expect(wrapper.props.onBlur).toBeUndefined()
102
+ call(input.props.onBlur, { type: 'blur' })
103
+ call(input.props.onKeydown, { type: 'keydown' })
104
+ expect(onBlur).toHaveBeenCalledOnce()
105
+ expect(onKeydown).toHaveBeenCalledOnce()
106
+ })
107
+
108
+ it('mantiene class y style en el div raíz', () => {
109
+ const { wrapper, input } = mount(Input, { class: 'col-span-2', style: { width: '10px' } })
110
+ expect(wrapper.props.class).toContain('col-span-2')
111
+ expect(wrapper.props.class).toContain('w-full')
112
+ expect(wrapper.props.style).toMatchObject({ width: '10px' })
113
+ expect(input.props.class).not.toContain('col-span-2')
114
+ expect(input.props.style).toBeUndefined()
115
+ })
116
+
117
+ it('actualiza los attrs reenviados cuando cambian', async () => {
118
+ const max = ref(10)
119
+ const root = makeNode('root')
120
+ mountApp(() => h(Input, { maxlength: max.value }), root)
121
+ expect(find(root, 'input')!.props.maxlength).toBe(10)
122
+ max.value = 30
123
+ await nextTick()
124
+ expect(find(root, 'input')!.props.maxlength).toBe(30)
125
+ })
126
+ })
127
+
128
+ describe('Forms.CurrencyInput reenvía $attrs al <input>', () => {
129
+ it('combina el @blur del consumidor con el blur interno', () => {
130
+ const onBlur = vi.fn()
131
+ const { wrapper, input } = mount(CurrencyInput, { onBlur, maxlength: 15, class: 'mb-2' })
132
+ expect(input.props.maxlength).toBe(15)
133
+ expect(wrapper.props.class).toContain('mb-2')
134
+ call(input.props.onBlur, { type: 'blur' })
135
+ expect(onBlur).toHaveBeenCalledOnce()
136
+ })
137
+ })
@@ -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
+
@@ -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
- if (current !== loginPath && !current?.endsWith('/login')) await navigateTo(loginPath)
87
- return null
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') ?? ''
@@ -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,6 +1,6 @@
1
1
  {
2
2
  "name": "@innertia-solutions/innertia-nuxt",
3
- "version": "0.1.83",
3
+ "version": "0.1.85",
4
4
  "description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
5
5
  "keywords": [
6
6
  "nuxt",
@@ -63,6 +63,7 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@pinia/nuxt": "^0.11.3",
66
+ "@vitejs/plugin-vue": "^5.2.4",
66
67
  "nuxt": "^4.4.2",
67
68
  "pinia": "^3.0.4",
68
69
  "pinia-plugin-persistedstate": "^4.7.1",
@@ -1,12 +1,21 @@
1
- import { readSession } from '../utils/session'
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 { token } = await readSession(event)
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
- await writeSession(event, { ...current, currentContext: context })
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
- const { token } = await readSession(event)
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 { readSession, clearSession } from '../../utils/session'
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 { token } = await readSession(event)
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
- // Token rechazado por Laravel → la sesión sellada no sirve: borrarla para que
17
- // /_auth/session deje de reportar authenticated (evita loops de redirección).
18
- onResponse: (ev, response) => {
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
+ }
@@ -0,0 +1,30 @@
1
+ import { defineConfig } from 'vitest/config'
2
+ import vue from '@vitejs/plugin-vue'
3
+
4
+ export default defineConfig({
5
+ plugins: [clientOnlyVue()],
6
+ test: {
7
+ include: ['**/__tests__/**/*.test.ts', '**/*.test.ts'],
8
+ environment: 'node',
9
+ },
10
+ })
11
+
12
+ /**
13
+ * plugin-vue para importar SFC en tests. En entorno node vitest los transforma
14
+ * en modo SSR (solo ssrRender); aquí se fuerza la compilación cliente para
15
+ * poder montarlos con un renderer propio.
16
+ */
17
+ function clientOnlyVue() {
18
+ const plugin = vue()
19
+ const transform = plugin.transform as any
20
+ const load = plugin.load as any
21
+ return {
22
+ ...plugin,
23
+ load(this: any, id: string, opts?: any) {
24
+ return load?.call(this, id, { ...opts, ssr: false })
25
+ },
26
+ transform(this: any, code: string, id: string, opts?: any) {
27
+ return transform.call(this, code, id, { ...opts, ssr: false })
28
+ },
29
+ }
30
+ }
package/vitest.config.ts DELETED
@@ -1,8 +0,0 @@
1
- import { defineConfig } from 'vitest/config'
2
-
3
- export default defineConfig({
4
- test: {
5
- include: ['**/__tests__/**/*.test.ts', '**/*.test.ts'],
6
- environment: 'node',
7
- },
8
- })