// @ts-nocheck -- vendored BioLock (public domain, Unlicense). See README.md in this folder. // BioLock: server side. // Sign in with the fingerprint or face reader built into your own device. Nothing else: // no passwords, no security keys, no QR codes, no phone-to-computer sign-in. // Under the hood it uses the W3C Web Authentication standard, because that is the only way // browsers let a website use the device's own reader, and turns off every other part of it. // Runs anywhere with Web Crypto (Cloudflare Workers, Deno, Bun, Node 20+, browsers). // No dependencies. Public domain (Unlicense). const enc = new TextEncoder(); const dec = new TextDecoder(); // ---------- base64url ---------- export function toB64u(bytes) { const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes); let s = ''; for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); } export function fromB64u(str) { const s = String(str).replace(/-/g, '+').replace(/_/g, '/'); const bin = atob(s + '='.repeat((4 - (s.length % 4)) % 4)); const out = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } export function randomB64u(n = 32) { return toB64u(crypto.getRandomValues(new Uint8Array(n))); } // ---------- tiny CBOR reader (only what WebAuthn uses) ---------- export function cborDecode(buf, pos = 0) { const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength); function len(info) { if (info < 24) return info; if (info === 24) return buf[pos++]; if (info === 25) { const v = dv.getUint16(pos); pos += 2; return v; } if (info === 26) { const v = dv.getUint32(pos); pos += 4; return v; } if (info === 27) { const v = Number(dv.getBigUint64(pos)); pos += 8; return v; } throw new Error('CBOR: unsupported length'); } function item() { if (pos >= buf.length) throw new Error('CBOR: ran out of data'); const ib = buf[pos++], major = ib >> 5, info = ib & 31; switch (major) { case 0: return len(info); case 1: return -1 - len(info); case 2: { const n = len(info); const v = buf.slice(pos, pos + n); pos += n; return v; } case 3: { const n = len(info); const v = dec.decode(buf.subarray(pos, pos + n)); pos += n; return v; } case 4: { const n = len(info); const a = []; for (let i = 0; i < n; i++) a.push(item()); return a; } case 5: { const n = len(info); const m = new Map(); for (let i = 0; i < n; i++) { const k = item(); m.set(k, item()); } return m; } case 6: len(info); return item(); // tag: keep the value case 7: if (info === 20) return false; if (info === 21) return true; if (info === 22) return null; throw new Error('CBOR: unsupported simple value'); } throw new Error('CBOR: bad major type'); } const value = item(); return { value, end: pos }; } // ---------- authenticator data ---------- export const FLAGS = { UP: 0x01, UV: 0x04, BE: 0x08, BS: 0x10, AT: 0x40, ED: 0x80 }; export function parseAuthData(ad) { if (ad.length < 37) throw new Error('authenticator data too short'); const flags = ad[32]; const out = { rpIdHash: ad.slice(0, 32), flags, userPresent: !!(flags & FLAGS.UP), userVerified: !!(flags & FLAGS.UV), backupEligible: !!(flags & FLAGS.BE), backedUp: !!(flags & FLAGS.BS), counter: new DataView(ad.buffer, ad.byteOffset + 33, 4).getUint32(0), }; if (flags & FLAGS.AT) { let p = 37; out.aaguid = ad.slice(p, p + 16); p += 16; const idLen = (ad[p] << 8) | ad[p + 1]; p += 2; out.credentialId = ad.slice(p, p + idLen); p += idLen; const { value, end } = cborDecode(ad, p); out.coseKey = value; out.coseKeyBytes = ad.slice(p, end); } return out; } // ---------- keys ---------- // COSE key (from the authenticator) -> JWK we can store as plain JSON. export function coseToJwk(cose) { const kty = cose.get(1), alg = cose.get(3); if (kty === 2 && alg === -7 && cose.get(-1) === 1) return { alg: -7, jwk: { kty: 'EC', crv: 'P-256', x: toB64u(cose.get(-2)), y: toB64u(cose.get(-3)) } }; if (kty === 1 && alg === -8 && cose.get(-1) === 6) return { alg: -8, jwk: { kty: 'OKP', crv: 'Ed25519', x: toB64u(cose.get(-2)) } }; if (kty === 3 && alg === -257) return { alg: -257, jwk: { kty: 'RSA', n: toB64u(cose.get(-1)), e: toB64u(cose.get(-2)) } }; throw new Error('unsupported key type (we accept ES256, Ed25519 and RS256)'); } const ALGS = { [-7]: { imp: { name: 'ECDSA', namedCurve: 'P-256' }, ver: { name: 'ECDSA', hash: 'SHA-256' } }, [-8]: { imp: { name: 'Ed25519' }, ver: { name: 'Ed25519' } }, [-257]: { imp: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, ver: { name: 'RSASSA-PKCS1-v1_5' } }, }; // WebAuthn ES256 signatures are DER; Web Crypto wants raw r||s. export function derToRaw(der, size = 32) { let p = 0; if (der[p++] !== 0x30) throw new Error('bad signature'); if (der[p] & 0x80) p += 1 + (der[p] & 0x7f); else p++; const part = () => { if (der[p++] !== 0x02) throw new Error('bad signature'); const n = der[p++]; let v = der.slice(p, p + n); p += n; while (v.length > size && v[0] === 0) v = v.slice(1); const o = new Uint8Array(size); o.set(v, size - v.length); return o; }; const r = part(), s = part(), out = new Uint8Array(size * 2); out.set(r); out.set(s, size); return out; } async function verifySig(alg, jwk, sig, data) { const a = ALGS[alg]; if (!a) throw new Error('unsupported algorithm'); const key = await crypto.subtle.importKey('jwk', jwk, a.imp, false, ['verify']); return crypto.subtle.verify(a.ver, key, alg === -7 ? derToRaw(sig) : sig, data); } async function sha256(bytes) { return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); } function same(a, b) { if (a.length !== b.length) return false; let d = 0; for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i]; return d === 0; } // ---------- options ---------- // Enroll this device's own fingerprint or face reader. Built-in reader only, verified every time. export function registrationOptions({ rpId, rpName, userId, userName, displayName, excludeIds = [], timeout = 120000 }) { return { challenge: randomB64u(32), rp: { id: rpId, name: rpName || rpId }, user: { id: userId || randomB64u(16), name: userName, displayName: displayName || userName }, pubKeyCredParams: [{ type: 'public-key', alg: -8 }, { type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }], authenticatorSelection: { authenticatorAttachment: 'platform', residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, hints: ['client-device'], excludeCredentials: excludeIds.map((id) => ({ type: 'public-key', id, transports: ['internal'] })), attestation: 'none', timeout, }; } // Sign in with this device's reader. `deviceCredentialIds` are the IDs this device enrolled // (client.js enrolledOnThisDevice()). Only the built-in reader is allowed, so the browser goes // straight to the fingerprint or face and has no other way to offer. export function signInOptions({ rpId, deviceCredentialIds = [], timeout = 120000 }) { return { challenge: randomB64u(32), rpId, userVerification: 'required', allowCredentials: deviceCredentialIds.map((id) => ({ type: 'public-key', id, transports: ['internal'] })), hints: ['client-device'], timeout, }; } // Built-in readers only: refuse security keys and phone-to-computer (QR) sign-ins. const OUTSIDE = ['usb', 'nfc', 'ble', 'hybrid', 'smart-card']; function builtInOnly(credential) { if (credential.authenticatorAttachment && credential.authenticatorAttachment !== 'platform') throw new Error('only this device\'s own fingerprint or face reader is allowed'); // Built-in readers that sync (iCloud Keychain, Google Password Manager) report ["hybrid", "internal"]. // Allow that pair from a built-in reader; "hybrid" alone (a phone over QR) is still refused. const t = (credential.response && credential.response.transports) || []; const outside = credential.authenticatorAttachment === 'platform' && t.includes('internal') ? OUTSIDE.filter((x) => x !== 'hybrid') : OUTSIDE; if (t.some((x) => outside.includes(x))) throw new Error('only this device\'s own fingerprint or face reader is allowed'); } function checkClientData(cdjBytes, type, expectedChallenge, origins) { const cd = JSON.parse(dec.decode(cdjBytes)); if (cd.type !== type) throw new Error('wrong ceremony type'); if (cd.challenge !== expectedChallenge) throw new Error('challenge does not match'); const allowed = Array.isArray(origins) ? origins : [origins]; if (!allowed.includes(cd.origin)) throw new Error('wrong website: ' + cd.origin); if (cd.crossOrigin === true) throw new Error('cross-origin frames are not allowed'); return cd; } // ---------- verify a new device ---------- // Returns a record to store: { id, alg, publicKey (JWK), counter, transports, backupEligible, backedUp }. // The private key stays sealed inside the device; the server only ever holds this public key. export async function verifyRegistration({ credential, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) { if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential'); builtInOnly(credential); const r = credential.response; checkClientData(fromB64u(r.clientDataJSON), 'webauthn.create', expectedChallenge, expectedOrigin); const att = cborDecode(fromB64u(r.attestationObject)).value; const ad = parseAuthData(att.get('authData')); if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site'); if (!ad.userPresent) throw new Error('no user presence'); if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used'); if (!ad.credentialId) throw new Error('nothing enrolled in response'); if (toB64u(ad.credentialId) !== credential.id) throw new Error('device id mismatch'); const { alg, jwk } = coseToJwk(ad.coseKey); return { id: credential.id, alg, publicKey: jwk, counter: ad.counter, transports: ['internal'], backupEligible: ad.backupEligible, backedUp: ad.backedUp, createdAt: Date.now(), }; } // ---------- verify a sign-in ---------- // `stored` is the record from verifyRegistration. Returns { userHandle, counter, backedUp } on success; // save the new counter back to your store. export async function verifySignIn({ credential, stored, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) { if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential'); builtInOnly(credential); if (credential.id !== stored.id) throw new Error('unknown device'); const r = credential.response; const cdj = fromB64u(r.clientDataJSON); checkClientData(cdj, 'webauthn.get', expectedChallenge, expectedOrigin); const adBytes = fromB64u(r.authenticatorData); const ad = parseAuthData(adBytes); if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site'); if (!ad.userPresent) throw new Error('no user presence'); if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used'); const signed = new Uint8Array(adBytes.length + 32); signed.set(adBytes); signed.set(await sha256(cdj), adBytes.length); if (!(await verifySig(stored.alg, stored.publicKey, fromB64u(r.signature), signed))) throw new Error('signature check failed'); // Counter: some devices keep it at 0. If both are non-zero it must go up, or the key may be cloned. if ((ad.counter !== 0 || stored.counter !== 0) && ad.counter <= stored.counter) throw new Error('counter went backwards: possible cloned key'); return { userHandle: r.userHandle || null, counter: ad.counter, backedUp: ad.backedUp }; } // ---------- "Add a device" links ---------- // A one-time link made on a signed-in device (send it to yourself by email or message). Opening // it on the new device enrolls that device's own fingerprint or face. Signed with your server secret. // Single use: keep `nonce` in your store after it is used and refuse it again. async function hmac(secret, data) { const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data))); } export async function makeDeviceInvite({ secret, accountId, minutes = 10 }) { const body = toB64u(enc.encode(JSON.stringify({ a: accountId, n: randomB64u(12), x: Date.now() + minutes * 60000 }))); return body + '.' + toB64u(await hmac(secret, body)); } export async function readDeviceInvite({ secret, token }) { const [body, sig] = String(token).split('.'); if (!body || !sig || !same(fromB64u(sig), await hmac(secret, body))) throw new Error('invite link is not valid'); const p = JSON.parse(dec.decode(fromB64u(body))); if (Date.now() > p.x) throw new Error('invite link expired, make a new one'); return { accountId: p.a, nonce: p.n, expiresAt: p.x }; }