"use client"; import * as C from "./client.js"; // Browser side of BioLock sign-in for this site. type Mode = "signin" | "create" | "link"; const BASE = "/api/auth/biolock/"; async function post(step: string, body: unknown): Promise { const response = await fetch(BASE + step, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const data = await response.json().catch(() => ({})) as T & { error?: string; removed?: string }; if (data.removed) await C.removedOnServer(data.removed); if (!response.ok) throw new Error(data.error || "Something went wrong. Try again."); return data; } export const hasReader = () => C.hasBuiltInReader(); export const enrolledHere = () => C.enrolledOnThisDevice(); export async function biolock(mode: Mode, extra: { name?: string; token?: string } = {}) { const deviceName = guessDeviceName(); try { if (mode === "signin") { const options = await post("options", { mode, ids: C.enrolledOnThisDevice() }); const credential = await C.signIn(options); await post("verify", { mode, credential }); } else { const options = await post("options", { mode, ...extra }); const credential = await C.enrollThisDevice(options); await post("verify", { mode, credential, deviceName, ...extra }); } } catch (error) { if (error instanceof DOMException && error.name === "NotAllowedError") throw new Error("Cancelled, or your fingerprint or face did not match. Try again."); if (error instanceof DOMException && error.name === "InvalidStateError") throw new Error("This device is already set up. Use Sign in instead."); throw error; } } function guessDeviceName() { const ua = navigator.userAgent; const os = /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Android/.test(ua) ? "Android" : /Mac/.test(ua) ? "Mac" : /Windows/.test(ua) ? "Windows PC" : /Linux/.test(ua) ? "Linux" : "Device"; const browser = /Edg\//.test(ua) ? "Edge" : /Firefox\//.test(ua) ? "Firefox" : /Chrome\//.test(ua) ? "Chrome" : /Safari\//.test(ua) ? "Safari" : "browser"; return `${os}, ${browser}`; } export async function makeDeviceLink() { return post<{ url: string; expiresAt: number }>("link", {}); } export async function listDevices() { const response = await fetch(BASE + "devices", { cache: "no-store" }); if (!response.ok) throw new Error("Could not load your devices."); return (await response.json() as { devices: { id: string; name: string; created_at: number; last_used: number | null }[] }).devices; } export async function removeDevice(id: string) { await post("remove", { id }); await C.removedOnServer(id); }