@innertia-solutions/innertia-nuxt 0.1.80 → 0.1.82
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 +105 -0
- package/components/Auth/PasskeyInvite.vue +78 -0
- package/components/Auth/PasskeyManager.vue +176 -0
- package/components/Auth/PasskeySettings.vue +130 -0
- package/components/Auth/UserPasskeys.vue +72 -0
- package/composables/useAuth.js +9 -1
- package/composables/usePasskeys/index.ts +348 -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/__tests__/statusCache.test.ts +38 -0
- package/composables/usePasskeys/internal/passkeys.ts +80 -0
- package/composables/usePasskeys/internal/runGuard.ts +41 -0
- package/composables/usePasskeys/internal/statusCache.ts +43 -0
- package/docs/passkeys.md +104 -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
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
import { ref, computed, 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
|
+
import { createStatusCache } from './internal/statusCache'
|
|
20
|
+
|
|
21
|
+
// Solo se exporta el composable (los helpers de ./internal no se auto-importan).
|
|
22
|
+
|
|
23
|
+
/** Marca de sesión: el último ingreso fue con passkey (la invitación no se muestra). */
|
|
24
|
+
const PASSKEY_LOGIN_FLAG = 'innertia:logged-in-with-passkey'
|
|
25
|
+
|
|
26
|
+
/** El reto vive 300 s en el backend: el autocompletado se renueva antes. */
|
|
27
|
+
const AUTOFILL_RENEW_MS = 270_000
|
|
28
|
+
|
|
29
|
+
/** Soporte de autocompletado: se consulta una vez por página (solo en el cliente). */
|
|
30
|
+
let autofillSupport: Promise<boolean> | null = null
|
|
31
|
+
function supportsAutofill(): Promise<boolean> {
|
|
32
|
+
if (!import.meta.client) return Promise.resolve(false)
|
|
33
|
+
autofillSupport ??= browserSupportsWebAuthnAutofill().catch(() => false)
|
|
34
|
+
return autofillSupport
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Estado del interruptor de plataforma: una consulta por base durante la vida de la página. */
|
|
38
|
+
const statusCaches = createStatusCache()
|
|
39
|
+
|
|
40
|
+
function debug(...args: any[]) {
|
|
41
|
+
if (import.meta.dev) console.debug('[passkeys]', ...args)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PasskeyItem {
|
|
45
|
+
id: string
|
|
46
|
+
name: string
|
|
47
|
+
provider: string | null
|
|
48
|
+
created_at: string | null
|
|
49
|
+
last_used_at: string | null
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Passkeys (WebAuthn) sobre innertia-laravel \Innertia\Passkeys.
|
|
54
|
+
* - Ingreso: opciones por /api, ceremonia en el navegador, verificación por el BFF
|
|
55
|
+
* (/_auth/passkey/login) que sella la sesión solo si hay token.
|
|
56
|
+
* - Gestión propia: base 'auth' (tenant) o 'platform/auth' (cuenta de plataforma).
|
|
57
|
+
*
|
|
58
|
+
* Interruptor: el backend lo guarda en BD y lo expone en `GET auth/passkey/status`
|
|
59
|
+
* (o `platform/auth/passkey/status`). `usePasskeys({ platform: true })` consulta el de
|
|
60
|
+
* plataforma; sin opciones, el de tenant. `enabled` es false hasta saberlo y
|
|
61
|
+
* `available` = supported && enabled. Con el interruptor apagado, login/autocompletado/
|
|
62
|
+
* registro no hacen nada (el autocompletado devuelve null; el resto lanza un error legible).
|
|
63
|
+
* La administración por usuario (listForUser/revokeAll) sigue funcionando.
|
|
64
|
+
*
|
|
65
|
+
* Llamar durante el setup de un componente: `supported`/`autofillSupported` se
|
|
66
|
+
* resuelven en onMounted (false en SSR y en el primer render → sin hydration
|
|
67
|
+
* mismatch) y el autocompletado se libera en onBeforeUnmount.
|
|
68
|
+
*/
|
|
69
|
+
export function usePasskeys({ platform: platformStatus = false }: { platform?: boolean } = {}) {
|
|
70
|
+
const api = useApi()
|
|
71
|
+
const statusBase = platformStatus ? 'platform/auth' : 'auth'
|
|
72
|
+
const statusCache = statusCaches.for(base => api.get(`${base}/passkey/status`))
|
|
73
|
+
const authStore = useAuthStore()
|
|
74
|
+
const { finishLogin } = useAuth()
|
|
75
|
+
|
|
76
|
+
const supported = ref(false)
|
|
77
|
+
const autofillSupported = ref(false)
|
|
78
|
+
/** true una vez resuelto el soporte en el cliente (para no mostrar "no soportado" antes de tiempo). */
|
|
79
|
+
const ready = ref(false)
|
|
80
|
+
/** Interruptor de plataforma (false hasta conocerse y ante cualquier fallo). */
|
|
81
|
+
const enabled = ref(false)
|
|
82
|
+
/** Soporte del navegador Y interruptor encendido: lo que decide si se ofrece la función. */
|
|
83
|
+
const available = computed(() => supported.value && enabled.value)
|
|
84
|
+
|
|
85
|
+
/** Resuelve (con caché) el interruptor y lo refleja en `enabled`. */
|
|
86
|
+
async function ensureEnabled(): Promise<boolean> {
|
|
87
|
+
if (!import.meta.client) return false
|
|
88
|
+
enabled.value = await statusCache.get(statusBase)
|
|
89
|
+
return enabled.value
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Descarta la caché (tras guardar el interruptor en /platform) y lo vuelve a leer. */
|
|
93
|
+
async function refreshStatus(): Promise<boolean> {
|
|
94
|
+
statusCache.reset()
|
|
95
|
+
return ensureEnabled()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function disabledError() {
|
|
99
|
+
return Object.assign(new Error('El ingreso con passkey está desactivado.'), {
|
|
100
|
+
data: { message: 'El ingreso con passkey está desactivado.' },
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function assertEnabled() {
|
|
105
|
+
if (!(await ensureEnabled())) throw disabledError()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function detectSupport() {
|
|
109
|
+
supported.value = browserSupportsWebAuthn()
|
|
110
|
+
autofillSupported.value = await supportsAutofill()
|
|
111
|
+
await ensureEnabled()
|
|
112
|
+
ready.value = true
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Autocompletado: corridas (generación) + fase + temporizador de renovación.
|
|
116
|
+
const guard = createRunGuard()
|
|
117
|
+
let autofillPhase: 'idle' | 'options' | 'waiting' | 'verifying' = 'idle'
|
|
118
|
+
let renewTimer: ReturnType<typeof setTimeout> | null = null
|
|
119
|
+
let renewRequested = false
|
|
120
|
+
|
|
121
|
+
function clearRenewTimer() {
|
|
122
|
+
if (renewTimer) clearTimeout(renewTimer)
|
|
123
|
+
renewTimer = null
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Dentro de un hook de ciclo de vida la instancia ya está montada: onMounted no
|
|
127
|
+
// correría nunca, así que se detecta el soporte de inmediato.
|
|
128
|
+
const instance = getCurrentInstance()
|
|
129
|
+
if (instance) onBeforeUnmount(dispose)
|
|
130
|
+
if (instance && !instance.isMounted) onMounted(() => { detectSupport() })
|
|
131
|
+
else if (import.meta.client) detectSupport()
|
|
132
|
+
|
|
133
|
+
function markPasskeyLogin(on: boolean) {
|
|
134
|
+
if (!import.meta.client) return
|
|
135
|
+
try { on ? sessionStorage.setItem(PASSKEY_LOGIN_FLAG, '1') : sessionStorage.removeItem(PASSKEY_LOGIN_FLAG) } catch {}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function loggedInWithPasskey(): boolean {
|
|
139
|
+
if (!import.meta.client) return false
|
|
140
|
+
try { return sessionStorage.getItem(PASSKEY_LOGIN_FLAG) === '1' } catch { return false }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function assertContexts(platform: boolean, contexts: string[]) {
|
|
144
|
+
if (platform || contexts?.length) return
|
|
145
|
+
if (import.meta.dev) console.warn('[passkeys] PasskeyButton requiere contexts (login de tenant): pasa :contexts="[...]" o usa la prop platform.')
|
|
146
|
+
throw contextsRequiredError()
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function fetchLoginOptions(platform: boolean) {
|
|
150
|
+
const res: any = await api.post(platform ? 'platform/auth/passkey/login/options' : 'auth/passkey/login/options')
|
|
151
|
+
if (!res?.key || !res?.options) throw new Error('No se pudieron obtener las opciones de la passkey.')
|
|
152
|
+
return res as { key: string; options: any }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Verificación por el BFF (+ cierre del login). Devuelve el body; si hubo token, ya cerró el login. */
|
|
156
|
+
async function verify(platform: boolean, contexts: string[], key: string, response: any) {
|
|
157
|
+
const data: any = await $fetch(platform ? '/_auth/platform/passkey/login' : '/_auth/passkey/login', {
|
|
158
|
+
method: 'POST',
|
|
159
|
+
body: platform ? { key, response } : { key, response, contexts },
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
if (!data?.user) return data // paso previo (cambio forzado / verificación de correo)
|
|
163
|
+
|
|
164
|
+
markPasskeyLogin(true)
|
|
165
|
+
if (platform) {
|
|
166
|
+
authStore.setAuthenticated(true)
|
|
167
|
+
authStore.saveUser(data.user)
|
|
168
|
+
return data
|
|
169
|
+
}
|
|
170
|
+
return finishLogin(data.context, data)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Ceremonia iniciada por el usuario (botón). Invalida antes el autocompletado. */
|
|
174
|
+
async function authenticate(platform: boolean, contexts: string[]) {
|
|
175
|
+
assertContexts(platform, contexts)
|
|
176
|
+
stopAutofill()
|
|
177
|
+
await assertEnabled()
|
|
178
|
+
const { key, options } = await fetchLoginOptions(platform)
|
|
179
|
+
const response = await startAuthentication({ optionsJSON: options })
|
|
180
|
+
return verify(platform, contexts, key, response)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Botón "Ingresar con huella o passkey". */
|
|
184
|
+
const login = ({ contexts }: { contexts: string[] }) => authenticate(false, contexts)
|
|
185
|
+
|
|
186
|
+
const loginPlatform = () => authenticate(true, [])
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Autocompletado (conditional UI): el navegador sugiere la passkey al enfocar el
|
|
190
|
+
* campo de correo (necesita un input con autocomplete="username webauthn").
|
|
191
|
+
* Queda esperando hasta que el usuario elija una, se llame a stopAutofill() o se
|
|
192
|
+
* desmonte el componente; se renueva solo antes de que venza el reto (300 s).
|
|
193
|
+
*
|
|
194
|
+
* Devuelve null si no arrancó o se canceló. Los errores previos a que el usuario
|
|
195
|
+
* elija una passkey se silencian (console.debug); solo lanza los errores del BFF
|
|
196
|
+
* tras elegir una, y el de configuración (login de tenant sin contexts).
|
|
197
|
+
*/
|
|
198
|
+
async function startAutofill({ contexts = [], platform = false }: { contexts?: string[]; platform?: boolean } = {}) {
|
|
199
|
+
if (!import.meta.client || guard.disposed) return null
|
|
200
|
+
assertContexts(platform, contexts)
|
|
201
|
+
// Reentrante: aborta la ceremonia de una corrida anterior antes de abrir otra.
|
|
202
|
+
stopAutofill()
|
|
203
|
+
const id = guard.next()
|
|
204
|
+
|
|
205
|
+
if (!(await supportsAutofill())) return null
|
|
206
|
+
if (!guard.isCurrent(id)) return null
|
|
207
|
+
// Interruptor apagado (o sin respuesta): silencio, sin pedir opciones.
|
|
208
|
+
if (!(await statusCache.get(platform ? 'platform/auth' : 'auth'))) return null
|
|
209
|
+
if (!guard.isCurrent(id)) return null
|
|
210
|
+
|
|
211
|
+
while (guard.isCurrent(id)) {
|
|
212
|
+
if (!document.querySelector(WEBAUTHN_INPUT_SELECTOR)) {
|
|
213
|
+
debug('sin input con autocomplete "… webauthn": no se arranca el autocompletado')
|
|
214
|
+
return null
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
let key: string
|
|
218
|
+
let options: any
|
|
219
|
+
autofillPhase = 'options'
|
|
220
|
+
try {
|
|
221
|
+
({ key, options } = await fetchLoginOptions(platform))
|
|
222
|
+
} catch (err) {
|
|
223
|
+
debug('opciones del autocompletado', err)
|
|
224
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
225
|
+
return null
|
|
226
|
+
}
|
|
227
|
+
if (!guard.isCurrent(id)) return null
|
|
228
|
+
|
|
229
|
+
let response: any
|
|
230
|
+
autofillPhase = 'waiting'
|
|
231
|
+
renewRequested = false
|
|
232
|
+
renewTimer = setTimeout(() => {
|
|
233
|
+
renewTimer = null
|
|
234
|
+
if (!guard.isCurrent(id) || autofillPhase !== 'waiting') return
|
|
235
|
+
renewRequested = true
|
|
236
|
+
WebAuthnAbortService.cancelCeremony()
|
|
237
|
+
}, AUTOFILL_RENEW_MS)
|
|
238
|
+
try {
|
|
239
|
+
response = await startAuthentication({ optionsJSON: options, useBrowserAutofill: true })
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (guard.isCurrent(id)) clearRenewTimer()
|
|
242
|
+
if (renewRequested && guard.isCurrent(id)) {
|
|
243
|
+
renewRequested = false
|
|
244
|
+
continue // reto por vencer: pedir uno nuevo
|
|
245
|
+
}
|
|
246
|
+
debug('autocompletado terminado', err)
|
|
247
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
248
|
+
return null
|
|
249
|
+
}
|
|
250
|
+
clearRenewTimer()
|
|
251
|
+
if (!guard.isCurrent(id)) return null
|
|
252
|
+
|
|
253
|
+
// El usuario eligió una passkey: desde aquí los errores sí se muestran.
|
|
254
|
+
autofillPhase = 'verifying'
|
|
255
|
+
try {
|
|
256
|
+
return await verify(platform, contexts, key, response)
|
|
257
|
+
} finally {
|
|
258
|
+
if (guard.isCurrent(id)) autofillPhase = 'idle'
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return null
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Detiene el autocompletado (también las corridas aún pidiendo opciones). */
|
|
265
|
+
function stopAutofill() {
|
|
266
|
+
const wasWaiting = autofillPhase === 'waiting'
|
|
267
|
+
guard.invalidate()
|
|
268
|
+
clearRenewTimer()
|
|
269
|
+
renewRequested = false
|
|
270
|
+
autofillPhase = 'idle'
|
|
271
|
+
if (wasWaiting) WebAuthnAbortService.cancelCeremony()
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Libera el composable: ningún autocompletado vuelve a arrancar. */
|
|
275
|
+
function dispose() {
|
|
276
|
+
stopAutofill()
|
|
277
|
+
guard.dispose()
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ── Gestión propia ────────────────────────────────────────────────────────
|
|
281
|
+
|
|
282
|
+
async function list(base = 'auth'): Promise<PasskeyItem[]> {
|
|
283
|
+
const res: any = await api.get(`${base}/me/passkeys`)
|
|
284
|
+
return res?.data ?? []
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** useApi devuelve null en 401: error legible (passkeyErrorMessage lee data.message). */
|
|
288
|
+
function sessionError() {
|
|
289
|
+
return Object.assign(new Error('Tu sesión expiró. Vuelve a ingresar para gestionar tus passkeys.'), {
|
|
290
|
+
data: { message: 'Tu sesión expiró. Vuelve a ingresar para gestionar tus passkeys.' },
|
|
291
|
+
})
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async function register(name?: string, base = 'auth'): Promise<PasskeyItem> {
|
|
295
|
+
if (!(await statusCache.get(base))) throw disabledError()
|
|
296
|
+
const res: any = await api.post(`${base}/me/passkeys/options`)
|
|
297
|
+
if (!res?.key || !res?.options) throw sessionError()
|
|
298
|
+
const response = await startRegistration({ optionsJSON: res.options })
|
|
299
|
+
const ua = import.meta.client ? navigator.userAgent : ''
|
|
300
|
+
const created: any = await api.post(`${base}/me/passkeys`, { key: res.key, response, name: name || suggestPasskeyName(ua) })
|
|
301
|
+
if (!created) throw sessionError()
|
|
302
|
+
return created
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const rename = (id: string, name: string, base = 'auth') => api.patch(`${base}/me/passkeys/${id}`, { name })
|
|
306
|
+
|
|
307
|
+
const remove = (id: string, base = 'auth') => api.delete(`${base}/me/passkeys/${id}`)
|
|
308
|
+
|
|
309
|
+
// ── Administración ────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
async function listForUser(userId: string | number): Promise<PasskeyItem[]> {
|
|
312
|
+
const res: any = await api.get(`users/${userId}/passkeys`)
|
|
313
|
+
return res?.data ?? []
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async function revokeAll(userId: string | number): Promise<number> {
|
|
317
|
+
const res: any = await api.delete(`users/${userId}/passkeys`)
|
|
318
|
+
return res?.revoked ?? 0
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return {
|
|
322
|
+
supported,
|
|
323
|
+
autofillSupported,
|
|
324
|
+
ready,
|
|
325
|
+
enabled,
|
|
326
|
+
available,
|
|
327
|
+
ensureEnabled,
|
|
328
|
+
refreshStatus,
|
|
329
|
+
login,
|
|
330
|
+
loginPlatform,
|
|
331
|
+
startAutofill,
|
|
332
|
+
stopAutofill,
|
|
333
|
+
dispose,
|
|
334
|
+
isDisposed: () => guard.disposed,
|
|
335
|
+
loggedInWithPasskey,
|
|
336
|
+
markPasskeyLogin,
|
|
337
|
+
list,
|
|
338
|
+
register,
|
|
339
|
+
rename,
|
|
340
|
+
remove,
|
|
341
|
+
listForUser,
|
|
342
|
+
revokeAll,
|
|
343
|
+
errorMessage: passkeyErrorMessage,
|
|
344
|
+
isCancel: isPasskeyCancel,
|
|
345
|
+
isDismissed: isPasskeyDismissed,
|
|
346
|
+
isContextsError: (err: any) => err?.code === CONTEXTS_REQUIRED,
|
|
347
|
+
}
|
|
348
|
+
}
|
|
@@ -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,38 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { createStatusCache } from '../statusCache'
|
|
3
|
+
|
|
4
|
+
describe('createStatusCache', () => {
|
|
5
|
+
it('consulta una sola vez por base', async () => {
|
|
6
|
+
const fetcher = vi.fn(async () => ({ enabled: true }))
|
|
7
|
+
const c = createStatusCache().for(fetcher)
|
|
8
|
+
expect(await Promise.all([c.get('auth'), c.get('auth')])).toEqual([true, true])
|
|
9
|
+
expect(fetcher).toHaveBeenCalledTimes(1)
|
|
10
|
+
await c.get('platform/auth')
|
|
11
|
+
expect(fetcher).toHaveBeenCalledTimes(2)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('fallo = desactivado y se reintenta después', async () => {
|
|
15
|
+
const fetcher = vi.fn()
|
|
16
|
+
.mockRejectedValueOnce(new Error('x'))
|
|
17
|
+
.mockResolvedValueOnce({ enabled: true })
|
|
18
|
+
const c = createStatusCache().for(fetcher)
|
|
19
|
+
expect(await c.get('auth')).toBe(false)
|
|
20
|
+
expect(await c.get('auth')).toBe(true)
|
|
21
|
+
expect(fetcher).toHaveBeenCalledTimes(2)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('respuesta nula o sin enabled es false', async () => {
|
|
25
|
+
const c = createStatusCache().for(async () => null)
|
|
26
|
+
expect(await c.get('auth')).toBe(false)
|
|
27
|
+
})
|
|
28
|
+
|
|
29
|
+
it('reset fuerza una nueva consulta', async () => {
|
|
30
|
+
let enabled = false
|
|
31
|
+
const c = createStatusCache().for(async () => ({ enabled }))
|
|
32
|
+
expect(await c.get('auth')).toBe(false)
|
|
33
|
+
enabled = true
|
|
34
|
+
expect(await c.get('auth')).toBe(false)
|
|
35
|
+
c.reset('auth')
|
|
36
|
+
expect(await c.get('auth')).toBe(true)
|
|
37
|
+
})
|
|
38
|
+
})
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Caché de la promesa del estado (interruptor) de passkeys, por base ('auth' | 'platform/auth').
|
|
2
|
+
// Lógica pura (testeable en node): una consulta por base durante la vida de la página;
|
|
3
|
+
// un fallo cuenta como "desactivado" y NO se cachea (la próxima lectura reintenta).
|
|
4
|
+
|
|
5
|
+
export type StatusFetcher = (base: string) => Promise<{ enabled?: boolean } | null | undefined>
|
|
6
|
+
|
|
7
|
+
export interface StatusCache {
|
|
8
|
+
/** Estado de la base; nunca rechaza (fallo → false). */
|
|
9
|
+
get(base: string): Promise<boolean>
|
|
10
|
+
/** Olvida una base (o todas) para que la próxima lectura consulte de nuevo. */
|
|
11
|
+
reset(base?: string): void
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function createStatusCache(): { for(fetcher: StatusFetcher): StatusCache } {
|
|
15
|
+
const promises = new Map<string, Promise<boolean>>()
|
|
16
|
+
return {
|
|
17
|
+
for(fetcher) {
|
|
18
|
+
return {
|
|
19
|
+
get(base) {
|
|
20
|
+
let p = promises.get(base)
|
|
21
|
+
if (!p) {
|
|
22
|
+
const created: Promise<boolean> = (async () => {
|
|
23
|
+
try {
|
|
24
|
+
const res = await fetcher(base)
|
|
25
|
+
return res?.enabled === true
|
|
26
|
+
} catch {
|
|
27
|
+
if (promises.get(base) === created) promises.delete(base)
|
|
28
|
+
return false
|
|
29
|
+
}
|
|
30
|
+
})()
|
|
31
|
+
p = created
|
|
32
|
+
promises.set(base, p)
|
|
33
|
+
}
|
|
34
|
+
return p
|
|
35
|
+
},
|
|
36
|
+
reset(base) {
|
|
37
|
+
if (base) promises.delete(base)
|
|
38
|
+
else promises.clear()
|
|
39
|
+
},
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
}
|