feat: align with upstream 1.5.9.9
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import { generateAuthenticationOptions } from '@simplewebauthn/server'
|
||||
import { setWebAuthnChallenge } from '~~/server/utils/webauthn-token'
|
||||
import { getWebAuthnConfig } from '~~/server/utils/webauthn-config'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const { rpID } = getWebAuthnConfig(event)
|
||||
if (!rpID) {
|
||||
throw createApiError(500, 'AUTH_WEBAUTHN_RP_ID_INVALID', 'WebAuthn RP ID 配置无效')
|
||||
}
|
||||
|
||||
const options = await generateAuthenticationOptions({
|
||||
rpID,
|
||||
userVerification: 'preferred',
|
||||
allowCredentials: []
|
||||
})
|
||||
|
||||
setWebAuthnChallenge(event, options.challenge, 'authentication')
|
||||
|
||||
return options
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import { verifyAuthenticationResponse } from '@simplewebauthn/server'
|
||||
import { getWebAuthnChallenge, clearWebAuthnChallenge } from '~~/server/utils/webauthn-token'
|
||||
import { getWebAuthnConfig } from '~~/server/utils/webauthn-config'
|
||||
import { db, eq, and, userIdentities } from '~/drizzle/db'
|
||||
import { defineEventHandler, setCookie } from 'h3'
|
||||
import { createAuthSession } from '~~/server/utils/auth-session'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody(event)
|
||||
const challengeData = getWebAuthnChallenge(event)
|
||||
|
||||
if (!challengeData) {
|
||||
throw createApiError(400, 'AUTH_CHALLENGE_EXPIRED', 'Challenge 已失效')
|
||||
}
|
||||
|
||||
// 通过 credentialID 查找对应的用户身份
|
||||
const credentialID = body.id
|
||||
if (!credentialID) {
|
||||
throw createApiError(400, 'AUTH_MISSING_CREDENTIAL_ID', '缺少 Credential ID')
|
||||
}
|
||||
|
||||
// Challenge 只能使用一次,避免失败响应被重复提交。
|
||||
clearWebAuthnChallenge(event)
|
||||
|
||||
const identity = await db.query.userIdentities.findFirst({
|
||||
where: and(
|
||||
eq(userIdentities.provider, 'webauthn'),
|
||||
eq(userIdentities.providerUserId, credentialID)
|
||||
),
|
||||
with: { user: true }
|
||||
})
|
||||
|
||||
if (!identity) {
|
||||
throw createApiError(400, 'AUTH_PASSKEY_ACCOUNT_NOT_FOUND', '未找到该 Passkey 关联的账号')
|
||||
}
|
||||
|
||||
const user = identity.user
|
||||
|
||||
// 检查用户账号状态
|
||||
if (!user || user.status !== 'active') {
|
||||
throw createApiError(403, 'AUTH_ACCOUNT_UNAVAILABLE_OR_RESTRICTED', '该账号不可用或已限制访问')
|
||||
}
|
||||
|
||||
// 解析存储的凭证数据
|
||||
if (!identity.providerUsername) {
|
||||
throw createApiError(500, 'AUTH_CREDENTIAL_MISSING', '凭证数据缺失')
|
||||
}
|
||||
|
||||
let credentialData
|
||||
try {
|
||||
credentialData = JSON.parse(identity.providerUsername)
|
||||
} catch {
|
||||
throw createApiError(500, 'AUTH_CREDENTIAL_CORRUPTED', '凭证数据损坏')
|
||||
}
|
||||
|
||||
const { publicKey, counter } = credentialData
|
||||
|
||||
// 验证公钥存在
|
||||
if (!publicKey) {
|
||||
throw createApiError(500, 'AUTH_CREDENTIAL_MISSING_PUBLICKEY', '凭证数据缺失 publicKey')
|
||||
}
|
||||
|
||||
const { rpID, origin } = getWebAuthnConfig(event)
|
||||
if (!rpID) {
|
||||
throw createApiError(500, 'AUTH_WEBAUTHN_RP_ID_INVALID', 'WebAuthn RP ID 配置无效')
|
||||
}
|
||||
|
||||
// 构造 WebAuthn 凭证对象
|
||||
const credential = {
|
||||
id: credentialID,
|
||||
publicKey: Buffer.from(publicKey, 'base64url'),
|
||||
counter: Number(counter || 0),
|
||||
transports: credentialData.transports
|
||||
}
|
||||
|
||||
try {
|
||||
const verification = await verifyAuthenticationResponse({
|
||||
response: body,
|
||||
expectedChallenge: challengeData.challenge,
|
||||
expectedOrigin: origin,
|
||||
expectedRPID: rpID,
|
||||
credential,
|
||||
requireUserVerification: true
|
||||
})
|
||||
|
||||
if (verification.verified) {
|
||||
const { newCounter, credentialDeviceType, credentialBackedUp } =
|
||||
verification.authenticationInfo
|
||||
credentialData.counter = newCounter
|
||||
credentialData.credentialDeviceType = credentialDeviceType
|
||||
credentialData.credentialBackedUp = credentialBackedUp
|
||||
|
||||
await db
|
||||
.update(userIdentities)
|
||||
.set({ providerUsername: JSON.stringify(credentialData) })
|
||||
.where(eq(userIdentities.id, identity.id))
|
||||
|
||||
// 签发登录 Token
|
||||
const { token } = await createAuthSession(event, identity.user, 'webauthn')
|
||||
setCookie(event, 'auth-token', token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
path: '/'
|
||||
})
|
||||
|
||||
return { success: true, redirect: '/' }
|
||||
} else {
|
||||
throw createApiError(400, 'AUTH_VERIFICATION_FAILED', '验证失败')
|
||||
}
|
||||
} catch (error) {
|
||||
// 透传已携带错误码的业务错误,避免被重新包装后丢失 code 通道。
|
||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||
console.error('WebAuthn 登录验证失败:', error)
|
||||
const message = error instanceof Error ? error.message : '验证失败'
|
||||
throw createApiError(400, 'AUTH_VERIFICATION_FAILED', message)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,65 @@
|
||||
import { generateRegistrationOptions } from '@simplewebauthn/server'
|
||||
import { isoUint8Array } from '@simplewebauthn/server/helpers'
|
||||
import { setWebAuthnChallenge } from '~~/server/utils/webauthn-token'
|
||||
import { getWebAuthnConfig } from '~~/server/utils/webauthn-config'
|
||||
import { db, eq, and, userIdentities } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
// 获取该用户已绑定的 WebAuthn 凭证
|
||||
const existingCredentials = await db.query.userIdentities.findMany({
|
||||
where: and(eq(userIdentities.userId, user.id), eq(userIdentities.provider, 'webauthn')),
|
||||
columns: {
|
||||
providerUserId: true,
|
||||
providerUsername: true
|
||||
}
|
||||
})
|
||||
|
||||
// 防止重复注册相同凭证,使用存储的实际 transports 信息
|
||||
const excludeCredentials = existingCredentials.map((cred) => {
|
||||
let transports: string[] | undefined
|
||||
try {
|
||||
if (cred.providerUsername) {
|
||||
const data = JSON.parse(cred.providerUsername)
|
||||
transports = data.transports
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('解析 WebAuthn 凭证数据失败:', e)
|
||||
}
|
||||
return {
|
||||
id: cred.providerUserId,
|
||||
type: 'public-key' as const,
|
||||
transports
|
||||
}
|
||||
})
|
||||
|
||||
const { rpID } = getWebAuthnConfig(event)
|
||||
const rpName = 'VoiceHub'
|
||||
const userName = user.username || user.email || user.id.toString()
|
||||
const userDisplayName = user.name || userName
|
||||
|
||||
const options = await generateRegistrationOptions({
|
||||
rpName,
|
||||
rpID,
|
||||
userID: isoUint8Array.fromUTF8String(user.id.toString()),
|
||||
userName,
|
||||
userDisplayName,
|
||||
attestationType: 'none',
|
||||
supportedAlgorithmIDs: [-7, -257],
|
||||
excludeCredentials,
|
||||
authenticatorSelection: {
|
||||
residentKey: 'required',
|
||||
userVerification: 'preferred'
|
||||
}
|
||||
})
|
||||
|
||||
// 存储注册挑战到 Cookie
|
||||
setWebAuthnChallenge(event, options.challenge, user.id.toString())
|
||||
|
||||
return options
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import { verifyRegistrationResponse } from '@simplewebauthn/server'
|
||||
import { getWebAuthnChallenge, clearWebAuthnChallenge } from '~~/server/utils/webauthn-token'
|
||||
import { getWebAuthnConfig } from '~~/server/utils/webauthn-config'
|
||||
import { db, userIdentities } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
const VALID_TRANSPORTS = ['ble', 'cable', 'hybrid', 'internal', 'nfc', 'smart-card', 'usb']
|
||||
|
||||
function sanitizeTransports(transports: unknown): string[] {
|
||||
if (!Array.isArray(transports)) return []
|
||||
return transports.filter(
|
||||
(t): t is string => typeof t === 'string' && VALID_TRANSPORTS.includes(t)
|
||||
)
|
||||
}
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
const body = await readBody(event)
|
||||
const challengeData = getWebAuthnChallenge(event)
|
||||
|
||||
if (!challengeData || challengeData.userId !== user.id.toString()) {
|
||||
throw createApiError(400, 'AUTH_CHALLENGE_INVALID', 'Challenge 已失效或不匹配')
|
||||
}
|
||||
|
||||
// Challenge 只能使用一次,验证失败后也必须重新生成。
|
||||
clearWebAuthnChallenge(event)
|
||||
|
||||
const { rpID, origin } = getWebAuthnConfig(event)
|
||||
|
||||
try {
|
||||
const verification = await verifyRegistrationResponse({
|
||||
response: body,
|
||||
expectedChallenge: challengeData.challenge,
|
||||
expectedOrigin: origin,
|
||||
expectedRPID: rpID,
|
||||
requireUserVerification: true
|
||||
})
|
||||
|
||||
if (verification.verified && verification.registrationInfo) {
|
||||
const { credential, credentialDeviceType, credentialBackedUp } = verification.registrationInfo
|
||||
|
||||
// 提取凭证数据
|
||||
const { id: credentialID, publicKey: credentialPublicKey, counter, transports } = credential
|
||||
|
||||
if (!credentialID || !credentialPublicKey) {
|
||||
throw new Error('注册信息缺少凭证 ID 或公钥')
|
||||
}
|
||||
|
||||
// 转换为 Base64URL 格式存储
|
||||
const credentialIDBase64 = credentialID
|
||||
const publicKeyBase64 = Buffer.from(credentialPublicKey).toString('base64url')
|
||||
|
||||
if (!publicKeyBase64) {
|
||||
throw new Error('生成的公钥为空,注册失败')
|
||||
}
|
||||
|
||||
// 构造凭证数据
|
||||
const credentialData = {
|
||||
label: body.label || 'WebAuthn 设备',
|
||||
publicKey: publicKeyBase64,
|
||||
counter: Number(counter),
|
||||
transports: sanitizeTransports(transports),
|
||||
credentialDeviceType,
|
||||
credentialBackedUp
|
||||
}
|
||||
|
||||
// 存储到数据库
|
||||
await db.insert(userIdentities).values({
|
||||
userId: user.id,
|
||||
provider: 'webauthn',
|
||||
providerUserId: credentialIDBase64,
|
||||
providerUsername: JSON.stringify(credentialData),
|
||||
createdAt: new Date()
|
||||
})
|
||||
|
||||
return { success: true }
|
||||
} else {
|
||||
throw createApiError(400, 'AUTH_VERIFICATION_FAILED', '验证失败')
|
||||
}
|
||||
} catch (error) {
|
||||
// 透传已携带错误码的业务错误,避免被重新包装后丢失 code 通道。
|
||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||
console.error('WebAuthn 验证失败:', error)
|
||||
const message = error instanceof Error ? error.message : '验证失败'
|
||||
throw createApiError(400, 'AUTH_VERIFICATION_FAILED', message)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
import { db, eq, and, userIdentities, sql } from '~/drizzle/db'
|
||||
import { createApiError } from '~~/server/utils/apiError'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const user = event.context.user
|
||||
if (!user) {
|
||||
throw createApiError(401, 'AUTH_UNAUTHORIZED_ACCESS', '未授权访问')
|
||||
}
|
||||
|
||||
interface RenameRequestBody {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
const body = await readBody<RenameRequestBody>(event)
|
||||
const { id, name: rawName } = body
|
||||
const name = typeof rawName === 'string' ? rawName.trim() : ''
|
||||
|
||||
if (!id || !name) {
|
||||
throw createApiError(400, 'COMMON_INVALID_PARAMS', '参数错误')
|
||||
}
|
||||
|
||||
if (name.length > 50) {
|
||||
throw createApiError(400, 'AUTH_DEVICE_NAME_TOO_LONG', '设备名称过长')
|
||||
}
|
||||
|
||||
// 查找对应的 Passkey
|
||||
const identity = await db.query.userIdentities.findFirst({
|
||||
where: and(
|
||||
eq(userIdentities.id, id),
|
||||
eq(userIdentities.userId, user.id),
|
||||
eq(userIdentities.provider, 'webauthn')
|
||||
)
|
||||
})
|
||||
|
||||
if (!identity) {
|
||||
throw createApiError(404, 'AUTH_DEVICE_NOT_FOUND', '未找到该设备')
|
||||
}
|
||||
|
||||
try {
|
||||
// 使用 jsonb_set 原子更新 label,避免覆盖 concurrent login 产生的 counter 更新
|
||||
await db.update(userIdentities)
|
||||
.set({
|
||||
providerUsername: sql`jsonb_set(${userIdentities.providerUsername}::jsonb, '{label}', ${JSON.stringify(name)}::jsonb)::text`
|
||||
})
|
||||
.where(eq(userIdentities.id, id))
|
||||
|
||||
return { success: true }
|
||||
} catch (e) {
|
||||
console.error('更新设备名称失败:', e)
|
||||
throw createApiError(500, 'AUTH_UPDATE_FAILED', '更新失败')
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user