mirror of
https://github.com/Sagit-chu/flvx.git
synced 2026-10-02 08:56:38 +08:00
feat: add secure passkey login for issue 536
This commit is contained in:
@@ -70,6 +70,44 @@ export interface LoginResponse {
|
||||
export const login = (data: LoginData) =>
|
||||
Network.post<LoginResponse>("/user/login", data);
|
||||
|
||||
export interface PasskeyOptions {
|
||||
sessionId: string;
|
||||
options: { publicKey: Record<string, unknown> };
|
||||
}
|
||||
|
||||
export interface PasskeyItem {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt: number;
|
||||
lastUsedAt: number;
|
||||
}
|
||||
|
||||
export const getPasskeyStatus = () =>
|
||||
Network.post<{ enabled: boolean }>("/user/passkey/status");
|
||||
export const beginPasskeyLogin = (username: string) =>
|
||||
Network.post<PasskeyOptions>("/user/passkey/login/begin", { username });
|
||||
export const finishPasskeyLogin = (sessionId: string, credential: unknown) =>
|
||||
Network.post<LoginResponse>("/user/passkey/login/finish", {
|
||||
sessionId,
|
||||
credential,
|
||||
});
|
||||
export const beginPasskeyRegistration = (password: string) =>
|
||||
Network.post<PasskeyOptions>("/user/passkey/register/begin", { password });
|
||||
export const finishPasskeyRegistration = (
|
||||
sessionId: string,
|
||||
credential: unknown,
|
||||
name: string,
|
||||
) =>
|
||||
Network.post("/user/passkey/register/finish", {
|
||||
sessionId,
|
||||
credential,
|
||||
name,
|
||||
});
|
||||
export const listPasskeys = () =>
|
||||
Network.post<PasskeyItem[]>("/user/passkey/list");
|
||||
export const deletePasskey = (id: string, password: string) =>
|
||||
Network.post("/user/passkey/delete", { id, password });
|
||||
|
||||
// 用户CRUD操作 - 全部使用POST请求
|
||||
export const createUser = (data: UserMutationPayload) =>
|
||||
Network.post("/user/create", data);
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
|
||||
import { Card, CardBody } from "@/shadcn-bridge/heroui/card";
|
||||
import { Button } from "@/shadcn-bridge/heroui/button";
|
||||
import { Input } from "@/shadcn-bridge/heroui/input";
|
||||
import {
|
||||
beginPasskeyRegistration,
|
||||
deletePasskey,
|
||||
finishPasskeyRegistration,
|
||||
getPasskeyStatus,
|
||||
listPasskeys,
|
||||
type PasskeyItem,
|
||||
} from "@/api";
|
||||
import { createPasskey } from "@/utils/passkey";
|
||||
|
||||
export function PasskeyManager() {
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const [items, setItems] = useState<PasskeyItem[]>([]);
|
||||
const [password, setPassword] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const refresh = () =>
|
||||
listPasskeys()
|
||||
.then((res) => {
|
||||
if (res.code === 0) setItems(res.data || []);
|
||||
})
|
||||
.catch(() => setItems([]));
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!window.isSecureContext ||
|
||||
typeof window.PublicKeyCredential === "undefined"
|
||||
)
|
||||
return;
|
||||
getPasskeyStatus()
|
||||
.then((res) => {
|
||||
if (res.code === 0 && res.data.enabled) {
|
||||
setEnabled(true);
|
||||
void refresh();
|
||||
}
|
||||
})
|
||||
.catch(() => setEnabled(false));
|
||||
}, []);
|
||||
|
||||
if (!enabled) return null;
|
||||
|
||||
const register = async () => {
|
||||
if (!password) {
|
||||
toast.error("请输入当前密码");
|
||||
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const begin = await beginPasskeyRegistration(password);
|
||||
|
||||
if (begin.code !== 0) {
|
||||
toast.error(begin.msg || "无法绑定通行证密钥");
|
||||
|
||||
return;
|
||||
}
|
||||
const credential = await createPasskey(begin.data.options);
|
||||
const finish = await finishPasskeyRegistration(
|
||||
begin.data.sessionId,
|
||||
credential,
|
||||
name.trim(),
|
||||
);
|
||||
|
||||
if (finish.code !== 0) {
|
||||
toast.error(finish.msg || "绑定失败");
|
||||
|
||||
return;
|
||||
}
|
||||
toast.success("通行证密钥已绑定");
|
||||
setPassword("");
|
||||
setName("");
|
||||
await refresh();
|
||||
} catch {
|
||||
toast.error("绑定已取消或失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string) => {
|
||||
if (!password) {
|
||||
toast.error("请输入当前密码以删除密钥");
|
||||
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
const result = await deletePasskey(id, password);
|
||||
|
||||
if (result.code !== 0) {
|
||||
toast.error(result.msg || "删除失败");
|
||||
|
||||
return;
|
||||
}
|
||||
toast.success("通行证密钥已删除");
|
||||
setPassword("");
|
||||
await refresh();
|
||||
} catch {
|
||||
toast.error("删除失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardBody className="p-4 space-y-4">
|
||||
<div>
|
||||
<h3 className="text-base font-medium">通行证密钥</h3>
|
||||
<p className="text-sm text-default-500">
|
||||
绑定后可使用设备解锁登录,无需 Cloudflare
|
||||
验证。绑定和删除均需输入当前密码。
|
||||
</p>
|
||||
</div>
|
||||
<Input
|
||||
label="当前密码"
|
||||
type="password"
|
||||
value={password}
|
||||
variant="bordered"
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
<Input
|
||||
label="密钥名称(可选)"
|
||||
value={name}
|
||||
variant="bordered"
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
/>
|
||||
<Button disabled={busy} onPress={register}>
|
||||
绑定通行证密钥
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.id}
|
||||
className="flex items-center justify-between gap-3 rounded-lg border border-default-200 p-3"
|
||||
>
|
||||
<div>
|
||||
<div className="text-sm font-medium">{item.name}</div>
|
||||
<div className="text-xs text-default-500">
|
||||
创建于 {new Date(item.createdAt).toLocaleDateString()}{" "}
|
||||
{item.lastUsedAt
|
||||
? ` · 最近使用 ${new Date(item.lastUsedAt).toLocaleDateString()}`
|
||||
: ""}
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
color="danger"
|
||||
disabled={busy}
|
||||
size="sm"
|
||||
variant="light"
|
||||
onPress={() => void remove(item.id)}
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import toast from "react-hot-toast";
|
||||
import { Turnstile } from "@marsidev/react-turnstile";
|
||||
@@ -10,8 +10,17 @@ import { Button } from "@/shadcn-bridge/heroui/button";
|
||||
import { siteConfig } from "@/config/site";
|
||||
import { VersionFooter } from "@/components/version-footer";
|
||||
import { BrandLogo } from "@/components/brand-logo";
|
||||
import { login, LoginData, checkCaptcha, getPublicConfigByName } from "@/api";
|
||||
import {
|
||||
login,
|
||||
LoginData,
|
||||
checkCaptcha,
|
||||
getPublicConfigByName,
|
||||
getPasskeyStatus,
|
||||
beginPasskeyLogin,
|
||||
finishPasskeyLogin,
|
||||
} from "@/api";
|
||||
import { writeLoginSession } from "@/utils/session";
|
||||
import { getPasskey } from "@/utils/passkey";
|
||||
import { useWebViewMode } from "@/hooks/useWebViewMode";
|
||||
|
||||
interface LoginForm {
|
||||
@@ -30,9 +39,56 @@ export default function IndexPage() {
|
||||
const [errors, setErrors] = useState<Partial<LoginForm>>({});
|
||||
const [showCaptcha, setShowCaptcha] = useState(false);
|
||||
const [siteKey, setSiteKey] = useState("");
|
||||
const [passkeyEnabled, setPasskeyEnabled] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const isWebView = useWebViewMode();
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
window.isSecureContext &&
|
||||
typeof window.PublicKeyCredential !== "undefined"
|
||||
) {
|
||||
getPasskeyStatus()
|
||||
.then((res) => setPasskeyEnabled(res.code === 0 && res.data.enabled))
|
||||
.catch(() => setPasskeyEnabled(false));
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handlePasskeyLogin = async () => {
|
||||
if (!form.username.trim()) {
|
||||
toast.error("请输入用户名");
|
||||
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
try {
|
||||
const begin = await beginPasskeyLogin(form.username.trim());
|
||||
|
||||
if (begin.code !== 0) {
|
||||
toast.error(begin.msg || "无法使用通行证密钥登录");
|
||||
|
||||
return;
|
||||
}
|
||||
const credential = await getPasskey(begin.data.options);
|
||||
const result = await finishPasskeyLogin(begin.data.sessionId, credential);
|
||||
|
||||
if (result.code !== 0) {
|
||||
toast.error(result.msg || "通行证密钥登录失败");
|
||||
|
||||
return;
|
||||
}
|
||||
writeLoginSession(result.data);
|
||||
toast.success("登录成功");
|
||||
navigate(
|
||||
result.data.requirePasswordChange ? "/change-password" : "/dashboard",
|
||||
);
|
||||
} catch {
|
||||
toast.error("通行证密钥登录已取消或失败");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 验证表单
|
||||
const validateForm = (): boolean => {
|
||||
const newErrors: Partial<LoginForm> = {};
|
||||
@@ -221,6 +277,16 @@ export default function IndexPage() {
|
||||
: "Signing in..."
|
||||
: "Sign In"}
|
||||
</Button>
|
||||
{passkeyEnabled && (
|
||||
<Button
|
||||
className="h-12 rounded-xl"
|
||||
disabled={loading}
|
||||
variant="bordered"
|
||||
onPress={handlePasskeyLogin}
|
||||
>
|
||||
使用通行证密钥登录
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
|
||||
@@ -19,6 +19,7 @@ import { VersionFooter } from "@/components/version-footer";
|
||||
import { updatePassword } from "@/api";
|
||||
import { safeLogout } from "@/utils/logout";
|
||||
import { getAdminFlag, getSessionName } from "@/utils/session";
|
||||
import { PasskeyManager } from "@/components/passkey-manager";
|
||||
interface PasswordForm {
|
||||
newUsername: string;
|
||||
currentPassword: string;
|
||||
@@ -241,6 +242,7 @@ export default function ProfilePage() {
|
||||
</Card>
|
||||
|
||||
{/* 功能网格 */}
|
||||
<PasskeyManager />
|
||||
<Card>
|
||||
<CardBody className="p-4">
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
// Convert the WebAuthn JSON wire format to the browser's ArrayBuffer format.
|
||||
function decode(value: string): ArrayBuffer {
|
||||
const padded = value.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const bytes = Uint8Array.from(atob(padded), (character) =>
|
||||
character.charCodeAt(0),
|
||||
);
|
||||
|
||||
return bytes.buffer;
|
||||
}
|
||||
|
||||
function encode(value: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(value);
|
||||
let binary = "";
|
||||
|
||||
bytes.forEach((byte) => {
|
||||
binary += String.fromCharCode(byte);
|
||||
});
|
||||
|
||||
return btoa(binary)
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
}
|
||||
|
||||
export async function createPasskey(options: {
|
||||
publicKey: Record<string, unknown>;
|
||||
}) {
|
||||
const source = options.publicKey as unknown as {
|
||||
challenge: string;
|
||||
user: { id: string };
|
||||
excludeCredentials?: Array<{ id: string }>;
|
||||
};
|
||||
const publicKey: PublicKeyCredentialCreationOptions = {
|
||||
...(options.publicKey as unknown as PublicKeyCredentialCreationOptions),
|
||||
challenge: decode(source.challenge),
|
||||
user: {
|
||||
...(source.user as unknown as PublicKeyCredentialUserEntity),
|
||||
id: decode(source.user.id),
|
||||
},
|
||||
excludeCredentials: source.excludeCredentials?.map((item) => ({
|
||||
...(item as unknown as PublicKeyCredentialDescriptor),
|
||||
id: decode(item.id),
|
||||
})),
|
||||
};
|
||||
const credential = (await navigator.credentials.create({
|
||||
publicKey,
|
||||
})) as PublicKeyCredential | null;
|
||||
|
||||
if (!credential) throw new Error("未创建通行证密钥");
|
||||
const result = credential.response as AuthenticatorAttestationResponse;
|
||||
|
||||
return {
|
||||
id: credential.id,
|
||||
rawId: encode(credential.rawId),
|
||||
type: credential.type,
|
||||
response: {
|
||||
attestationObject: encode(result.attestationObject),
|
||||
clientDataJSON: encode(result.clientDataJSON),
|
||||
transports: result.getTransports?.() || [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPasskey(options: {
|
||||
publicKey: Record<string, unknown>;
|
||||
}) {
|
||||
const source = options.publicKey as unknown as {
|
||||
challenge: string;
|
||||
allowCredentials?: Array<{ id: string }>;
|
||||
};
|
||||
const publicKey: PublicKeyCredentialRequestOptions = {
|
||||
...(options.publicKey as unknown as PublicKeyCredentialRequestOptions),
|
||||
challenge: decode(source.challenge),
|
||||
allowCredentials: source.allowCredentials?.map((item) => ({
|
||||
...(item as unknown as PublicKeyCredentialDescriptor),
|
||||
id: decode(item.id),
|
||||
})),
|
||||
};
|
||||
const credential = (await navigator.credentials.get({
|
||||
publicKey,
|
||||
})) as PublicKeyCredential | null;
|
||||
|
||||
if (!credential) throw new Error("未选择通行证密钥");
|
||||
const result = credential.response as AuthenticatorAssertionResponse;
|
||||
|
||||
return {
|
||||
id: credential.id,
|
||||
rawId: encode(credential.rawId),
|
||||
type: credential.type,
|
||||
response: {
|
||||
authenticatorData: encode(result.authenticatorData),
|
||||
clientDataJSON: encode(result.clientDataJSON),
|
||||
signature: encode(result.signature),
|
||||
userHandle: result.userHandle ? encode(result.userHandle) : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user