Branchwell

BioLock / source · biolock.dev / src / client.js

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