Branchwell

BioLock / source · biolock.dev / commits / 6e78aa17

Fingerprint sign-in: built-in reader only, no keys, no QR. Server checks, browser client, demo, tests new

written by Moontrace · 6e78aa17d30d9bd36b90546affc56e091b9d5c40

8 files changed

.gitignore added

1+ node_modules

LICENSE added

1+ This is free and unencumbered software released into the public domain.
2+
3+ Anyone is free to copy, modify, publish, use, compile, sell, or
4+ distribute this software, either in source code form or as a compiled
5+ binary, for any purpose, commercial or non-commercial, and by any
6+ means.
7+
8+ In jurisdictions that recognize copyright laws, the author or authors
9+ of this software dedicate any and all copyright interest in the
10+ software to the public domain. We make this dedication for the benefit
11+ of the public at large and to the detriment of our heirs and
12+ successors. We intend this dedication to be an overt act of
13+ relinquishment in perpetuity of all present and future rights to this
14+ software under copyright law.
15+
16+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22+ OTHER DEALINGS IN THE SOFTWARE.
23+
24+ For more information, please refer to <https://unlicense.org>

README.md added

1+ # Moontrace fingerprint sign-in
2+
3+ Sign in with your own fingerprint or face. That is the only way: no passwords, no security keys,
4+ no QR codes, no phone-to-computer sign-in. A Moontrace project, public domain (Unlicense).
5+
6+ Live: https://moontrace.ai/fingerprint/ · Demo: https://moontrace.ai/fingerprint/demo/
7+
8+ ## How it works
9+
10+ 1. **Enroll a device.** On a device you are signed in to, make a one-time "Add a device" link
11+ (10 minutes, single use). Open it on the new device and touch your fingerprint.
12+ 2. **A key sealed inside.** The device makes its own key, locked behind its reader. The website keeps
13+ only the public key.
14+ 3. **Touch to sign in.** The website allows only this device's own built-in reader, so the browser goes
15+ straight to the fingerprint or face. Nothing else is offered.
16+ 4. **Lose one, remove it** from any other enrolled device.
17+
18+ The server refuses anything that is not a built-in reader: USB, NFC and Bluetooth keys, and QR
19+ phone-to-computer sign-in.
20+
21+ Under the hood: browsers let a website reach the device's reader through one open standard,
22+ W3C Web Authentication. We use only its built-in reader part and switch the rest off. No new
23+ cryptography: Ed25519, P-256 and RSA signatures only.
24+
25+ ## Files
26+
27+ - `src/server.js`: enroll and sign-in options, every check, add-a-device links. Runs anywhere with
28+ Web Crypto (Cloudflare Workers, Deno, Bun, Node 20+, browsers). No dependencies.
29+ - `src/client.js`: `hasBuiltInReader()`, `enrollThisDevice()`, `signIn()`, `removedOnServer()`,
30+ `enrolledOnThisDevice()`.
31+ - `demo/`: the working demo on moontrace.ai.
32+ - `test/server.test.js`: software devices (P-256 and Ed25519) enroll and sign in; the checks refuse a
33+ wrong site, a reused challenge, a missing biometric, a bad signature, a cloned key, security keys and QR.
34+
35+ ## Add it to a site in five steps
36+
37+ ```js
38+ // server
39+ import { registrationOptions, verifyRegistration, signInOptions, verifySignIn,
40+ makeDeviceInvite, readDeviceInvite } from './server.js';
41+
42+ // 1. On a signed-in device: make a one-time link and send it to yourself.
43+ const token = await makeDeviceInvite({ secret: env.INVITE_SECRET, accountId });
44+ // https://example.com/add-device#<token> (store the nonce once used, refuse it again)
45+
46+ // 2. On the new device: read the link, send enroll options (keep options.challenge).
47+ const { accountId } = await readDeviceInvite({ secret: env.INVITE_SECRET, token });
48+ const options = registrationOptions({ rpId: 'example.com', rpName: 'Example', userId, userName });
49+
50+ // 3. Check it and store the record for the account.
51+ const record = await verifyRegistration({ credential, expectedChallenge, expectedOrigin: 'https://example.com', rpId: 'example.com' });
52+
53+ // 4. Sign in: the browser sends the IDs it enrolled (client enrolledOnThisDevice()).
54+ const opts = signInOptions({ rpId: 'example.com', deviceCredentialIds });
55+
56+ // 5. Check it and save the new counter.
57+ const { counter } = await verifySignIn({ credential, stored: record, expectedChallenge, expectedOrigin: 'https://example.com', rpId: 'example.com' });
58+ ```
59+
60+ ```js
61+ // browser
62+ import { hasBuiltInReader, enrollThisDevice, signIn, enrolledOnThisDevice } from './client.js';
63+ const enrolled = await enrollThisDevice(optionsFromServer); // touch fingerprint
64+ const login = await signIn(signInOptionsFromServer); // straight to fingerprint
65+ ```
66+
67+ ## Honest limits
68+
69+ - A device with no fingerprint or face reader cannot sign in, by design.
70+ - The browser draws the final prompt. Some older browsers may still show extra choices; the server
71+ refuses anything that is not the built-in reader.
72+ - Keep at least two enrolled devices. There is no password fallback.
73+
74+ ## Test
75+
76+ ```sh
77+ node --test test/*.test.js
78+ ```
79+
80+ Public domain. See LICENSE.

