// Paywell customer-rating API (paywell.company/api/rate/*). No accounts, no cookies. // A rating link carries a signed token: base64url(JSON visit) + "." + base64url(HMAC-SHA256 truncated to 12 bytes). // Test mode (default): signs with a public test key, accepts sample links, and records nothing. // Live mode needs PAYWELL_LIVE=1, a secret PAYWELL_LINK_KEY and a D1 binding PAYWELL_DB (see tools/paywell-gen/schema.sql). const TEST_KEY = 'paywell-test-key-not-for-production'; const enc = new TextEncoder(); import { appApi, setSigner } from './paywell-app.js'; const b64u = (bytes) => btoa(String.fromCharCode(...bytes)).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 json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-robots-tag': 'noindex' } }); function live(env) { return env.PAYWELL_LIVE === '1' && env.PAYWELL_LINK_KEY && env.PAYWELL_DB; } async function hmac(env, data) { const key = await crypto.subtle.importKey('raw', enc.encode(live(env) ? env.PAYWELL_LINK_KEY : TEST_KEY), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data))).slice(0, 12); } async function sign(env, visit) { const p = b64u(enc.encode(JSON.stringify(visit))); return p + '.' + b64u(await hmac(env, p)); } async function verify(env, token) { if (typeof token !== 'string' || token.length > 800 || !token.includes('.')) return { error: 'This link doesn’t look right. Check that you copied all of it.' }; const [p, s] = token.split('.'); let good; try { good = await hmac(env, p); } catch { return { error: 'This link doesn’t look right.' }; } let given; try { given = unb64u(s); } catch { return { error: 'This link doesn’t look right.' }; } let diff = given.length ^ good.length; for (let i = 0; i < good.length; i++) diff |= (given[i] | 0) ^ good[i]; if (diff) return { error: 'We couldn’t verify this link. Please use the link from your receipt, text or email.' }; let v; try { v = JSON.parse(new TextDecoder().decode(unb64u(p))); } catch { return { error: 'This link doesn’t look right.' }; } if (!v.v || !v.p) return { error: 'This link doesn’t look right.' }; if (v.x && Date.now() > v.x) return { error: 'This rating link has expired. Links work for 14 days after a visit.', expired: true }; return { visit: v }; } const pub = (v) => ({ brand: v.b || '', service: v.s || '', person: v.p, date: v.d || '', sample: !!v.t }); // Wallet vault (paywell.company/api/vault/*): keeps each person's wallet backup so they never write down recovery words. // The phone encrypts the backup with a key that only their passkey can produce (WebAuthn PRF), so we store a locked box // we cannot open. `auth` is a second value from the same passkey; we keep only its SHA-256, and it is needed to read, // replace or delete the box. Needs only the D1 binding PAYWELL_DB. const B64U = /^[A-Za-z0-9_-]+$/; async function sha(s) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(s)))); } async function vault(request, env, path) { if (!env.PAYWELL_DB) return json({ error: 'Backups are not switched on yet.' }, 503); if (request.method !== 'POST') return json({ error: 'method' }, 405); const db = env.PAYWELL_DB, now = Date.now(); const ipHash = (await sha((request.headers.get('cf-connecting-ip') || '') + (env.PAYWELL_LINK_KEY || TEST_KEY))).slice(0, 16); const hits = await db.prepare('SELECT COUNT(*) AS n FROM vault_hits WHERE ip_hash=? AND at>?').bind(ipHash, now - 6e5).first(); if (hits && hits.n >= 30) return json({ error: 'Too many tries. Wait a few minutes and try again.' }, 429); await db.batch([ db.prepare('INSERT INTO vault_hits (ip_hash, at) VALUES (?,?)').bind(ipHash, now), db.prepare('DELETE FROM vault_hits WHERE at 400 || !B64U.test(auth) || auth.length !== 43) return json({ error: 'bad request' }, 400); const authHash = await sha(auth); const row = await db.prepare('SELECT auth, blob, salt, updated FROM vault WHERE cred=?').bind(cred).first(); const owns = row && row.auth === authHash; if (path === '/api/vault/get') { if (!owns) return json({ error: 'No backup found for this passkey.' }, 404); return json({ blob: row.blob, salt: row.salt, updated: row.updated }); } if (path === '/api/vault/save') { const blob = String(b.blob || ''), salt = String(b.salt || ''); if (!B64U.test(blob) || blob.length > 4096 || !B64U.test(salt) || salt.length > 64) return json({ error: 'bad request' }, 400); if (row && !owns) return json({ error: 'This passkey already has a different backup.' }, 409); await db.prepare('INSERT INTO vault (cred, auth, blob, salt, created, updated) VALUES (?,?,?,?,?,?) ON CONFLICT(cred) DO UPDATE SET blob=excluded.blob, salt=excluded.salt, updated=excluded.updated') .bind(cred, authHash, blob, salt, now, now).run(); return json({ ok: true, updated: now }); } if (path === '/api/vault/delete') { if (!owns) return json({ error: 'No backup found for this passkey.' }, 404); await db.prepare('DELETE FROM vault WHERE cred=?').bind(cred).run(); return json({ ok: true }); } return json({ error: 'not found' }, 404); } export async function paywellApi(request, env, path) { if (path.startsWith('/api/app/') || path.startsWith('/api/chain/')) return appApi(request, env, path); if (path.startsWith('/api/vault/')) return vault(request, env, path); const isLive = !!live(env); if (path === '/api/rate/price') { // USD per BTC, cached at the edge for a minute so pages never call third parties from the browser. 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 }); } if (path === '/api/rate/sample' && request.method === 'GET') { if (isLive) return json({ error: 'not available' }, 404); const d = new Date(); const token = await sign(env, { v: 'sample-' + crypto.randomUUID().slice(0, 8), b: 'Sample visit', s: 'Dog grooming', p: 'Maya', d: d.toISOString().slice(0, 10), x: Date.now() + 14 * 864e5, t: 1 }); return json({ token }); } if (request.method !== 'POST') return json({ error: 'method' }, 405); let body = {}; try { body = await request.json(); } catch {} if (path === '/api/rate/code') { const code = String(body.code || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); if (code.length < 6 || code.length > 16) return json({ error: 'Codes are 8 letters and numbers, like K7Q2-M9XA.' }, 400); if (!isLive) return json({ error: 'Codes from real receipts start working when Paywell opens. Try the sample visit below.' }, 404); const row = await env.PAYWELL_DB.prepare('SELECT token FROM codes WHERE code=?').bind(code).first(); return row ? json({ token: row.token }) : json({ error: 'We couldn’t find that code. Check it and try again.' }, 404); } const r = await verify(env, body.token); if (r.error) return json({ error: r.error, expired: !!r.expired }, 400); const v = r.visit; if (path === '/api/rate/check') { if (isLive || (v.pid && env.PAYWELL_DB)) { const used = await env.PAYWELL_DB.prepare('SELECT 1 FROM ratings WHERE visit=?').bind(v.v).first(); if (used) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409); } return json({ ok: true, visit: pub(v), test: !isLive }); } if (path === '/api/rate/submit') { if (body.website) return json({ ok: true, test: !isLive }); const stars = Number(body.stars); if (!Number.isInteger(stars) || stars < 1 || stars > 5) return json({ error: 'Please pick a rating from 1 to 5.' }, 400); const note = String(body.note || '').slice(0, 1000); const effect = stars >= 4 ? 'bonus' : stars === 3 ? 'none' : 'review'; if (v.pid && env.PAYWELL_DB) { // A visit from a team in the working test app: record it so it counts in that person's score (no money moves). const res = await env.PAYWELL_DB.prepare('INSERT OR IGNORE INTO ratings (visit, brand, person, stars, note, status, ip_hash, created) VALUES (?,?,?,?,?,?,?,?)') .bind(v.v, v.b || '', v.pid, stars, note, effect === 'review' ? 'held' : 'counted', '', Date.now()).run(); if (!res.meta.changes) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409); return json({ ok: true, effect, person: v.p, recorded: true, test: !isLive }); } if (isLive) { const ip = request.headers.get('cf-connecting-ip') || ''; const ipHash = b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(ip + env.PAYWELL_LINK_KEY)))).slice(0, 16); const res = await env.PAYWELL_DB.prepare('INSERT OR IGNORE INTO ratings (visit, brand, person, stars, note, status, ip_hash, created) VALUES (?,?,?,?,?,?,?,?)') .bind(v.v, v.b || '', v.p, stars, note, effect === 'review' ? 'held' : 'counted', ipHash, Date.now()).run(); if (!res.meta.changes) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409); } return json({ ok: true, effect, person: v.p, recorded: isLive, test: !isLive }); } return json({ error: 'not found' }, 404); } setSigner(sign);