Security key support
This commit is contained in:
parent
ede90f8c7f
commit
c991fe7b6d
6 changed files with 384 additions and 47 deletions
|
|
@ -2,14 +2,30 @@
|
|||
import { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
function b64uToBuf(b64u: string): ArrayBuffer {
|
||||
const b64 = b64u.replace(/-/g, "+").replace(/_/g, "/");
|
||||
const bin = atob(b64);
|
||||
const buf = new Uint8Array(bin.length);
|
||||
for (let i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
|
||||
return buf.buffer;
|
||||
}
|
||||
|
||||
function bufToB64u(buf: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buf);
|
||||
let bin = "";
|
||||
for (const b of bytes) bin += String.fromCharCode(b);
|
||||
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
||||
}
|
||||
|
||||
type Status = "idle" | "checking" | "waiting_yubikey" | "verifying";
|
||||
|
||||
export default function AuthPage() {
|
||||
const router = useRouter();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [totp, setTotp] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [checking, setChecking] = useState(true);
|
||||
const [status, setStatus] = useState<Status>("idle");
|
||||
const [initialChecking, setInitialChecking] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
async function checkAuth() {
|
||||
|
|
@ -22,7 +38,7 @@ export default function AuthPage() {
|
|||
router.push(callbackUrl);
|
||||
}
|
||||
} finally {
|
||||
setChecking(false);
|
||||
setInitialChecking(false);
|
||||
}
|
||||
}
|
||||
checkAuth();
|
||||
|
|
@ -30,29 +46,96 @@ export default function AuthPage() {
|
|||
|
||||
async function handleLogin(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setStatus("checking");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/login", {
|
||||
// Step 1: verify password → get WebAuthn challenge
|
||||
const loginRes = await fetch("/api/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username, password, totp }),
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
setError("Invalid credentials or authenticator code.");
|
||||
setLoading(false);
|
||||
|
||||
if (!loginRes.ok) {
|
||||
setError("Invalid credentials.");
|
||||
setStatus("idle");
|
||||
return;
|
||||
}
|
||||
|
||||
const { session_id, challenge } = await loginRes.json();
|
||||
|
||||
// Step 2: prompt YubiKey tap
|
||||
setStatus("waiting_yubikey");
|
||||
const opts = challenge.publicKey;
|
||||
opts.challenge = b64uToBuf(opts.challenge);
|
||||
if (opts.allowCredentials) {
|
||||
opts.allowCredentials = opts.allowCredentials.map(
|
||||
(c: { id: string; type: string; transports?: string[] }) => ({
|
||||
...c,
|
||||
id: b64uToBuf(c.id),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let cred: PublicKeyCredential;
|
||||
try {
|
||||
cred = (await navigator.credentials.get({
|
||||
publicKey: opts,
|
||||
})) as PublicKeyCredential;
|
||||
} catch (err: unknown) {
|
||||
setError(
|
||||
"YubiKey error: " +
|
||||
(err instanceof Error ? err.message : "cancelled"),
|
||||
);
|
||||
setStatus("idle");
|
||||
return;
|
||||
}
|
||||
|
||||
// Step 3: verify assertion → set cookie
|
||||
setStatus("verifying");
|
||||
const assertion = cred.response as AuthenticatorAssertionResponse;
|
||||
|
||||
const verifyRes = await fetch("/api/auth/verify", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
session_id,
|
||||
credential: {
|
||||
id: cred.id,
|
||||
rawId: bufToB64u(cred.rawId),
|
||||
type: cred.type,
|
||||
response: {
|
||||
authenticatorData: bufToB64u(assertion.authenticatorData),
|
||||
clientDataJSON: bufToB64u(assertion.clientDataJSON),
|
||||
signature: bufToB64u(assertion.signature),
|
||||
userHandle: assertion.userHandle
|
||||
? bufToB64u(assertion.userHandle)
|
||||
: null,
|
||||
},
|
||||
extensions: {},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
if (!verifyRes.ok) {
|
||||
setError("YubiKey verification failed.");
|
||||
setStatus("idle");
|
||||
return;
|
||||
}
|
||||
|
||||
const callbackUrl =
|
||||
new URLSearchParams(window.location.search).get("callbackUrl") ?? "/";
|
||||
router.push(callbackUrl);
|
||||
} catch {
|
||||
setError("Something went wrong. Try again.");
|
||||
setLoading(false);
|
||||
setStatus("idle");
|
||||
}
|
||||
}
|
||||
|
||||
if (checking) return null;
|
||||
if (initialChecking) return null;
|
||||
|
||||
const busy = status !== "idle";
|
||||
|
||||
return (
|
||||
<main className="h-full bg-gray-100 flex items-center justify-center">
|
||||
|
|
@ -79,13 +162,14 @@ export default function AuthPage() {
|
|||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
disabled={busy}
|
||||
autoComplete="username"
|
||||
className="w-full px-3.5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-900 bg-gray-50 outline-none focus:border-blue-300 focus:ring-2 focus:ring-blue-50 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Password */}
|
||||
<div className="mb-4">
|
||||
<div className="mb-6">
|
||||
<label className="block text-[11px] tracking-wider text-gray-400 uppercase mb-1.5">
|
||||
Password
|
||||
</label>
|
||||
|
|
@ -94,44 +178,38 @@ export default function AuthPage() {
|
|||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
disabled={busy}
|
||||
autoComplete="current-password"
|
||||
className="w-full px-3.5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-900 bg-gray-50 outline-none focus:border-blue-300 focus:ring-2 focus:ring-blue-50 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* TOTP */}
|
||||
<div className="mb-6">
|
||||
<label className="block text-[11px] tracking-wider text-gray-400 uppercase mb-1.5">
|
||||
Authenticator code
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={totp}
|
||||
onChange={(e) =>
|
||||
setTotp(e.target.value.replace(/\D/g, "").slice(0, 6))
|
||||
}
|
||||
required
|
||||
autoComplete="one-time-code"
|
||||
inputMode="numeric"
|
||||
placeholder="000000"
|
||||
className="w-full px-3.5 py-2.5 border border-gray-200 rounded-xl text-sm text-gray-900 bg-gray-50 outline-none focus:border-blue-300 focus:ring-2 focus:ring-blue-50 transition-colors tracking-widest"
|
||||
/>
|
||||
</div>
|
||||
{/* YubiKey cue */}
|
||||
{status === "waiting_yubikey" && (
|
||||
<p className="text-sm text-blue-500 mb-4 text-center animate-pulse">
|
||||
Touch your YubiKey…
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Error */}
|
||||
{error && <p className="text-[13px] text-red-400 mb-4">{error}</p>}
|
||||
{error && (
|
||||
<p className="text-[13px] text-red-400 mb-4">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
disabled={busy}
|
||||
className={`w-full py-2.5 rounded-xl text-md border border-blue-600 shadow-sm text-white font-[600] tracking-wide transition-colors ${
|
||||
loading
|
||||
busy
|
||||
? "bg-blue-200 cursor-not-allowed"
|
||||
: "bg-blue-500 hover:bg-blue-400 cursor-pointer"
|
||||
}`}
|
||||
>
|
||||
{loading ? "Signing in..." : "Sign in"}
|
||||
{status === "idle" && "Sign in"}
|
||||
{status === "checking" && "Checking…"}
|
||||
{status === "waiting_yubikey" && "Waiting for YubiKey…"}
|
||||
{status === "verifying" && "Verifying…"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue