Branchwell

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

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