demo/app.js added

1+ // Working demo. The server part runs in this page with the same server.js a real server uses,
2+ // so you can try it with no account. Anything enrolled here works only for this demo.
3+ import * as S from '../code/server.js';
4+ import * as C from '../code/client.js';
5+
6+ const rpId = location.hostname, origin = location.origin;
7+ const DB = 'moontrace-fingerprint-demo';
8+ const db = () => { try { return JSON.parse(localStorage.getItem(DB) || '{"creds":[]}'); } catch { return { creds: [] }; } };
9+ const put = (v) => { try { localStorage.setItem(DB, JSON.stringify(v)); } catch { /* private mode */ } };
10+ const $ = (s) => document.querySelector(s);
11+ const say = (msg, ok = true) => { const el = $('#fp-status'); el.textContent = msg; el.dataset.ok = ok ? '1' : '0'; };
12+
13+ function render() {
14+ const list = $('#fp-devices'); list.innerHTML = '';
15+ const creds = db().creds;
16+ if (!creds.length) { list.innerHTML = '<li class="fp-empty">No devices yet. Enroll this one first.</li>'; return; }
17+ for (const c of creds) {
18+ const li = document.createElement('li');
19+ const here = C.enrolledOnThisDevice(rpId).includes(c.id);
20+ li.innerHTML = '<span><b></b><small></small></span><button class="fp-small" type="button">Remove</button>';
21+ li.querySelector('b').textContent = c.name + (here ? ' (this device)' : '');
22+ li.querySelector('small').textContent = 'Enrolled ' + new Date(c.createdAt).toLocaleString() + (c.lastUsed ? ' · last used ' + new Date(c.lastUsed).toLocaleString() : '');
23+ li.querySelector('button').onclick = async () => {
24+ const d = db(); d.creds = d.creds.filter((x) => x.id !== c.id); put(d);
25+ await C.removedOnServer(c.id, rpId); render(); say('Removed. That device can no longer sign in.');
26+ };
27+ list.appendChild(li);
28+ }
29+ }
30+
31+ $('#fp-add').onclick = async () => {
32+ try {
33+ const opts = S.registrationOptions({ rpId, rpName: 'Moontrace fingerprint sign-in demo', userName: 'demo', displayName: 'Demo member', excludeIds: C.enrolledOnThisDevice(rpId) });
34+ const cred = await C.enrollThisDevice(opts);
35+ const rec = await S.verifyRegistration({ credential: cred, expectedChallenge: opts.challenge, expectedOrigin: origin, rpId });
36+ rec.name = ($('#fp-name').value || '').trim() || 'This device';
37+ const d = db(); d.creds.push(rec); put(d); render();
38+ say('Enrolled. This device now signs in with its own fingerprint or face.');
39+ } catch (e) { say(nice(e), false); }
40+ };
41+
42+ $('#fp-signin').onclick = async () => {
43+ try {
44+ const opts = S.signInOptions({ rpId, deviceCredentialIds: C.enrolledOnThisDevice(rpId) });
45+ const cred = await C.signIn(opts);
46+ const d = db(); const stored = d.creds.find((c) => c.id === cred.id);
47+ if (!stored) { await C.removedOnServer(cred.id, rpId); throw new Error('This device was removed. Enroll it again.'); }
48+ const r = await S.verifySignIn({ credential: cred, stored, expectedChallenge: opts.challenge, expectedOrigin: origin, rpId });
49+ stored.counter = r.counter; stored.lastUsed = Date.now(); put(d); render();
50+ say('Signed in with "' + stored.name + '". Checked: right site, fresh challenge, valid signature, fingerprint or face used.');
51+ } catch (e) { say(nice(e), false); }
52+ };
53+
54+ function nice(e) {
55+ if (e && e.name === 'NotAllowedError') return 'Cancelled, or the reader did not match. Try again.';
56+ if (e && e.name === 'InvalidStateError') return 'This device is already enrolled.';
57+ return (e && e.message) ? e.message : String(e);
58+ }
59+
60+ (async () => {
61+ const builtIn = await C.hasBuiltInReader();
62+ $('#fp-check').textContent = builtIn ? 'This device has a fingerprint or face reader. Ready.' : 'This device has no fingerprint or face reader, so it cannot sign in. Try a phone or a computer with a reader.';
63+ if (!builtIn) { $('#fp-add').disabled = true; $('#fp-signin').disabled = true; }
64+ render();
65+ })();

