import { buildRegistrationOptions } from '../../../utils/webauthnHelper' import { issueChallenge } from '../../../utils/webauthnChallengeStore' import { readCredentials } from '../../../utils/adUserCredentials' export default defineEventHandler(async (event) => { const userIdRaw = getCookie(event, 'logship_user_id') const token = getCookie(event, 'logship_it') const userCookie = getCookie(event, 'logship_user') const userId = Number(userIdRaw) if (!userId || !token) { throw createError({ statusCode: 401, statusMessage: 'Not authenticated' }) } let userName = '' let displayName = '' if (userCookie) { try { const u = typeof userCookie === 'string' ? JSON.parse(userCookie) : userCookie userName = u?.Name ?? u?.Value ?? String(userId) displayName = u?.Name ?? userName } catch { userName = String(userId) } } else { userName = String(userId) } // Use existing keys' credentialIds as exclusion so the user can't register // the same hardware key twice on the same account. const existing = await readCredentials(event, userId, token).catch(() => ({ keys: [], password: null })) const excludeCredentialIds = existing.keys.map(k => k.credentialId) const options = await buildRegistrationOptions({ userId, userName, userDisplayName: displayName, excludeCredentialIds, }) issueChallenge(event, options.challenge, { userId, kind: 'register' }) return options })