// Paywell team app. Open source, public domain. TEST MODE: real accounts, ratings, reviews, scores and a real // Bitcoin wallet on the signet test network (test coins have no value). Daily bonuses are worked out and shown; // no real money moves until licensed payroll and custody partners are in place. (function () { 'use strict'; const $ = (s, r) => (r || document).querySelector(s); const esc = (t) => String(t == null ? '' : t).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const usd = (cents) => (cents < 0 ? '−' : '') + '$' + (Math.abs(cents) / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const usdSats = (sats) => price ? usd(Math.round(sats / 1e8 * price * 100)) : (sats.toLocaleString() + ' sats'); const stars = (n) => '' + '★'.repeat(n) + '' + '★'.repeat(5 - n) + ''; const b64u = (buf) => { const b = new Uint8Array(buf); let s = ''; for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; const unb64u = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0)); const enc = new TextEncoder(); const dayName = (d) => new Date(d + 'T12:00:00Z').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }); const when = (t) => new Date(t).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); const GIFS = [{ id: 'party', e: '🎉', word: 'Woohoo!', a: 'pop', bg: '#ffd166,#ef476f' }, { id: 'dog', e: '🐶', word: 'Good boy!', a: 'wag', bg: '#a0e7e5,#4cc9f0' }, { id: 'fire', e: '🔥', word: 'On fire', a: 'pulse', bg: '#ffb347,#ff5e62' }, { id: 'clap', e: '👏', word: 'Bravo', a: 'shake', bg: '#b8f2a5,#2ec4b6' }, { id: 'coffee', e: '☕', word: 'Coffee time', a: 'float', bg: '#f6d6ad,#c08552' }, { id: 'taco', e: '🌮', word: 'Taco Tuesday', a: 'spin', bg: '#ffe66d,#ff9f1c' }, { id: 'cat', e: '🐱', word: 'Mood', a: 'wag', bg: '#e0c3fc,#8ec5fc' }, { id: 'rocket', e: '🚀', word: 'Let’s go', a: 'launch', bg: '#a1c4fd,#5e60ce' }, { id: 'heart', e: '💚', word: 'Thank you', a: 'pulse', bg: '#c1f7d5,#2d6a4f' }]; const gifHtml = (g) => { const c = g.bg.split(','); return '' + g.e + '' + g.word + ''; }; const COLORS = ['#2d6a4f', '#c2185b', '#e76f51', '#5e60ce', '#0077b6', '#b5838d', '#6a994e', '#bc6c25']; const colorFor = (id) => COLORS[[...String(id)].reduce((a, c) => a + c.charCodeAt(0), 0) % COLORS.length]; let S = null; // summary from the server let price = 0; // USD per BTC let wallet = null; // { w, words } in memory only, after passkey unlock let chainState = null; // last wallet sync let cur = 'home', curCh = 'general', chatTimer = null, lastMsg = 0, chatMsgs = []; let lastCred = null; // credential id used this session (for the vault) // ---------- API ---------- async function api(path, body) { const r = await fetch(path, body === undefined ? { credentials: 'same-origin' } : { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); const j = await r.json().catch(() => ({})); if (!r.ok) { const e = new Error(j.error || 'Something went wrong. Try again.'); e.status = r.status; throw e; } return j; } async function loadPrice() { try { const j = await api('/api/chain/price'); price = j.usd || 0; } catch (e) {} } // ---------- Passkeys (WebAuthn) with the PRF extension for the wallet lock ---------- let PRF_IN = null; async function prfIn() { if (!PRF_IN) PRF_IN = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode('paywell-wallet-vault-v1'))); return PRF_IN; } const passkeysOk = () => !!(window.PublicKeyCredential && navigator.credentials && navigator.credentials.create); async function createPasskey(name) { const { challenge, rpId } = await api('/api/app/challenge', {}); const cred = await navigator.credentials.create({ publicKey: { challenge: unb64u(challenge), rp: { id: rpId, name: 'Paywell' }, user: { id: crypto.getRandomValues(new Uint8Array(16)), name: name + ' (Paywell)', displayName: name }, pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }], authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, attestation: 'none', timeout: 120000, extensions: { prf: { eval: { first: await prfIn() } } }, } }); const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; return { payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), attestationObject: b64u(cred.response.attestationObject) }, prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, prfOn: !!(ext.prf && ext.prf.enabled), }; } async function getPasskey(allowId) { const { challenge, rpId } = await api('/api/app/challenge', {}); const pk = { challenge: unb64u(challenge), rpId, userVerification: 'required', timeout: 120000, extensions: { prf: { eval: { first: await prfIn() } } } }; if (allowId) pk.allowCredentials = [{ type: 'public-key', id: unb64u(allowId) }]; const cred = await navigator.credentials.get({ publicKey: pk }); const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; lastCred = cred.id; return { payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), authenticatorData: b64u(cred.response.authenticatorData), signature: b64u(cred.response.signature) }, prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, }; } function passkeyError(e) { if (e && e.name === 'NotAllowedError') return 'The passkey step was cancelled or timed out. Try again.'; if (e && e.name === 'InvalidStateError') return 'This device already has a Paywell passkey. Use “Sign in” instead.'; return (e && e.message) || 'Something went wrong. Try again.'; } // ---------- Wallet lock: AES-GCM key from the passkey's PRF secret (HKDF), same as everywhere else in Paywell ---------- async function hkdf(prf, salt, info) { const k = await crypto.subtle.importKey('raw', prf, 'HKDF', false, ['deriveBits']); return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: salt.length ? salt : new Uint8Array(32), info: enc.encode(info) }, k, 256)); } async function vaultSave(credId, prf, words) { const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12)); const key = await crypto.subtle.importKey('raw', await hkdf(prf, salt, 'paywell-vault-key'), 'AES-GCM', false, ['encrypt']); const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: enc.encode(credId) }, key, enc.encode(words))); const box = new Uint8Array(12 + ct.length); box.set(iv); box.set(ct, 12); await api('/api/vault/save', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')), blob: b64u(box), salt: b64u(salt) }); } async function vaultOpen(credId, prf) { const j = await api('/api/vault/get', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')) }); const box = unb64u(j.blob); const key = await crypto.subtle.importKey('raw', await hkdf(prf, unb64u(j.salt), 'paywell-vault-key'), 'AES-GCM', false, ['decrypt']); return new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: box.slice(0, 12), additionalData: enc.encode(credId) }, key, box.slice(12))); } async function unlockWallet(cred) { if (!cred.prf) throw new Error('This browser’s passkeys can’t open a locked wallet yet. Try Chrome or Safari, or use your own wallet.'); const words = await vaultOpen(cred.payload.id, cred.prf); wallet = { w: PWW.open(words) }; return wallet; } // ---------- Screens ---------- const panel = () => $('#panel'); function setTab(t) { cur = t; document.querySelectorAll('.tabs button').forEach((b) => b.setAttribute('aria-current', b.dataset.tab === t ? 'page' : 'false')); if (chatTimer) { clearInterval(chatTimer); chatTimer = null; } render(); } function shell(signedIn) { $('#app').classList.toggle('out', !signedIn); } function gate(msg) { shell(false); const setup = (location.hash.match(/setup=([A-Za-z0-9_-]+)/) || [])[1]; if (setup) return setupScreen(setup); panel().innerHTML = '
Sign in with your face, fingerprint or screen lock. No username or password.
' + (msg ? '' + esc(msg) + '
' : '') + (passkeysOk() ? '' : 'This browser doesn’t support passkeys. Try a recent Chrome, Safari, Edge or Firefox.
') + 'Joining a team? Open the setup link your team sent you.
Checking your setup link…
You’ve been added to ' + esc(s.team) + '. Save a passkey on this device and your face, fingerprint or screen lock becomes your sign-in.
' + '' + esc(S.org.name) + ' · ' + esc(S.me.tierName) + ' (' + S.me.shares + ' bonus share' + (S.me.shares === 1 ? '' : 's') + ')
Paid automatically every day to ' + paidTo + '. Test mode: worked out for real, no money moves.
Customers ' + (s.customerN ? s.customerAvg + ' ★ (' + s.customerN + ')' : 'no ratings yet') + ' · 60%
Teammates ' + (s.peerN ? s.peerAvg + ' ★ (' + s.peerN + ')' : 'no reviews yet') + ' · 40%' + (!s.customerN && !s.peerN ? '
Everyone starts at 70 until reviews come in.' : '') + '
Score ' + s.score + ' × ' + S.me.shares + ' share' + (S.me.shares === 1 ? '' : 's') + ' (' + esc(S.me.tierName) + ') × ' + usd(S.org.shareCents) + ' per share = ' + usd(S.todayCents) + '
Your wage is separate: at least the minimum wage where you work, and reviews never lower it.
Your first daily bonus shows here tomorrow.
') + 'Rate each teammate you worked with today, 1 to 5 stars, on teamwork, care and reliability. One review per teammate per day. They see the stars and your note, never who wrote it. Only your own team can see reviews.
No teammates yet. ' + (S.me.admin ? 'Add people in the Team tab.' : 'Your team will add people soon.') + '
Customer ratings (60% of your score) and teammate reviews (40%), from the last four weeks. Customers’ contact details stay private.
No customer ratings yet. Make a rating link above to try it.
') + 'No teammate reviews yet.
') + '1 and 2 star customer ratings are checked before they count. Ratings about prices, scheduling or company rules don’t count. You can dispute any rating within 14 days, and it has no effect while it’s reviewed. Reviews never lower your wage. How disputes work
Show this to the customer. They scan it, or tap it on Android, and pay from any Bitcoin wallet. Shown in dollars. No tip screen, ever.
Unlock your wallet first so we know where the payment goes.
Locked. Your passkey opens it.
' + (st ? st.balance.toLocaleString() + ' sats on the test network' + (price ? ' · ' + usd(Math.round(price * 100)) + ' per BTC' : '') : 'Checking the network…') + '
Nothing yet. Get free test coins from a signet faucet, then send them to your Receive address.
') + 'Loading…
Three tiers: Explorer (1 share), Builder (1½), Guide (2). Tiers are reviewed every three months.
' + esc(m.body) + '
') + 'No messages yet. Say hello! 👋
'; if (atEnd || body || j.messages.length) box.scrollTop = box.scrollHeight; } catch (e) { if (e.status === 401) { S = null; gate(); } } } // ---------- Wallet actions ---------- async function refreshWallet() { if (!wallet) return; try { chainState = await PWW.sync(wallet.w); } catch (e) { chainState = chainState || { balance: 0, history: [], utxos: [], nextReceive: 0, nextChange: 0 }; } if (cur === 'wallet') render(); } function receiveBox() { const a = wallet.w.address(chainState ? chainState.nextReceive : 0); $('#wbox').innerHTML = '' + esc(a) + '
' + esc(j.url) + '
Works once, for 14 days. Refresh this tab after rating to see it count.
Ask them to scan this with their phone camera. It opens the payment, then asks them to rate the visit. No tip.
' + ('NDEFReader' in window ? ' ' : '') + '' + esc(r.txid) + '
' + esc(j.url) + '
Good for 24 hours, works once.
'; btn.disabled = false; await refresh(); return; } if (f.id === 'say') { const v = $('#sayin').value.trim(); if (!v) { btn.disabled = false; return; } $('#sayin').value = ''; await pollChat(v); btn.disabled = false; $('#sayin').focus(); return; } } catch (x) { fail(passkeyError(x)); } }); document.addEventListener('click', async (e) => { const b = e.target.closest('#nfcw'); if (!b) return; try { const w = new NDEFReader(); await w.write({ records: [{ recordType: 'url', data: b.dataset.link }] }); $('#nfcmsg').textContent = 'Written. Customers can tap that tag with their phone to pay.'; } catch (x) { $('#nfcmsg').textContent = 'Couldn’t write the tag: ' + (x.message || x); } }); // ---------- Start ---------- (async () => { loadPrice(); if (/setup=/.test(location.hash)) { gate(); return; } try { S = await api('/api/app/me'); render(); } catch (e) { gate(e.status === 401 ? '' : e.message); } })(); window.addEventListener('hashchange', () => { if (/setup=/.test(location.hash)) gate(); }); })();