package.json added

1+ {"name":"open-passkeys","version":"1.0.0","type":"module","license":"Unlicense","exports":{"./server":"./src/server.js","./client":"./src/client.js"},"scripts":{"test":"node --test test/*.test.js"}}

src/client.js added

1+ // Moontrace fingerprint sign-in: 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+
6+ const KEY = 'moontrace-fingerprint:enrolled-here';
7+
8+ function 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+ }
13+ function 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+ }
20+ function load() { try { return JSON.parse(localStorage.getItem(KEY) || '{}'); } catch { return {}; } }
21+ function 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.
24+ export function enrolledOnThisDevice(rpId = location.hostname) { return load()[rpId] || []; }
25+ export 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+ }
28+ export 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?
33+ export 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+
44+ function 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+ }
49+ function 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+ }
53+ function 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().
67+ export 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.
79+ export 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.
89+ export 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+ }

src/server.js added

1+ // Moontrace fingerprint sign-in: 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+
9+ const enc = new TextEncoder();
10+ const dec = new TextDecoder();
11+
12+ // ---------- base64url ----------
13+ export 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+ }
19+ export 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+ }
26+ export function randomB64u(n = 32) { return toB64u(crypto.getRandomValues(new Uint8Array(n))); }
27+
28+ // ---------- tiny CBOR reader (only what WebAuthn uses) ----------
29+ export 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 ----------
63+ export const FLAGS = { UP: 0x01, UV: 0x04, BE: 0x08, BS: 0x10, AT: 0x40, ED: 0x80 };
64+ export 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.
90+ export 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+ }
97+ const 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.
103+ export 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+ }
116+ async 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+ }
122+ async function sha256(bytes) { return new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)); }
123+ 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; }
124+
125+ // ---------- options ----------
126+ // Enroll this device's own fingerprint or face reader. Built-in reader only, verified every time.
127+ export 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.
143+ export 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.
155+ const OUTSIDE = ['usb', 'nfc', 'ble', 'hybrid', 'smart-card'];
156+ function 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+
162+ function 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.
175+ export 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.
199+ export 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.
223+ async 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+ }
227+ export 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+ }
231+ export 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+ }

test/server.test.js added

