// Lock with a fingerprint or face: the padlock's "Protect this device?" offers // a passkey instead of a password. The saved-wallets vault is then sealed // under a secret only that passkey's PRF produces — nothing in this browser's // storage opens it — and unlocking is the passkey's check, asked for as the // locked screen opens. Turning it off returns to an unlocked vault. Chrome's // virtual authenticator (CDP WebAuthn, with PRF) plays the phone. // Run: bun tools/passkey-lock-test.js import puppeteer from './puppeteer.js'; import { generateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; import { decryptVault } from '../src/wallet.js'; import { buildHtml } from '../build.js'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; const html = await buildHtml({ minify: true, pwa: false }); const server = Bun.serve({ port: 5314, fetch: (req) => { const p = new URL(req.url).pathname; if (p.endsWith('.js') && p !== '/') { const f = Bun.file('dist' + p); return f.size ? new Response(f, { headers: { 'content-type': 'text/javascript' } }) : new Response('', { status: 404 }); } return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); const page = await browser.newPage(); const cdp = await page.createCDPSession(); await cdp.send('WebAuthn.enable'); const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { options: { protocol: 'ctap2', ctap2Version: 'ctap2_1', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, hasPrf: true, automaticPresenceSimulation: true } }); await page.evaluateOnNewDocument(() => { window.__gets = []; const real = navigator.credentials.get.bind(navigator.credentials); navigator.credentials.get = (o) => { const r = { at: Date.now() }; window.__gets.push(r); // the person cancels the next fingerprint dialog if (localStorage.getItem('__refuseNext')) { localStorage.removeItem('__refuseNext'); r.err = 'refused'; return Promise.reject(new DOMException('The operation either timed out or was not allowed.', 'NotAllowedError')); } return real(o).then((c) => { r.ok = true; return c; }, (e) => { r.err = e.name + ': ' + e.message; throw e; }); }; }); const errs = []; page.on('pageerror', (e) => errs.push(String(e))); const click = (sel, t) => page.evaluate((s, x) => { const e = [...document.querySelectorAll(s)].find((n) => n.textContent.trim().toLowerCase().includes(x.toLowerCase())); if (e) { e.click(); return true; } return false; }, sel, t); const bodyText = () => page.evaluate(() => document.body.innerText); const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await bodyText()).toLowerCase().includes(x.toLowerCase())) return true; await sleep(250); } return false; }; const vault = () => page.evaluate(() => JSON.parse(localStorage.getItem('btc-wallet-vault') || 'null')); const opensBlank = (b) => { try { decryptVault(b, ''); return true; } catch { return false; } }; // the padlock on the wallet's settings page: "Unlock" when locked, "Lock wallet" when open const padlockSays = async () => { await page.evaluate(() => document.querySelector('.balance-gear')?.click()); await sleep(700); const s = await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((e) => /^(unlock|lock wallet)$/i.test(e.getAttribute('aria-label') || '')); return b ? b.getAttribute('aria-label') : null; }); return s; }; try { await page.setViewport({ width: 390, height: 844 }); await page.goto('http://localhost:5314/', { waitUntil: 'domcontentloaded' }); await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); const mn = generateMnemonic(wordlist); await click('button', 'create a new wallet'); await sleep(500); await click('button', 'Have an existing seed'); await sleep(400); await page.waitForSelector('textarea'); await page.type('textarea', mn); await click('button', 'Open wallet'); await waitText('receive', 20000); await sleep(800); check('the wallet saved itself, under no password', opensBlank(await vault())); console.log('\n[the padlock offers a fingerprint]'); await page.evaluate(() => document.querySelector('.balance-gear')?.click()); await sleep(900); await page.evaluate(() => { const b = [...document.querySelectorAll('button')].find((e) => /lock/i.test(e.getAttribute('aria-label') || '')); b && b.click(); }); await sleep(500); check('"Protect this device?" offers fingerprint or face', await waitText('lock with fingerprint or face', 3000)); await click('button', 'lock with fingerprint or face'); let v = null; for (let i = 0; i < 40; i++) { v = await vault(); if (v && v.passkey) break; await sleep(250); } check('the vault names its passkey', !!(v && v.passkey), JSON.stringify(v && Object.keys(v))); check('...and no longer opens without it', v && !opensBlank(v)); check('...and certainly not with the seed lying around in storage', !(await page.evaluate((m) => Object.keys(localStorage).some((k) => (localStorage.getItem(k) || '').includes(m)), mn))); const creds = (await cdp.send('WebAuthn.getCredentials', { authenticatorId })).credentials; check('one passkey made, marked as a lock (user handle)', creds.length === 1 && Buffer.from(creds[0].userHandle || '', 'base64').toString().startsWith('coinos-lock:'), JSON.stringify(creds.map((c) => c.isResidentCredential))); await sleep(600); check('the wallet is locked in place', /^unlock$/i.test(await padlockSays() || '')); console.log('\n[a fresh start: the fingerprint opens it]'); // a new browser session: the tab's copy of the keys is gone. The first // fingerprint check fails (as a cancel would) — the screen must wait. await page.evaluate(() => { sessionStorage.clear(); localStorage.setItem('__refuseNext', '1'); }); await page.reload({ waitUntil: 'domcontentloaded' }); check('the app opens on the locked screen, which speaks of the fingerprint', await waitText('use your fingerprint or face', 8000)); await sleep(1500); check('...with no password field, and still there after a refused check', /use your fingerprint or face/i.test(await bodyText()) && !(await page.$('input[type=password]'))); const before = (await cdp.send('WebAuthn.getCredentials', { authenticatorId })).credentials[0].signCount; await click('button', 'unlock with fingerprint or face'); await sleep(1500); check('the first ask came by itself, on opening', (await page.evaluate(() => window.__gets)).some((g) => g.err === 'refused')); const after = (await cdp.send('WebAuthn.getCredentials', { authenticatorId })).credentials[0].signCount; check('the button asks the passkey', after > before, before + ' → ' + after); check('...and the wallet opens, spendable', /^lock wallet$/i.test(await padlockSays() || '')); console.log('\n[turning it off]'); check('Security says it\'s on and offers to turn it off', await waitText('turn off fingerprint lock', 3000)); check('...and no "Change password" for a password that doesn\'t exist', !/change password/i.test(await bodyText())); await click('button', 'turn off fingerprint lock'); for (let i = 0; i < 20; i++) { v = await vault(); if (v && !v.passkey) break; await sleep(250); } check('the vault opens without a passkey again', v && !v.passkey && opensBlank(v)); check('Security offers the fingerprint lock again', await waitText('lock with fingerprint or face', 3000)); check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | ')); } finally { await browser.close(); server.stop(true); } console.log(ok ? '\n✅ fingerprint lock works' : '\n❌ failed'); process.exit(ok ? 0 : 1);