Paywell / website / open / src / app.js.txt
| 1 | // Paywell team app. Open source, public domain. TEST MODE: real accounts, ratings, reviews, scores and a real |
| 2 | // Bitcoin wallet on the signet test network (test coins have no value). Daily bonuses are worked out and shown; |
| 3 | // no real money moves until licensed payroll and custody partners are in place. |
| 4 | (function () { |
| 5 | 'use strict'; |
| 6 | const $ = (s, r) => (r || document).querySelector(s); |
| 7 | const esc = (t) => String(t == null ? '' : t).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); |
| 8 | const usd = (cents) => (cents < 0 ? '−' : '') + '$' + (Math.abs(cents) / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); |
| 9 | const usdSats = (sats) => price ? usd(Math.round(sats / 1e8 * price * 100)) : (sats.toLocaleString() + ' sats'); |
| 10 | const stars = (n) => '<span class="stars" aria-label="' + n + ' of 5 stars">' + '★'.repeat(n) + '<span style="opacity:.25">' + '★'.repeat(5 - n) + '</span></span>'; |
| 11 | 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(/=+$/, ''); }; |
| 12 | const unb64u = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0)); |
| 13 | const enc = new TextEncoder(); |
| 14 | const dayName = (d) => new Date(d + 'T12:00:00Z').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }); |
| 15 | const when = (t) => new Date(t).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); |
| 16 | |
| 17 | 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' }]; |
| 18 | const gifHtml = (g) => { const c = g.bg.split(','); return '<span class="gif a-' + g.a + '" style="background:linear-gradient(135deg,' + c[0] + ',' + c[1] + ')"><span class="ge">' + g.e + '</span><span class="gw">' + g.word + '</span></span>'; }; |
| 19 | const COLORS = ['#2d6a4f', '#c2185b', '#e76f51', '#5e60ce', '#0077b6', '#b5838d', '#6a994e', '#bc6c25']; |
| 20 | const colorFor = (id) => COLORS[[...String(id)].reduce((a, c) => a + c.charCodeAt(0), 0) % COLORS.length]; |
| 21 | |
| 22 | let S = null; // summary from the server |
| 23 | let price = 0; // USD per BTC |
| 24 | let wallet = null; // { w, words } in memory only, after passkey unlock |
| 25 | let chainState = null; // last wallet sync |
| 26 | let cur = 'home', curCh = 'general', chatTimer = null, lastMsg = 0, chatMsgs = []; |
| 27 | let lastCred = null; // credential id used this session (for the vault) |
| 28 | |
| 29 | // ---------- API ---------- |
| 30 | async function api(path, body) { |
| 31 | const r = await fetch(path, body === undefined ? { credentials: 'same-origin' } : { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); |
| 32 | const j = await r.json().catch(() => ({})); |
| 33 | if (!r.ok) { const e = new Error(j.error || 'Something went wrong. Try again.'); e.status = r.status; throw e; } |
| 34 | return j; |
| 35 | } |
| 36 | async function loadPrice() { try { const j = await api('/api/chain/price'); price = j.usd || 0; } catch (e) {} } |
| 37 | |
| 38 | // ---------- Passkeys (WebAuthn) with the PRF extension for the wallet lock ---------- |
| 39 | let PRF_IN = null; |
| 40 | 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; } |
| 41 | const passkeysOk = () => !!(window.PublicKeyCredential && navigator.credentials && navigator.credentials.create); |
| 42 | |
| 43 | async function createPasskey(name) { |
| 44 | const { challenge, rpId } = await api('/api/app/challenge', {}); |
| 45 | const cred = await navigator.credentials.create({ publicKey: { |
| 46 | challenge: unb64u(challenge), rp: { id: rpId, name: 'Paywell' }, |
| 47 | user: { id: crypto.getRandomValues(new Uint8Array(16)), name: name + ' (Paywell)', displayName: name }, |
| 48 | pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }], |
| 49 | authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, |
| 50 | attestation: 'none', timeout: 120000, |
| 51 | extensions: { prf: { eval: { first: await prfIn() } } }, |
| 52 | } }); |
| 53 | const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; |
| 54 | return { |
| 55 | payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), attestationObject: b64u(cred.response.attestationObject) }, |
| 56 | prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, |
| 57 | prfOn: !!(ext.prf && ext.prf.enabled), |
| 58 | }; |
| 59 | } |
| 60 | async function getPasskey(allowId) { |
| 61 | const { challenge, rpId } = await api('/api/app/challenge', {}); |
| 62 | const pk = { challenge: unb64u(challenge), rpId, userVerification: 'required', timeout: 120000, extensions: { prf: { eval: { first: await prfIn() } } } }; |
| 63 | if (allowId) pk.allowCredentials = [{ type: 'public-key', id: unb64u(allowId) }]; |
| 64 | const cred = await navigator.credentials.get({ publicKey: pk }); |
| 65 | const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; |
| 66 | lastCred = cred.id; |
| 67 | return { |
| 68 | payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), authenticatorData: b64u(cred.response.authenticatorData), signature: b64u(cred.response.signature) }, |
| 69 | prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, |
| 70 | }; |
| 71 | } |
| 72 | function passkeyError(e) { |
| 73 | if (e && e.name === 'NotAllowedError') return 'The passkey step was cancelled or timed out. Try again.'; |
| 74 | if (e && e.name === 'InvalidStateError') return 'This device already has a Paywell passkey. Use “Sign in” instead.'; |
| 75 | return (e && e.message) || 'Something went wrong. Try again.'; |
| 76 | } |
| 77 | |
| 78 | // ---------- Wallet lock: AES-GCM key from the passkey's PRF secret (HKDF), same as everywhere else in Paywell ---------- |
| 79 | async function hkdf(prf, salt, info) { |
| 80 | const k = await crypto.subtle.importKey('raw', prf, 'HKDF', false, ['deriveBits']); |
| 81 | 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)); |
| 82 | } |
| 83 | async function vaultSave(credId, prf, words) { |
| 84 | const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12)); |
| 85 | const key = await crypto.subtle.importKey('raw', await hkdf(prf, salt, 'paywell-vault-key'), 'AES-GCM', false, ['encrypt']); |
| 86 | const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: enc.encode(credId) }, key, enc.encode(words))); |
| 87 | const box = new Uint8Array(12 + ct.length); box.set(iv); box.set(ct, 12); |
| 88 | await api('/api/vault/save', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')), blob: b64u(box), salt: b64u(salt) }); |
| 89 | } |
| 90 | async function vaultOpen(credId, prf) { |
| 91 | const j = await api('/api/vault/get', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')) }); |
| 92 | const box = unb64u(j.blob); |
| 93 | const key = await crypto.subtle.importKey('raw', await hkdf(prf, unb64u(j.salt), 'paywell-vault-key'), 'AES-GCM', false, ['decrypt']); |
| 94 | return new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: box.slice(0, 12), additionalData: enc.encode(credId) }, key, box.slice(12))); |
| 95 | } |
| 96 | async function unlockWallet(cred) { |
| 97 | 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.'); |
| 98 | const words = await vaultOpen(cred.payload.id, cred.prf); |
| 99 | wallet = { w: PWW.open(words) }; |
| 100 | return wallet; |
| 101 | } |
| 102 | |
| 103 | // ---------- Screens ---------- |
| 104 | const panel = () => $('#panel'); |
| 105 | function setTab(t) { |
| 106 | cur = t; |
| 107 | document.querySelectorAll('.tabs button').forEach((b) => b.setAttribute('aria-current', b.dataset.tab === t ? 'page' : 'false')); |
| 108 | if (chatTimer) { clearInterval(chatTimer); chatTimer = null; } |
| 109 | render(); |
| 110 | } |
| 111 | function shell(signedIn) { |
| 112 | $('#app').classList.toggle('out', !signedIn); |
| 113 | } |
| 114 | |
| 115 | function gate(msg) { |
| 116 | shell(false); |
| 117 | const setup = (location.hash.match(/setup=([A-Za-z0-9_-]+)/) || [])[1]; |
| 118 | if (setup) return setupScreen(setup); |
| 119 | panel().innerHTML = '<div class="signin"><h2>Paywell team app</h2><p class="small">Sign in with your face, fingerprint or screen lock. No username or password.</p>' + |
| 120 | (msg ? '<p class="err" role="alert">' + esc(msg) + '</p>' : '') + |
| 121 | (passkeysOk() ? '<button class="btn" type="button" data-act="signin">Sign in with passkey</button>' : '<p class="note">This browser doesn’t support passkeys. Try a recent Chrome, Safari, Edge or Firefox.</p>') + |
| 122 | '<div class="or"><span>or</span></div>' + |
| 123 | '<form class="fm" id="startteam"><h3>Start a test team</h3><p class="small">Try everything for real: passkey sign-in, ratings, peer reviews, scores, tiers, team chat and a Bitcoin wallet on the test network. Test coins have no value and no real money moves.</p>' + |
| 124 | '<label for="sname">Your first name</label><input id="sname" required maxlength="40" autocomplete="given-name">' + |
| 125 | '<label for="steam">Team name</label><input id="steam" required maxlength="60" placeholder="e.g. Maple Street Bakery">' + |
| 126 | '<button class="btn o" type="submit">Create my passkey and team</button></form>' + |
| 127 | '<p class="small">Joining a team? Open the setup link your team sent you.</p></div>'; |
| 128 | } |
| 129 | async function setupScreen(token) { |
| 130 | panel().innerHTML = '<div class="signin"><p class="small">Checking your setup link…</p></div>'; |
| 131 | try { |
| 132 | const s = await api('/api/app/setup', { token }); |
| 133 | panel().innerHTML = '<div class="signin"><h2>Welcome, ' + esc(s.name) + '</h2><p class="small">You’ve been added to <b>' + esc(s.team) + '</b>. Save a passkey on this device and your face, fingerprint or screen lock becomes your sign-in.</p>' + |
| 134 | '<p class="err" id="serr" role="alert"></p><button class="btn" type="button" data-act="join" data-token="' + esc(token) + '" data-name="' + esc(s.name) + '">Create my passkey</button></div>'; |
| 135 | } catch (e) { |
| 136 | history.replaceState(null, '', '/app/'); |
| 137 | gate(e.message); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | function payoutScreen(note) { |
| 142 | panel().innerHTML = '<form class="fm signin wide" id="payoutf"><h2>Where should your Bitcoin go?</h2><p class="small">Your daily Bitcoin bonus needs a wallet. You can change this any time.</p>' + |
| 143 | (note ? '<p class="err" role="alert">' + esc(note) + '</p>' : '') + |
| 144 | '<label class="choice"><input type="radio" name="pm" value="paywell" checked><span><b>Create a wallet for me</b><span class="small">Easiest. Made right here with your account, and your passkey locks its backup. Nothing to write down.</span></span></label>' + |
| 145 | '<label class="choice"><input type="radio" name="pm" value="own"><span><b>Use my own wallet</b><span class="small">Paste the address of a wallet you already have. Bonuses go straight there.</span></span></label>' + |
| 146 | '<div id="ownbox" hidden><label for="oaddr">Your Bitcoin wallet address</label><input id="oaddr" autocomplete="off" spellcheck="false" placeholder="tb1… while in test mode"></div>' + |
| 147 | '<button class="btn" type="submit">Continue</button></form>'; |
| 148 | } |
| 149 | |
| 150 | function tierChip(t) { return '<span class="pill">' + esc(S.tiers[t].name) + '</span>'; } |
| 151 | function scoreBar(n) { return '<div class="bar" role="img" aria-label="Score ' + n + ' of 100"><i style="width:' + n + '%"></i></div>'; } |
| 152 | |
| 153 | const views = { |
| 154 | home() { |
| 155 | const s = S.score; |
| 156 | const paidTo = S.me.payout === 'own' ? 'your own wallet' : 'your Paywell wallet'; |
| 157 | return '<div class="pg"><div><h2>Hi, ' + esc(S.me.name) + '</h2><p class="small">' + esc(S.org.name) + ' · ' + esc(S.me.tierName) + ' (' + S.me.shares + ' bonus share' + (S.me.shares === 1 ? '' : 's') + ')</p></div>' + |
| 158 | '<div class="g2"><div class="tile"><h3>Today’s Bitcoin bonus</h3><div class="usd big">' + usd(S.todayCents) + '</div><p>Paid automatically every day to ' + paidTo + '. Test mode: worked out for real, no money moves.</p></div>' + |
| 159 | '<div class="tile"><h3>Your score: ' + s.score + '</h3>' + scoreBar(s.score) + '<p>Customers ' + (s.customerN ? s.customerAvg + ' ★ (' + s.customerN + ')' : 'no ratings yet') + ' · 60%<br>Teammates ' + (s.peerN ? s.peerAvg + ' ★ (' + s.peerN + ')' : 'no reviews yet') + ' · 40%' + (!s.customerN && !s.peerN ? '<br>Everyone starts at 70 until reviews come in.' : '') + '</p></div></div>' + |
| 160 | '<div class="tile"><h3>How today’s bonus is worked out</h3><p class="calc">Score ' + s.score + ' × ' + S.me.shares + ' share' + (S.me.shares === 1 ? '' : 's') + ' (' + esc(S.me.tierName) + ') × ' + usd(S.org.shareCents) + ' per share = <b>' + usd(S.todayCents) + '</b></p><p>Your wage is separate: at least the minimum wage where you work, and reviews never lower it.</p></div>' + |
| 161 | '<div class="tile"><h3>Daily bonuses</h3>' + (S.days.length ? S.days.map((d) => '<div class="row"><div class="l"><b>' + dayName(d.day) + '</b><span>Score ' + d.score + ' · ' + esc(S.tiers[d.tier].name) + '</span></div><div class="r"><b>' + usd(d.cents) + '</b><div class="small">test</div></div></div>').join('') : '<p>Your first daily bonus shows here tomorrow.</p>') + '</div>' + |
| 162 | '<div class="acts"><button class="btn" data-go="take">Get paid</button><button class="btn o" data-go="checkin">Daily check-in</button><button class="btn o" data-go="wallet">Wallet</button></div></div>'; |
| 163 | }, |
| 164 | checkin() { |
| 165 | const mates = S.team.filter((m) => m.id !== S.me.id); |
| 166 | return '<div class="pg"><div><h2>Daily check-in</h2><p class="small">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.</p></div>' + |
| 167 | (mates.length ? mates.map((m) => { |
| 168 | const done = S.reviewedToday.includes(m.id); |
| 169 | return '<form class="tile peer" data-person="' + esc(m.id) + '"><div class="row"><div class="l"><b>' + esc(m.name) + '</b><span>' + esc(S.tiers[m.tier].name) + '</span></div><div class="r">' + (done ? '<span class="pill">Reviewed today ✓</span>' : '') + '</div></div>' + |
| 170 | (done ? '' : '<div class="starpick" role="radiogroup" aria-label="Stars for ' + esc(m.name) + '">' + [1, 2, 3, 4, 5].map((n) => '<label><input type="radio" name="st" value="' + n + '" required><span>' + n + '★</span></label>').join('') + '</div><input name="note" maxlength="500" placeholder="A kind, honest note (optional)"><button class="btn" type="submit">Send review</button><p class="small res" role="status"></p>') + '</form>'; |
| 171 | }).join('') : '<div class="tile"><p>No teammates yet. ' + (S.me.admin ? 'Add people in the Team tab.' : 'Your team will add people soon.') + '</p></div>') + '</div>'; |
| 172 | }, |
| 173 | ratings() { |
| 174 | const r = S.ratings, p = S.peers; |
| 175 | return '<div class="pg"><div><h2>Your ratings and reviews</h2><p class="small">Customer ratings (60% of your score) and teammate reviews (40%), from the last four weeks. Customers’ contact details stay private.</p></div>' + |
| 176 | '<form class="tile fm" id="visitf"><h3>Ask a customer to rate a visit</h3><p>Makes a one-time rating link for a visit you just did. In a real shop this comes on the receipt by itself.</p><label for="vsvc">What was the visit?</label><input id="vsvc" maxlength="60" placeholder="e.g. Haircut"><button class="btn" type="submit">Make rating link</button><div id="vout"></div></form>' + |
| 177 | '<div class="tile"><h3>From customers</h3>' + (r.length ? r.map((x) => '<div class="row"><div class="l">' + stars(x.stars) + '<b>' + esc(x.brand) + '</b><span>' + when(x.created) + (x.note ? ' · “' + esc(x.note) + '”' : '') + '</span></div><div class="r"><span class="pill ' + (x.status === 'counted' ? '' : 'hold') + '">' + (x.status === 'counted' ? 'Counted' : 'Being checked') + '</span></div></div>').join('') : '<p>No customer ratings yet. Make a rating link above to try it.</p>') + '</div>' + |
| 178 | '<div class="tile"><h3>From teammates</h3>' + (p.length ? p.map((x) => '<div class="row"><div class="l">' + stars(x.stars) + '<span>' + dayName(x.day) + (x.note ? ' · “' + esc(x.note) + '”' : '') + '</span></div></div>').join('') : '<p>No teammate reviews yet.</p>') + '</div>' + |
| 179 | '<div class="tile"><h3>Fair rules</h3><p>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. <a href="/how-it-works/#disputes">How disputes work</a></p></div></div>'; |
| 180 | }, |
| 181 | take() { |
| 182 | const need = S.me.payout === 'paywell' && !wallet; |
| 183 | return '<div class="pg"><div><h2>Get paid</h2><p class="small">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.</p></div>' + |
| 184 | (need ? '<div class="tile"><p>Unlock your wallet first so we know where the payment goes.</p><button class="btn" data-act="unlock">Unlock wallet with passkey</button></div>' : |
| 185 | '<form class="tile fm" id="takef"><label for="tamt">Amount (dollars)</label><input id="tamt" inputmode="decimal" placeholder="25.00"><label for="tfor">For</label><input id="tfor" maxlength="60" placeholder="e.g. Dog grooming"><button class="btn" type="submit">Show payment code</button></form>') + |
| 186 | '<div id="tbox"></div></div>'; |
| 187 | }, |
| 188 | wallet() { |
| 189 | const own = S.me.payout === 'own'; |
| 190 | let h = '<div class="pg"><div class="tile"><h3>Where your daily bonus goes</h3><div class="row"><div class="l">' + (own ? '<b>Your own wallet</b><span class="mono">' + esc(S.me.payoutAddr) + '</span>' : '<b>Your Paywell wallet</b><span>Made with your account. Your passkey locks its backup; we can’t open it.</span>') + '</div><div class="r"><button class="btn o sm" data-act="payout">Change</button></div></div></div>'; |
| 191 | if (!own || wallet) { |
| 192 | if (!wallet) h += '<div class="tile"><h3>Wallet</h3><p>Locked. Your passkey opens it.</p><button class="btn" data-act="unlock">Unlock wallet with passkey</button><p class="err" id="werr" role="alert"></p></div>'; |
| 193 | else { |
| 194 | const st = chainState; |
| 195 | h += '<div class="tile"><h3>Wallet balance</h3><div class="usd big">' + (st ? usdSats(st.balance) : '…') + '</div><p>' + (st ? st.balance.toLocaleString() + ' sats on the test network' + (price ? ' · ' + usd(Math.round(price * 100)) + ' per BTC' : '') : 'Checking the network…') + '</p></div>' + |
| 196 | '<div class="acts"><button class="btn" data-act="receive">Receive</button><button class="btn o" data-act="send">Send</button><button class="btn o" data-act="refresh">Refresh</button></div><div id="wbox"></div>' + |
| 197 | '<div class="tile"><h3>Activity</h3>' + (st && st.history.length ? st.history.slice(0, 30).map((t) => '<div class="row"><div class="l"><b>' + (t.delta >= 0 ? 'Received' : 'Sent') + '</b><span>' + (t.time ? when(t.time) : 'Just now') + (t.confirmed ? '' : ' · pending') + '</span></div><div class="r"><b>' + (t.delta >= 0 ? '+' : '−') + usdSats(Math.abs(t.delta)) + '</b></div></div>').join('') : '<p>Nothing yet. Get free test coins from a signet faucet, then send them to your Receive address.</p><p><a class="btn o sm" href="https://signetfaucet.com/" rel="noopener" target="_blank">Get free test coins</a></p>') + '</div>'; |
| 198 | } |
| 199 | } |
| 200 | h += '<div class="note">Test network only: test coins have no value. Trading between Bitcoin and dollars goes through a licensed exchange partner and opens with live mode.</div></div>'; |
| 201 | return h; |
| 202 | }, |
| 203 | chat() { |
| 204 | const ch = [['general', 'Hellos, news and everyday stuff'], ['shout-outs', 'Great days and high fives'], ['random', 'Anything goes (keep it kind)']]; |
| 205 | return '<div class="chat"><aside class="chs" aria-label="Channels">' + ch.map((c) => '<button class="ch" data-ch="' + c[0] + '"' + (c[0] === curCh ? ' aria-current="true"' : '') + '><span>#</span>' + c[0] + '</button>').join('') + '</aside>' + |
| 206 | '<section class="room"><header class="roomh"><b>#' + curCh + '</b><span>' + ch.find((c) => c[0] === curCh)[1] + '</span></header><div class="msgs" id="msgs" role="log" aria-live="polite"><p class="small">Loading…</p></div>' + |
| 207 | '<div class="gifs" id="gifs" hidden>' + GIFS.map((g) => '<button type="button" data-gif="' + g.id + '" aria-label="' + esc(g.word) + '">' + gifHtml(g) + '</button>').join('') + '</div>' + |
| 208 | '<form class="compose" id="say"><button type="button" class="gifbtn" data-act="gifs" aria-label="Stickers">GIF</button><input id="sayin" maxlength="1000" placeholder="Message #' + curCh + '" autocomplete="off"><button class="btn send" type="submit">Send</button></form></section></div>'; |
| 209 | }, |
| 210 | team() { |
| 211 | let h = '<div class="pg"><div><h2>' + esc(S.org.name) + '</h2><p class="small">Three tiers: Explorer (1 share), Builder (1½), Guide (2). Tiers are reviewed every three months.</p></div><div class="tile">' + |
| 212 | S.team.map((m) => '<div class="row"><div class="l"><b>' + esc(m.name) + (m.id === S.me.id ? ' (you)' : '') + '</b><span>' + esc(S.tiers[m.tier].name) + '</span></div><div class="r">' + |
| 213 | (S.me.admin && m.id !== S.me.id ? '<select data-tier="' + esc(m.id) + '" aria-label="Tier for ' + esc(m.name) + '">' + [1, 2, 3].map((t) => '<option value="' + t + '"' + (t === m.tier ? ' selected' : '') + '>' + S.tiers[t].name + '</option>').join('') + '</select>' : tierChip(m.tier)) + '</div></div>').join('') + '</div>'; |
| 214 | if (S.me.admin) h += '<form class="tile fm" id="invitef"><h3>Add a teammate</h3><p>Makes a one-time setup link (good for 24 hours). Send it only to them, by text or email. Opening it lets them save a passkey and join.</p><label for="iname">Their first name</label><input id="iname" required maxlength="40"><label for="itier">Tier</label><select id="itier"><option value="1">Explorer</option><option value="2">Builder</option><option value="3">Guide</option></select><button class="btn" type="submit">Make setup link</button><div id="iout"></div></form>'; |
| 215 | return h + '</div>'; |
| 216 | }, |
| 217 | security() { |
| 218 | return '<div class="pg"><div><h2>Security</h2></div><div class="tile">' + |
| 219 | '<div class="check"><i>✓</i><div><b>Passkey sign-in</b><div class="small">Your face, fingerprint or screen lock is your sign-in. No username, no password, nothing to steal or forget.</div></div></div>' + |
| 220 | '<div class="check"><i>✓</i><div><b>Wallet locked by your passkey</b><div class="small">Your wallet’s backup is locked on your device before it reaches us. We store it but can’t open it. Nothing to write down.</div></div></div>' + |
| 221 | '<div class="check"><i>✓</i><div><b>Confirm before money moves</b><div class="small">Sending, and changing where your bonus goes, always asks for your passkey again.</div></div></div>' + |
| 222 | '<div class="check"><i>✓</i><div><b>Reviews stay in your team</b><div class="small">Only signed-in members of your own team can see your team’s ratings and reviews.</div></div></div>' + |
| 223 | '</div><p><button class="btn o" data-act="signout">Sign out</button></p><div class="note">We will never ask for a setup link or recovery words, by phone, text, email or in person. Anyone who asks is trying to steal from you.</div></div>'; |
| 224 | }, |
| 225 | }; |
| 226 | |
| 227 | function render() { |
| 228 | if (!S) return; |
| 229 | shell(true); |
| 230 | panel().innerHTML = views[cur] ? views[cur]() : views.home(); |
| 231 | if (cur === 'chat') { lastMsg = 0; chatMsgs = []; pollChat(); chatTimer = setInterval(pollChat, 4000); } |
| 232 | if (cur === 'wallet' && wallet && !chainState) refreshWallet(); |
| 233 | } |
| 234 | |
| 235 | async function refresh() { S = await api('/api/app/me'); render(); } |
| 236 | |
| 237 | // ---------- Chat ---------- |
| 238 | function msgHtml(m) { |
| 239 | const g = (m.body.match(/^:gif:([a-z]+):$/) || [])[1]; |
| 240 | const gif = g && GIFS.find((x) => x.id === g); |
| 241 | return '<div class="msg"><span class="av" style="background:' + colorFor(m.person) + '">' + esc(m.name[0] || '?') + '</span><div class="mb"><div class="mh"><b>' + esc(m.name) + '</b><span>' + when(m.created) + '</span></div>' + (gif ? gifHtml(gif) : '<p>' + esc(m.body) + '</p>') + '</div></div>'; |
| 242 | } |
| 243 | async function pollChat(body) { |
| 244 | try { |
| 245 | const j = body ? await api('/api/app/chat?c=' + curCh + '&since=' + lastMsg, { channel: curCh, body }) : await api('/api/app/chat?c=' + curCh + '&since=' + lastMsg); |
| 246 | if (j.messages.length) { chatMsgs = chatMsgs.concat(j.messages); lastMsg = j.messages[j.messages.length - 1].id; } |
| 247 | const box = $('#msgs'); if (!box) return; |
| 248 | const atEnd = box.scrollHeight - box.scrollTop - box.clientHeight < 60; |
| 249 | box.innerHTML = chatMsgs.length ? chatMsgs.map(msgHtml).join('') : '<p class="small">No messages yet. Say hello! 👋</p>'; |
| 250 | if (atEnd || body || j.messages.length) box.scrollTop = box.scrollHeight; |
| 251 | } catch (e) { if (e.status === 401) { S = null; gate(); } } |
| 252 | } |
| 253 | |
| 254 | // ---------- Wallet actions ---------- |
| 255 | async function refreshWallet() { |
| 256 | if (!wallet) return; |
| 257 | try { chainState = await PWW.sync(wallet.w); } |
| 258 | catch (e) { chainState = chainState || { balance: 0, history: [], utxos: [], nextReceive: 0, nextChange: 0 }; } |
| 259 | if (cur === 'wallet') render(); |
| 260 | } |
| 261 | function receiveBox() { |
| 262 | const a = wallet.w.address(chainState ? chainState.nextReceive : 0); |
| 263 | $('#wbox').innerHTML = '<div class="tile center"><h3>Your receive address</h3><div class="qrbox">' + PWW.qrSvg('bitcoin:' + a) + '</div><p class="mono">' + esc(a) + '</p><button class="btn o sm" data-copy="' + esc(a) + '">Copy address</button></div>'; |
| 264 | } |
| 265 | function sendBox() { |
| 266 | $('#wbox').innerHTML = '<form class="tile fm" id="sendf"><h3>Send Bitcoin</h3><label for="sto">To address</label><input id="sto" autocomplete="off" spellcheck="false" placeholder="tb1…"><label for="samt">Amount (dollars)</label><input id="samt" inputmode="decimal" placeholder="5.00"><p class="small" id="sout"></p><button class="btn" type="submit">Review and confirm with passkey</button><p class="err" role="alert" id="serr"></p><p class="small">Bitcoin payments can’t be undone. Check the address and amount.</p></form>'; |
| 267 | } |
| 268 | |
| 269 | // ---------- Events ---------- |
| 270 | document.addEventListener('click', async (e) => { |
| 271 | const t = e.target.closest('button, a'); |
| 272 | if (!t) return; |
| 273 | if (t.dataset.tab) { setTab(t.dataset.tab); return; } |
| 274 | if (t.dataset.go) { setTab(t.dataset.go); return; } |
| 275 | if (t.dataset.ch) { curCh = t.dataset.ch; render(); return; } |
| 276 | if (t.dataset.copy) { try { await navigator.clipboard.writeText(t.dataset.copy); t.textContent = 'Copied ✓'; } catch (x) {} return; } |
| 277 | if (t.dataset.gif) { $('#gifs').hidden = true; pollChat(':gif:' + t.dataset.gif + ':'); return; } |
| 278 | const act = t.dataset.act; |
| 279 | if (!act) return; |
| 280 | try { |
| 281 | if (act === 'gifs') { const g = $('#gifs'); g.hidden = !g.hidden; return; } |
| 282 | if (act === 'signin') { |
| 283 | t.disabled = true; t.textContent = 'Waiting for your passkey…'; |
| 284 | const c = await getPasskey(); |
| 285 | await api('/api/app/login', { credential: c.payload }); |
| 286 | S = await api('/api/app/me'); |
| 287 | if (S.me.payout === 'paywell' && c.prf) { try { await unlockWallet(c); } catch (x) {} } |
| 288 | cur = 'home'; render(); loadPrice(); return; |
| 289 | } |
| 290 | if (act === 'join') { |
| 291 | t.disabled = true; t.textContent = 'Waiting for your passkey…'; |
| 292 | const c = await createPasskey(t.dataset.name); |
| 293 | await api('/api/app/register', { credential: c.payload, setup: t.dataset.token }); |
| 294 | history.replaceState(null, '', '/app/'); |
| 295 | await afterSignup(c); |
| 296 | return; |
| 297 | } |
| 298 | if (act === 'unlock') { |
| 299 | const c = await getPasskey(); |
| 300 | await unlockWallet(c); |
| 301 | chainState = null; render(); refreshWallet(); return; |
| 302 | } |
| 303 | if (act === 'refresh') { chainState = null; render(); refreshWallet(); return; } |
| 304 | if (act === 'receive') { if (chainState) receiveBox(); return; } |
| 305 | if (act === 'send') { sendBox(); return; } |
| 306 | if (act === 'payout') { payoutScreen(); return; } |
| 307 | if (act === 'signout') { await api('/api/app/logout', {}); S = null; wallet = null; chainState = null; gate(); return; } |
| 308 | } catch (x) { |
| 309 | const msg = passkeyError(x); |
| 310 | const where = $('#werr') || $('#serr'); |
| 311 | if (S && !where) { alertBox(msg); } else if (where) where.textContent = msg; else gate(msg); |
| 312 | } |
| 313 | }); |
| 314 | function alertBox(msg) { const p = document.createElement('p'); p.className = 'err'; p.setAttribute('role', 'alert'); p.textContent = msg; panel().prepend(p); } |
| 315 | |
| 316 | async function afterSignup(c) { |
| 317 | S = await api('/api/app/me'); |
| 318 | lastCred = c.payload.id; |
| 319 | window._signupCred = c; |
| 320 | payoutScreen(); |
| 321 | } |
| 322 | |
| 323 | document.addEventListener('change', async (e) => { |
| 324 | if (e.target.name === 'pm') { const b = $('#ownbox'); if (b) b.hidden = e.target.value !== 'own'; } |
| 325 | if (e.target.dataset && e.target.dataset.tier) { |
| 326 | try { await api('/api/app/tier', { person: e.target.dataset.tier, tier: Number(e.target.value) }); await refresh(); } catch (x) { alertBox(x.message); } |
| 327 | } |
| 328 | }); |
| 329 | document.addEventListener('input', (e) => { |
| 330 | if (e.target.id === 'samt') { const v = parseFloat(e.target.value) || 0; $('#sout').textContent = v && price ? Math.round(v / price * 1e8).toLocaleString() + ' sats' : ''; } |
| 331 | }); |
| 332 | |
| 333 | document.addEventListener('submit', async (e) => { |
| 334 | const f = e.target; e.preventDefault(); |
| 335 | const btn = f.querySelector('button[type=submit]'); |
| 336 | const fail = (msg) => { let p = f.querySelector('.err'); if (!p) { p = document.createElement('p'); p.className = 'err'; p.setAttribute('role', 'alert'); f.appendChild(p); } p.textContent = msg; if (btn) btn.disabled = false; }; |
| 337 | try { |
| 338 | if (btn) btn.disabled = true; |
| 339 | if (f.id === 'startteam') { |
| 340 | const name = $('#sname').value.trim(), team = $('#steam').value.trim(); |
| 341 | if (!name || !team) return fail('Add your first name and a team name.'); |
| 342 | const c = await createPasskey(name); |
| 343 | await api('/api/app/register', { credential: c.payload, name, team }); |
| 344 | await afterSignup(c); |
| 345 | return; |
| 346 | } |
| 347 | if (f.id === 'payoutf') { |
| 348 | const mode = f.querySelector('input[name=pm]:checked').value; |
| 349 | if (mode === 'own') { |
| 350 | const addr = $('#oaddr').value.trim(); |
| 351 | if (!PWW.validAddress(addr)) return fail('That doesn’t look like a test-network Bitcoin address (they start with tb1).'); |
| 352 | const c = await getPasskey(); |
| 353 | await api('/api/app/payout', { mode: 'own', addr, credential: c.payload }); |
| 354 | } else { |
| 355 | // Make the wallet here, lock its backup with the passkey and store the locked copy with us. |
| 356 | let c = window._signupCred && window._signupCred.prf ? window._signupCred : null; |
| 357 | if (!c) c = await getPasskey(); |
| 358 | if (!c.prf) return fail('This browser’s passkeys can’t lock a wallet backup yet. Choose “Use my own wallet”, or try Chrome or Safari.'); |
| 359 | let words = null; |
| 360 | try { words = await vaultOpen(c.payload.id, c.prf); } catch (x) { words = PWW.newWords(); await vaultSave(c.payload.id, c.prf, words); } |
| 361 | wallet = { w: PWW.open(words) }; |
| 362 | const body = { mode: 'paywell', walletAddr: wallet.w.address(0) }; |
| 363 | if (S.me.payout === 'own') { const c2 = await getPasskey(c.payload.id); body.credential = c2.payload; } |
| 364 | await api('/api/app/payout', body); |
| 365 | } |
| 366 | window._signupCred = null; |
| 367 | S = await api('/api/app/me'); cur = mode === 'own' ? 'home' : 'wallet'; chainState = null; render(); loadPrice(); |
| 368 | return; |
| 369 | } |
| 370 | if (f.classList.contains('peer')) { |
| 371 | const st = f.querySelector('input[name=st]:checked'); |
| 372 | if (!st) return fail('Pick 1 to 5 stars.'); |
| 373 | await api('/api/app/peer', { person: f.dataset.person, stars: Number(st.value), note: f.note.value }); |
| 374 | S = await api('/api/app/me'); render(); return; |
| 375 | } |
| 376 | if (f.id === 'visitf') { |
| 377 | const j = await api('/api/app/visit', { service: $('#vsvc').value }); |
| 378 | $('#vout').innerHTML = '<div class="center"><div class="qrbox">' + PWW.qrSvg(j.url) + '</div><p class="mono small">' + esc(j.url) + '</p><p><button class="btn o sm" type="button" data-copy="' + esc(j.url) + '">Copy link</button> <a class="btn o sm" href="' + esc(j.url) + '" target="_blank" rel="noopener">Open it as the customer</a></p><p class="small">Works once, for 14 days. Refresh this tab after rating to see it count.</p></div>'; |
| 379 | btn.disabled = false; return; |
| 380 | } |
| 381 | if (f.id === 'takef') { |
| 382 | const dollars = parseFloat($('#tamt').value) || 0; |
| 383 | if (!price) await loadPrice(); |
| 384 | const addr = S.me.payout === 'own' ? S.me.payoutAddr : wallet.w.address(chainState ? chainState.nextReceive : 0); |
| 385 | const visit = await api('/api/app/visit', { service: $('#tfor').value || 'Payment' }); |
| 386 | const btcAmt = dollars && price ? (dollars / price).toFixed(8).replace(/0+$/, '').replace(/\.$/, '') : ''; |
| 387 | const bip21 = 'bitcoin:' + addr + (btcAmt ? '?amount=' + btcAmt : '') + ($('#tfor').value ? (btcAmt ? '&' : '?') + 'label=' + encodeURIComponent($('#tfor').value) : ''); |
| 388 | const link = 'https://paywell.company/pay/?u=' + encodeURIComponent(bip21) + '&r=' + encodeURIComponent(visit.url); |
| 389 | $('#tbox').innerHTML = '<div class="tile center"><h3>' + (dollars ? usd(Math.round(dollars * 100)) : 'Any amount') + '</h3><div class="qrbox">' + PWW.qrSvg(link) + '</div><p>Ask them to scan this with their phone camera. It opens the payment, then asks them to rate the visit. No tip.</p>' + |
| 390 | ('NDEFReader' in window ? '<button class="btn o sm" type="button" id="nfcw" data-link="' + esc(link) + '">Write to an NFC tag</button> ' : '') + '<button class="btn o sm" type="button" data-copy="' + esc(link) + '">Copy link</button><p class="small" id="nfcmsg"></p></div>'; |
| 391 | btn.disabled = false; return; |
| 392 | } |
| 393 | if (f.id === 'sendf') { |
| 394 | const to = $('#sto').value.trim(), dollars = parseFloat($('#samt').value) || 0; |
| 395 | if (!price) await loadPrice(); |
| 396 | if (!dollars || !price) return fail('Enter an amount in dollars.'); |
| 397 | const sats = Math.round(dollars / price * 1e8); |
| 398 | const fees = await api('/api/chain/fees').catch(() => ({})); |
| 399 | const rate = Math.max(1, Math.ceil(fees['3'] || 2)); |
| 400 | if (!chainState) chainState = await PWW.sync(wallet.w); |
| 401 | const tx = PWW.buildPayment(wallet.w, chainState, to, sats, rate); |
| 402 | if (!confirm('Send ' + usd(Math.round(dollars * 100)) + ' (' + sats.toLocaleString() + ' test sats) plus a network fee of about ' + usdSats(tx.fee) + '? You’ll confirm with your passkey next.')) { btn.disabled = false; return; } |
| 403 | await getPasskey(lastCred || undefined); // a fresh face, fingerprint or screen-lock check before money moves |
| 404 | const r = await fetch('/api/chain/tx', { method: 'POST', body: tx.hex }).then((x) => x.json()); |
| 405 | if (r.error) return fail('The network didn’t take it: ' + r.error); |
| 406 | $('#wbox').innerHTML = '<div class="tile center"><div class="big-ok">✓</div><h3>Sent</h3><p class="mono small">' + esc(r.txid) + '</p></div>'; |
| 407 | setTimeout(refreshWallet, 3000); return; |
| 408 | } |
| 409 | if (f.id === 'invitef') { |
| 410 | const j = await api('/api/app/invite', { name: $('#iname').value, tier: Number($('#itier').value) }); |
| 411 | $('#iout').innerHTML = '<p class="mono small">' + esc(j.url) + '</p><p><button class="btn o sm" type="button" data-copy="' + esc(j.url) + '">Copy setup link</button></p><p class="small">Good for 24 hours, works once.</p>'; |
| 412 | btn.disabled = false; await refresh(); return; |
| 413 | } |
| 414 | if (f.id === 'say') { |
| 415 | const v = $('#sayin').value.trim(); if (!v) { btn.disabled = false; return; } |
| 416 | $('#sayin').value = ''; await pollChat(v); btn.disabled = false; $('#sayin').focus(); return; |
| 417 | } |
| 418 | } catch (x) { fail(passkeyError(x)); } |
| 419 | }); |
| 420 | document.addEventListener('click', async (e) => { |
| 421 | const b = e.target.closest('#nfcw'); if (!b) return; |
| 422 | 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.'; } |
| 423 | catch (x) { $('#nfcmsg').textContent = 'Couldn’t write the tag: ' + (x.message || x); } |
| 424 | }); |
| 425 | |
| 426 | // ---------- Start ---------- |
| 427 | (async () => { |
| 428 | loadPrice(); |
| 429 | if (/setup=/.test(location.hash)) { gate(); return; } |
| 430 | try { S = await api('/api/app/me'); render(); } |
| 431 | catch (e) { gate(e.status === 401 ? '' : e.message); } |
| 432 | })(); |
| 433 | window.addEventListener('hashchange', () => { if (/setup=/.test(location.hash)) gate(); }); |
| 434 | })(); |