Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 81 additions & 0 deletions src/__tests__/biometric.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
BIOMETRIC_CREDENTIAL_KEY,
enableBiometric,
isBiometricAvailable,
verifyBiometric,
} from "@/lib/biometric";
import { readSecurityEvents } from "@/lib/walletSecurity";

const credentialId = new Uint8Array([1, 2, 3, 4]).buffer;

function installWebAuthnMocks({ verified = true, matchingId = true } = {}) {
const authenticatorData = new Uint8Array(37);
authenticatorData[32] = verified ? 0x04 : 0x01;
const credentials = {
create: vi.fn().mockResolvedValue({ rawId: credentialId }),
get: vi.fn().mockResolvedValue({
type: "public-key",
rawId: matchingId ? credentialId : new Uint8Array([9, 9, 9]).buffer,
response: { authenticatorData: authenticatorData.buffer },
}),
};

Object.defineProperty(window, "isSecureContext", { configurable: true, value: true });
Object.defineProperty(window, "PublicKeyCredential", {
configurable: true,
value: { isUserVerifyingPlatformAuthenticatorAvailable: vi.fn().mockResolvedValue(true) },
});
Object.defineProperty(navigator, "credentials", { configurable: true, value: credentials });
return credentials;
}

describe("biometric authentication", () => {
beforeEach(() => {
localStorage.clear();
});

it("is available only in secure contexts with a platform authenticator", async () => {
installWebAuthnMocks();
expect(await isBiometricAvailable()).toBe(true);

Object.defineProperty(window, "isSecureContext", { configurable: true, value: false });
expect(await isBiometricAvailable()).toBe(false);
});

it("enrolls a platform credential and records enrollment analytics", async () => {
const credentials = installWebAuthnMocks();
await enableBiometric();

expect(credentials.create).toHaveBeenCalledWith(expect.objectContaining({
publicKey: expect.objectContaining({
authenticatorSelection: expect.objectContaining({
authenticatorAttachment: "platform",
userVerification: "required",
}),
}),
}));
expect(localStorage.getItem(BIOMETRIC_CREDENTIAL_KEY)).toBe("AQIDBA");
expect(readSecurityEvents()[0].type).toBe("biometric_enrolled");
});

it("accepts only the enrolled credential with user verification", async () => {
installWebAuthnMocks();
localStorage.setItem(BIOMETRIC_CREDENTIAL_KEY, "AQIDBA");
expect(await verifyBiometric()).toBe(true);
expect(readSecurityEvents()[0].type).toBe("biometric_success");
});

it("rejects an assertion without user verification or with another credential", async () => {
localStorage.setItem(BIOMETRIC_CREDENTIAL_KEY, "AQIDBA");
installWebAuthnMocks({ verified: false });
expect(await verifyBiometric()).toBe(false);
expect(readSecurityEvents()[0].type).toBe("biometric_failed");

localStorage.clear();
readSecurityEvents();
localStorage.setItem(BIOMETRIC_CREDENTIAL_KEY, "AQIDBA");
installWebAuthnMocks({ matchingId: false });
expect(await verifyBiometric()).toBe(false);
});
});
4 changes: 4 additions & 0 deletions src/components/security/WalletSecuritySettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const EVENT_LABELS: Record<SecurityEventType, string> = {
secret_detected: "Secret key or recovery phrase entered",
rate_limited: "Wallet action rate limited",
session_locked: "Session locked after inactivity",
biometric_enrolled: "Biometric unlock enabled",
biometric_disabled: "Biometric unlock disabled",
biometric_success: "Biometric verification succeeded",
biometric_failed: "Biometric verification failed",
};

