Branchwell

Become a Pro / website · becomeapro.ai / src / lib / biolock / client.js

1// @ts-nocheck
2// BioLock: browser side.
3// Sign in with this device's own fingerprint or face reader. Nothing else: no security keys,
4// no QR codes, no phone-to-computer sign-in. Uses the browser's W3C Web Authentication API,
5// limited to the built-in reader. Public domain (Unlicense).
6
7const KEY = 'biolock:enrolled-here';
8
9function toB64u(buf) {
10 const b = new Uint8Array(buf); let s = '';
11 for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
12 return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
13}
14function fromB64u(str) {
15 const s = String(str).replace(/-/g, '+').replace(/_/g, '/');
16 const bin = atob(s + '='.repeat((4 - (s.length % 4)) % 4));
17 const out = new Uint8Array(bin.length);
18 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
19 return out;
20}
21function load() { try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch { return {}; } }
22function save(v) { try { localStorage.setItem(KEY, JSON.stringify(v)); } catch { /* private mode: still works, just less smooth */ } }
23
24// Which IDs this device enrolled, per site. Only IDs, never secrets.
25export function enrolledOnThisDevice(rpId = location.hostname) { return load()[rpId] || []; }
26export function rememberEnrolled(id, rpId = location.hostname) {
27 const all = load(); const list = new Set(all[rpId] || []); list.add(id); all[rpId] = [...list]; save(all);
28}
29export function forgetEnrolled(id, rpId = location.hostname) {
30 const all = load(); all[rpId] = (all[rpId] || []).filter((x) => x !== id); save(all);
31}
32
33// Does this device have its own fingerprint or face reader the browser can use?
34export async function hasBuiltInReader() {
35 if (!window.PublicKeyCredential) return false;
36 try {
37 if (PublicKeyCredential.getClientCapabilities) {
38 const c = await PublicKeyCredential.getClientCapabilities();
39 if (typeof c.userVerifyingPlatformAuthenticator === 'boolean') return c.userVerifyingPlatformAuthenticator;
40 }
41 return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
42 } catch { return false; }
43}
44
45function creationFromJSON(o) {
46 if (PublicKeyCredential.parseCreationOptionsFromJSON) return PublicKeyCredential.parseCreationOptionsFromJSON(o);
47 return { ...o, challenge: fromB64u(o.challenge), user: { ...o.user, id: fromB64u(o.user.id) },
48 excludeCredentials: (o.excludeCredentials || []).map((c) => ({ ...c, id: fromB64u(c.id) })) };
49}
50function requestFromJSON(o) {
51 if (PublicKeyCredential.parseRequestOptionsFromJSON) return PublicKeyCredential.parseRequestOptionsFromJSON(o);
52 return { ...o, challenge: fromB64u(o.challenge), allowCredentials: (o.allowCredentials || []).map((c) => ({ ...c, id: fromB64u(c.id) })) };
53}
54function credToJSON(c) {
55 const r = c.response, out = { id: c.id, rawId: toB64u(c.rawId), type: c.type, authenticatorAttachment: c.authenticatorAttachment || null, response: { clientDataJSON: toB64u(r.clientDataJSON) } };
56 if (r.attestationObject) {
57 out.response.attestationObject = toB64u(r.attestationObject);
58 out.response.transports = r.getTransports ? r.getTransports() : [];
59 } else {
60 out.response.authenticatorData = toB64u(r.authenticatorData);
61 out.response.signature = toB64u(r.signature);
62 out.response.userHandle = r.userHandle ? toB64u(r.userHandle) : null;
63 }
64 return out;
65}
66
67// Enroll this device's reader. `options` comes from server.registrationOptions().
68export async function enrollThisDevice(options) {
69 if (!(await hasBuiltInReader())) throw new Error('This device has no fingerprint or face reader.');
70 const cred = await navigator.credentials.create({ publicKey: creationFromJSON(options) });
71 if (cred.authenticatorAttachment && cred.authenticatorAttachment !== 'platform') throw new Error('Only this device\'s own reader can be used.');
72 const json = credToJSON(cred);
73 rememberEnrolled(json.id, options.rp.id);
74 return json;
75}
76
77// Sign in with this device's reader. `options` comes from
78// server.signInOptions({ deviceCredentialIds: enrolledOnThisDevice() }).
79// If this device has nothing enrolled, nothing is shown: enroll it first with a one-time link.
80export async function signIn(options, { signal } = {}) {
81 if (!options.allowCredentials || !options.allowCredentials.length) throw new Error('This device is not enrolled yet.');
82 const o = { ...options, hints: ['client-device'], allowCredentials: options.allowCredentials.map((c) => ({ ...c, transports: ['internal'] })) };
83 const cred = await navigator.credentials.get({ publicKey: requestFromJSON(o), signal });
84 if (cred.authenticatorAttachment && cred.authenticatorAttachment !== 'platform') throw new Error('Only this device\'s own reader can be used.');
85 return credToJSON(cred);
86}
87
88// After a device is removed on the server, forget it here and tell the browser to drop it,
89// where supported, so it is never offered again.
90export async function removedOnServer(id, rpId = location.hostname) {
91 forgetEnrolled(id, rpId);
92 try { if (PublicKeyCredential.signalUnknownCredential) await PublicKeyCredential.signalUnknownCredential({ rpId, credentialId: id }); } catch { /* fine */ }
93}