// Paywell team app API (paywell.company/api/app/* and /api/chain/*). Open source, public domain. // // TEST MODE: everything works for real (passkey accounts, teams, setup links, customer ratings, peer reviews, // scores, tiers, daily bonus amounts, team chat, a Bitcoin wallet on the signet test network) but no real money // moves. Daily bonuses are worked out and shown; paying them needs a licensed payroll and custody partner first. // // Sign-in is passkeys only (WebAuthn). We store each passkey's public key, never a password. // Needs the D1 binding PAYWELL_DB (schema: tools/paywell-gen/schema.sql). const RP_ID = 'paywell.company'; const ORIGINS = ['https://paywell.company']; const TIERS = { 1: { name: 'Explorer', shares: 1 }, 2: { name: 'Builder', shares: 1.5 }, 3: { name: 'Guide', shares: 2 } }; const START_SCORE = 70; // new team members start here until reviews come in const TEST_SHARE_CENTS = 1000; // test teams: one bonus share is worth $10 a day (sample value, no money moves) const WINDOW_DAYS = 28; // score uses the last four weeks of reviews const ESPLORA = 'https://mempool.space/signet/api'; const SESSION_DAYS = 30; const enc = new TextEncoder(); const b64u = (bytes) => { let s = ''; const b = new Uint8Array(bytes); 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(String(s).replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((String(s).length + 3) % 4)), (c) => c.charCodeAt(0)); const json = (o, status = 200, headers = {}) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-robots-tag': 'noindex', ...headers } }); const rid = (n = 16) => b64u(crypto.getRandomValues(new Uint8Array(n))); const sha256 = async (data) => new Uint8Array(await crypto.subtle.digest('SHA-256', typeof data === 'string' ? enc.encode(data) : data)); const day = (t) => new Date(t).toISOString().slice(0, 10); const clean = (s, n) => String(s || '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, n); let signVisit = null; // rating-link signer, shared with the rating API export function setSigner(fn) { signVisit = fn; } // ---------- Minimal CBOR (enough for WebAuthn attestation objects and COSE keys) ---------- function cbor(buf) { let i = 0; const u8 = buf; const len = (ai) => { if (ai < 24) return ai; if (ai === 24) return u8[i++]; if (ai === 25) { const v = (u8[i] << 8) | u8[i + 1]; i += 2; return v; } if (ai === 26) { const v = ((u8[i] << 24) >>> 0) + ((u8[i + 1] << 16) | (u8[i + 2] << 8) | u8[i + 3]); i += 4; return v; } throw new Error('cbor length'); }; const item = () => { const b = u8[i++], mt = b >> 5, ai = b & 31; if (mt === 0) return len(ai); if (mt === 1) return -1 - len(ai); if (mt === 2) { const n = len(ai); const v = u8.slice(i, i + n); i += n; return v; } if (mt === 3) { const n = len(ai); const v = new TextDecoder().decode(u8.slice(i, i + n)); i += n; return v; } if (mt === 4) { const n = len(ai); const a = []; for (let k = 0; k < n; k++) a.push(item()); return a; } if (mt === 5) { const n = len(ai); const m = new Map(); for (let k = 0; k < n; k++) { const key = item(); m.set(key, item()); } return m; } if (mt === 7) { if (ai === 20) return false; if (ai === 21) return true; if (ai === 22) return null; } throw new Error('cbor type'); }; const v = item(); return { value: v, end: i }; } // ---------- WebAuthn ---------- function parseAuthData(ad) { const flags = ad[32]; const out = { rpIdHash: ad.slice(0, 32), up: !!(flags & 1), uv: !!(flags & 4), counter: new DataView(ad.buffer, ad.byteOffset + 33, 4).getUint32(0) }; if (flags & 64) { const credLen = (ad[53] << 8) | ad[54]; out.credId = ad.slice(55, 55 + credLen); const rest = ad.slice(55 + credLen); out.cose = cbor(rest).value; } return out; } function coseToJwk(m) { const kty = m.get(1), alg = m.get(3); if (kty === 2 && alg === -7) return { kty: 'EC', crv: 'P-256', x: b64u(m.get(-2)), y: b64u(m.get(-3)), alg: 'ES256' }; if (kty === 3 && alg === -257) return { kty: 'RSA', n: b64u(m.get(-1)), e: b64u(m.get(-2)), alg: 'RS256' }; throw new Error('Unsupported passkey type'); } function derToRaw(der) { // ECDSA DER signature -> 64-byte r||s let i = 2; if (der[1] & 0x80) i = 2 + (der[1] & 0x7f); const read = () => { i++; const n = der[i++]; let v = der.slice(i, i + n); i += n; while (v.length > 32 && v[0] === 0) v = v.slice(1); const o = new Uint8Array(32); o.set(v, 32 - v.length); return o; }; const r = read(), s = read(); const out = new Uint8Array(64); out.set(r); out.set(s, 32); return out; } async function checkClientData(db, cdj, type, request) { const cd = JSON.parse(new TextDecoder().decode(unb64u(cdj))); if (cd.type !== type) throw new Error('Wrong passkey step'); const origin = new URL(request.url).origin; if (!ORIGINS.includes(cd.origin) && cd.origin !== origin) throw new Error('Wrong website'); const row = await db.prepare('SELECT exp FROM chal WHERE id=?').bind(cd.challenge).first(); if (!row || row.exp < Date.now()) throw new Error('This sign-in took too long. Try again.'); await db.prepare('DELETE FROM chal WHERE id=? OR exp?').bind(b64u(await sha256(t)), Date.now()).first(); return row || null; } // ---------- Scores and daily bonuses ---------- const to100 = (avg) => Math.round(((avg - 1) / 4) * 100); async function scoreAt(db, person, until) { const from = until - WINDOW_DAYS * 864e5; const c = await db.prepare("SELECT AVG(stars) a, COUNT(*) n FROM ratings WHERE person=? AND status='counted' AND created>? AND created<=?").bind(person, from, until).first(); const p = await db.prepare('SELECT AVG(stars) a, COUNT(*) n FROM peer WHERE target=? AND created>? AND created<=?').bind(person, from, until).first(); const cs = c.n ? to100(c.a) : null, ps = p.n ? to100(p.a) : null; let score = START_SCORE; if (cs !== null && ps !== null) score = Math.round(cs * 0.6 + ps * 0.4); else if (cs !== null) score = cs; else if (ps !== null) score = ps; return { score, customer: cs, customerN: c.n, customerAvg: c.a ? Math.round(c.a * 10) / 10 : null, peer: ps, peerN: p.n, peerAvg: p.a ? Math.round(p.a * 10) / 10 : null }; } const bonusCents = (share, tier, score) => Math.round(share * TIERS[tier].shares * score / 100); async function summary(db, person) { const org = await db.prepare('SELECT * FROM orgs WHERE id=?').bind(person.org).first(); const now = Date.now(); const s = await scoreAt(db, person.id, now); const days = []; const joined = new Date(day(person.created) + 'T00:00:00Z').getTime(); for (let k = 0; k < 14; k++) { const end = new Date(day(now) + 'T00:00:00Z').getTime() - k * 864e5; // end of the previous day if (end <= joined) break; const sc = (await scoreAt(db, person.id, end)).score; days.push({ day: day(end - 1), score: sc, tier: person.tier, cents: bonusCents(org.share_cents, person.tier, sc) }); } const team = (await db.prepare('SELECT id, name, tier, admin FROM people WHERE org=? ORDER BY created').bind(person.org).all()).results; const today = day(now); const reviewed = (await db.prepare('SELECT target FROM peer WHERE author=? AND day=?').bind(person.id, today).all()).results.map((r) => r.target); const ratings = (await db.prepare('SELECT visit, brand, stars, note, status, created FROM ratings WHERE person=? ORDER BY created DESC LIMIT 30').bind(person.id).all()).results; const peers = (await db.prepare('SELECT stars, note, day FROM peer WHERE target=? ORDER BY created DESC LIMIT 30').bind(person.id).all()).results; return { me: { id: person.id, name: person.name, tier: person.tier, tierName: TIERS[person.tier].name, shares: TIERS[person.tier].shares, admin: !!person.admin, payout: person.payout_mode, payoutAddr: person.payout_addr, joined: person.created }, org: { name: org.name, shareCents: org.share_cents, test: true }, score: s, todayCents: bonusCents(org.share_cents, person.tier, s.score), days, team, reviewedToday: reviewed, ratings, peers, tiers: TIERS, }; } // ---------- Rate limit ---------- async function limited(db, request, key, max, windowMs) { const ip = request.headers.get('cf-connecting-ip') || ''; const h = b64u(await sha256(ip + '|' + key)).slice(0, 16), now = Date.now(); const r = await db.prepare('SELECT COUNT(*) n FROM vault_hits WHERE ip_hash=? AND at>?').bind(h, now - windowMs).first(); if (r && r.n >= max) return true; await db.prepare('INSERT INTO vault_hits (ip_hash, at) VALUES (?,?)').bind(h, now).run(); return false; } // ---------- Chain proxy (signet test network): the browser never calls third parties directly ---------- async function chain(request, path) { const sub = path.slice('/api/chain/'.length); if (request.method === 'POST' && sub === 'tx') { const hex = (await request.text()).trim(); if (!/^[0-9a-f]{100,200000}$/i.test(hex)) return json({ error: 'bad transaction' }, 400); const r = await fetch(ESPLORA + '/tx', { method: 'POST', body: hex }); const t = await r.text(); return r.ok ? json({ txid: t }) : json({ error: t.slice(0, 300) }, 400); } let target = null; if (sub === 'fees') target = '/fee-estimates'; else if (sub === 'price') { const r = await fetch('https://mempool.space/api/v1/prices', { cf: { cacheTtl: 60, cacheEverything: true } }).catch(() => null); const j = r && r.ok ? await r.json().catch(() => null) : null; return json({ usd: j && j.USD ? j.USD : null }); } else { const m = sub.match(/^address\/((?:tb1|bc1)[0-9a-z]{20,90})\/(utxo|txs)$/); if (m) target = `/address/${m[1]}/${m[2]}`; } if (!target) return json({ error: 'not found' }, 404); const r = await fetch(ESPLORA + target, { cf: { cacheTtl: 10, cacheEverything: true } }); return new Response(await r.text(), { status: r.status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }); } // ---------- Routes ---------- export async function appApi(request, env, path) { if (path.startsWith('/api/chain/')) return chain(request, path); const db = env.PAYWELL_DB; if (!db) return json({ error: 'The app isn’t switched on yet.' }, 503); const method = request.method; let b = {}; if (method === 'POST') { try { b = await request.json(); } catch {} } try { // A fresh challenge for any passkey step (5 minutes). if (path === '/api/app/challenge' && method === 'POST') { if (await limited(db, request, 'chal', 60, 6e5)) return json({ error: 'Too many tries. Wait a few minutes.' }, 429); const id = rid(32); await db.prepare('INSERT INTO chal (id, exp) VALUES (?,?)').bind(id, Date.now() + 3e5).run(); return json({ challenge: id, rpId: RP_ID }); } // What a setup link is for (team name, the person's name). if (path === '/api/app/setup' && method === 'POST') { const row = await db.prepare('SELECT s.name, o.name team, s.exp, s.used FROM setup s JOIN orgs o ON o.id=s.org WHERE s.token=?').bind(clean(b.token, 64)).first(); if (!row || row.used || row.exp < Date.now()) return json({ error: 'This setup link has expired or was already used. Ask your team for a new one.' }, 404); return json({ name: row.name, team: row.team }); } // Create an account with a new passkey: either start a test team, or join one with a setup link. if (path === '/api/app/register' && method === 'POST') { if (await limited(db, request, 'reg', 20, 36e5)) return json({ error: 'Too many new accounts from here. Try again later.' }, 429); const c = b.credential || {}; await checkClientData(db, c.clientDataJSON, 'webauthn.create', request); const att = cbor(unb64u(c.attestationObject)).value; const a = parseAuthData(att.get('authData')); if (b64u(a.rpIdHash) !== b64u(await sha256(RP_ID))) throw new Error('Wrong website'); if (!a.up || !a.uv) throw new Error('Face, fingerprint or screen lock is needed.'); const jwk = coseToJwk(a.cose); const credId = b64u(a.credId); let org, name, tier = 1, admin = 0, setupToken = null; if (b.setup) { setupToken = clean(b.setup, 64); const s = await db.prepare('SELECT * FROM setup WHERE token=?').bind(setupToken).first(); if (!s || s.used || s.exp < Date.now()) throw new Error('This setup link has expired or was already used.'); org = s.org; name = s.name; tier = s.tier; } else { const team = clean(b.team, 60); name = clean(b.name, 40); if (!team || !name) throw new Error('Add your name and a team name.'); org = rid(9); await db.prepare('INSERT INTO orgs (id, name, share_cents, created) VALUES (?,?,?,?)').bind(org, team, TEST_SHARE_CENTS, Date.now()).run(); tier = 3; admin = 1; // whoever starts a team guides it } const person = rid(9), now = Date.now(); const stmts = [ db.prepare('INSERT INTO people (id, org, name, tier, admin, payout_mode, payout_addr, created) VALUES (?,?,?,?,?,?,?,?)').bind(person, org, name, tier, admin, 'paywell', null, now), db.prepare('INSERT INTO creds (id, person, jwk, counter, created, used) VALUES (?,?,?,?,?,?)').bind(credId, person, JSON.stringify(jwk), a.counter, now, now), ]; if (setupToken) stmts.push(db.prepare('UPDATE setup SET used=? WHERE token=?').bind(now, setupToken)); await db.batch(stmts); return json({ ok: true, credId }, 200, { 'set-cookie': await startSession(db, person) }); } if (path === '/api/app/login' && method === 'POST') { if (await limited(db, request, 'login', 40, 6e5)) return json({ error: 'Too many tries. Wait a few minutes.' }, 429); const person = await verifyAssertion(db, b.credential || {}, request); return json({ ok: true }, 200, { 'set-cookie': await startSession(db, person) }); } if (path === '/api/app/logout' && method === 'POST') { const t = cookie(request, 'pw_s'); if (t) await db.prepare('DELETE FROM sessions WHERE hash=?').bind(b64u(await sha256(t))).run(); return json({ ok: true }, 200, { 'set-cookie': 'pw_s=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0' }); } // Everything below needs a signed-in person. const p = await me(db, request); if (!p) return json({ error: 'signed out' }, 401); if (path === '/api/app/me' && method === 'GET') return json(await summary(db, p)); // Where the daily bonus goes. Changing it needs a fresh passkey check. if (path === '/api/app/payout' && method === 'POST') { const mode = b.mode === 'own' ? 'own' : 'paywell'; const addr = clean(b.addr, 100); if (mode === 'own' && !/^(bc1|tb1)[02-9ac-hj-np-z]{20,90}$|^[13mn2][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(addr)) throw new Error('That doesn’t look like a Bitcoin address.'); if (mode === 'own' || p.payout_mode === 'own') { const who = await verifyAssertion(db, b.credential || {}, request); if (who !== p.id) throw new Error('Use your own passkey.'); } await db.prepare('UPDATE people SET payout_mode=?, payout_addr=? WHERE id=?').bind(mode, mode === 'own' ? addr : (b.walletAddr ? clean(b.walletAddr, 100) : null), p.id).run(); return json({ ok: true }); } // The wallet's first receive address, so the team can see where bonuses go. if (path === '/api/app/wallet-address' && method === 'POST') { if (p.payout_mode !== 'paywell') return json({ ok: true }); const addr = clean(b.addr, 100); if (!/^tb1[02-9ac-hj-np-z]{20,90}$/.test(addr)) throw new Error('bad address'); await db.prepare('UPDATE people SET payout_addr=? WHERE id=?').bind(addr, p.id).run(); return json({ ok: true }); } // A one-time setup link for a new teammate (only the team's guide in test mode). if (path === '/api/app/invite' && method === 'POST') { if (!p.admin) throw new Error('Only the person who started the team can add people.'); const name = clean(b.name, 40); const tier = [1, 2, 3].includes(Number(b.tier)) ? Number(b.tier) : 1; if (!name) throw new Error('Add their first name.'); const n = await db.prepare('SELECT COUNT(*) n FROM people WHERE org=?').bind(p.org).first(); if (n.n >= 50) throw new Error('Test teams can have up to 50 people.'); const token = rid(18); await db.prepare('INSERT INTO setup (token, org, name, tier, exp, used, created) VALUES (?,?,?,?,?,?,?)').bind(token, p.org, name, tier, Date.now() + 864e5, 0, Date.now()).run(); return json({ url: 'https://paywell.company/app/#setup=' + token, expires: Date.now() + 864e5 }); } // Change a teammate's tier (the team's guide; written notice is the live rule). if (path === '/api/app/tier' && method === 'POST') { if (!p.admin) throw new Error('Only the person who started the team can change tiers.'); const tier = Number(b.tier); if (![1, 2, 3].includes(tier)) throw new Error('Pick a tier.'); await db.prepare('UPDATE people SET tier=? WHERE id=? AND org=?').bind(tier, clean(b.person, 20), p.org).run(); return json({ ok: true }); } // A customer rating link for a visit you just did (in live mode this comes from the shop's checkout). if (path === '/api/app/visit' && method === 'POST') { if (await limited(db, request, 'visit:' + p.id, 60, 36e5)) throw new Error('That’s a lot of visits. Try again later.'); const org = await db.prepare('SELECT name FROM orgs WHERE id=?').bind(p.org).first(); const service = clean(b.service, 60) || 'Visit'; const token = await signVisit(env, { v: 'v-' + rid(9), b: org.name, s: service, p: p.name, pid: p.id, d: day(Date.now()), x: Date.now() + 14 * 864e5 }); return json({ url: 'https://paywell.company/r/' + token }); } // Peer review: one per teammate per day, never yourself, kept private from the person reviewed. if (path === '/api/app/peer' && method === 'POST') { const target = clean(b.person, 20), stars = Number(b.stars); if (target === p.id) throw new Error('You can’t review yourself.'); if (!Number.isInteger(stars) || stars < 1 || stars > 5) throw new Error('Pick 1 to 5 stars.'); const t = await db.prepare('SELECT id FROM people WHERE id=? AND org=?').bind(target, p.org).first(); if (!t) throw new Error('They’re not on your team.'); const r = await db.prepare('INSERT OR IGNORE INTO peer (author, target, day, stars, note, created) VALUES (?,?,?,?,?,?)').bind(p.id, target, day(Date.now()), stars, clean(b.note, 500), Date.now()).run(); if (!r.meta.changes) throw new Error('You already reviewed them today.'); return json({ ok: true }); } // Team chat: channels per team, newest 100 messages, polled by the app. if (path === '/api/app/chat') { const ch = ['general', 'shout-outs', 'random'].includes(new URL(request.url).searchParams.get('c') || b.channel) ? (new URL(request.url).searchParams.get('c') || b.channel) : 'general'; if (method === 'POST') { const body = clean(b.body, 1000); if (!body) throw new Error('Write something first.'); if (await limited(db, request, 'chat:' + p.id, 120, 6e5)) throw new Error('Slow down a little.'); await db.prepare('INSERT INTO messages (org, channel, person, body, created) VALUES (?,?,?,?,?)').bind(p.org, ch, p.id, body, Date.now()).run(); } const since = Number(new URL(request.url).searchParams.get('since') || 0); const rows = (await db.prepare('SELECT m.id, m.body, m.created, m.person, p.name FROM messages m JOIN people p ON p.id=m.person WHERE m.org=? AND m.channel=? AND m.id>? ORDER BY m.id DESC LIMIT 100').bind(p.org, ch, since).all()).results.reverse(); return json({ messages: rows, me: p.id }); } return json({ error: 'not found' }, 404); } catch (e) { return json({ error: e.message || 'Something went wrong.' }, 400); } }