@innertia-solutions/innertia-nuxt 0.1.79 → 0.1.81

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
@@ -6,6 +6,7 @@ All notable changes to `@innertia-solutions/innertia-nuxt` are documented here.
6
6
 
7
7
  ### Added
8
8
 
9
+ - Passkeys (WebAuthn): composable `usePasskeys()`, componentes `Auth.PasskeyButton` (login tenant y `/platform`, con autocompletado), `Auth.PasskeyInvite`, `Auth.PasskeyManager` y `Auth.UserPasskeys`, y rutas BFF `/_auth/passkey/login` y `/_auth/platform/passkey/login` que sellan la sesión solo si hay token. Requiere `PASSKEYS_ENABLED=true` en el backend. Ver `docs/passkeys.md`.
9
10
  - `Kanban.Standard`: reordenamiento intra-columna con drag&drop (prop `reorderEndpoint`); orden por `position`, placeholder de inserción, y persistencia vía POST. Retrocompatible: sin la prop se comporta igual que antes (solo cross-column).
10
11
 
11
12
  ### Fixed
@@ -153,7 +153,7 @@ const otherMobileApps = computed(() => {
153
153
  v-model="form.values.email"
154
154
  type="email"
155
155
  :disabled="processing"
156
- autocomplete="email"
156
+ autocomplete="username webauthn"
157
157
  placeholder="tu@correo.com"
158
158
  @blur="form.validate('email')"
159
159
  class="py-2.5 px-3 block w-full border rounded-lg sm:text-sm placeholder:text-slate-400 focus:ring-1 disabled:opacity-50 dark:bg-transparent dark:text-slate-300"
@@ -0,0 +1,103 @@
1
+ <script setup>
2
+ import { IconFingerprint } from '@tabler/icons-vue'
3
+
4
+ // Botón "Ingresar con huella o passkey" para cualquier login.
5
+ // - contexts: lista ordenada (login tenant). OBLIGATORIA salvo con `platform`:
6
+ // sin contexts el composable lanza 'PasskeyButton requiere contexts' antes de
7
+ // cualquier ceremonia (el backend exige al menos uno).
8
+ // - platform: login de /platform.
9
+ // - autofill: además arranca el autocompletado (el campo de correo del form
10
+ // debe tener autocomplete="username webauthn"; sin ese input no arranca).
11
+ // Emite success(data) con el body del BFF (data.context; data.tenantDestination
12
+ // en modo open), pending(data) si hay un paso previo (cambio forzado de clave) o
13
+ // error(message, originalError). Las cancelaciones no emiten nada.
14
+ const props = defineProps({
15
+ contexts: {
16
+ type: Array,
17
+ default: () => [],
18
+ // Nota: la validación real (contexts requeridos sin `platform`) ocurre al
19
+ // iniciar la ceremonia, porque depende de otra prop.
20
+ validator: v => Array.isArray(v) && v.every(c => typeof c === 'string'),
21
+ },
22
+ platform: { type: Boolean, default: false },
23
+ autofill: { type: Boolean, default: true },
24
+ label: { type: String, default: 'Ingresar con huella o passkey' },
25
+ })
26
+ const emit = defineEmits(['success', 'pending', 'error'])
27
+
28
+ const passkeys = usePasskeys()
29
+ const loading = ref(false)
30
+ const error = ref('')
31
+ let mounted = false
32
+
33
+ function handle(data) {
34
+ if (!data) return false
35
+ if (data.user) {
36
+ emit('success', data)
37
+ return true
38
+ }
39
+ emit('pending', data)
40
+ return true
41
+ }
42
+
43
+ function fail(e) {
44
+ error.value = passkeys.errorMessage(e)
45
+ emit('error', error.value, e)
46
+ }
47
+
48
+ async function click() {
49
+ error.value = ''
50
+ loading.value = true
51
+ let done = false
52
+ try {
53
+ // login() invalida el autocompletado antes de su propia ceremonia.
54
+ done = handle(props.platform ? await passkeys.loginPlatform() : await passkeys.login({ contexts: props.contexts }))
55
+ } catch (e) {
56
+ if (!passkeys.isDismissed(e)) fail(e)
57
+ } finally {
58
+ loading.value = false
59
+ }
60
+ // Tras un ingreso exitoso no se reanuda; solo tras fallo/cancelación y si sigue montado.
61
+ if (!done && mounted) startAutofill()
62
+ }
63
+
64
+ async function startAutofill() {
65
+ if (!props.autofill || !mounted) return
66
+ try {
67
+ const done = handle(await passkeys.startAutofill({ contexts: props.contexts, platform: props.platform }))
68
+ if (done) return
69
+ } catch (e) {
70
+ // Solo llegan aquí errores tras elegir una passkey (BFF) o de configuración (ya avisado por consola).
71
+ if (passkeys.isContextsError(e)) return
72
+ if (!passkeys.isDismissed(e)) fail(e)
73
+ // Falló la verificación: se vuelve a ofrecer el autocompletado.
74
+ if (mounted && !loading.value) startAutofill()
75
+ }
76
+ }
77
+
78
+ onMounted(() => {
79
+ mounted = true
80
+ startAutofill()
81
+ })
82
+ onBeforeUnmount(() => {
83
+ mounted = false
84
+ passkeys.dispose()
85
+ })
86
+ </script>
87
+
88
+ <template>
89
+ <div v-if="passkeys.supported.value" class="space-y-2">
90
+ <button
91
+ type="button"
92
+ :disabled="loading"
93
+ :aria-busy="loading ? 'true' : 'false'"
94
+ class="inline-flex w-full items-center justify-center gap-2 rounded-control border border-card-line bg-card px-4 py-2.5 text-sm font-medium text-foreground hover:bg-muted-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/30 disabled:cursor-not-allowed disabled:opacity-60 transition-colors"
95
+ @click="click"
96
+ >
97
+ <span v-if="loading" class="size-4 animate-spin rounded-full border-2 border-current/30 border-t-current" aria-hidden="true" />
98
+ <IconFingerprint v-else class="size-4" aria-hidden="true" />
99
+ {{ label }}
100
+ </button>
101
+ <p v-if="error" class="text-xs text-red-500" role="alert">{{ error }}</p>
102
+ </div>
103
+ </template>
@@ -0,0 +1,76 @@
1
+ <script setup>
2
+ import { IconFingerprint, IconX } from '@tabler/icons-vue'
3
+ import { shouldShowPasskeyInvite, inviteStorageKey } from '../../composables/usePasskeys/internal/passkeys'
4
+
5
+ // Aviso discreto tras ingresar con contraseña: "Ingresa con tu huella la próxima
6
+ // vez". Una vez por usuario y dispositivo (localStorage). base: 'auth' | 'platform/auth'.
7
+ const props = defineProps({
8
+ base: { type: String, default: 'auth' },
9
+ })
10
+
11
+ const passkeys = usePasskeys()
12
+ const authStore = useAuthStore()
13
+ const toast = useToast()
14
+ const visible = ref(false)
15
+ const saving = ref(false)
16
+
17
+ const userId = computed(() => authStore.user?.id)
18
+
19
+ function dismissed() {
20
+ try { return localStorage.getItem(inviteStorageKey(userId.value)) === 'dismissed' } catch { return true }
21
+ }
22
+
23
+ function dismiss() {
24
+ try { localStorage.setItem(inviteStorageKey(userId.value), 'dismissed') } catch {}
25
+ visible.value = false
26
+ }
27
+
28
+ // usePasskeys resuelve `supported` en su propio onMounted, que corre antes que este.
29
+ onMounted(async () => {
30
+ if (!userId.value || !passkeys.supported.value) return
31
+ let hasPasskeys = true
32
+ try { hasPasskeys = (await passkeys.list(props.base)).length > 0 } catch { return }
33
+ visible.value = shouldShowPasskeyInvite({
34
+ supported: passkeys.supported.value,
35
+ enabled: true,
36
+ dismissed: dismissed(),
37
+ hasPasskeys,
38
+ loggedInWithPasskey: passkeys.loggedInWithPasskey(),
39
+ })
40
+ })
41
+
42
+ async function activate() {
43
+ saving.value = true
44
+ try {
45
+ await passkeys.register(undefined, props.base)
46
+ toast.success('Listo: la próxima vez ingresa con tu huella.')
47
+ dismiss()
48
+ } catch (e) {
49
+ if (!passkeys.isCancel(e)) toast.error(passkeys.errorMessage(e))
50
+ } finally {
51
+ saving.value = false
52
+ }
53
+ }
54
+ </script>
55
+
56
+ <template>
57
+ <div
58
+ v-if="visible"
59
+ class="flex items-center gap-3 rounded-card border border-card-line bg-card px-4 py-3 shadow-sm"
60
+ role="status"
61
+ >
62
+ <IconFingerprint class="size-5 shrink-0 text-primary" aria-hidden="true" />
63
+ <p class="flex-1 text-sm text-foreground">
64
+ Ingresa con tu huella la próxima vez, sin contraseña.
65
+ </p>
66
+ <App.Button text="Activar" severity="primary" size="sm" :loading="saving" @click="activate" />
67
+ <button
68
+ type="button"
69
+ class="rounded-control p-1 text-muted-foreground hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/30"
70
+ aria-label="Ahora no, cerrar la invitación a usar passkey"
71
+ @click="dismiss"
72
+ >
73
+ <IconX class="size-4" aria-hidden="true" />
74
+ </button>
75
+ </div>
76
+ </template>
@@ -0,0 +1,168 @@
1
+ <script setup>
2
+ import { IconFingerprint, IconPencil, IconTrash, IconPlus } from '@tabler/icons-vue'
3
+
4
+ // Gestión de las passkeys propias (perfil › Seguridad). base: 'auth' | 'platform/auth'.
5
+ const props = defineProps({
6
+ base: { type: String, default: 'auth' },
7
+ })
8
+
9
+ const passkeys = usePasskeys()
10
+ const toast = useToast()
11
+ const { confirm } = useModal()
12
+ const items = ref([])
13
+ const loading = ref(true)
14
+ const loadError = ref('')
15
+ const adding = ref(false)
16
+ const editingId = ref(null)
17
+ const editName = ref('')
18
+ const editInput = ref(null)
19
+
20
+ const fmt = (iso) => iso ? new Date(iso).toLocaleDateString('es-CL', { day: 'numeric', month: 'short', year: 'numeric' }) : 'Nunca'
21
+
22
+ async function load() {
23
+ loading.value = true
24
+ loadError.value = ''
25
+ try {
26
+ items.value = await passkeys.list(props.base)
27
+ } catch (e) {
28
+ loadError.value = passkeys.errorMessage(e)
29
+ } finally {
30
+ loading.value = false
31
+ }
32
+ }
33
+
34
+ async function add() {
35
+ adding.value = true
36
+ try {
37
+ await passkeys.register(undefined, props.base)
38
+ toast.success('Passkey agregada.')
39
+ await load()
40
+ } catch (e) {
41
+ if (!passkeys.isCancel(e)) toast.error(passkeys.errorMessage(e))
42
+ } finally {
43
+ adding.value = false
44
+ }
45
+ }
46
+
47
+ async function startEdit(item) {
48
+ editingId.value = item.id
49
+ editName.value = item.name
50
+ await nextTick()
51
+ // ref dentro de v-for → arreglo
52
+ const el = Array.isArray(editInput.value) ? editInput.value[0] : editInput.value
53
+ el?.focus()
54
+ el?.select()
55
+ }
56
+
57
+ // Esc cancela sin guardar: se suelta la edición ANTES del blur que provoca
58
+ // desmontar el input, así saveEdit (por blur) ve que ya no se edita y no guarda.
59
+ function cancelEdit() {
60
+ editingId.value = null
61
+ }
62
+
63
+ async function saveEdit(item) {
64
+ // Enter + blur: solo la primera llamada guarda (evita doble PATCH).
65
+ if (editingId.value !== item.id) return
66
+ editingId.value = null
67
+ const name = editName.value.trim()
68
+ if (!name || name === item.name) return
69
+ const previous = item.name
70
+ item.name = name
71
+ try {
72
+ await passkeys.rename(item.id, name, props.base)
73
+ } catch (e) {
74
+ item.name = previous
75
+ toast.error(passkeys.errorMessage(e))
76
+ }
77
+ }
78
+
79
+ async function removeItem(item) {
80
+ const ok = await confirm({ severity: 'danger', message: `¿Eliminar la passkey "${item.name}"? Ya no podrás ingresar con ella.` })
81
+ if (!ok) return
82
+ try {
83
+ await passkeys.remove(item.id, props.base)
84
+ items.value = items.value.filter(i => i.id !== item.id)
85
+ toast.success('Passkey eliminada.')
86
+ } catch (e) {
87
+ toast.error(passkeys.errorMessage(e))
88
+ }
89
+ }
90
+
91
+ onMounted(load)
92
+ </script>
93
+
94
+ <template>
95
+ <div class="rounded-card border border-card-line bg-card">
96
+ <div class="flex items-center justify-between gap-3 border-b border-card-line px-5 py-4">
97
+ <div>
98
+ <h3 class="text-sm font-semibold text-foreground">Passkeys</h3>
99
+ <p class="mt-0.5 text-xs text-muted-foreground">Ingresa con tu huella, rostro o PIN del dispositivo, sin contraseña.</p>
100
+ </div>
101
+ <App.Button
102
+ v-if="passkeys.ready.value && passkeys.supported.value"
103
+ text="Agregar en este dispositivo"
104
+ :icon="IconPlus"
105
+ severity="primary"
106
+ size="sm"
107
+ :loading="adding"
108
+ @click="add"
109
+ />
110
+ </div>
111
+
112
+ <div v-if="!passkeys.ready.value" class="px-5 py-6 text-sm text-muted-foreground">Cargando…</div>
113
+
114
+ <p v-else-if="!passkeys.supported.value" class="px-5 py-4 text-sm text-muted-foreground">
115
+ Este navegador no permite usar passkeys.
116
+ </p>
117
+
118
+ <div v-else-if="loading" class="px-5 py-6 text-sm text-muted-foreground">Cargando…</div>
119
+
120
+ <div v-else-if="loadError" class="flex items-center justify-between gap-3 px-5 py-6" role="alert">
121
+ <p class="text-sm text-red-600">{{ loadError }}</p>
122
+ <App.Button text="Reintentar" size="sm" @click="load" />
123
+ </div>
124
+
125
+ <p v-else-if="!items.length" class="px-5 py-6 text-sm text-muted-foreground">
126
+ Aún no tienes passkeys. Agrega una para ingresar con tu huella.
127
+ </p>
128
+
129
+ <ul v-else class="divide-y divide-card-line">
130
+ <li v-for="item in items" :key="item.id" class="flex items-center gap-3 px-5 py-3">
131
+ <IconFingerprint class="size-5 shrink-0 text-muted-foreground" aria-hidden="true" />
132
+ <div class="min-w-0 flex-1">
133
+ <input
134
+ v-if="editingId === item.id"
135
+ ref="editInput"
136
+ v-model="editName"
137
+ maxlength="120"
138
+ :aria-label="`Nuevo nombre para la passkey ${item.name}`"
139
+ class="w-full rounded-control border border-card-line bg-transparent px-2 py-1 text-sm text-foreground focus:border-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/30"
140
+ @keydown.enter.prevent="saveEdit(item)"
141
+ @keydown.esc.prevent.stop="cancelEdit"
142
+ @blur="saveEdit(item)"
143
+ />
144
+ <p v-else class="truncate text-sm font-medium text-foreground">{{ item.name }}</p>
145
+ <p class="text-xs text-muted-foreground">
146
+ <span v-if="item.provider">{{ item.provider }} · </span>Creada {{ fmt(item.created_at) }} · Último uso {{ fmt(item.last_used_at) }}
147
+ </p>
148
+ </div>
149
+ <button
150
+ type="button"
151
+ class="rounded-control p-1 text-muted-foreground hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/30"
152
+ :aria-label="`Renombrar passkey ${item.name}`"
153
+ @click="startEdit(item)"
154
+ >
155
+ <IconPencil class="size-4" aria-hidden="true" />
156
+ </button>
157
+ <button
158
+ type="button"
159
+ class="rounded-control p-1 text-muted-foreground hover:text-red-600 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500/30"
160
+ :aria-label="`Eliminar passkey ${item.name}`"
161
+ @click="removeItem(item)"
162
+ >
163
+ <IconTrash class="size-4" aria-hidden="true" />
164
+ </button>
165
+ </li>
166
+ </ul>
167
+ </div>
168
+ </template>
@@ -0,0 +1,72 @@
1
+ <script setup>
2
+ import { IconFingerprint } from '@tabler/icons-vue'
3
+
4
+ // Para administradores: passkeys de un usuario (cantidad, último uso) y
5
+ // "Revocar todas" (dispositivo perdido, funcionario que se va).
6
+ const props = defineProps({
7
+ userId: { type: [String, Number], required: true },
8
+ })
9
+
10
+ const passkeys = usePasskeys()
11
+ const toast = useToast()
12
+ const { confirm } = useModal()
13
+ const items = ref([])
14
+ const loading = ref(true)
15
+ const loadError = ref('')
16
+ const revoking = ref(false)
17
+
18
+ const lastUsed = computed(() => {
19
+ const dates = items.value.map(i => i.last_used_at).filter(Boolean).sort()
20
+ return dates.length ? new Date(dates[dates.length - 1]).toLocaleString('es-CL', { dateStyle: 'medium', timeStyle: 'short' }) : null
21
+ })
22
+
23
+ async function load() {
24
+ loading.value = true
25
+ loadError.value = ''
26
+ try {
27
+ items.value = await passkeys.listForUser(props.userId)
28
+ } catch (e) {
29
+ items.value = []
30
+ loadError.value = passkeys.errorMessage(e)
31
+ } finally {
32
+ loading.value = false
33
+ }
34
+ }
35
+
36
+ async function revoke() {
37
+ const ok = await confirm({ severity: 'danger', message: 'Se revocarán todas las passkeys de este usuario. Tendrá que ingresar con su contraseña. ¿Continuar?' })
38
+ if (!ok) return
39
+ revoking.value = true
40
+ try {
41
+ const n = await passkeys.revokeAll(props.userId)
42
+ toast.success(n === 1 ? '1 passkey revocada.' : `${n} passkeys revocadas.`)
43
+ await load()
44
+ } catch (e) {
45
+ toast.error(passkeys.errorMessage(e))
46
+ } finally {
47
+ revoking.value = false
48
+ }
49
+ }
50
+
51
+ watch(() => props.userId, load)
52
+ onMounted(load)
53
+ </script>
54
+
55
+ <template>
56
+ <div class="flex items-center gap-3 rounded-card border border-card-line bg-card px-5 py-4">
57
+ <IconFingerprint class="size-5 shrink-0 text-muted-foreground" aria-hidden="true" />
58
+ <div class="min-w-0 flex-1">
59
+ <p class="text-sm font-medium text-foreground">Passkeys</p>
60
+ <p class="text-xs text-muted-foreground">
61
+ <template v-if="loading">Cargando…</template>
62
+ <span v-else-if="loadError" class="text-red-600" role="alert">{{ loadError }}</span>
63
+ <template v-else-if="!items.length">No tiene passkeys.</template>
64
+ <template v-else>
65
+ {{ items.length === 1 ? '1 passkey' : `${items.length} passkeys` }}<template v-if="lastUsed"> · último uso {{ lastUsed }}</template>
66
+ </template>
67
+ </p>
68
+ </div>
69
+ <App.Button v-if="loadError" text="Reintentar" size="sm" @click="load" />
70
+ <App.Button v-else-if="items.length" text="Revocar todas" severity="danger" size="sm" :loading="revoking" @click="revoke" />
71
+ </div>
72
+ </template>
@@ -65,6 +65,9 @@ const initHsSelect = async () => {
65
65
  return
66
66
  }
67
67
  if (HSSelect.getInstance?.(el)) return
68
+ // HSSelect toma el valor inicial de el.value: si las <option> llegaron después
69
+ // del binding :value, el nativo puede haber quedado en ''. Se re-aplica.
70
+ el.value = props.modelValue === null || props.modelValue === undefined ? '' : String(props.modelValue)
68
71
  try {
69
72
  new HSSelect(el)
70
73
  } catch (e) {
@@ -99,6 +102,28 @@ watch(
99
102
  },
100
103
  )
101
104
 
105
+ /**
106
+ * Si el valor llega o cambia desde afuera después del mount (ej. formulario de
107
+ * edición que hidrata con datos async), HSSelect conserva el valor con que se
108
+ * inicializó y el toggle sigue mostrando la opción vacía. Se lo empuja con setValue.
109
+ * Cuando el cambio viene del propio usuario, el valor ya coincide y no hace nada.
110
+ */
111
+ watch(
112
+ () => props.modelValue,
113
+ async (val) => {
114
+ await nextTick()
115
+ const el = selectRef.value
116
+ const inst = el && (window as any).HSSelect?.getInstance?.(el)
117
+ const next = val === null || val === undefined ? '' : String(val)
118
+ if (!inst || String(inst.value ?? '') === next) return
119
+ try {
120
+ inst.setValue(next)
121
+ } catch (e) {
122
+ console.warn('[FormsSelect] HSSelect setValue falló:', e)
123
+ }
124
+ },
125
+ )
126
+
102
127
  const handleChange = (e: Event) => {
103
128
  const val = (e.target as HTMLSelectElement).value
104
129
  emit('update:modelValue', val || null)
@@ -131,7 +156,10 @@ const handleChange = (e: Event) => {
131
156
  </button>
132
157
  </div>
133
158
 
134
- <!-- Select (HSSelect) -->
159
+ <!-- Select (HSSelect). OJO: el <select> nativo NO puede llevar la clase
160
+ "hs-select": HSSelect.destroy() borra el primer ".hs-select" del
161
+ contenedor, que sería el nativo en vez del wrapper (se perdía el select
162
+ al re-inicializar por cambio de options). -->
135
163
  <ClientOnly v-else>
136
164
  <template #fallback>
137
165
  <div class="innertia-field bg-surface animate-pulse" />
@@ -140,7 +168,7 @@ const handleChange = (e: Event) => {
140
168
  <div :class="['relative', error ? 'select-error' : '']">
141
169
  <select
142
170
  ref="selectRef"
143
- class="hs-select w-full"
171
+ class="innertia-select-native w-full"
144
172
  :value="modelValue ?? ''"
145
173
  :disabled="disabled"
146
174
  :data-hs-select="hsConfig"
@@ -14,6 +14,10 @@ export function useAuth() {
14
14
  */
15
15
  async function performLogin(context, email, password, remember = false) {
16
16
  authStore.rememberUser = remember
17
+ // Un ingreso con contraseña borra la marca de "ingresó con passkey" (la invitación vuelve a aparecer).
18
+ if (import.meta.client) {
19
+ try { sessionStorage.removeItem('innertia:logged-in-with-passkey') } catch {}
20
+ }
17
21
  // Sella la sesión en el server (Nitro). Devuelve user+contexts, SIN token.
18
22
  const data = await $fetch('/_auth/login', {
19
23
  method: 'POST',
@@ -101,6 +105,10 @@ export function useAuth() {
101
105
  async function logout() {
102
106
  try { await $fetch('/_auth/logout', { method: 'POST' }) } catch { /* best-effort */ }
103
107
  queryClient.clear()
108
+ // La marca "ingresó con passkey" es de la sesión que termina.
109
+ if (import.meta.client) {
110
+ try { sessionStorage.removeItem('innertia:logged-in-with-passkey') } catch {}
111
+ }
104
112
  authStore.logout() // limpia el state en memoria
105
113
  organizationStore.reset()
106
114
  // En open, limpiar también el tenant seleccionado
@@ -120,5 +128,5 @@ export function useAuth() {
120
128
  return data.url ?? data
121
129
  }
122
130
 
123
- return { performLogin, verifyOtp, changeForcedPassword, fetchMe, logout, getOauthRedirectUrl }
131
+ return { performLogin, verifyOtp, changeForcedPassword, finishLogin, fetchMe, logout, getOauthRedirectUrl }
124
132
  }