Paywell / website · paywell.company / open / src / paywell-app.js.txt
| 1 | // Paywell team app API (paywell.company/api/app/* and /api/chain/*). Open source, public domain. |
| 2 | // |
| 3 | // TEST MODE: everything works for real (passkey accounts, teams, setup links, customer ratings, peer reviews, |
| 4 | // scores, tiers, daily bonus amounts, team chat, a Bitcoin wallet on the signet test network) but no real money |
| 5 | // moves. Daily bonuses are worked out and shown; paying them needs a licensed payroll and custody partner first. |
| 6 | // |
| 7 | // Sign-in is passkeys only (WebAuthn). We store each passkey's public key, never a password. |
| 8 | // Needs the D1 binding PAYWELL_DB (schema: tools/paywell-gen/schema.sql). |
| 9 | |
| 10 | const RP_ID = 'paywell.company'; |
| 11 | const ORIGINS = ['https://paywell.company']; |
| 12 | const TIERS = { 1: { name: 'Explorer', shares: 1 }, 2: { name: 'Builder', shares: 1.5 }, 3: { name: 'Guide', shares: 2 } }; |
| 13 | const START_SCORE = 70; // new team members start here until reviews come in |
| 14 | const TEST_SHARE_CENTS = 1000; // test teams: one bonus share is worth $10 a day (sample value, no money moves) |
| 15 | const WINDOW_DAYS = 28; // score uses the last four weeks of reviews |
| 16 | const ESPLORA = 'https://mempool.space/signet/api'; |
| 17 | const SESSION_DAYS = 30; |
| 18 | |
| 19 | const enc = new TextEncoder(); |
| 20 | 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(/=+$/, ''); }; |
| 21 | const unb64u = (s) => Uint8Array.from(atob(String(s).replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((String(s).length + 3) % 4)), (c) => c.charCodeAt(0)); |
| 22 | 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 } }); |
| 23 | const rid = (n = 16) => b64u(crypto.getRandomValues(new Uint8Array(n))); |
| 24 | const sha256 = async (data) => new Uint8Array(await crypto.subtle.digest('SHA-256', typeof data === 'string' ? enc.encode(data) : data)); |
| 25 | const day = (t) => new Date(t).toISOString().slice(0, 10); |
| 26 | const clean = (s, n) => String(s || '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, n); |
| 27 | |
| 28 | let signVisit = null; // rating-link signer, shared with the rating API |
| 29 | export function setSigner(fn) { signVisit = fn; } |
| 30 | |
| 31 | // ---------- Minimal CBOR (enough for WebAuthn attestation objects and COSE keys) ---------- |
| 32 | function cbor(buf) { |
| 33 | let i = 0; |
| 34 | const u8 = buf; |
| 35 | const len = (ai) => { |
| 36 | if (ai < 24) return ai; |
| 37 | if (ai === 24) return u8[i++]; |
| 38 | if (ai === 25) { const v = (u8[i] << 8) | u8[i + 1]; i += 2; return v; } |
| 39 | if (ai === 26) { const v = ((u8[i] << 24) >>> 0) + ((u8[i + 1] << 16) | (u8[i + 2] << 8) | u8[i + 3]); i += 4; return v; } |
| 40 | throw new Error('cbor length'); |
| 41 | }; |
| 42 | const item = () => { |
| 43 | const b = u8[i++], mt = b >> 5, ai = b & 31; |
| 44 | if (mt === 0) return len(ai); |
| 45 | if (mt === 1) return -1 - len(ai); |
| 46 | if (mt === 2) { const n = len(ai); const v = u8.slice(i, i + n); i += n; return v; } |
| 47 | if (mt === 3) { const n = len(ai); const v = new TextDecoder().decode(u8.slice(i, i + n)); i += n; return v; } |
| 48 | if (mt === 4) { const n = len(ai); const a = []; for (let k = 0; k < n; k++) a.push(item()); return a; } |
| 49 | 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; } |
| 50 | if (mt === 7) { if (ai === 20) return false; if (ai === 21) return true; if (ai === 22) return null; } |
| 51 | throw new Error('cbor type'); |
| 52 | }; |
| 53 | const v = item(); |
| 54 | return { value: v, end: i }; |
| 55 | } |
| 56 | |
| 57 | // ---------- WebAuthn ---------- |
| 58 | function parseAuthData(ad) { |
| 59 | const flags = ad[32]; |
| 60 | const out = { rpIdHash: ad.slice(0, 32), up: !!(flags & 1), uv: !!(flags & 4), counter: new DataView(ad.buffer, ad.byteOffset + 33, 4).getUint32(0) }; |
| 61 | if (flags & 64) { |
| 62 | const credLen = (ad[53] << 8) | ad[54]; |
| 63 | out.credId = ad.slice(55, 55 + credLen); |
| 64 | const rest = ad.slice(55 + credLen); |
| 65 | out.cose = cbor(rest).value; |
| 66 | } |
| 67 | return out; |
| 68 | } |
| 69 | function coseToJwk(m) { |
| 70 | const kty = m.get(1), alg = m.get(3); |
| 71 | if (kty === 2 && alg === -7) return { kty: 'EC', crv: 'P-256', x: b64u(m.get(-2)), y: b64u(m.get(-3)), alg: 'ES256' }; |
| 72 | if (kty === 3 && alg === -257) return { kty: 'RSA', n: b64u(m.get(-1)), e: b64u(m.get(-2)), alg: 'RS256' }; |
| 73 | throw new Error('Unsupported passkey type'); |
| 74 | } |
| 75 | function derToRaw(der) { // ECDSA DER signature -> 64-byte r||s |
| 76 | let i = 2; if (der[1] & 0x80) i = 2 + (der[1] & 0x7f); |
| 77 | 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; }; |
| 78 | const r = read(), s = read(); const out = new Uint8Array(64); out.set(r); out.set(s, 32); return out; |
| 79 | } |
| 80 | async function checkClientData(db, cdj, type, request) { |
| 81 | const cd = JSON.parse(new TextDecoder().decode(unb64u(cdj))); |
| 82 | if (cd.type !== type) throw new Error('Wrong passkey step'); |
| 83 | const origin = new URL(request.url).origin; |
| 84 | if (!ORIGINS.includes(cd.origin) && cd.origin !== origin) throw new Error('Wrong website'); |
| 85 | const row = await db.prepare('SELECT exp FROM chal WHERE id=?').bind(cd.challenge).first(); |
| 86 | if (!row || row.exp < Date.now()) throw new Error('This sign-in took too long. Try again.'); |
| 87 | await db.prepare('DELETE FROM chal WHERE id=? OR exp<?').bind(cd.challenge, Date.now()).run(); |
| 88 | return cd; |
| 89 | } |
| 90 | async function verifyAssertion(db, c, request) { |
| 91 | await checkClientData(db, c.clientDataJSON, 'webauthn.get', request); |
| 92 | const cred = await db.prepare('SELECT * FROM creds WHERE id=?').bind(c.id).first(); |
| 93 | if (!cred) throw new Error('We don’t know this passkey. Use your setup link first.'); |
| 94 | const ad = unb64u(c.authenticatorData); |
| 95 | const a = parseAuthData(ad); |
| 96 | if (b64u(a.rpIdHash) !== b64u(await sha256(RP_ID))) throw new Error('Wrong website'); |
| 97 | if (!a.up || !a.uv) throw new Error('Face, fingerprint or screen lock is needed.'); |
| 98 | const jwk = JSON.parse(cred.jwk); |
| 99 | const data = new Uint8Array(ad.length + 32); data.set(ad); data.set(await sha256(unb64u(c.clientDataJSON)), ad.length); |
| 100 | let ok; |
| 101 | if (jwk.kty === 'EC') { |
| 102 | const key = await crypto.subtle.importKey('jwk', jwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify']); |
| 103 | ok = await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, derToRaw(unb64u(c.signature)), data); |
| 104 | } else { |
| 105 | const key = await crypto.subtle.importKey('jwk', jwk, { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }, false, ['verify']); |
| 106 | ok = await crypto.subtle.verify('RSASSA-PKCS1-v1_5', key, unb64u(c.signature), data); |
| 107 | } |
| 108 | if (!ok) throw new Error('Passkey check failed.'); |
| 109 | await db.prepare('UPDATE creds SET counter=?, used=? WHERE id=?').bind(a.counter, Date.now(), c.id).run(); |
| 110 | return cred.person; |
| 111 | } |
| 112 | |
| 113 | // ---------- Sessions ---------- |
| 114 | function cookie(request, name) { |
| 115 | const m = (request.headers.get('cookie') || '').match(new RegExp('(?:^|; )' + name + '=([^;]+)')); |
| 116 | return m ? m[1] : null; |
| 117 | } |
| 118 | async function startSession(db, person) { |
| 119 | const token = rid(24); |
| 120 | await db.prepare('INSERT INTO sessions (hash, person, exp) VALUES (?,?,?)').bind(b64u(await sha256(token)), person, Date.now() + SESSION_DAYS * 864e5).run(); |
| 121 | return `pw_s=${token}; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=${SESSION_DAYS * 86400}`; |
| 122 | } |
| 123 | async function me(db, request) { |
| 124 | const t = cookie(request, 'pw_s'); |
| 125 | if (!t) return null; |
| 126 | const row = await db.prepare('SELECT p.* FROM sessions s JOIN people p ON p.id=s.person WHERE s.hash=? AND s.exp>?').bind(b64u(await sha256(t)), Date.now()).first(); |
| 127 | return row || null; |
| 128 | } |
| 129 | |
| 130 | // ---------- Scores and daily bonuses ---------- |
| 131 | const to100 = (avg) => Math.round(((avg - 1) / 4) * 100); |
| 132 | async function scoreAt(db, person, until) { |
| 133 | const from = until - WINDOW_DAYS * 864e5; |
| 134 | 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(); |
| 135 | const p = await db.prepare('SELECT AVG(stars) a, COUNT(*) n FROM peer WHERE target=? AND created>? AND created<=?').bind(person, from, until).first(); |
| 136 | const cs = c.n ? to100(c.a) : null, ps = p.n ? to100(p.a) : null; |
| 137 | let score = START_SCORE; |
| 138 | if (cs !== null && ps !== null) score = Math.round(cs * 0.6 + ps * 0.4); |
| 139 | else if (cs !== null) score = cs; else if (ps !== null) score = ps; |
| 140 | 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 }; |
| 141 | } |
| 142 | const bonusCents = (share, tier, score) => Math.round(share * TIERS[tier].shares * score / 100); |
| 143 | |
| 144 | async function summary(db, person) { |
| 145 | const org = await db.prepare('SELECT * FROM orgs WHERE id=?').bind(person.org).first(); |
| 146 | const now = Date.now(); |
| 147 | const s = await scoreAt(db, person.id, now); |
| 148 | const days = []; |
| 149 | const joined = new Date(day(person.created) + 'T00:00:00Z').getTime(); |
| 150 | for (let k = 0; k < 14; k++) { |
| 151 | const end = new Date(day(now) + 'T00:00:00Z').getTime() - k * 864e5; // end of the previous day |
| 152 | if (end <= joined) break; |
| 153 | const sc = (await scoreAt(db, person.id, end)).score; |
| 154 | days.push({ day: day(end - 1), score: sc, tier: person.tier, cents: bonusCents(org.share_cents, person.tier, sc) }); |
| 155 | } |
| 156 | const team = (await db.prepare('SELECT id, name, tier, admin FROM people WHERE org=? ORDER BY created').bind(person.org).all()).results; |
| 157 | const today = day(now); |
| 158 | const reviewed = (await db.prepare('SELECT target FROM peer WHERE author=? AND day=?').bind(person.id, today).all()).results.map((r) => r.target); |
| 159 | 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; |
| 160 | const peers = (await db.prepare('SELECT stars, note, day FROM peer WHERE target=? ORDER BY created DESC LIMIT 30').bind(person.id).all()).results; |
| 161 | return { |
| 162 | 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 }, |
| 163 | org: { name: org.name, shareCents: org.share_cents, test: true }, |
| 164 | score: s, todayCents: bonusCents(org.share_cents, person.tier, s.score), days, team, reviewedToday: reviewed, ratings, peers, |
| 165 | tiers: TIERS, |
| 166 | }; |
| 167 | } |
| 168 | |
| 169 | // ---------- Rate limit ---------- |
| 170 | async function limited(db, request, key, max, windowMs) { |
| 171 | const ip = request.headers.get('cf-connecting-ip') || ''; |
| 172 | const h = b64u(await sha256(ip + '|' + key)).slice(0, 16), now = Date.now(); |
| 173 | const r = await db.prepare('SELECT COUNT(*) n FROM vault_hits WHERE ip_hash=? AND at>?').bind(h, now - windowMs).first(); |
| 174 | if (r && r.n >= max) return true; |
| 175 | await db.prepare('INSERT INTO vault_hits (ip_hash, at) VALUES (?,?)').bind(h, now).run(); |
| 176 | return false; |
| 177 | } |
| 178 | |
| 179 | // ---------- Chain proxy (signet test network): the browser never calls third parties directly ---------- |
| 180 | async function chain(request, path) { |
| 181 | const sub = path.slice('/api/chain/'.length); |
| 182 | if (request.method === 'POST' && sub === 'tx') { |
| 183 | const hex = (await request.text()).trim(); |
| 184 | if (!/^[0-9a-f]{100,200000}$/i.test(hex)) return json({ error: 'bad transaction' }, 400); |
| 185 | const r = await fetch(ESPLORA + '/tx', { method: 'POST', body: hex }); |
| 186 | const t = await r.text(); |
| 187 | return r.ok ? json({ txid: t }) : json({ error: t.slice(0, 300) }, 400); |
| 188 | } |
| 189 | let target = null; |
| 190 | if (sub === 'fees') target = '/fee-estimates'; |
| 191 | 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 }); } |
| 192 | else { const m = sub.match(/^address\/((?:tb1|bc1)[0-9a-z]{20,90})\/(utxo|txs)$/); if (m) target = `/address/${m[1]}/${m[2]}`; } |
| 193 | if (!target) return json({ error: 'not found' }, 404); |
| 194 | const r = await fetch(ESPLORA + target, { cf: { cacheTtl: 10, cacheEverything: true } }); |
| 195 | return new Response(await r.text(), { status: r.status, headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }); |
| 196 | } |
| 197 | |
| 198 | // ---------- Routes ---------- |
| 199 | export async function appApi(request, env, path) { |
| 200 | if (path.startsWith('/api/chain/')) return chain(request, path); |
| 201 | const db = env.PAYWELL_DB; |
| 202 | if (!db) return json({ error: 'The app isn’t switched on yet.' }, 503); |
| 203 | const method = request.method; |
| 204 | let b = {}; |
| 205 | if (method === 'POST') { try { b = await request.json(); } catch {} } |
| 206 | try { |
| 207 | // A fresh challenge for any passkey step (5 minutes). |
| 208 | if (path === '/api/app/challenge' && method === 'POST') { |
| 209 | if (await limited(db, request, 'chal', 60, 6e5)) return json({ error: 'Too many tries. Wait a few minutes.' }, 429); |
| 210 | const id = rid(32); |
| 211 | await db.prepare('INSERT INTO chal (id, exp) VALUES (?,?)').bind(id, Date.now() + 3e5).run(); |
| 212 | return json({ challenge: id, rpId: RP_ID }); |
| 213 | } |
| 214 | // What a setup link is for (team name, the person's name). |
| 215 | if (path === '/api/app/setup' && method === 'POST') { |
| 216 | 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(); |
| 217 | 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); |
| 218 | return json({ name: row.name, team: row.team }); |
| 219 | } |
| 220 | // Create an account with a new passkey: either start a test team, or join one with a setup link. |
| 221 | if (path === '/api/app/register' && method === 'POST') { |
| 222 | if (await limited(db, request, 'reg', 20, 36e5)) return json({ error: 'Too many new accounts from here. Try again later.' }, 429); |
| 223 | const c = b.credential || {}; |
| 224 | await checkClientData(db, c.clientDataJSON, 'webauthn.create', request); |
| 225 | const att = cbor(unb64u(c.attestationObject)).value; |
| 226 | const a = parseAuthData(att.get('authData')); |
| 227 | if (b64u(a.rpIdHash) !== b64u(await sha256(RP_ID))) throw new Error('Wrong website'); |
| 228 | if (!a.up || !a.uv) throw new Error('Face, fingerprint or screen lock is needed.'); |
| 229 | const jwk = coseToJwk(a.cose); |
| 230 | const credId = b64u(a.credId); |
| 231 | let org, name, tier = 1, admin = 0, setupToken = null; |
| 232 | if (b.setup) { |
| 233 | setupToken = clean(b.setup, 64); |
| 234 | const s = await db.prepare('SELECT * FROM setup WHERE token=?').bind(setupToken).first(); |
| 235 | if (!s || s.used || s.exp < Date.now()) throw new Error('This setup link has expired or was already used.'); |
| 236 | org = s.org; name = s.name; tier = s.tier; |
| 237 | } else { |
| 238 | const team = clean(b.team, 60); name = clean(b.name, 40); |
| 239 | if (!team || !name) throw new Error('Add your name and a team name.'); |
| 240 | org = rid(9); |
| 241 | await db.prepare('INSERT INTO orgs (id, name, share_cents, created) VALUES (?,?,?,?)').bind(org, team, TEST_SHARE_CENTS, Date.now()).run(); |
| 242 | tier = 3; admin = 1; // whoever starts a team guides it |
| 243 | } |
| 244 | const person = rid(9), now = Date.now(); |
| 245 | const stmts = [ |
| 246 | 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), |
| 247 | db.prepare('INSERT INTO creds (id, person, jwk, counter, created, used) VALUES (?,?,?,?,?,?)').bind(credId, person, JSON.stringify(jwk), a.counter, now, now), |
| 248 | ]; |
| 249 | if (setupToken) stmts.push(db.prepare('UPDATE setup SET used=? WHERE token=?').bind(now, setupToken)); |
| 250 | await db.batch(stmts); |
| 251 | return json({ ok: true, credId }, 200, { 'set-cookie': await startSession(db, person) }); |
| 252 | } |
| 253 | if (path === '/api/app/login' && method === 'POST') { |
| 254 | if (await limited(db, request, 'login', 40, 6e5)) return json({ error: 'Too many tries. Wait a few minutes.' }, 429); |
| 255 | const person = await verifyAssertion(db, b.credential || {}, request); |
| 256 | return json({ ok: true }, 200, { 'set-cookie': await startSession(db, person) }); |
| 257 | } |
| 258 | if (path === '/api/app/logout' && method === 'POST') { |
| 259 | const t = cookie(request, 'pw_s'); |
| 260 | if (t) await db.prepare('DELETE FROM sessions WHERE hash=?').bind(b64u(await sha256(t))).run(); |
| 261 | return json({ ok: true }, 200, { 'set-cookie': 'pw_s=; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=0' }); |
| 262 | } |
| 263 | |
| 264 | // Everything below needs a signed-in person. |
| 265 | const p = await me(db, request); |
| 266 | if (!p) return json({ error: 'signed out' }, 401); |
| 267 | |
| 268 | if (path === '/api/app/me' && method === 'GET') return json(await summary(db, p)); |
| 269 | |
| 270 | // Where the daily bonus goes. Changing it needs a fresh passkey check. |
| 271 | if (path === '/api/app/payout' && method === 'POST') { |
| 272 | const mode = b.mode === 'own' ? 'own' : 'paywell'; |
| 273 | const addr = clean(b.addr, 100); |
| 274 | 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.'); |
| 275 | if (mode === 'own' || p.payout_mode === 'own') { |
| 276 | const who = await verifyAssertion(db, b.credential || {}, request); |
| 277 | if (who !== p.id) throw new Error('Use your own passkey.'); |
| 278 | } |
| 279 | 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(); |
| 280 | return json({ ok: true }); |
| 281 | } |
| 282 | // The wallet's first receive address, so the team can see where bonuses go. |
| 283 | if (path === '/api/app/wallet-address' && method === 'POST') { |
| 284 | if (p.payout_mode !== 'paywell') return json({ ok: true }); |
| 285 | const addr = clean(b.addr, 100); |
| 286 | if (!/^tb1[02-9ac-hj-np-z]{20,90}$/.test(addr)) throw new Error('bad address'); |
| 287 | await db.prepare('UPDATE people SET payout_addr=? WHERE id=?').bind(addr, p.id).run(); |
| 288 | return json({ ok: true }); |
| 289 | } |
| 290 | // A one-time setup link for a new teammate (only the team's guide in test mode). |
| 291 | if (path === '/api/app/invite' && method === 'POST') { |
| 292 | if (!p.admin) throw new Error('Only the person who started the team can add people.'); |
| 293 | const name = clean(b.name, 40); const tier = [1, 2, 3].includes(Number(b.tier)) ? Number(b.tier) : 1; |
| 294 | if (!name) throw new Error('Add their first name.'); |
| 295 | const n = await db.prepare('SELECT COUNT(*) n FROM people WHERE org=?').bind(p.org).first(); |
| 296 | if (n.n >= 50) throw new Error('Test teams can have up to 50 people.'); |
| 297 | const token = rid(18); |
| 298 | 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(); |
| 299 | return json({ url: 'https://paywell.company/app/#setup=' + token, expires: Date.now() + 864e5 }); |
| 300 | } |
| 301 | // Change a teammate's tier (the team's guide; written notice is the live rule). |
| 302 | if (path === '/api/app/tier' && method === 'POST') { |
| 303 | if (!p.admin) throw new Error('Only the person who started the team can change tiers.'); |
| 304 | const tier = Number(b.tier); if (![1, 2, 3].includes(tier)) throw new Error('Pick a tier.'); |
| 305 | await db.prepare('UPDATE people SET tier=? WHERE id=? AND org=?').bind(tier, clean(b.person, 20), p.org).run(); |
| 306 | return json({ ok: true }); |
| 307 | } |
| 308 | // A customer rating link for a visit you just did (in live mode this comes from the shop's checkout). |
| 309 | if (path === '/api/app/visit' && method === 'POST') { |
| 310 | if (await limited(db, request, 'visit:' + p.id, 60, 36e5)) throw new Error('That’s a lot of visits. Try again later.'); |
| 311 | const org = await db.prepare('SELECT name FROM orgs WHERE id=?').bind(p.org).first(); |
| 312 | const service = clean(b.service, 60) || 'Visit'; |
| 313 | 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 }); |
| 314 | return json({ url: 'https://paywell.company/r/' + token }); |
| 315 | } |
| 316 | // Peer review: one per teammate per day, never yourself, kept private from the person reviewed. |
| 317 | if (path === '/api/app/peer' && method === 'POST') { |
| 318 | const target = clean(b.person, 20), stars = Number(b.stars); |
| 319 | if (target === p.id) throw new Error('You can’t review yourself.'); |
| 320 | if (!Number.isInteger(stars) || stars < 1 || stars > 5) throw new Error('Pick 1 to 5 stars.'); |
| 321 | const t = await db.prepare('SELECT id FROM people WHERE id=? AND org=?').bind(target, p.org).first(); |
| 322 | if (!t) throw new Error('They’re not on your team.'); |
| 323 | 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(); |
| 324 | if (!r.meta.changes) throw new Error('You already reviewed them today.'); |
| 325 | return json({ ok: true }); |
| 326 | } |
| 327 | // Team chat: channels per team, newest 100 messages, polled by the app. |
| 328 | if (path === '/api/app/chat') { |
| 329 | 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'; |
| 330 | if (method === 'POST') { |
| 331 | const body = clean(b.body, 1000); if (!body) throw new Error('Write something first.'); |
| 332 | if (await limited(db, request, 'chat:' + p.id, 120, 6e5)) throw new Error('Slow down a little.'); |
| 333 | await db.prepare('INSERT INTO messages (org, channel, person, body, created) VALUES (?,?,?,?,?)').bind(p.org, ch, p.id, body, Date.now()).run(); |
| 334 | } |
| 335 | const since = Number(new URL(request.url).searchParams.get('since') || 0); |
| 336 | 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(); |
| 337 | return json({ messages: rows, me: p.id }); |
| 338 | } |
| 339 | return json({ error: 'not found' }, 404); |
| 340 | } catch (e) { |
| 341 | return json({ error: e.message || 'Something went wrong.' }, 400); |
| 342 | } |
| 343 | } |