/**
Expand Down
77 changes: 52 additions & 25 deletions src/lib/biometric.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { recordSecurityEvent } from "@/lib/walletSecurity";

/**
* Optional biometric unlock using the device's platform authenticator
* (Touch ID, Face ID, Windows Hello, Android fingerprint) via WebAuthn.
Expand Down Expand Up @@ -31,6 +33,7 @@ function randomBytes(n: number): ArrayBuffer {
/** True when this browser/device offers a user-verifying platform authenticator. */
export async function isBiometricAvailable(): Promise<boolean> {
if (typeof window === "undefined" || !window.PublicKeyCredential || !navigator.credentials) return false;
if (!window.isSecureContext) return false;
try {
return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
} catch {
Expand All @@ -48,49 +51,60 @@ export function getBiometricCredentialId(): string | null {
}

export function isBiometricEnabled(): boolean {
return getBiometricCredentialId() !== null;
return Boolean(getBiometricCredentialId());
}

/** Register a platform credential and remember its ID. Prompts the OS biometric dialog. */
export async function enableBiometric(label = "StellarSplit"): Promise<void> {
if (!(await isBiometricAvailable())) {
throw new Error("Biometric authentication isn't available on this device.");
}
const credential = (await navigator.credentials.create({
publicKey: {
challenge: randomBytes(32),
rp: { name: "StellarSplit", id: window.location.hostname },
user: { id: randomBytes(16), name: label, displayName: label },
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
],
authenticatorSelection: {
authenticatorAttachment: "platform",
userVerification: "required",
residentKey: "discouraged",
try {
if (!(await isBiometricAvailable())) {
throw new Error("Biometric authentication isn't available on this device.");
}
const credential = (await navigator.credentials.create({
publicKey: {
challenge: randomBytes(32),
rp: { name: "StellarSplit", id: window.location.hostname },
user: { id: randomBytes(16), name: label, displayName: label },
pubKeyCredParams: [
{ type: "public-key", alg: -7 },
{ type: "public-key", alg: -257 },
],
authenticatorSelection: {
authenticatorAttachment: "platform",
userVerification: "required",
residentKey: "discouraged",
},
timeout: 60_000,
attestation: "none",
},
timeout: 60_000,
attestation: "none",
},
})) as PublicKeyCredential | null;
if (!credential) throw new Error("Biometric setup was cancelled.");
window.localStorage.setItem(BIOMETRIC_CREDENTIAL_KEY, toBase64Url(credential.rawId));
})) as PublicKeyCredential | null;
if (!credential?.rawId.byteLength) throw new Error("Biometric setup was cancelled.");
window.localStorage.setItem(BIOMETRIC_CREDENTIAL_KEY, toBase64Url(credential.rawId));
recordSecurityEvent({ type: "biometric_enrolled" });
} catch (error) {
recordSecurityEvent({ type: "biometric_failed", detail: "enrollment" });
throw error;
}
}

export function disableBiometric(): void {
if (typeof window === "undefined") return;
const wasEnabled = isBiometricEnabled();
try {
window.localStorage.removeItem(BIOMETRIC_CREDENTIAL_KEY);
} catch {
// ignore
}
if (wasEnabled) recordSecurityEvent({ type: "biometric_disabled" });
}

/** Ask the OS to verify the user with the registered credential. Resolves true on success. */
export async function verifyBiometric(): Promise<boolean> {
const id = getBiometricCredentialId();
if (!id || !navigator.credentials) return false;
if (!id || !navigator.credentials) {
recordSecurityEvent({ type: "biometric_failed", detail: "unavailable" });
return false;
}
try {
const assertion = await navigator.credentials.get({
publicKey: {
Expand All @@ -100,8 +114,21 @@ export async function verifyBiometric(): Promise<boolean> {
timeout: 60_000,
},
});
return assertion !== null;
const credentialId = fromBase64Url(id);
const rawId = (assertion as PublicKeyCredential | null)?.rawId;
const response = (assertion as PublicKeyCredential | null)?.response as AuthenticatorAssertionResponse | undefined;
const authenticatorData = response?.authenticatorData;
const matchesCredential = Boolean(
rawId && rawId.byteLength === credentialId.byteLength &&
new Uint8Array(rawId).every((byte, index) => byte === new Uint8Array(credentialId)[index]),
);
const userVerified = Boolean(authenticatorData && authenticatorData.byteLength >= 33 &&
(new Uint8Array(authenticatorData)[32] & 0x04) !== 0);
const verified = assertion?.type === "public-key" && matchesCredential && userVerified;
recordSecurityEvent({ type: verified ? "biometric_success" : "biometric_failed", detail: "verification" });
return verified;
} catch {
recordSecurityEvent({ type: "biometric_failed", detail: "verification" });
return false;
}
}
Loading
Loading