feat: 完成passkey登录认证功能

This commit is contained in:
Baobhan Sith
2025-04-15 15:16:50 +08:00
parent 1f3631539b
commit 7649a7b69d
13 changed files with 1195 additions and 34 deletions
+82 -6
View File
@@ -1,11 +1,13 @@
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import { getDb } from '../database';
import sqlite3, { RunResult } from 'sqlite3'; // 导入 RunResult 类型
import speakeasy from 'speakeasy'; // 导入 speakeasy
import qrcode from 'qrcode'; // 导入 qrcode
import sqlite3, { RunResult } from 'sqlite3';
import speakeasy from 'speakeasy';
import qrcode from 'qrcode';
import { PasskeyService } from '../services/passkey.service'; // 导入 PasskeyService
const db = getDb(); // 获取数据库实例
const db = getDb();
const passkeyService = new PasskeyService(); // 实例化 PasskeyService
// 用户数据结构占位符 (理想情况下应定义在共享的 types 文件中)
interface User {
@@ -21,8 +23,9 @@ declare module 'express-session' {
interface SessionData {
userId?: number;
username?: string;
tempTwoFactorSecret?: string; // 用于存储设置过程中的临时密钥
requiresTwoFactor?: boolean; // 标记登录流程是否需要 2FA 验证
tempTwoFactorSecret?: string;
requiresTwoFactor?: boolean;
currentChallenge?: string; // 用于存储 Passkey 操作的挑战
}
}
@@ -341,6 +344,79 @@ export const setup2FA = async (req: Request, res: Response): Promise<void> => {
}
};
// --- 新增 Passkey 相关方法 ---
/**
* 生成 Passkey 注册选项 (POST /api/v1/auth/passkey/register-options)
*/
export const generatePasskeyRegistrationOptions = async (req: Request, res: Response): Promise<void> => {
const userId = req.session.userId;
const username = req.session.username; // Passkey 需要用户名
if (!userId || !username || req.session.requiresTwoFactor) {
res.status(401).json({ message: '用户未认证或认证未完成。' });
return;
}
try {
const options = await passkeyService.generateRegistrationOptions(username);
// 将 challenge 存储在 session 中,用于后续验证
req.session.currentChallenge = options.challenge;
res.json(options);
} catch (error: any) {
console.error(`用户 ${userId} 生成 Passkey 注册选项时出错:`, error);
res.status(500).json({ message: '生成 Passkey 注册选项失败。', error: error.message });
}
};
/**
* 验证 Passkey 注册响应 (POST /api/v1/auth/passkey/verify-registration)
*/
export const verifyPasskeyRegistration = async (req: Request, res: Response): Promise<void> => {
const userId = req.session.userId;
const expectedChallenge = req.session.currentChallenge;
const { registrationResponse, name } = req.body; // name 是用户给 Passkey 起的名字 (可选)
if (!userId || req.session.requiresTwoFactor) {
res.status(401).json({ message: '用户未认证或认证未完成。' });
return;
}
if (!expectedChallenge) {
res.status(400).json({ message: '未找到预期的挑战,请重新生成注册选项。' });
return;
}
if (!registrationResponse) {
res.status(400).json({ message: '缺少注册响应数据。' });
return;
}
// 清除 session 中的 challenge,无论成功与否
delete req.session.currentChallenge;
try {
const verification = await passkeyService.verifyRegistration(
registrationResponse,
expectedChallenge,
name
);
if (verification.verified) {
res.status(201).json({ message: 'Passkey 注册成功!', verified: true });
} else {
console.error(`用户 ${userId} Passkey 注册验证失败:`, verification);
res.status(400).json({ message: 'Passkey 注册验证失败。', verified: false });
}
} catch (error: any) {
console.error(`用户 ${userId} 验证 Passkey 注册时出错:`, error);
res.status(500).json({ message: '验证 Passkey 注册失败。', error: error.message });
}
};
/**
* 验证并激活 2FA (POST /api/v1/auth/2fa/verify)
*/
+10 -1
View File
@@ -6,7 +6,9 @@ import {
setup2FA,
verifyAndActivate2FA,
disable2FA,
getAuthStatus // 导入获取状态的方法
getAuthStatus, // 导入获取状态的方法
generatePasskeyRegistrationOptions, // 导入 Passkey 方法
verifyPasskeyRegistration // 导入 Passkey 方法
} from './auth.controller';
import { isAuthenticated } from './auth.middleware';
@@ -34,6 +36,13 @@ router.delete('/2fa', isAuthenticated, disable2FA);
// GET /api/v1/auth/status - 获取当前认证状态 (需要认证)
router.get('/status', isAuthenticated, getAuthStatus);
// --- Passkey 管理接口 (都需要认证) ---
// POST /api/v1/auth/passkey/register-options - 生成 Passkey 注册选项
router.post('/passkey/register-options', isAuthenticated, generatePasskeyRegistrationOptions);
// POST /api/v1/auth/passkey/verify-registration - 验证 Passkey 注册响应
router.post('/passkey/verify-registration', isAuthenticated, verifyPasskeyRegistration);
// 未来可以添加的其他认证相关路由
// router.post('/logout', logout); // 登出
+22
View File
@@ -28,6 +28,19 @@ CREATE TABLE IF NOT EXISTS api_keys (
);
`;
const createPasskeysTableSQL = `
CREATE TABLE IF NOT EXISTS passkeys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
credential_id TEXT UNIQUE NOT NULL, -- Base64URL encoded
public_key TEXT NOT NULL, -- Base64URL encoded
counter INTEGER NOT NULL,
transports TEXT, -- JSON array as string, e.g., '["internal", "usb"]'
name TEXT, -- User-provided name for the key
created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);
`;
export const runMigrations = async (db: Database): Promise<void> => {
try {
// 创建 settings 表 (如果不存在)
@@ -74,6 +87,15 @@ export const runMigrations = async (db: Database): Promise<void> => {
});
});
// 创建 passkeys 表 (如果不存在)
await new Promise<void>((resolve, reject) => {
db.run(createPasskeysTableSQL, (err: Error | null) => {
if (err) return reject(new Error(`创建 passkeys 表时出错: ${err.message}`));
console.log('Passkeys 表已检查/创建。');
resolve();
});
});
console.log('所有数据库迁移已完成。');
} catch (error) {
console.error('数据库迁移过程中出错:', error);
@@ -0,0 +1,175 @@
import { Database } from 'sqlite3';
import { getDb } from '../database';
// 定义 Passkey 数据库记录的接口
export interface PasskeyRecord {
id: number;
credential_id: string; // Base64URL encoded
public_key: string; // Base64URL encoded
counter: number;
transports: string | null; // JSON string or null
name: string | null;
created_at: number;
updated_at: number;
}
export class PasskeyRepository {
private db: Database;
constructor() {
this.db = getDb();
}
/**
* 保存新的 Passkey 凭证
* @param credentialId Base64URL 编码的凭证 ID
* @param publicKey Base64URL 编码的公钥
* @param counter 签名计数器
* @param transports 传输方式 (JSON 字符串)
* @param name 用户提供的名称 (可选)
* @returns Promise<number> 新插入记录的 ID
*/
async savePasskey(
credentialId: string,
publicKey: string,
counter: number,
transports: string | null,
name?: string
): Promise<number> {
const sql = `
INSERT INTO passkeys (credential_id, public_key, counter, transports, name, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, strftime('%s', 'now'), strftime('%s', 'now'))
`;
return new Promise((resolve, reject) => {
this.db.run(sql, [credentialId, publicKey, counter, transports, name ?? null], function (err) {
if (err) {
console.error('保存 Passkey 时出错:', err.message);
return reject(new Error(`保存 Passkey 时出错: ${err.message}`));
}
resolve(this.lastID);
});
});
}
/**
* 根据 Credential ID 获取 Passkey 记录
* @param credentialId Base64URL 编码的凭证 ID
* @returns Promise<PasskeyRecord | null> 找到的记录或 null
*/
async getPasskeyByCredentialId(credentialId: string): Promise<PasskeyRecord | null> {
const sql = `SELECT * FROM passkeys WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.get(sql, [credentialId], (err, row: PasskeyRecord) => {
if (err) {
console.error('按 Credential ID 获取 Passkey 时出错:', err.message);
return reject(new Error(`按 Credential ID 获取 Passkey 时出错: ${err.message}`));
}
resolve(row || null);
});
});
}
/**
* 获取所有已注册的 Passkey 记录
* @returns Promise<PasskeyRecord[]> 所有记录的数组
*/
async getAllPasskeys(): Promise<PasskeyRecord[]> {
const sql = `SELECT id, credential_id, name, transports, created_at FROM passkeys ORDER BY created_at DESC`; // 仅选择必要字段
return new Promise((resolve, reject) => {
this.db.all(sql, [], (err, rows: PasskeyRecord[]) => {
if (err) {
console.error('获取所有 Passkey 时出错:', err.message);
return reject(new Error(`获取所有 Passkey 时出错: ${err.message}`));
}
resolve(rows);
});
});
}
/**
* 更新 Passkey 的签名计数器
* @param credentialId Base64URL 编码的凭证 ID
* @param newCounter 新的计数器值
* @returns Promise<void>
*/
async updatePasskeyCounter(credentialId: string, newCounter: number): Promise<void> {
const sql = `UPDATE passkeys SET counter = ?, updated_at = strftime('%s', 'now') WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [newCounter, credentialId], function (err) {
if (err) {
console.error('更新 Passkey 计数器时出错:', err.message);
return reject(new Error(`更新 Passkey 计数器时出错: ${err.message}`));
}
if (this.changes === 0) {
return reject(new Error(`未找到 Credential ID 为 ${credentialId} 的 Passkey 进行更新`));
}
resolve();
});
});
}
/**
* 根据 ID 删除 Passkey
* @param id Passkey 记录的 ID
* @returns Promise<void>
*/
async deletePasskeyById(id: number): Promise<void> {
const sql = `DELETE FROM passkeys WHERE id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [id], function (err) {
if (err) {
console.error('按 ID 删除 Passkey 时出错:', err.message);
return reject(new Error(`按 ID 删除 Passkey 时出错: ${err.message}`));
}
if (this.changes === 0) {
return reject(new Error(`未找到 ID 为 ${id} 的 Passkey 进行删除`));
}
console.log(`ID 为 ${id} 的 Passkey 已删除。`);
resolve();
});
});
}
/**
* 根据 Credential ID 删除 Passkey
* @param credentialId Base64URL 编码的凭证 ID
* @returns Promise<void>
*/
async deletePasskeyByCredentialId(credentialId: string): Promise<void> {
const sql = `DELETE FROM passkeys WHERE credential_id = ?`;
return new Promise((resolve, reject) => {
this.db.run(sql, [credentialId], function (err) {
if (err) {
console.error('按 Credential ID 删除 Passkey 时出错:', err.message);
return reject(new Error(`按 Credential ID 删除 Passkey 时出错: ${err.message}`));
}
if (this.changes === 0) {
// It's possible the user tries to delete a non-existent key, maybe not an error?
console.warn(`尝试删除不存在的 Credential ID: ${credentialId}`);
} else {
console.log(`Credential ID 为 ${credentialId} 的 Passkey 已删除。`);
}
resolve();
});
});
}
/**
* 根据 credential_id 或 name 前缀模糊查找 Passkey 记录(自动补全)
* @param prefix 前缀字符串
* @returns Promise<PasskeyRecord[]> 匹配的记录数组
*/
async searchPasskeyByPrefix(prefix: string): Promise<PasskeyRecord[]> {
const sql = `SELECT * FROM passkeys WHERE credential_id LIKE ? OR name LIKE ? ORDER BY created_at DESC`;
const likePrefix = `${prefix}%`;
return new Promise((resolve, reject) => {
this.db.all(sql, [likePrefix, likePrefix], (err, rows: PasskeyRecord[]) => {
if (err) {
console.error('模糊查找 Passkey 时出错:', err.message);
return reject(new Error(`模糊查找 Passkey 时出错: ${err.message}`));
}
resolve(rows);
});
});
}
}
@@ -0,0 +1,256 @@
import {
generateRegistrationOptions,
verifyRegistrationResponse,
generateAuthenticationOptions,
verifyAuthenticationResponse,
VerifiedRegistrationResponse,
VerifiedAuthenticationResponse,
} from '@simplewebauthn/server';
import type {
GenerateRegistrationOptionsOpts,
GenerateAuthenticationOptionsOpts,
VerifyRegistrationResponseOpts,
VerifyAuthenticationResponseOpts,
RegistrationResponseJSON,
AuthenticationResponseJSON,
// AuthenticatorDevice is not typically needed here
} from '@simplewebauthn/server'; // Import types directly from the package
import { PasskeyRepository, PasskeyRecord } from '../repositories/passkey.repository';
import { settingsService } from './settings.service'; // Import the exported object
// 定义 Relying Party (RP) 信息 - 这些应该来自配置或设置
// TODO: 从 SettingsService 或环境变量获取这些值
const rpName = 'Nexus Terminal';
// 重要: rpID 应该是你的网站域名 (不包含协议和端口)
// 对于本地开发,通常是 'localhost'
const rpID = process.env.NODE_ENV === 'development' ? 'localhost' : 'YOUR_PRODUCTION_DOMAIN'; // 需要替换为实际域名
// 重要: origin 应该是你的前端应用的完整源 (包含协议和端口)
const expectedOrigin = process.env.FRONTEND_URL || 'http://localhost:5173'; // 确保与前端 URL 匹配
export class PasskeyService {
private passkeyRepository: PasskeyRepository;
// No need to instantiate settingsService if it's an object export
// private settingsService: typeof settingsService; // Use typeof for the object type
constructor() {
this.passkeyRepository = new PasskeyRepository();
// this.settingsService = settingsService; // Assign the imported object if needed
// TODO: Load rpID, rpName, expectedOrigin using settingsService.getSetting()
}
/**
* 生成 Passkey 注册选项 (挑战)
*/
async generateRegistrationOptions(userName: string = 'nexus-user') { // WebAuthn 需要一个用户名
// 暂时不获取已存在的凭证,允许同一用户注册多个设备
// const existingCredentials = await this.passkeyRepository.getAllPasskeys();
const options: GenerateRegistrationOptionsOpts = {
rpName,
rpID,
userID: Buffer.from(userName), // userID should be a Buffer/Uint8Array
userName: userName,
// 不建议排除已存在的凭证,除非有特定原因
// excludeCredentials: existingCredentials.map(cred => ({
// id: cred.credential_id, // 需要是 Base64URL 格式,存储时确保是这个格式
// type: 'public-key',
// transports: cred.transports ? JSON.parse(cred.transports) : undefined,
// })),
authenticatorSelection: {
// authenticatorAttachment: 'platform', // 倾向于平台认证器 (如 Windows Hello, Touch ID)
userVerification: 'preferred', // 倾向于需要用户验证 (PIN, 生物识别)
residentKey: 'preferred', // 倾向于创建可发现凭证 (存储在认证器上)
},
// 可选:增加超时时间
timeout: 60000, // 60 秒
// attestation: 'none', // Temporarily remove to resolve TS error, 'none' is often default
};
const registrationOptions = await generateRegistrationOptions(options);
// TODO: 需要将生成的 challenge 临时存储起来 (例如在 session 或 内存缓存中),以便后续验证
// 这里暂时返回 challenge,让 Controller 处理存储
return registrationOptions;
}
/**
* 验证 Passkey 注册响应
* @param registrationResponse 来自客户端的注册响应
* @param expectedChallenge 之前生成的、临时存储的挑战
* @param passkeyName 用户为这个 Passkey 起的名字 (可选)
*/
async verifyRegistration(
registrationResponse: RegistrationResponseJSON,
expectedChallenge: string,
passkeyName?: string
): Promise<VerifiedRegistrationResponse> {
const verificationOptions: VerifyRegistrationResponseOpts = {
response: registrationResponse,
expectedChallenge: expectedChallenge,
expectedOrigin: expectedOrigin,
expectedRPID: rpID,
requireUserVerification: true, // 强制要求用户验证, simplewebauthn defaults this to true now
};
let verification: VerifiedRegistrationResponse;
try {
verification = await verifyRegistrationResponse(verificationOptions);
} catch (error: any) {
console.error('Passkey 注册验证时发生异常:', error);
// Provide more context in the error
const err = error as Error;
throw new Error(`Passkey registration verification failed: ${err.message || err}`);
}
if (verification.verified && verification.registrationInfo) {
// Use type assertion to bypass strict type checking for registrationInfo properties
const registrationInfo = verification.registrationInfo as any;
const { credentialPublicKey, credentialID, counter } = registrationInfo;
// Optional: Access other potential properties if needed
// const { credentialDeviceType, credentialBackedUp } = registrationInfo;
// 将公钥和 ID 转换为 Base64URL 字符串存储 (如果它们还不是)
// @simplewebauthn/server 返回的是 Buffer,需要转换
const credentialIdBase64Url = Buffer.from(credentialID).toString('base64url');
const publicKeyBase64Url = Buffer.from(credentialPublicKey).toString('base64url');
// 获取 transports 信息
const transports = registrationResponse.response.transports ?? null;
// 保存到数据库
await this.passkeyRepository.savePasskey(
credentialIdBase64Url,
publicKeyBase64Url,
counter,
transports ? JSON.stringify(transports) : null,
passkeyName
);
console.log(`Passkey 注册成功: ${credentialIdBase64Url}, Name: ${passkeyName ?? 'N/A'}`);
} else {
console.error('Passkey 注册验证失败:', verification);
}
return verification;
}
/**
* 生成 Passkey 认证选项 (挑战)
*/
async generateAuthenticationOptions(): Promise<ReturnType<typeof generateAuthenticationOptions>> {
// 可选:可以只允许已注册的凭证进行认证
// const allowedCredentials = (await this.passkeyRepository.getAllPasskeys()).map(cred => ({
// id: cred.credential_id, // 确保是 Base64URL 格式
// type: 'public-key',
// transports: cred.transports ? JSON.parse(cred.transports) : undefined,
// }));
const options: GenerateAuthenticationOptionsOpts = {
rpID,
// allowCredentials: allowedCredentials, // 如果只想允许已注册的凭证
userVerification: 'preferred', // 倾向于需要用户验证
timeout: 60000, // 60 秒
};
const authenticationOptions = await generateAuthenticationOptions(options);
// TODO: 需要将生成的 challenge 临时存储起来,以便后续验证
// 这里暂时返回 challenge,让 Controller 处理存储
return authenticationOptions;
}
/**
* 验证 Passkey 认证响应
* @param authenticationResponse 来自客户端的认证响应
* @param expectedChallenge 之前生成的、临时存储的挑战
*/
async verifyAuthentication(
authenticationResponse: AuthenticationResponseJSON,
expectedChallenge: string
): Promise<VerifiedAuthenticationResponse> {
const credentialIdBase64Url = authenticationResponse.id; // 客户端传回的 ID 已经是 Base64URL
const authenticator = await this.passkeyRepository.getPasskeyByCredentialId(credentialIdBase64Url);
if (!authenticator) {
throw new Error(`未找到 Credential ID 为 ${credentialIdBase64Url} 的认证器`);
}
// 将存储的公钥从 Base64URL 转回 Buffer
// const authenticatorPublicKeyBuffer = Buffer.from(authenticator.public_key, 'base64url'); // Moved lookup after verification
// Prepare the verification options object - authenticator is looked up internally by the library
// based on the response's credential ID, or requires allowCredentials
const verificationOptions: VerifyAuthenticationResponseOpts = {
response: authenticationResponse,
expectedChallenge: expectedChallenge,
expectedOrigin: expectedOrigin,
expectedRPID: rpID,
// We need to provide a way for the library to get the authenticator details.
// Option 1: Provide `allowCredentials` (if known beforehand)
// Option 2: Let the library handle it (requires authenticator to be discoverable/resident key)
// Option 3 (Most robust): Provide the authenticator directly after fetching it.
// The library likely uses the credential ID from the response to find the authenticator,
// especially with discoverable credentials, or requires `allowCredentials`.
// Re-adding the authenticator property based on the new error message,
// ensuring the structure matches what the library likely expects.
authenticator: {
credentialID: Buffer.from(authenticator.credential_id, 'base64url'),
credentialPublicKey: Buffer.from(authenticator.public_key, 'base64url'),
counter: authenticator.counter,
transports: authenticator.transports ? JSON.parse(authenticator.transports) : undefined,
},
requireUserVerification: true, // simplewebauthn defaults this to true now
} as any; // Use type assertion to bypass strict property check for 'authenticator'
let verification: VerifiedAuthenticationResponse;
try {
verification = await verifyAuthenticationResponse(verificationOptions);
} catch (error: any) {
// If verification fails, log the error but potentially re-throw a more generic one
console.error('Passkey 认证验证时发生异常:', error);
const err = error as Error;
// Check if the error is due to the authenticator not being found (already handled)
if (!err.message.includes(credentialIdBase64Url)) {
throw new Error(`Passkey authentication verification failed: ${err.message || err}`);
}
// If error is related to authenticator not found, rethrow the original specific error
throw error;
}
if (verification.verified && verification.authenticationInfo) {
const { newCounter } = verification.authenticationInfo;
// 更新数据库中的计数器
await this.passkeyRepository.updatePasskeyCounter(authenticator.credential_id, newCounter);
console.log(`Passkey 认证成功: ${authenticator.credential_id}`);
} else {
console.error('Passkey 认证验证失败:', verification);
}
return verification;
}
/**
* 获取所有已注册 Passkey 的简要信息 (用于管理)
*/
async listPasskeys(): Promise<Partial<PasskeyRecord>[]> {
// 只返回 ID, Name, Transports, CreatedAt 以减少暴露敏感信息
const keys = await this.passkeyRepository.getAllPasskeys();
return keys.map(k => ({
id: k.id,
name: k.name,
transports: k.transports,
created_at: k.created_at
}));
}
/**
* 根据 ID 删除 Passkey
* @param id Passkey 记录的 ID
*/
async deletePasskey(id: number): Promise<void> {
await this.passkeyRepository.deletePasskeyById(id);
}
}