Branchwell

Paywell / website · paywell.company / open / src / paywell-api.js.txt

1// Paywell customer-rating API (paywell.company/api/rate/*). No accounts, no cookies.
2// A rating link carries a signed token: base64url(JSON visit) + "." + base64url(HMAC-SHA256 truncated to 12 bytes).
3// Test mode (default): signs with a public test key, accepts sample links, and records nothing.
4// Live mode needs PAYWELL_LIVE=1, a secret PAYWELL_LINK_KEY and a D1 binding PAYWELL_DB (see tools/paywell-gen/schema.sql).
5const TEST_KEY = 'paywell-test-key-not-for-production';
6const enc = new TextEncoder();
7import { appApi, setSigner } from './paywell-app.js';
8const b64u = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
9const unb64u = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0));
10const json = (o, status = 200) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store', 'x-robots-tag': 'noindex' } });
11
12function live(env) { return env.PAYWELL_LIVE === '1' && env.PAYWELL_LINK_KEY && env.PAYWELL_DB; }
13async function hmac(env, data) {
14 const key = await crypto.subtle.importKey('raw', enc.encode(live(env) ? env.PAYWELL_LINK_KEY : TEST_KEY), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
15 return new Uint8Array(await crypto.subtle.sign('HMAC', key, enc.encode(data))).slice(0, 12);
16}
17async function sign(env, visit) {
18 const p = b64u(enc.encode(JSON.stringify(visit)));
19 return p + '.' + b64u(await hmac(env, p));
20}
21async function verify(env, token) {
22 if (typeof token !== 'string' || token.length > 800 || !token.includes('.')) return { error: 'This link doesn’t look right. Check that you copied all of it.' };
23 const [p, s] = token.split('.');
24 let good;
25 try { good = await hmac(env, p); } catch { return { error: 'This link doesn’t look right.' }; }
26 let given;
27 try { given = unb64u(s); } catch { return { error: 'This link doesn’t look right.' }; }
28 let diff = given.length ^ good.length;
29 for (let i = 0; i < good.length; i++) diff |= (given[i] | 0) ^ good[i];
30 if (diff) return { error: 'We couldn’t verify this link. Please use the link from your receipt, text or email.' };
31 let v;
32 try { v = JSON.parse(new TextDecoder().decode(unb64u(p))); } catch { return { error: 'This link doesn’t look right.' }; }
33 if (!v.v || !v.p) return { error: 'This link doesn’t look right.' };
34 if (v.x && Date.now() > v.x) return { error: 'This rating link has expired. Links work for 14 days after a visit.', expired: true };
35 return { visit: v };
36}
37const pub = (v) => ({ brand: v.b || '', service: v.s || '', person: v.p, date: v.d || '', sample: !!v.t });
38
39// Wallet vault (paywell.company/api/vault/*): keeps each person's wallet backup so they never write down recovery words.
40// The phone encrypts the backup with a key that only their passkey can produce (WebAuthn PRF), so we store a locked box
41// we cannot open. `auth` is a second value from the same passkey; we keep only its SHA-256, and it is needed to read,
42// replace or delete the box. Needs only the D1 binding PAYWELL_DB.
43const B64U = /^[A-Za-z0-9_-]+$/;
44async function sha(s) { return b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(s)))); }
45async function vault(request, env, path) {
46 if (!env.PAYWELL_DB) return json({ error: 'Backups are not switched on yet.' }, 503);
47 if (request.method !== 'POST') return json({ error: 'method' }, 405);
48 const db = env.PAYWELL_DB, now = Date.now();
49 const ipHash = (await sha((request.headers.get('cf-connecting-ip') || '') + (env.PAYWELL_LINK_KEY || TEST_KEY))).slice(0, 16);
50 const hits = await db.prepare('SELECT COUNT(*) AS n FROM vault_hits WHERE ip_hash=? AND at>?').bind(ipHash, now - 6e5).first();
51 if (hits && hits.n >= 30) return json({ error: 'Too many tries. Wait a few minutes and try again.' }, 429);
52 await db.batch([
53 db.prepare('INSERT INTO vault_hits (ip_hash, at) VALUES (?,?)').bind(ipHash, now),
54 db.prepare('DELETE FROM vault_hits WHERE at<?').bind(now - 864e5),
55 ]);
56 let b = {};
57 try { b = await request.json(); } catch {}
58 const cred = String(b.cred || ''), auth = String(b.auth || '');
59 if (!B64U.test(cred) || cred.length < 16 || cred.length > 400 || !B64U.test(auth) || auth.length !== 43) return json({ error: 'bad request' }, 400);
60 const authHash = await sha(auth);
61 const row = await db.prepare('SELECT auth, blob, salt, updated FROM vault WHERE cred=?').bind(cred).first();
62 const owns = row && row.auth === authHash;
63 if (path === '/api/vault/get') {
64 if (!owns) return json({ error: 'No backup found for this passkey.' }, 404);
65 return json({ blob: row.blob, salt: row.salt, updated: row.updated });
66 }
67 if (path === '/api/vault/save') {
68 const blob = String(b.blob || ''), salt = String(b.salt || '');
69 if (!B64U.test(blob) || blob.length > 4096 || !B64U.test(salt) || salt.length > 64) return json({ error: 'bad request' }, 400);
70 if (row && !owns) return json({ error: 'This passkey already has a different backup.' }, 409);
71 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')
72 .bind(cred, authHash, blob, salt, now, now).run();
73 return json({ ok: true, updated: now });
74 }
75 if (path === '/api/vault/delete') {
76 if (!owns) return json({ error: 'No backup found for this passkey.' }, 404);
77 await db.prepare('DELETE FROM vault WHERE cred=?').bind(cred).run();
78 return json({ ok: true });
79 }
80 return json({ error: 'not found' }, 404);
81}
82
83export async function paywellApi(request, env, path) {
84 if (path.startsWith('/api/app/') || path.startsWith('/api/chain/')) return appApi(request, env, path);
85 if (path.startsWith('/api/vault/')) return vault(request, env, path);
86 const isLive = !!live(env);
87 if (path === '/api/rate/price') {
88 // USD per BTC, cached at the edge for a minute so pages never call third parties from the browser.
89 const r = await fetch('https://mempool.space/api/v1/prices', { cf: { cacheTtl: 60, cacheEverything: true } }).catch(() => null);
90 const j = r && r.ok ? await r.json().catch(() => null) : null;
91 return json({ usd: j && j.USD ? j.USD : null });
92 }
93 if (path === '/api/rate/sample' && request.method === 'GET') {
94 if (isLive) return json({ error: 'not available' }, 404);
95 const d = new Date();
96 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 });
97 return json({ token });
98 }
99 if (request.method !== 'POST') return json({ error: 'method' }, 405);
100 let body = {};
101 try { body = await request.json(); } catch {}
102 if (path === '/api/rate/code') {
103 const code = String(body.code || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
104 if (code.length < 6 || code.length > 16) return json({ error: 'Codes are 8 letters and numbers, like K7Q2-M9XA.' }, 400);
105 if (!isLive) return json({ error: 'Codes from real receipts start working when Paywell opens. Try the sample visit below.' }, 404);
106 const row = await env.PAYWELL_DB.prepare('SELECT token FROM codes WHERE code=?').bind(code).first();
107 return row ? json({ token: row.token }) : json({ error: 'We couldn’t find that code. Check it and try again.' }, 404);
108 }
109 const r = await verify(env, body.token);
110 if (r.error) return json({ error: r.error, expired: !!r.expired }, 400);
111 const v = r.visit;
112 if (path === '/api/rate/check') {
113 if (isLive || (v.pid && env.PAYWELL_DB)) {
114 const used = await env.PAYWELL_DB.prepare('SELECT 1 FROM ratings WHERE visit=?').bind(v.v).first();
115 if (used) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409);
116 }
117 return json({ ok: true, visit: pub(v), test: !isLive });
118 }
119 if (path === '/api/rate/submit') {
120 if (body.website) return json({ ok: true, test: !isLive });
121 const stars = Number(body.stars);
122 if (!Number.isInteger(stars) || stars < 1 || stars > 5) return json({ error: 'Please pick a rating from 1 to 5.' }, 400);
123 const note = String(body.note || '').slice(0, 1000);
124 const effect = stars >= 4 ? 'bonus' : stars === 3 ? 'none' : 'review';
125 if (v.pid && env.PAYWELL_DB) {
126 // A visit from a team in the working test app: record it so it counts in that person's score (no money moves).
127 const res = await env.PAYWELL_DB.prepare('INSERT OR IGNORE INTO ratings (visit, brand, person, stars, note, status, ip_hash, created) VALUES (?,?,?,?,?,?,?,?)')
128 .bind(v.v, v.b || '', v.pid, stars, note, effect === 'review' ? 'held' : 'counted', '', Date.now()).run();
129 if (!res.meta.changes) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409);
130 return json({ ok: true, effect, person: v.p, recorded: true, test: !isLive });
131 }
132 if (isLive) {
133 const ip = request.headers.get('cf-connecting-ip') || '';
134 const ipHash = b64u(new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode(ip + env.PAYWELL_LINK_KEY)))).slice(0, 16);
135 const res = await env.PAYWELL_DB.prepare('INSERT OR IGNORE INTO ratings (visit, brand, person, stars, note, status, ip_hash, created) VALUES (?,?,?,?,?,?,?,?)')
136 .bind(v.v, v.b || '', v.p, stars, note, effect === 'review' ? 'held' : 'counted', ipHash, Date.now()).run();
137 if (!res.meta.changes) return json({ error: 'This visit has already been rated. Thank you!', used: true }, 409);
138 }
139 return json({ ok: true, effect, person: v.p, recorded: isLive, test: !isLive });
140 }
141 return json({ error: 'not found' }, 404);
142}
143
144setSigner(sign);