@innertia-solutions/innertia-nuxt 0.1.80 → 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 +1 -0
- package/components/Auth/LoginForm.vue +1 -1
- package/components/Auth/PasskeyButton.vue +103 -0
- package/components/Auth/PasskeyInvite.vue +76 -0
- package/components/Auth/PasskeyManager.vue +168 -0
- package/components/Auth/UserPasskeys.vue +72 -0
- package/composables/useAuth.js +9 -1
- package/composables/usePasskeys/index.ts +298 -0
- package/composables/usePasskeys/internal/__tests__/passkeys.test.ts +83 -0
- package/composables/usePasskeys/internal/__tests__/runGuard.test.ts +42 -0
- package/composables/usePasskeys/internal/passkeys.ts +80 -0
- package/composables/usePasskeys/internal/runGuard.ts +41 -0
- package/docs/passkeys.md +97 -0
- package/nuxt.config.ts +1 -1
- package/package.json +4 -3
- package/server/routes/_auth/passkey/login.post.ts +27 -0
- package/server/routes/_auth/platform/passkey/login.post.ts +25 -0
- package/server/utils/__tests__/passkeyLogin.test.ts +38 -0
- package/server/utils/passkeyLogin.ts +15 -0
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="
|
|
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>
|
package/composables/useAuth.js
CHANGED
|
@@ -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
|
}
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { ref, getCurrentInstance, onMounted, onBeforeUnmount } from 'vue'
|
|
2
|
+
import {
|
|
3
|
+
startAuthentication,
|
|
4
|
+
startRegistration,
|
|
5
|
+
browserSupportsWebAuthn,
|
|
6
|
+
browserSupportsWebAuthnAutofill,
|
|
7
|
+
WebAuthnAbortService,
|
|
8
|
+
} from '@simplewebauthn/browser'
|
|
9
|
+
import {
|
|
10
|
+
passkeyErrorMessage,
|
|
11
|
+
isPasskeyCancel,
|
|
12
|
+
isPasskeyDismissed,
|
|
13
|
+
suggestPasskeyName,
|
|
14
|
+
contextsRequiredError,
|
|
15
|
+
CONTEXTS_REQUIRED,
|
|
16
|
+
WEBAUTHN_INPUT_SELECTOR,
|
|
17
|
+
} from './internal/passkeys'
|
|
18
|
+
import { createRunGuard } from './internal/runGuard'
|
|
19
|
+
|
|
20
|
+
// Solo se exporta el composable (los helpers de ./internal no se auto-importan).
|
|
21
|
+
|
|
22
|
+
/** Marca de sesión: el último ingreso fue con passkey (la invitación no se muestra). */
|
|
23
|
+
const PASSKEY_LOGIN_FLAG = 'innertia:logged-in-with-passkey'
|
|
24
|
+
|
|
25
|
+
/** El reto vive 300 s en el backend: el autocompletado se renueva antes. */
|
|
26
|
+
const AUTOFILL_RENEW_MS = 270_000
|
|
27
|
+
|
|
28
|
+
/** Soporte de autocompletado: se consulta una vez por página (solo en el cliente). */
|
|
29
|
+
let autofillSupport: Promise<boolean> | null = null
|
|
30
|
+
function supportsAutofill(): Promise<boolean> {
|
|
31
|
+
if (!import.meta.client) return Promise.resolve(false)
|
|
32
|
+
autofillSupport ??= browserSupportsWebAuthnAutofill().catch(() => false)
|
|
33
|
+
return autofillSupport
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function debug(...args: any[]) {
|
|
37
|
+
if (import.meta.dev) console.debug('[passkeys]', ...args)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface PasskeyItem {
|
|
41
|
+
id: string
|
|
42
|
+
name: string
|
|
43
|
+
provider: string | null
|
|
44
|
+
created_at: string | null
|
|
45
|
+
last_used_at: string | null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Passkeys (WebAuthn) sobre innertia-laravel \Innertia\Passkeys.
|
|
50
|
+
* - Ingreso: opciones por /api, ceremonia en el navegador, verificación por el BFF
|
|
51
|
+
* (/_auth/passkey/login) que sella la sesión solo si hay token.
|
|
52
|
+
* - Gestión propia: base 'auth' (tenant) o 'platform/auth' (cuenta de plataforma).
|
|
53
|
+
*
|
|
54
|
+
* Llamar durante el setup de un componente: `supported`/`autofillSupported` se
|
|
55
|
+
* resuelven en onMounted (false en SSR y en el primer render → sin hydration
|
|
56
|
+
* mismatch) y el autocompletado se libera en onBeforeUnmount.
|
|
57
|
+
*/
|
|
58
|
+
export function usePasskeys() {
|
|
59
|
+
const api = useApi()
|
|
60
|
+
const authStore = useAuthStore()
|
|
61
|
+
const { finishLogin } = useAuth()
|
|
62
|
+
|
|
63
|
+
const supported = ref(false)
|
|
64
|
+
const autofillSupported = ref(false)
|
|
65
|
+
/** true una vez resuelto el soporte en el cliente (para no mostrar "no soportado" antes de tiempo). */
|
|
66
|
+
const ready = ref(false)
|
|
67
|
+
|
|
68
|
+
async function detectSupport() {
|
|
69
|
+
supported.value = browserSupportsWebAuthn()
|
|
70
|
+
autofillSupported.value = await supportsAutofill()
|
|
71
|
+
ready.value = true
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Autocompletado: corridas (generación) + fase + temporizador de renovación.
|
|
75
|
+
const guard = createRunGuard()
|
|
76
|
+
let autofillPhase: 'idle' | 'options' | 'waiting' | 'verifying' = 'idle'
|
|
77
|
+
let renewTimer: ReturnType<typeof setTimeout> | null = null
|
|
78
|
+
let renewRequested = false
|
|
79
|
+
|
|
80
|
+
function clearRenewTimer() {
|
|
81
|
+
if (renewTimer) clearTimeout(renewTimer)
|
|
82
|
+
renewTimer = null
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Dentro de un hook de ciclo de vida la instancia ya está montada: onMounted no
|
|
86
|
+
// correría nunca, así que se detecta el soporte de inmediato.
|
|
87
|
+
const instance = getCurrentInstance()
|
|
88
|
+
if (instance) onBeforeUnmount(dispose)
|
|
89
|
+
if (instance && !instance.isMounted) onMounted(() => { detectSupport() })
|
|
90
|
+
else if (import.meta.client) detectSupport()
|
|
91
|
+
|
|
92
|
+
function markPasskeyLogin(on: boolean) {
|
|
93
|
+
if (!import.meta.client) return
|
|
94
|
+
try { on ? sessionStorage.setItem(PASSKEY_LOGIN_FLAG, '1') : sessionStorage.removeItem(PASSKEY_LOGIN_FLAG) } catch {}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function loggedInWithPasskey(): boolean {
|
|
98
|
+
if (!import.meta.client) return false
|
|
99
|
+
try { return sessionStorage.getItem(PASSKEY_LOGIN_FLAG) === '1' } catch { return false }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function assertContexts(platform: boolean, contexts: string[]) {
|
|
103
|
+
if (platform || contexts?.length) return
|
|
104
|
+
if (import.meta.dev) console.warn('[passkeys] PasskeyButton requiere contexts (login de tenant): pasa :contexts="[...]" o usa la prop platform.')
|
|
105
|
+
throw contextsRequiredError()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fetchLoginOptions(platform: boolean) {
|
|
109
|
+
const res: any = await api.post(platform ? 'platform/auth/passkey/login/options' : 'auth/passkey/login/options')
|
|
110
|
+
if (!res?.key || !res?.options) throw new Error('No se pudieron obtener las opciones de la passkey.')
|
|
111
|
+
return res as { key: string; options: any }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Verificación por el BFF (+ cierre del login). Devuelve el body; si hubo token, ya cerró el login. */
|
|
115
|
+
async function verify(platform: boolean, contexts: string[], key: string, response: any) {
|
|
116
|
+
const data: any = await $fetch(platform ? '/_auth/platform/passkey/login' : '/_auth/passkey/login', {
|
|
117
|
+
method: 'POST',
|
|
118
|
+
body: platform ? { key, response } : { key, response, contexts },
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
if (!data?.user) return data // paso previo (cambio forzado / verificación de correo)
|
|
122
|
+
|
|
123
|
+
markPasskeyLogin(true)
|
|
124
|
+
if (platform) {
|
|
125
|
+
authStore.setAuthenticated(true)
|
|
126
|
+
authStore.saveUser(data.user)
|
|
127
|
+
return data
|
|
128
|
+
}
|
|
129
|
+
return finishLogin(data.context, data)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Ceremonia iniciada por el usuario (botón). Invalida antes el autocompletado. */
|
|
133
|
+
async function authenticate(platform: boolean, contexts: string[]) {
|
|
134
|
+
assertContexts(platform, contexts)
|
|
135
|
+
stopAutofill()
|
|
136
|
+
const { key, options } = await fetchLoginOptions(platform)
|
|
137
|
+
const response = await startAuthentication({ optionsJSON: options })
|
|
138
|
+
return verify(platform, contexts, key, response)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Botón "Ingresar con huella o passkey". */
|
|
142
|
+
const login = ({ contexts }: { contexts: string[] }) => authenticate(false, contexts)
|
|
143
|
+
|
|
144
|
+
const loginPlatform = () => authenticate(true, [])
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Autocompletado (conditional UI): el navegador sugiere la passkey al enfocar el
|
|
148
|
+
* campo de correo (necesita un input con autocomplete="username webauthn").
|
|
149
|
+
* Queda esperando hasta que el usuario elija una, se llame a stopAutofill() o se
|
|
150
|
+
* desmonte el componente; se renueva solo antes de que venza el reto (300 s).
|
|
151
|
+
*
|
|
152
|
+
* Devuelve null si no arrancó o se canceló. Los errores previos a que el usuario
|
|
153
|
+
* elija una passkey se silencian (console.debug); solo lanza los errores del BFF
|
|
154
|
+
* tras elegir una, y el de configuración (login de tenant sin contexts).
|
|
155
|
+
*/
|
|
156
|
+
async function startAutofill({ contexts = [], platform = false }: { contexts?: string[]; platform?: boolean } = {}) {
|
|
157
|
+
if (!import.meta.client || guard.disposed) return null
|
|
158
|
+
assertContexts(platform, contexts)
|
|
159
|
+
// Reentrante: aborta la ceremonia de una corrida anterior antes de abrir otra.
|
|
160
|
+
stopAutofill()
|
|
161
|
+
const id = guard.next()
|
|
162
|
+
|
|
163
|
+
if (!(await supportsAutofill())) return null
|
|
164
|
+
if (!guard.isCurrent(id)) return null
|
|
165
|
+
|
|
166
|
+
while (guard.isCurrent(id)) {
|
|
167
|
+
if (!document.querySelector(WEBAUTHN_INPUT_SELECTOR)) {
|
|
168
|
+
debug('sin input con autocomplete "… webauthn": no se arranca el autocompletado')
|
|
169
|
+
return null
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
let key: string
|
|
173
|
+
let options: any
|
|
174
|
+
autofillPhase = 'options'
|
|
175
|
+
try {
|
|
176
|
+
({ key, options } = await fetchLoginOptions(platform))
|
|
177
|
+
} catch (err) {
|
|
178
|
+
debug('opciones del autocompletado', err)
|
|
179
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
180
|
+
return null
|
|
181
|
+
}
|
|
182
|
+
if (!guard.isCurrent(id)) return null
|
|
183
|
+
|
|
184
|
+
let response: any
|
|
185
|
+
autofillPhase = 'waiting'
|
|
186
|
+
renewRequested = false
|
|
187
|
+
renewTimer = setTimeout(() => {
|
|
188
|
+
renewTimer = null
|
|
189
|
+
if (!guard.isCurrent(id) || autofillPhase !== 'waiting') return
|
|
190
|
+
renewRequested = true
|
|
191
|
+
WebAuthnAbortService.cancelCeremony()
|
|
192
|
+
}, AUTOFILL_RENEW_MS)
|
|
193
|
+
try {
|
|
194
|
+
response = await startAuthentication({ optionsJSON: options, useBrowserAutofill: true })
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (guard.isCurrent(id)) clearRenewTimer()
|
|
197
|
+
if (renewRequested && guard.isCurrent(id)) {
|
|
198
|
+
renewRequested = false
|
|
199
|
+
continue // reto por vencer: pedir uno nuevo
|
|
200
|
+
}
|
|
201
|
+
debug('autocompletado terminado', err)
|
|
202
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
203
|
+
return null
|
|
204
|
+
}
|
|
205
|
+
clearRenewTimer()
|
|
206
|
+
if (!guard.isCurrent(id)) return null
|
|
207
|
+
|
|
208
|
+
// El usuario eligió una passkey: desde aquí los errores sí se muestran.
|
|
209
|
+
autofillPhase = 'verifying'
|
|
210
|
+
try {
|
|
211
|
+
return await verify(platform, contexts, key, response)
|
|
212
|
+
} finally {
|
|
213
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return null
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Detiene el autocompletado (también las corridas aún pidiendo opciones). */
|
|
220
|
+
function stopAutofill() {
|
|
221
|
+
const wasWaiting = autofillPhase === 'waiting'
|
|
222
|
+
guard.invalidate()
|
|
223
|
+
clearRenewTimer()
|
|
224
|
+
renewRequested = false
|
|
225
|
+
autofillPhase = 'idle'
|
|
226
|
+
if (wasWaiting) WebAuthnAbortService.cancelCeremony()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Libera el composable: ningún autocompletado vuelve a arrancar. */
|
|
230
|
+
function dispose() {
|
|
231
|
+
stopAutofill()
|
|
232
|
+
guard.dispose()
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// ── Gestión propia ────────────────────────────────────────────────────────
|
|
236
|
+
|
|
237
|
+
async function list(base = 'auth'): Promise<PasskeyItem[]> {
|
|
238
|
+
const res: any = await api.get(`${base}/me/passkeys`)
|
|
239
|
+
return res?.data ?? []
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** useApi devuelve null en 401: error legible (passkeyErrorMessage lee data.message). */
|
|
243
|
+
function sessionError() {
|
|
244
|
+
return Object.assign(new Error('Tu sesión expiró. Vuelve a ingresar para gestionar tus passkeys.'), {
|
|
245
|
+
data: { message: 'Tu sesión expiró. Vuelve a ingresar para gestionar tus passkeys.' },
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function register(name?: string, base = 'auth'): Promise<PasskeyItem> {
|
|
250
|
+
const res: any = await api.post(`${base}/me/passkeys/options`)
|
|
251
|
+
if (!res?.key || !res?.options) throw sessionError()
|
|
252
|
+
const response = await startRegistration({ optionsJSON: res.options })
|
|
253
|
+
const ua = import.meta.client ? navigator.userAgent : ''
|
|
254
|
+
const created: any = await api.post(`${base}/me/passkeys`, { key: res.key, response, name: name || suggestPasskeyName(ua) })
|
|
255
|
+
if (!created) throw sessionError()
|
|
256
|
+
return created
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const rename = (id: string, name: string, base = 'auth') => api.patch(`${base}/me/passkeys/${id}`, { name })
|
|
260
|
+
|
|
261
|
+
const remove = (id: string, base = 'auth') => api.delete(`${base}/me/passkeys/${id}`)
|
|
262
|
+
|
|
263
|
+
// ── Administración ────────────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
async function listForUser(userId: string | number): Promise<PasskeyItem[]> {
|
|
266
|
+
const res: any = await api.get(`users/${userId}/passkeys`)
|
|
267
|
+
return res?.data ?? []
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
async function revokeAll(userId: string | number): Promise<number> {
|
|
271
|
+
const res: any = await api.delete(`users/${userId}/passkeys`)
|
|
272
|
+
return res?.revoked ?? 0
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
supported,
|
|
277
|
+
autofillSupported,
|
|
278
|
+
ready,
|
|
279
|
+
login,
|
|
280
|
+
loginPlatform,
|
|
281
|
+
startAutofill,
|
|
282
|
+
stopAutofill,
|
|
283
|
+
dispose,
|
|
284
|
+
isDisposed: () => guard.disposed,
|
|
285
|
+
loggedInWithPasskey,
|
|
286
|
+
markPasskeyLogin,
|
|
287
|
+
list,
|
|
288
|
+
register,
|
|
289
|
+
rename,
|
|
290
|
+
remove,
|
|
291
|
+
listForUser,
|
|
292
|
+
revokeAll,
|
|
293
|
+
errorMessage: passkeyErrorMessage,
|
|
294
|
+
isCancel: isPasskeyCancel,
|
|
295
|
+
isDismissed: isPasskeyDismissed,
|
|
296
|
+
isContextsError: (err: any) => err?.code === CONTEXTS_REQUIRED,
|
|
297
|
+
}
|
|
298
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { passkeyErrorMessage, isPasskeyCancel, isPasskeyDismissed, contextsRequiredError, CONTEXTS_REQUIRED, suggestPasskeyName, shouldShowPasskeyInvite, inviteStorageKey } from '../passkeys'
|
|
3
|
+
|
|
4
|
+
const domErr = (name: string) => Object.assign(new Error(name), { name })
|
|
5
|
+
|
|
6
|
+
describe('passkeyErrorMessage', () => {
|
|
7
|
+
it('traduce errores del navegador', () => {
|
|
8
|
+
expect(passkeyErrorMessage(domErr('NotAllowedError'))).toBe('Se canceló o se agotó el tiempo. Inténtalo de nuevo.')
|
|
9
|
+
expect(passkeyErrorMessage(domErr('InvalidStateError'))).toBe('Este dispositivo ya tiene una passkey para tu cuenta.')
|
|
10
|
+
expect(passkeyErrorMessage(domErr('SecurityError'))).toBe('Este sitio no está habilitado para passkeys. Avisa al administrador.')
|
|
11
|
+
expect(passkeyErrorMessage(domErr('NotSupportedError'))).toBe('Este navegador no permite usar passkeys.')
|
|
12
|
+
})
|
|
13
|
+
it('usa el mensaje del backend (FetchError de ofetch)', () => {
|
|
14
|
+
expect(passkeyErrorMessage({ data: { message: 'No pudimos verificar la passkey.' } })).toBe('No pudimos verificar la passkey.')
|
|
15
|
+
})
|
|
16
|
+
it('cae a un genérico', () => {
|
|
17
|
+
expect(passkeyErrorMessage(new Error('x'))).toBe('No se pudo completar la operación con la passkey.')
|
|
18
|
+
})
|
|
19
|
+
it('simplewebauthn envuelve el error del navegador en .cause', () => {
|
|
20
|
+
expect(passkeyErrorMessage({ name: 'WebAuthnError', code: 'ERROR_CEREMONY_ABORTED', cause: domErr('NotAllowedError') }))
|
|
21
|
+
.toBe('Se canceló o se agotó el tiempo. Inténtalo de nuevo.')
|
|
22
|
+
})
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
describe('isPasskeyCancel', () => {
|
|
26
|
+
it('detecta cancelaciones y aborts (no se muestran como error)', () => {
|
|
27
|
+
expect(isPasskeyCancel(domErr('AbortError'))).toBe(true)
|
|
28
|
+
expect(isPasskeyCancel({ name: 'WebAuthnError', code: 'ERROR_CEREMONY_ABORTED' })).toBe(true)
|
|
29
|
+
expect(isPasskeyCancel(domErr('SecurityError'))).toBe(false)
|
|
30
|
+
})
|
|
31
|
+
it('NotAllowedError no es un abort (en gestión sigue mostrando mensaje)', () => {
|
|
32
|
+
expect(isPasskeyCancel(domErr('NotAllowedError'))).toBe(false)
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
describe('isPasskeyDismissed (botón de ingreso)', () => {
|
|
37
|
+
it('trata NotAllowedError como cancelación del usuario', () => {
|
|
38
|
+
expect(isPasskeyDismissed(domErr('NotAllowedError'))).toBe(true)
|
|
39
|
+
expect(isPasskeyDismissed({ name: 'WebAuthnError', code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY', cause: domErr('NotAllowedError') })).toBe(true)
|
|
40
|
+
})
|
|
41
|
+
it('incluye los aborts', () => {
|
|
42
|
+
expect(isPasskeyDismissed(domErr('AbortError'))).toBe(true)
|
|
43
|
+
expect(isPasskeyDismissed({ name: 'WebAuthnError', code: 'ERROR_CEREMONY_ABORTED' })).toBe(true)
|
|
44
|
+
})
|
|
45
|
+
it('no oculta errores reales', () => {
|
|
46
|
+
expect(isPasskeyDismissed(domErr('SecurityError'))).toBe(false)
|
|
47
|
+
expect(isPasskeyDismissed({ data: { message: 'No pudimos verificar la passkey.' } })).toBe(false)
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe('contextsRequiredError', () => {
|
|
52
|
+
it('lleva mensaje y código', () => {
|
|
53
|
+
const e: any = contextsRequiredError()
|
|
54
|
+
expect(e.message).toBe('PasskeyButton requiere contexts')
|
|
55
|
+
expect(e.code).toBe(CONTEXTS_REQUIRED)
|
|
56
|
+
})
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
describe('suggestPasskeyName', () => {
|
|
60
|
+
it('arma "Dispositivo · Navegador"', () => {
|
|
61
|
+
expect(suggestPasskeyName('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15')).toBe('Mac · Safari')
|
|
62
|
+
expect(suggestPasskeyName('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36')).toBe('Mac · Chrome')
|
|
63
|
+
expect(suggestPasskeyName('Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Version/18.0 Mobile/15E148 Safari/604.1')).toBe('iPhone · Safari')
|
|
64
|
+
expect(suggestPasskeyName('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 Edg/130.0')).toBe('Windows · Edge')
|
|
65
|
+
expect(suggestPasskeyName('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36')).toBe('Android · Chrome')
|
|
66
|
+
expect(suggestPasskeyName('')).toBe('Passkey')
|
|
67
|
+
})
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
describe('shouldShowPasskeyInvite', () => {
|
|
71
|
+
const base = { supported: true, enabled: true, dismissed: false, hasPasskeys: false, loggedInWithPasskey: false }
|
|
72
|
+
it('se muestra solo si todo calza', () => {
|
|
73
|
+
expect(shouldShowPasskeyInvite(base)).toBe(true)
|
|
74
|
+
expect(shouldShowPasskeyInvite({ ...base, supported: false })).toBe(false)
|
|
75
|
+
expect(shouldShowPasskeyInvite({ ...base, enabled: false })).toBe(false)
|
|
76
|
+
expect(shouldShowPasskeyInvite({ ...base, dismissed: true })).toBe(false)
|
|
77
|
+
expect(shouldShowPasskeyInvite({ ...base, hasPasskeys: true })).toBe(false)
|
|
78
|
+
expect(shouldShowPasskeyInvite({ ...base, loggedInWithPasskey: true })).toBe(false)
|
|
79
|
+
})
|
|
80
|
+
it('la clave de localStorage es por usuario', () => {
|
|
81
|
+
expect(inviteStorageKey(42)).toBe('innertia:passkey-invite:42')
|
|
82
|
+
})
|
|
83
|
+
})
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { createRunGuard } from '../runGuard'
|
|
3
|
+
|
|
4
|
+
describe('createRunGuard', () => {
|
|
5
|
+
it('la última corrida es la vigente', () => {
|
|
6
|
+
const g = createRunGuard()
|
|
7
|
+
const a = g.next()
|
|
8
|
+
expect(g.isCurrent(a)).toBe(true)
|
|
9
|
+
const b = g.next()
|
|
10
|
+
expect(g.isCurrent(a)).toBe(false)
|
|
11
|
+
expect(g.isCurrent(b)).toBe(true)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('invalidate() deja sin vigencia la corrida en vuelo', () => {
|
|
15
|
+
const g = createRunGuard()
|
|
16
|
+
const a = g.next()
|
|
17
|
+
g.invalidate()
|
|
18
|
+
expect(g.isCurrent(a)).toBe(false)
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
it('dispose() invalida la actual y las futuras', () => {
|
|
22
|
+
const g = createRunGuard()
|
|
23
|
+
const a = g.next()
|
|
24
|
+
g.dispose()
|
|
25
|
+
expect(g.disposed).toBe(true)
|
|
26
|
+
expect(g.isCurrent(a)).toBe(false)
|
|
27
|
+
const b = g.next()
|
|
28
|
+
expect(g.isCurrent(b)).toBe(false)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('descarta una corrida vieja tras un await (carrera)', async () => {
|
|
32
|
+
const g = createRunGuard()
|
|
33
|
+
const results: string[] = []
|
|
34
|
+
const run = async (label: string, delay: number) => {
|
|
35
|
+
const id = g.next()
|
|
36
|
+
await new Promise(r => setTimeout(r, delay))
|
|
37
|
+
if (g.isCurrent(id)) results.push(label)
|
|
38
|
+
}
|
|
39
|
+
await Promise.all([run('vieja', 20), run('nueva', 5)])
|
|
40
|
+
expect(results).toEqual(['nueva'])
|
|
41
|
+
})
|
|
42
|
+
})
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Lógica pura de passkeys (sin Vue ni navegador): testeable en node.
|
|
2
|
+
|
|
3
|
+
const BROWSER_ERRORS: Record<string, string> = {
|
|
4
|
+
NotAllowedError: 'Se canceló o se agotó el tiempo. Inténtalo de nuevo.',
|
|
5
|
+
InvalidStateError: 'Este dispositivo ya tiene una passkey para tu cuenta.',
|
|
6
|
+
SecurityError: 'Este sitio no está habilitado para passkeys. Avisa al administrador.',
|
|
7
|
+
NotSupportedError: 'Este navegador no permite usar passkeys.',
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const GENERIC = 'No se pudo completar la operación con la passkey.'
|
|
11
|
+
|
|
12
|
+
function browserErrorName(err: any): string | undefined {
|
|
13
|
+
// simplewebauthn lanza WebAuthnError con el DOMException original en .cause
|
|
14
|
+
return err?.cause?.name ?? err?.name
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Cancelación del usuario o abort del autocompletado: no se muestra como error. */
|
|
18
|
+
export function isPasskeyCancel(err: any): boolean {
|
|
19
|
+
const name = browserErrorName(err)
|
|
20
|
+
return name === 'AbortError' || err?.code === 'ERROR_CEREMONY_ABORTED'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Botón de ingreso: además de los aborts, NotAllowedError (el usuario cerró el
|
|
25
|
+
* diálogo del navegador o se agotó el tiempo) cuenta como cancelación y no se muestra.
|
|
26
|
+
*/
|
|
27
|
+
export function isPasskeyDismissed(err: any): boolean {
|
|
28
|
+
return isPasskeyCancel(err) || browserErrorName(err) === 'NotAllowedError'
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Código del error de configuración: login de tenant sin contexts. */
|
|
32
|
+
export const CONTEXTS_REQUIRED = 'PASSKEY_CONTEXTS_REQUIRED'
|
|
33
|
+
|
|
34
|
+
export function contextsRequiredError(): Error {
|
|
35
|
+
return Object.assign(new Error('PasskeyButton requiere contexts'), { code: CONTEXTS_REQUIRED })
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Selector del campo que habilita el autocompletado (simplewebauthn exige "webauthn" al final). */
|
|
39
|
+
export const WEBAUTHN_INPUT_SELECTOR = "input[autocomplete$='webauthn']"
|
|
40
|
+
|
|
41
|
+
export function passkeyErrorMessage(err: any): string {
|
|
42
|
+
const backend = err?.data?.message
|
|
43
|
+
if (typeof backend === 'string' && backend) return backend
|
|
44
|
+
const name = browserErrorName(err)
|
|
45
|
+
return (name && BROWSER_ERRORS[name]) || GENERIC
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function suggestPasskeyName(userAgent: string): string {
|
|
49
|
+
const ua = userAgent || ''
|
|
50
|
+
const device = /iPhone/.test(ua) ? 'iPhone'
|
|
51
|
+
: /iPad/.test(ua) ? 'iPad'
|
|
52
|
+
: /Android/.test(ua) ? 'Android'
|
|
53
|
+
: /Macintosh|Mac OS X/.test(ua) ? 'Mac'
|
|
54
|
+
: /Windows/.test(ua) ? 'Windows'
|
|
55
|
+
: /Linux/.test(ua) ? 'Linux'
|
|
56
|
+
: ''
|
|
57
|
+
const browser = /Edg\//.test(ua) ? 'Edge'
|
|
58
|
+
: /Firefox\//.test(ua) ? 'Firefox'
|
|
59
|
+
: /Chrome\//.test(ua) ? 'Chrome'
|
|
60
|
+
: /Safari\//.test(ua) ? 'Safari'
|
|
61
|
+
: ''
|
|
62
|
+
if (!device && !browser) return 'Passkey'
|
|
63
|
+
return [device, browser].filter(Boolean).join(' · ')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PasskeyInviteState {
|
|
67
|
+
supported: boolean
|
|
68
|
+
enabled: boolean
|
|
69
|
+
dismissed: boolean
|
|
70
|
+
hasPasskeys: boolean
|
|
71
|
+
loggedInWithPasskey: boolean
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function shouldShowPasskeyInvite(s: PasskeyInviteState): boolean {
|
|
75
|
+
return s.supported && s.enabled && !s.dismissed && !s.hasPasskeys && !s.loggedInWithPasskey
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function inviteStorageKey(userId: string | number): string {
|
|
79
|
+
return `innertia:passkey-invite:${userId}`
|
|
80
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Seguimiento de "corridas" (lógica pura, testeable en node): cada arranque del
|
|
2
|
+
// autocompletado pide un id con next(); una corrida sigue vigente mientras sea la
|
|
3
|
+
// última y el guard no se haya liberado. Sirve para descartar resultados de
|
|
4
|
+
// corridas viejas (await en vuelo) aunque el AbortController de simplewebauthn
|
|
5
|
+
// todavía no exista.
|
|
6
|
+
|
|
7
|
+
export interface RunGuard {
|
|
8
|
+
/** Invalida la corrida actual y devuelve el id de una nueva. */
|
|
9
|
+
next(): number
|
|
10
|
+
/** Invalida la corrida actual sin abrir otra. */
|
|
11
|
+
invalidate(): void
|
|
12
|
+
/** true si `id` es la última corrida y el guard no se liberó. */
|
|
13
|
+
isCurrent(id: number): boolean
|
|
14
|
+
/** Libera el guard: ninguna corrida (actual o futura) queda vigente. */
|
|
15
|
+
dispose(): void
|
|
16
|
+
readonly disposed: boolean
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createRunGuard(): RunGuard {
|
|
20
|
+
let current = 0
|
|
21
|
+
let disposed = false
|
|
22
|
+
return {
|
|
23
|
+
next() {
|
|
24
|
+
current += 1
|
|
25
|
+
return current
|
|
26
|
+
},
|
|
27
|
+
invalidate() {
|
|
28
|
+
current += 1
|
|
29
|
+
},
|
|
30
|
+
isCurrent(id: number) {
|
|
31
|
+
return !disposed && id === current
|
|
32
|
+
},
|
|
33
|
+
dispose() {
|
|
34
|
+
disposed = true
|
|
35
|
+
current += 1
|
|
36
|
+
},
|
|
37
|
+
get disposed() {
|
|
38
|
+
return disposed
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
}
|
package/docs/passkeys.md
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# Passkeys (WebAuthn)
|
|
2
|
+
|
|
3
|
+
Ingreso con huella, rostro o llave de seguridad sobre `\Innertia\Passkeys` de innertia-laravel. Hay componentes para el login, la invitación a registrar, la gestión propia y la administración por usuario, más el composable `usePasskeys()`.
|
|
4
|
+
|
|
5
|
+
## Requisitos (backend Laravel)
|
|
6
|
+
|
|
7
|
+
1. En el `.env` del producto: `PASSKEYS_ENABLED=true`.
|
|
8
|
+
2. `php artisan migrate` (crea la tabla de passkeys).
|
|
9
|
+
3. `PASSKEYS_RP_ID` = host del **front** (en dev, `localhost`; en prod, por ejemplo `app.pomely.cl`). Los orígenes permitidos por defecto son la URL del front.
|
|
10
|
+
4. Si los tenants viven en subdominios: `PASSKEYS_ALLOW_SUBDOMAINS=true`.
|
|
11
|
+
5. El cache store de Laravel debe ser **compartido** entre instancias (Redis); las opciones de la ceremonia se guardan ahí.
|
|
12
|
+
|
|
13
|
+
Notas:
|
|
14
|
+
|
|
15
|
+
- Las cuentas de plataforma con cambio de contraseña forzado pendiente no pueden registrar una passkey hasta cambiarla.
|
|
16
|
+
- El BFF (`/_auth/passkey/login`, `/_auth/platform/passkey/login`) sella la sesión httpOnly **solo si Laravel devuelve token**. Los pasos previos (cambio forzado, verificación de correo) no traen token y llegan al componente como `pending`. El token nunca llega al navegador.
|
|
17
|
+
|
|
18
|
+
## Login de tenant
|
|
19
|
+
|
|
20
|
+
`<Auth.PasskeyButton>` arranca la ceremonia y, con `autofill` (por defecto), también el autocompletado del navegador.
|
|
21
|
+
|
|
22
|
+
- **Autocompletado:** necesita un input con `autocomplete="username webauthn"` (con `webauthn` al final) presente al montar el botón; si no existe, el autocompletado simplemente no arranca. `<Auth.LoginForm>` de la librería ya lo trae. El autocompletado se renueva solo cada ~270 s (el reto dura 300 s), se detiene al pulsar el botón y al desmontar, y no se reanuda tras un ingreso exitoso. Sus errores previos a que el usuario elija una passkey no se muestran (solo `console.debug` en dev).
|
|
23
|
+
- **`contexts` es obligatorio** en el login de tenant (el backend exige al menos uno). Sin `contexts` y sin `platform`, el composable lanza `Error('PasskeyButton requiere contexts')` antes de cualquier ceremonia y avisa por consola en dev.
|
|
24
|
+
|
|
25
|
+
```vue
|
|
26
|
+
<template>
|
|
27
|
+
<form @submit.prevent="onSubmit">
|
|
28
|
+
<input v-model="email" type="email" autocomplete="username webauthn" />
|
|
29
|
+
<input v-model="password" type="password" autocomplete="current-password" />
|
|
30
|
+
<button type="submit">Ingresar</button>
|
|
31
|
+
|
|
32
|
+
<Auth.PasskeyButton
|
|
33
|
+
:contexts="['backoffice']"
|
|
34
|
+
@success="onPasskeySuccess"
|
|
35
|
+
@pending="onPasskeyPending"
|
|
36
|
+
/>
|
|
37
|
+
</form>
|
|
38
|
+
</template>
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
- `@success(data)`: ingreso completo. `data.context` indica el contexto (y `data.tenantDestination` en modo `open`). Navega igual que tras `performLogin` (`finishLogin` ya dejó la sesión lista).
|
|
42
|
+
- `@pending(data)`: hay un paso previo, p. ej. cambio forzado de contraseña; reutiliza el mismo flujo que el login con contraseña.
|
|
43
|
+
- `@error(message, originalError)`: mensaje legible para mostrar y el error original (p. ej. para detectar un 409 `platform_account`: `originalError?.status === 409`). Las cancelaciones del usuario (cerrar el diálogo del navegador, `NotAllowedError`, aborts) no emiten nada.
|
|
44
|
+
|
|
45
|
+
Props: `contexts` (array), `platform` (bool), `autofill` (bool, `true`), `label` (texto del botón).
|
|
46
|
+
|
|
47
|
+
## Login de plataforma
|
|
48
|
+
|
|
49
|
+
En `/platform/login`, con la prop `platform` (identidad separada, sin contexto de tenant):
|
|
50
|
+
|
|
51
|
+
```vue
|
|
52
|
+
<Auth.PasskeyButton platform @success="navigateTo('/platform')" />
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
El ingreso de plataforma siempre devuelve token (no hay `pending`). Si la cuenta tiene un cambio de contraseña forzado pendiente, el ingreso funciona pero las llamadas siguientes responden `403 password_change_required`: en ese caso redirige a la pantalla de cambio de contraseña.
|
|
56
|
+
|
|
57
|
+
## Invitación tras ingresar con contraseña
|
|
58
|
+
|
|
59
|
+
`<Auth.PasskeyInvite />` muestra un aviso discreto "Ingresa con tu huella la próxima vez", una sola vez por usuario y dispositivo. No aparece si el navegador no soporta WebAuthn, si ya hay passkeys, si se descartó o si el ingreso fue con passkey. Colócalo en el layout autenticado:
|
|
60
|
+
|
|
61
|
+
```vue
|
|
62
|
+
<!-- layouts/backoffice.vue -->
|
|
63
|
+
<Auth.PasskeyInvite />
|
|
64
|
+
|
|
65
|
+
<!-- layouts/platform.vue -->
|
|
66
|
+
<Auth.PasskeyInvite base="platform/auth" />
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Gestión propia (perfil)
|
|
70
|
+
|
|
71
|
+
`<Auth.PasskeyManager>` lista, agrega, renombra y elimina las passkeys del usuario autenticado. `base` es `auth` (tenant, por defecto) o `platform/auth` (cuenta de plataforma).
|
|
72
|
+
|
|
73
|
+
```vue
|
|
74
|
+
<Auth.PasskeyManager base="auth" />
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Administración por usuario
|
|
78
|
+
|
|
79
|
+
`<Auth.UserPasskeys>` muestra las passkeys de otro usuario y permite revocarlas todas. Úsalo en la ficha de usuario **solo para administradores**.
|
|
80
|
+
|
|
81
|
+
```vue
|
|
82
|
+
<Auth.UserPasskeys v-if="isAdmin" :user-id="user.id" />
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Composable `usePasskeys()`
|
|
86
|
+
|
|
87
|
+
| Método | Uso |
|
|
88
|
+
|--------|-----|
|
|
89
|
+
| `supported`, `autofillSupported`, `ready` | refs con el soporte del navegador; `false` en SSR y en el primer render, se resuelven en `onMounted` (`ready` indica que ya se resolvió) |
|
|
90
|
+
| `login({ contexts })`, `loginPlatform()` | ceremonia de ingreso (tenant / plataforma) |
|
|
91
|
+
| `startAutofill({ contexts, platform })`, `stopAutofill()`, `dispose()` | autocompletado (conditional UI); se libera solo al desmontar el componente que llamó a `usePasskeys()` |
|
|
92
|
+
| `list(base)`, `register(name?, base)`, `rename(id, name, base)`, `remove(id, base)` | gestión propia |
|
|
93
|
+
| `listForUser(userId)`, `revokeAll(userId)` | administración |
|
|
94
|
+
| `loggedInWithPasskey()`, `markPasskeyLogin(on)` | marca de sesión (oculta la invitación) |
|
|
95
|
+
| `errorMessage(err)`, `isCancel(err)`, `isDismissed(err)` | mensajes legibles; `isCancel` = aborts; `isDismissed` = aborts + `NotAllowedError` (botón de ingreso) |
|
|
96
|
+
|
|
97
|
+
Llama a `usePasskeys()` durante el `setup` de un componente.
|
package/nuxt.config.ts
CHANGED
|
@@ -29,7 +29,7 @@ export default defineNuxtConfig({
|
|
|
29
29
|
{ path: './components', pathPrefix: true, prefix: '' },
|
|
30
30
|
],
|
|
31
31
|
imports: {
|
|
32
|
-
dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory'],
|
|
32
|
+
dirs: ['stores', 'composables', 'composables/useWorkflow', 'composables/useStorageTestRunner', 'composables/useNotificationHistory', 'composables/usePasskeys'],
|
|
33
33
|
presets: [
|
|
34
34
|
{
|
|
35
35
|
from: '@tanstack/vue-query',
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@innertia-solutions/innertia-nuxt",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.81",
|
|
4
4
|
"description": "Innertia Solutions — Nuxt layer unificada: core, auth, multitenancy, theme y app contexts",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"nuxt",
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
"@floating-ui/dom": "^1.7.6",
|
|
35
35
|
"@nuxtjs/seo": "^3.4.0",
|
|
36
36
|
"@pinia/nuxt": "^0.11.3",
|
|
37
|
+
"@simplewebauthn/browser": "^13.3.0",
|
|
37
38
|
"@tabler/icons-vue": "^3.44.0",
|
|
38
39
|
"@tailwindcss/aspect-ratio": "^0.4.2",
|
|
39
40
|
"@tailwindcss/forms": "^0.5.10",
|
|
@@ -48,14 +49,14 @@
|
|
|
48
49
|
"date-fns": "^4.1.0",
|
|
49
50
|
"date-fns-tz": "^3.2.0",
|
|
50
51
|
"dayjs": "^1.11.0",
|
|
52
|
+
"iron-webcrypto": "^1.2.1",
|
|
51
53
|
"pinia-plugin-persistedstate": "^4.7.1",
|
|
52
54
|
"preline": "^3.2.3",
|
|
53
55
|
"pusher-js": "^8.5.0",
|
|
54
56
|
"tailwindcss": "^4.0.0",
|
|
55
57
|
"uuid": "^13.0.0",
|
|
56
58
|
"vanilla-calendar-pro": "^3.1.0",
|
|
57
|
-
"vue3-apexcharts": "^1.11.1"
|
|
58
|
-
"iron-webcrypto": "^1.2.1"
|
|
59
|
+
"vue3-apexcharts": "^1.11.1"
|
|
59
60
|
},
|
|
60
61
|
"scripts": {
|
|
61
62
|
"test": "vitest run"
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { defineEventHandler, readBody, createError, getRequestHeader } from 'h3'
|
|
2
|
+
import { writeSession } from '../../../utils/session'
|
|
3
|
+
import { forwardClientHeaders } from '../../../utils/bff'
|
|
4
|
+
import { normalizePasskeyLoginResponse, passkeyLoginErrorMessage } from '../../../utils/passkeyLogin'
|
|
5
|
+
|
|
6
|
+
// Ingreso con passkey (tenant). Laravel valida la assertion y entra al primer
|
|
7
|
+
// contexto de `contexts` al que el usuario tenga acceso. En éxito sella el JWT
|
|
8
|
+
// en la sesión httpOnly con ese contexto y devuelve el body SIN token. Pasos
|
|
9
|
+
// previos (cambio forzado / verificación de correo) no traen token: no se sella.
|
|
10
|
+
export default defineEventHandler(async (event) => {
|
|
11
|
+
const { key, response, contexts } = await readBody(event)
|
|
12
|
+
const config = useRuntimeConfig(event)
|
|
13
|
+
let data: any
|
|
14
|
+
try {
|
|
15
|
+
data = await $fetch(`${config.apiInternalUrl}/auth/passkey/login`, {
|
|
16
|
+
method: 'POST',
|
|
17
|
+
body: { key, response, contexts },
|
|
18
|
+
headers: { Accept: 'application/json', ...forwardClientHeaders(n => getRequestHeader(event, n)) },
|
|
19
|
+
})
|
|
20
|
+
} catch (err: any) {
|
|
21
|
+
const status = err?.response?.status ?? err?.statusCode ?? 500
|
|
22
|
+
throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'passkey_login_failed', message: passkeyLoginErrorMessage(status, err?.data) })
|
|
23
|
+
}
|
|
24
|
+
const { token, body } = normalizePasskeyLoginResponse(data)
|
|
25
|
+
if (token) await writeSession(event, { token, currentContext: body.context as string | undefined })
|
|
26
|
+
return body
|
|
27
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { defineEventHandler, readBody, createError, getRequestHeader } from 'h3'
|
|
2
|
+
import { writeSession } from '../../../../utils/session'
|
|
3
|
+
import { forwardClientHeaders } from '../../../../utils/bff'
|
|
4
|
+
import { normalizePasskeyLoginResponse, passkeyLoginErrorMessage } from '../../../../utils/passkeyLogin'
|
|
5
|
+
|
|
6
|
+
// Ingreso con passkey a /platform (identidad separada, sin contexto de tenant).
|
|
7
|
+
// Igual que /_auth/platform/login: sella el JWT y devuelve el body sin token.
|
|
8
|
+
export default defineEventHandler(async (event) => {
|
|
9
|
+
const { key, response } = await readBody(event)
|
|
10
|
+
const config = useRuntimeConfig(event)
|
|
11
|
+
let data: any
|
|
12
|
+
try {
|
|
13
|
+
data = await $fetch(`${config.apiInternalUrl}/platform/auth/passkey/login`, {
|
|
14
|
+
method: 'POST',
|
|
15
|
+
body: { key, response },
|
|
16
|
+
headers: { Accept: 'application/json', ...forwardClientHeaders(n => getRequestHeader(event, n)) },
|
|
17
|
+
})
|
|
18
|
+
} catch (err: any) {
|
|
19
|
+
const status = err?.response?.status ?? err?.statusCode ?? 500
|
|
20
|
+
throw createError({ statusCode: status, data: err?.data ?? null, statusMessage: 'passkey_login_failed', message: passkeyLoginErrorMessage(status, err?.data) })
|
|
21
|
+
}
|
|
22
|
+
const { token, body } = normalizePasskeyLoginResponse(data)
|
|
23
|
+
if (token) await writeSession(event, { token })
|
|
24
|
+
return body
|
|
25
|
+
})
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { normalizePasskeyLoginResponse, passkeyLoginErrorMessage } from '../passkeyLogin'
|
|
3
|
+
|
|
4
|
+
describe('normalizePasskeyLoginResponse', () => {
|
|
5
|
+
it('separa el token y conserva el contexto elegido', () => {
|
|
6
|
+
const { token, body } = normalizePasskeyLoginResponse({ token: 't1', user: { id: 1 }, context: 'portal' })
|
|
7
|
+
expect(token).toBe('t1')
|
|
8
|
+
expect(body).toMatchObject({ user: { id: 1 }, context: 'portal' })
|
|
9
|
+
expect(body).not.toHaveProperty('token')
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
it('un paso previo no trae token y conserva el flag, user_id y contexto', () => {
|
|
13
|
+
const { token, body } = normalizePasskeyLoginResponse({ requires_password_change: true, user_id: 7, context: 'backoffice' })
|
|
14
|
+
expect(token).toBeUndefined()
|
|
15
|
+
expect(body).toMatchObject({ requires_password_change: true, user_id: 7, context: 'backoffice' })
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('sin contexto (plataforma) no agrega la clave', () => {
|
|
19
|
+
const { body } = normalizePasskeyLoginResponse({ token: 't', user: { id: 1 } })
|
|
20
|
+
expect(body).not.toHaveProperty('context')
|
|
21
|
+
})
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
describe('passkeyLoginErrorMessage', () => {
|
|
25
|
+
it('422 → mensaje genérico de passkey', () => {
|
|
26
|
+
expect(passkeyLoginErrorMessage(422, {})).toBe('No pudimos verificar la passkey.')
|
|
27
|
+
})
|
|
28
|
+
it('429 → demasiados intentos', () => {
|
|
29
|
+
expect(passkeyLoginErrorMessage(429, {})).toMatch(/Demasiados intentos/)
|
|
30
|
+
})
|
|
31
|
+
it('403/409 → mensaje del backend', () => {
|
|
32
|
+
expect(passkeyLoginErrorMessage(403, { message: 'Esta cuenta no tiene acceso a esta aplicación.' })).toBe('Esta cuenta no tiene acceso a esta aplicación.')
|
|
33
|
+
expect(passkeyLoginErrorMessage(409, { message: 'Usa el acceso de plataforma.' })).toBe('Usa el acceso de plataforma.')
|
|
34
|
+
})
|
|
35
|
+
it('otro error sin mensaje → genérico', () => {
|
|
36
|
+
expect(passkeyLoginErrorMessage(500, null)).toBe('No se pudo iniciar sesión con la passkey. Inténtalo de nuevo.')
|
|
37
|
+
})
|
|
38
|
+
})
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { normalizeLoginResponse, type LaravelLoginResponse } from './login'
|
|
2
|
+
|
|
3
|
+
/** Igual que normalizeLoginResponse, conservando el contexto que eligió Laravel
|
|
4
|
+
* (el ingreso con passkey recibe una lista de contextos y entra al primero válido). */
|
|
5
|
+
export function normalizePasskeyLoginResponse(data: LaravelLoginResponse & { context?: string }) {
|
|
6
|
+
const { token, body } = normalizeLoginResponse(data)
|
|
7
|
+
if (typeof data.context === 'string' && data.context) body.context = data.context
|
|
8
|
+
return { token, body }
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function passkeyLoginErrorMessage(status: number, data: any): string {
|
|
12
|
+
if (status === 422) return 'No pudimos verificar la passkey.'
|
|
13
|
+
if (status === 429) return 'Demasiados intentos. Espera un minuto e inténtalo de nuevo.'
|
|
14
|
+
return (typeof data?.message === 'string' && data.message) || 'No se pudo iniciar sesión con la passkey. Inténtalo de nuevo.'
|
|
15
|
+
}
|