1+ // Runs a software passkey (ES256 and Ed25519) against server.js. `node --test`
2+ import test from 'node:test';
3+ import assert from 'node:assert/strict';
4+ import * as S from '../src/server.js';
5+
6+ const enc = new TextEncoder();
7+ const RP = 'moontrace.ai', ORIGIN = 'https://moontrace.ai';
8+
9+ // --- tiny CBOR writer for the test authenticator ---
10+ function head(major, n) {
11+ if (n < 24) return [major << 5 | n];
12+ if (n < 256) return [major << 5 | 24, n];
13+ return [major << 5 | 25, n >> 8, n & 255];
14+ }
15+ function cbor(v) {
16+ if (v instanceof Uint8Array) return [...head(2, v.length), ...v];
17+ if (typeof v === 'string') { const b = enc.encode(v); return [...head(3, b.length), ...b]; }
18+ if (typeof v === 'number') return v >= 0 ? head(0, v) : head(1, -1 - v);
19+ if (v instanceof Map) { const o = head(5, v.size); for (const [k, x] of v) o.push(...cbor(k), ...cbor(x)); return o; }
20+ throw new Error('cbor');
21+ }
22+ const u8 = (a) => new Uint8Array(a);
23+ async function sha(b) { return u8(await crypto.subtle.digest('SHA-256', b)); }
24+ function rawToDer(raw) {
25+ const int = (b) => { let i = 0; while (i < b.length - 1 && b[i] === 0) i++; b = b.slice(i); if (b[0] & 0x80) b = u8([0, ...b]); return [2, b.length, ...b]; };
26+ const body = [...int(raw.slice(0, 32)), ...int(raw.slice(32))];
27+ return u8([0x30, body.length, ...body]);
28+ }
29+
30+ async function softKey(kind) {
31+ const p = kind === 'ed' ? await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
32+ : await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']);
33+ const jwk = await crypto.subtle.exportKey('jwk', p.publicKey);
34+ const cose = kind === 'ed' ? new Map([[1, 1], [3, -8], [-1, 6], [-2, S.fromB64u(jwk.x)]])
35+ : new Map([[1, 2], [3, -7], [-1, 1], [-2, S.fromB64u(jwk.x)], [-3, S.fromB64u(jwk.y)]]);
36+ const id = crypto.getRandomValues(new Uint8Array(16));
37+ let counter = 0;
38+ const sign = async (data) => kind === 'ed' ? u8(await crypto.subtle.sign('Ed25519', p.privateKey, data))
39+ : rawToDer(u8(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, p.privateKey, data)));
40+ const authData = async (flags, withKey, rp = RP) => {
41+ const ctr = [counter >>> 24, (counter >> 16) & 255, (counter >> 8) & 255, counter & 255];
42+ const parts = [...(await sha(enc.encode(rp))), flags, ...ctr];
43+ if (withKey) parts.push(...new Uint8Array(16), 0, id.length, ...id, ...cbor(cose));
44+ return u8(parts);
45+ };
46+ return {
47+ id: S.toB64u(id), setCounter(n) { counter = n; },
48+ async create(opts, { origin = ORIGIN, flags = 0x45, rp = RP } = {}) {
49+ const cdj = enc.encode(JSON.stringify({ type: 'webauthn.create', challenge: opts.challenge, origin }));
50+ const ao = u8(cbor(new Map([['fmt', 'none'], ['attStmt', new Map()], ['authData', await authData(flags, true, rp)]])));
51+ return { id: S.toB64u(id), type: 'public-key', response: { clientDataJSON: S.toB64u(cdj), attestationObject: S.toB64u(ao), transports: ['internal'] } };
52+ },
53+ async get(opts, { origin = ORIGIN, flags = 0x05 } = {}) {
54+ const cdj = enc.encode(JSON.stringify({ type: 'webauthn.get', challenge: opts.challenge, origin }));
55+ const ad = await authData(flags, false);
56+ const sig = await sign(u8([...ad, ...(await sha(cdj))]));
57+ return { id: S.toB64u(id), type: 'public-key', response: { clientDataJSON: S.toB64u(cdj), authenticatorData: S.toB64u(ad), signature: S.toB64u(sig), userHandle: null } };
58+ },
59+ };
60+ }
61+
62+ for (const kind of ['ec', 'ed']) {
63+ test(`${kind}: enroll a device, then sign in with its fingerprint`, async () => {
64+ const k = await softKey(kind);
65+ const ro = S.registrationOptions({ rpId: RP, userName: 'member' });
66+ assert.equal(ro.authenticatorSelection.authenticatorAttachment, 'platform');
67+ assert.deepEqual(ro.hints, ['client-device']);
68+ const stored = await S.verifyRegistration({ credential: await k.create(ro), expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP });
69+ assert.equal(stored.id, k.id);
70+ const so = S.signInOptions({ rpId: RP, deviceCredentialIds: [stored.id] });
71+ assert.deepEqual(so.allowCredentials[0].transports, ['internal']);
72+ const ok = await S.verifySignIn({ credential: await k.get(so), stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP });
73+ assert.equal(ok.counter, 0);
74+ });
75+ }
76+
77+ test('refuses a sign-in from the wrong website', async () => {
78+ const k = await softKey('ec');
79+ const ro = S.registrationOptions({ rpId: RP, userName: 'm' });
80+ await assert.rejects(S.verifyRegistration({ credential: await k.create(ro, { origin: 'https://evil.example' }), expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP }), /wrong website/);
81+ await assert.rejects(S.verifyRegistration({ credential: await k.create(ro, { rp: 'evil.example' }), expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP }), /different site/);
82+ });
83+
84+ test('refuses a reused challenge, a missing fingerprint, a bad signature and a cloned key', async () => {
85+ const k = await softKey('ec');
86+ const ro = S.registrationOptions({ rpId: RP, userName: 'm' });
87+ const stored = await S.verifyRegistration({ credential: await k.create(ro), expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP });
88+ const so = S.signInOptions({ rpId: RP });
89+ await assert.rejects(S.verifySignIn({ credential: await k.get(so), stored, expectedChallenge: 'other', expectedOrigin: ORIGIN, rpId: RP }), /challenge/);
90+ await assert.rejects(S.verifySignIn({ credential: await k.get(so, { flags: 0x01 }), stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP }), /fingerprint/);
91+ const bad = await k.get(so); const sig = S.fromB64u(bad.response.signature); sig[10] ^= 1; bad.response.signature = S.toB64u(sig);
92+ await assert.rejects(S.verifySignIn({ credential: bad, stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP }), /signature/);
93+ k.setCounter(5);
94+ const r = await S.verifySignIn({ credential: await k.get(so), stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP });
95+ stored.counter = r.counter;
96+ k.setCounter(3);
97+ await assert.rejects(S.verifySignIn({ credential: await k.get(so), stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP }), /cloned/);
98+ });
99+
100+ test('refuses security keys and QR (phone-to-computer) sign-ins', async () => {
101+ const k = await softKey('ec');
102+ const ro = S.registrationOptions({ rpId: RP, userName: 'm' });
103+ for (const t of ['usb', 'nfc', 'hybrid']) {
104+ const c = await k.create(ro); c.response.transports = [t];
105+ await assert.rejects(S.verifyRegistration({ credential: c, expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP }), /own fingerprint/);
106+ }
107+ const c = await k.create(ro); c.authenticatorAttachment = 'cross-platform';
108+ await assert.rejects(S.verifyRegistration({ credential: c, expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP }), /own fingerprint/);
109+ const stored = await S.verifyRegistration({ credential: await k.create(ro), expectedChallenge: ro.challenge, expectedOrigin: ORIGIN, rpId: RP });
110+ const so = S.signInOptions({ rpId: RP, deviceCredentialIds: [stored.id] });
111+ const g = await k.get(so); g.authenticatorAttachment = 'cross-platform';
112+ await assert.rejects(S.verifySignIn({ credential: g, stored, expectedChallenge: so.challenge, expectedOrigin: ORIGIN, rpId: RP }), /own fingerprint/);
113+ });
114+
115+ test('add-a-device invite links: valid, tampered, expired', async () => {
116+ const t = await S.makeDeviceInvite({ secret: 's3cret', accountId: 'acct1' });
117+ assert.equal((await S.readDeviceInvite({ secret: 's3cret', token: t })).accountId, 'acct1');
118+ await assert.rejects(S.readDeviceInvite({ secret: 'wrong', token: t }), /not valid/);
119+ const old = await S.makeDeviceInvite({ secret: 's3cret', accountId: 'a', minutes: -1 });
120+ await assert.rejects(S.readDeviceInvite({ secret: 's3cret', token: old }), /expired/);
121+ });

Browse files at this commit