Branchwell

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

Raw 12.5 KB on d167974600f47f3feabad21fed9b811c6e8e1617
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.
155const OUTSIDE = ['usb', 'nfc', 'ble', 'hybrid', 'smart-card'];
156function builtInOnly(credential) {
157 if (credential.authenticatorAttachment && credential.authenticatorAttachment !== 'platform') throw new Error('only this device\'s own fingerprint or face reader is allowed');
158 const t = (credential.response && credential.response.transports) || [];
159 if (t.some((x) => OUTSIDE.includes(x))) throw new Error('only this device\'s own fingerprint or face reader is allowed');
160}
161
162function checkClientData(cdjBytes, type, expectedChallenge, origins) {
163 const cd = JSON.parse(dec.decode(cdjBytes));
164 if (cd.type !== type) throw new Error('wrong ceremony type');
165 if (cd.challenge !== expectedChallenge) throw new Error('challenge does not match');
166 const allowed = Array.isArray(origins) ? origins : [origins];
167 if (!allowed.includes(cd.origin)) throw new Error('wrong website: ' + cd.origin);
168 if (cd.crossOrigin === true) throw new Error('cross-origin frames are not allowed');
169 return cd;
170}
171
172// ---------- verify a new device ----------
173// Returns a record to store: { id, alg, publicKey (JWK), counter, transports, backupEligible, backedUp }.
174// The private key stays sealed inside the device; the server only ever holds this public key.
175export async function verifyRegistration({ credential, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) {
176 if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential');
177 builtInOnly(credential);
178 const r = credential.response;
179 checkClientData(fromB64u(r.clientDataJSON), 'webauthn.create', expectedChallenge, expectedOrigin);
180 const att = cborDecode(fromB64u(r.attestationObject)).value;
181 const ad = parseAuthData(att.get('authData'));
182 if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site');
183 if (!ad.userPresent) throw new Error('no user presence');
184 if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used');
185 if (!ad.credentialId) throw new Error('nothing enrolled in response');
186 if (toB64u(ad.credentialId) !== credential.id) throw new Error('device id mismatch');
187 const { alg, jwk } = coseToJwk(ad.coseKey);
188 return {
189 id: credential.id, alg, publicKey: jwk, counter: ad.counter,
190 transports: ['internal'],
191 backupEligible: ad.backupEligible, backedUp: ad.backedUp,
192 createdAt: Date.now(),
193 };
194}
195
196// ---------- verify a sign-in ----------
197// `stored` is the record from verifyRegistration. Returns { userHandle, counter, backedUp } on success;
198// save the new counter back to your store.
199export async function verifySignIn({ credential, stored, expectedChallenge, expectedOrigin, rpId, requireUserVerification = true }) {
200 if (!credential || credential.type !== 'public-key') throw new Error('not a sign-in credential');
201 builtInOnly(credential);
202 if (credential.id !== stored.id) throw new Error('unknown device');
203 const r = credential.response;
204 const cdj = fromB64u(r.clientDataJSON);
205 checkClientData(cdj, 'webauthn.get', expectedChallenge, expectedOrigin);
206 const adBytes = fromB64u(r.authenticatorData);
207 const ad = parseAuthData(adBytes);
208 if (!same(ad.rpIdHash, await sha256(enc.encode(rpId)))) throw new Error('enrolled for a different site');
209 if (!ad.userPresent) throw new Error('no user presence');
210 if (requireUserVerification && !ad.userVerified) throw new Error('fingerprint, face or PIN was not used');
211 const signed = new Uint8Array(adBytes.length + 32);
212 signed.set(adBytes); signed.set(await sha256(cdj), adBytes.length);
213 if (!(await verifySig(stored.alg, stored.publicKey, fromB64u(r.signature), signed))) throw new Error('signature check failed');
214 // Counter: some devices keep it at 0. If both are non-zero it must go up, or the key may be cloned.
215 if ((ad.counter !== 0 || stored.counter !== 0) && ad.counter <= stored.counter) throw new Error('counter went backwards: possible cloned key');
216 return { userHandle: r.userHandle || null, counter: ad.counter, backedUp: ad.backedUp };
217}
218
219// ---------- "Add a device" links ----------
220// A one-time link made on a signed-in device (send it to yourself by email or message). Opening
221// it on the new device enrolls that device's own fingerprint or face. Signed with your server secret.
222// Single use: keep `nonce` in your store after it is used and refuse it again.
223async function hmac(secret, data) {
224 const key = await crypto.subtle.importKey('raw', enc.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
225 return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data)));
226}
227export async function makeDeviceInvite({ secret, accountId, minutes = 10 }) {
228 const body = toB64u(enc.encode(JSON.stringify({ a: accountId, n: randomB64u(12), x: Date.now() + minutes * 60000 })));
229 return body + '.' + toB64u(await hmac(secret, body));
230}
231export async function readDeviceInvite({ secret, token }) {
232 const [body, sig] = String(token).split('.');
233 if (!body || !sig || !same(fromB64u(sig), await hmac(secret, body))) throw new Error('invite link is not valid');
234 const p = JSON.parse(dec.decode(fromB64u(body)));
235 if (Date.now() > p.x) throw new Error('invite link expired, make a new one');
236 return { accountId: p.a, nonce: p.n, expiresAt: p.x };
237}