Branchwell

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

Raw 12.7 KB on d7e3ac21a818479a9f26db56f97698af79ae3835
1// BioLock: server side.
2// Sign in with the fingerprint or face reader built into your own device. Nothing else:
3// no passwords, no security keys, no QR codes, no phone-to-computer sign-in.
4// Under the hood it uses the W3C Web Authentication standard, because that is the only way
5// browsers let a website use the device's own reader, and turns off every other part of it.
6// Runs anywhere with Web Crypto (Cloudflare Workers, Deno, Bun, Node 20+, browsers).
7// No dependencies. Public domain (Unlicense).
8
9const enc = new TextEncoder();
10const dec = new TextDecoder();
11
12// ---------- base64url ----------
13export function toB64u(bytes) {
14 const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
15 let s = '';
16 for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]);
17 return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
18}
19export function fromB64u(str) {
20 const s = String(str).replace(/-/g, '+').replace(/_/g, '/');
21 const bin = atob(s + '='.repeat((4 - (s.length % 4)) % 4));
22 const out = new Uint8Array(bin.length);
23 for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
24 return out;
25}
26export function randomB64u(n = 32) { return toB64u(crypto.getRandomValues(new Uint8Array(n))); }
27
28// ---------- tiny CBOR reader (only what WebAuthn uses) ----------
29export function cborDecode(buf, pos = 0) {
30 const dv = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
31 function len(info) {
32 if (info < 24) return info;
33 if (info === 24) return buf[pos++];
34 if (info === 25) { const v = dv.getUint16(pos); pos += 2; return v; }
35 if (info === 26) { const v = dv.getUint32(pos); pos += 4; return v; }
36 if (info === 27) { const v = Number(dv.getBigUint64(pos)); pos += 8; return v; }
37 throw new Error('CBOR: unsupported length');
38 }
39 function item() {
40 if (pos >= buf.length) throw new Error('CBOR: ran out of data');
41 const ib = buf[pos++], major = ib >> 5, info = ib & 31;
42 switch (major) {
43 case 0: return len(info);
44 case 1: return -1 - len(info);
45 case 2: { const n = len(info); const v = buf.slice(pos, pos + n); pos += n; return v; }
46 case 3: { const n = len(info); const v = dec.decode(buf.subarray(pos, pos + n)); pos += n; return v; }
47 case 4: { const n = len(info); const a = []; for (let i = 0; i < n; i++) a.push(item()); return a; }
48 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; }
49 case 6: len(info); return item(); // tag: keep the value
50 case 7:
51 if (info === 20) return false;
52 if (info === 21) return true;
53 if (info === 22) return null;
54 throw new Error('CBOR: unsupported simple value');
55 }
56 throw new Error('CBOR: bad major type');
57 }
58 const value = item();
59 return { value, end: pos };
60}
61
62// ---------- authenticator data ----------
63export const FLAGS = { UP: 0x01, UV: 0x04, BE: 0x08, BS: 0x10, AT: 0x40, ED: 0x80 };
64export function parseAuthData(ad) {
65 if (ad.length < 37) throw new Error('authenticator data too short');
66 const flags = ad[32];
67 const out = {
68 rpIdHash: ad.slice(0, 32),
69 flags,
70 userPresent: !!(flags & FLAGS.UP),
71 userVerified: !!(flags & FLAGS.UV),
72 backupEligible: !!(flags & FLAGS.BE),
73 backedUp: !!(flags & FLAGS.BS),
74 counter: new DataView(ad.buffer, ad.byteOffset + 33, 4).getUint32(0),
75 };
76 if (flags & FLAGS.AT) {
77 let p = 37;
78 out.aaguid = ad.slice(p, p + 16); p += 16;
79 const idLen = (ad[p] << 8) | ad[p + 1]; p += 2;
80 out.credentialId = ad.slice(p, p + idLen); p += idLen;
81 const { value, end } = cborDecode(ad, p);
82 out.coseKey = value;
83 out.coseKeyBytes = ad.slice(p, end);
84 }
85 return out;
86}
87
88// ---------- keys ----------
89// COSE key (from the authenticator) -> JWK we can store as plain JSON.
90export function coseToJwk(cose) {
91 const kty = cose.get(1), alg = cose.get(3);
92 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)) } };
93 if (kty === 1 && alg === -8 && cose.get(-1) === 6) return { alg: -8, jwk: { kty: 'OKP', crv: 'Ed25519', x: toB64u(cose.get(-2)) } };
94 if (kty === 3 && alg === -257) return { alg: -257, jwk: { kty: 'RSA', n: toB64u(cose.get(-1)), e: toB64u(cose.get(-2)) } };
95 throw new Error('unsupported key type (we accept ES256, Ed25519 and RS256)');
96}
97const ALGS = {
98 [-7]: { imp: { name: 'ECDSA', namedCurve: 'P-256' }, ver: { name: 'ECDSA', hash: 'SHA-256' } },
99 [-8]: { imp: { name: 'Ed25519' }, ver: { name: 'Ed25519' } },
100 [-257]: { imp: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, ver: { name: 'RSASSA-PKCS1-v1_5' } },
101};
102// WebAuthn ES256 signatures are DER; Web Crypto wants raw r||s.
103export function derToRaw(der, size = 32) {
104 let p = 0;
105 if (der[p++] !== 0x30) throw new Error('bad signature');
106 if (der[p] & 0x80) p += 1 + (der[p] & 0x7f); else p++;
107 const part = () => {
108 if (der[p++] !== 0x02) throw new Error('bad signature');
109 const n = der[p++]; let v = der.slice(p, p + n); p += n;
110 while (v.length > size && v[0] === 0) v = v.slice(1);
111 const o = new Uint8Array(size); o.set(v, size - v.length); return o;
112 };
113 const r = part(), s = part(), out = new Uint8Array(size * 2);
114 out.set(r); out.set(s, size); return out;
115}
116async function verifySig(alg, jwk, sig, data) {
117 const a = ALGS[alg];
118 if (!a) throw new Error('unsupported algorithm');
119 const key = await crypto.subtle.importKey('jwk', jwk, a.imp, false, ['verify']);
120 return crypto.subtle.verify(a.ver, key, alg === -7 ? derToRaw(sig) : sig, data);
121}
122async function sha256(bytes) { return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); }
123function 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; }
124
125// ---------- options ----------
126// Enroll this device's own fingerprint or face reader. Built-in reader only, verified every time.
127export function registrationOptions({ rpId, rpName, userId, userName, displayName, excludeIds = [], timeout = 120000 }) {
128 return {
129 challenge: randomB64u(32),
130 rp: { id: rpId, name: rpName || rpId },
131 user: { id: userId || randomB64u(16), name: userName, displayName: displayName || userName },
132 pubKeyCredParams: [{ type: 'public-key', alg: -8 }, { type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
133 authenticatorSelection: { authenticatorAttachment: 'platform', residentKey: 'required', requireResidentKey: true, userVerification: 'required' },
134 hints: ['client-device'],
135 excludeCredentials: excludeIds.map((id) => ({ type: 'public-key', id, transports: ['internal'] })),
136 attestation: 'none',
137 timeout,
138 };
139}
140// Sign in with this device's reader. `deviceCredentialIds` are the IDs this device enrolled
141// (client.js enrolledOnThisDevice()). Only the built-in reader is allowed, so the browser goes
142// straight to the fingerprint or face and has no other way to offer.
143export function signInOptions({ rpId, deviceCredentialIds = [], timeout = 120000 }) {
144 return {
145 challenge: randomB64u(32),
146 rpId,
147 userVerification: 'required',
148 allowCredentials: deviceCredentialIds.map((id) => ({ type: 'public-key', id, transports: ['internal'] })),
149 hints: ['client-device'],
150 timeout,
151 };
152}
153
154// Built-in readers only: refuse security keys and phone-to-computer (QR) sign-ins.
155function builtInOnly(credential) {
156 if (credential.authenticatorAttachment && credential.authenticatorAttachment !== 'platform') throw new Error('only this device\'s own fingerprint or face reader is allowed');
157 // Built-in readers whose keys the device's own manager can also offer nearby report
158 // ["hybrid", "internal"] (real iPhones, Macs and Chrome do). Accept that; refuse anything
159 // without "internal", and anything that names a plug-in or tap key.
160 const t = (credential.response && credential.response.transports) || [];
161 if (t.length && (!t.includes('internal') || t.some((x) => x !== 'internal' && x !== 'hybrid'))) throw new Error('only this device\'s own fingerprint or face reader is allowed');
162}
163
164function checkClientData(cdjBytes, type, expectedChallenge, origins) {
165 const cd = JSON.parse(dec.decode(cdjBytes));
166 if (cd.type !== type) throw new Error('wrong ceremony type');
167 if (cd.challenge !== expectedChallenge) throw new Error('challenge does not match');
168 const allowed = Array.isArray(origins) ? origins : [origins];
169 if (!allowed.includes(cd.origin)) throw new Error('wrong website: ' + cd.origin);
170 if (cd.crossOrigin === true) throw new Error('cross-origin frames are not allowed');
171 return cd;
172}
173
174// ---------- verify a new device ----------
175// Returns a record to store: { id, alg, publicKey (JWK), counter, transports, backupEligible, backedUp }.
176// The private key stays sealed inside the device; the server only ever holds this public key.
177export async function verifyRegistration({ credential, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) {
178 if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential');
179 builtInOnly(credential);
180 const r = credential.response;
181 checkClientData(fromB64u(r.clientDataJSON), 'webauthn.create', expectedChallenge, expectedOrigin);
182 const att = cborDecode(fromB64u(r.attestationObject)).value;
183 const ad = parseAuthData(att.get('authData'));
184 if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site');
185 if (!ad.userPresent) throw new Error('no user presence');
186 if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used');
187 if (!ad.credentialId) throw new Error('nothing enrolled in response');
188 if (toB64u(ad.credentialId) !== credential.id) throw new Error('device id mismatch');
189 const { alg, jwk } = coseToJwk(ad.coseKey);
190 return {
191 id: credential.id, alg, publicKey: jwk, counter: ad.counter,
192 transports: ['internal'],
193 backupEligible: ad.backupEligible, backedUp: ad.backedUp,
194 createdAt: Date.now(),
195 };
196}
197
198// ---------- verify a sign-in ----------
199// `stored` is the record from verifyRegistration. Returns { userHandle, counter, backedUp } on success;
200// save the new counter back to your store.
201export async function verifySignIn({ credential, stored, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) {
202 if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential');
203 builtInOnly(credential);
204 if (credential.id !== stored.id) throw new Error('unknown device');
205 const r = credential.response;
206 const cdj = fromB64u(r.clientDataJSON);
207 checkClientData(cdj, 'webauthn.get', expectedChallenge, expectedOrigin);
208 const adBytes = fromB64u(r.authenticatorData);
209 const ad = parseAuthData(adBytes);
210 if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site');
211 if (!ad.userPresent) throw new Error('no user presence');
212 if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used');
213 const signed = new Uint8Array(adBytes.length + 32);
214 signed.set(adBytes); signed.set(await sha256(cdj), adBytes.length);
215 if (!(await verifySig(stored.alg, stored.publicKey, fromB64u(r.signature), signed))) throw new Error('signature check failed');
216 // Counter: some devices keep it at 0. If both are non-zero it must go up, or the key may be cloned.
217 if ((ad.counter !== 0 || stored.counter !== 0) && ad.counter <= stored.counter) throw new Error('counter went backwards: possible cloned key');
218 return { userHandle: r.userHandle || null, counter: ad.counter, backedUp: ad.backedUp };
219}
220
221// ---------- "Add a device" links ----------
222// A one-time link made on a signed-in device (send it to yourself by email or message). Opening
223// it on the new device enrolls that device's own fingerprint or face. Signed with your server secret.
224// Single use: keep `nonce` in your store after it is used and refuse it again.
225async function hmac(secret, data) {
226 const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
227 return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data)));
228}
229export async function makeDeviceInvite({ secret, accountId, minutes = 10 }) {
230 const body = toB64u(enc.encode(JSON.stringify({ a: accountId, n: randomB64u(12), x: Date.now() + minutes * 60000 })));
231 return body + '.' + toB64u(await hmac(secret, body));
232}
233export async function readDeviceInvite({ secret, token }) {
234 const [body, sig] = String(token).split('.');
235 if (!body || !sig || !same(fromB64u(sig), await hmac(secret, body))) throw new Error('invite link is not valid');
236 const p = JSON.parse(dec.decode(fromB64u(body)));
237 if (Date.now() > p.x) throw new Error('invite link expired, make a new one');
238 return { accountId: p.a, nonce: p.n, expiresAt: p.x };
239}