Branchwell

Become a Pro / website · becomeapro.ai / src / lib / biolock / use-biolock.ts

Raw 2.6 KB on f63bc385c0fa362af985bfb576a8b5aa2a3df60f
1"use client";
2
3import * as C from "./client.js";
4
5// Browser side of BioLock sign-in for this site.
6type Mode = "signin" | "create" | "link";
7const BASE = "/api/auth/biolock/";
8
9async function post<T>(step: string, body: unknown): Promise<T> {
10 const response = await fetch(BASE + step, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
11 const data = await response.json().catch(() => ({})) as T & { error?: string; removed?: string };
12 if (data.removed) await C.removedOnServer(data.removed);
13 if (!response.ok) throw new Error(data.error || "Something went wrong. Try again.");
14 return data;
15}
16
17export const hasReader = () => C.hasBuiltInReader();
18export const enrolledHere = () => C.enrolledOnThisDevice();
19
20export async function biolock(mode: Mode, extra: { name?: string; token?: string } = {}) {
21 const deviceName = guessDeviceName();
22 try {
23 if (mode === "signin") {
24 const options = await post("options", { mode, ids: C.enrolledOnThisDevice() });
25 const credential = await C.signIn(options);
26 await post("verify", { mode, credential });
27 } else {
28 const options = await post("options", { mode, ...extra });
29 const credential = await C.enrollThisDevice(options);
30 await post("verify", { mode, credential, deviceName, ...extra });
31 }
32 } catch (error) {
33 if (error instanceof DOMException && error.name === "NotAllowedError") throw new Error("Cancelled, or your fingerprint or face did not match. Try again.");
34 if (error instanceof DOMException && error.name === "InvalidStateError") throw new Error("This device is already set up. Use Sign in instead.");
35 throw error;
36 }
37}
38
39function guessDeviceName() {
40 const ua = navigator.userAgent;
41 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";
42 const browser = /Edg\//.test(ua) ? "Edge" : /Firefox\//.test(ua) ? "Firefox" : /Chrome\//.test(ua) ? "Chrome" : /Safari\//.test(ua) ? "Safari" : "browser";
43 return `${os}, ${browser}`;
44}
45
46export async function makeDeviceLink() {
47 return post<{ url: string; expiresAt: number }>("link", {});
48}
49export async function listDevices() {
50 const response = await fetch(BASE + "devices", { cache: "no-store" });
51 if (!response.ok) throw new Error("Could not load your devices.");
52 return (await response.json() as { devices: { id: string; name: string; created_at: number; last_used: number | null }[] }).devices;
53}
54export async function removeDevice(id: string) {
55 await post("remove", { id });
56 await C.removedOnServer(id);
57}