diff --git a/.gitignore b/.gitignore index f00cb92..8a675a1 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ dist/ .DS_Store .cache/ .wrangler/ +service/wrangler.production.jsonc diff --git a/package-lock.json b/package-lock.json index ffe332b..9361ffd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,7 +25,7 @@ "vitest": "5.0.3" }, "engines": { - "node": ">=22" + "node": ">=22.13" } }, "node_modules/@astrojs/astro2tsx": { diff --git a/package.json b/package.json index 36da59d..434f967 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "license": "MIT", "type": "module", "engines": { - "node": ">=22" + "node": ">=22.13" }, "scripts": { "dev": "astro dev", diff --git a/service/README.md b/service/README.md new file mode 100644 index 0000000..322dcd7 --- /dev/null +++ b/service/README.md @@ -0,0 +1,38 @@ +# Contributions service + +Receives the guided forms (ADR 0003). It checks each contribution, keeps it +for a maintainer and erases e-mails 30 days after a decision, 180 days after +they came at most. It never publishes anything, and the site works without it. + +The maintainer reads, corrects and decides in the review space, behind +Cloudflare Access. The service checks the Access token again by itself, and +admits one e-mail. Sending to check opens a public issue, without the e-mail. + +No personal data enters this repository. Secrets are set at deployment. + +## Run it locally + +``` +PUBLIC_TURNSTILE_SITE_KEY=1x00000000000000000000AA npm run build +cp -R service/assets/review dist/review +npx wrangler@4 d1 migrations apply paymap-local --local -c service/wrangler.local.jsonc +npx wrangler@4 dev -c service/wrangler.local.jsonc --port 4399 +``` + +The forms are on `localhost:4399`, the review space on +`review.localhost:4399`. The local entry, `worker.local.ts`, opens it without +Access and invents issues: never deploy it. + +The key above is Turnstile's public test key. A build without a key shows the +forms but cannot send them, so a deployed build always sets it. + +The service checks answers with the same rules as the forms. When a rule or a +list changes, deploy the service first, then the site. + +## Before deploying + +Create the Access application for `review.paymap.africa` first, then fill +`ACCESS_TEAM` (`https://.cloudflareaccess.com`, no final slash) and +`ACCESS_AUD` in `wrangler.production.jsonc`, an unversioned copy of +`wrangler.jsonc` that also names the database. Always deploy with that copy. Secrets: `TURNSTILE_SECRET`, `SENDER_KEY`, +`REVIEWER` (the admitted e-mail) and `GITHUB_TOKEN` (issues of this repository). diff --git a/service/assets/review/hanken-grotesk-latin-400-normal.woff2 b/service/assets/review/hanken-grotesk-latin-400-normal.woff2 new file mode 100644 index 0000000..e4b074d Binary files /dev/null and b/service/assets/review/hanken-grotesk-latin-400-normal.woff2 differ diff --git a/service/assets/review/hanken-grotesk-latin-600-normal.woff2 b/service/assets/review/hanken-grotesk-latin-600-normal.woff2 new file mode 100644 index 0000000..0b3c5e7 Binary files /dev/null and b/service/assets/review/hanken-grotesk-latin-600-normal.woff2 differ diff --git a/service/assets/review/newsreader-latin-500-normal.woff2 b/service/assets/review/newsreader-latin-500-normal.woff2 new file mode 100644 index 0000000..a84e016 Binary files /dev/null and b/service/assets/review/newsreader-latin-500-normal.woff2 differ diff --git a/service/assets/review/review.css b/service/assets/review/review.css new file mode 100644 index 0000000..e8657f2 --- /dev/null +++ b/service/assets/review/review.css @@ -0,0 +1,176 @@ +@font-face { font-family: Newsreader; font-weight: 500; src: url(newsreader-latin-500-normal.woff2) format('woff2'); font-display: swap; } +@font-face { font-family: Hanken; font-weight: 400; src: url(hanken-grotesk-latin-400-normal.woff2) format('woff2'); font-display: swap; } +@font-face { font-family: Hanken; font-weight: 600; src: url(hanken-grotesk-latin-600-normal.woff2) format('woff2'); font-display: swap; } +:root { --sable: #f6f1e7; --creux: #efe8da; --surface: #fffcf6; --ink: #14110f; --ink-2: #5e574c; --lagune: #0e6b66; --lagune-50: #e2eeeb; --safran: #f2b33d; --safran-50: #f8ebc9; --safran-text: #7a4f00; --ok: #2e6b1f; --ok-deep: #235417; --ok-bg: #e3eed8; --bad: #9a2f1f; --bad-bg: #f6e1da; --shadow: 0 1px 2px rgba(20, 17, 15, .05), 0 6px 16px rgba(20, 17, 15, .07); --display: Newsreader, Georgia, serif; --ui: Hanken, system-ui, sans-serif; } +* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } +[hidden] { display: none !important; } +body { margin: 0; background: var(--sable); color: var(--ink); font: 16px/1.45 var(--ui); -webkit-font-smoothing: antialiased; } +:focus-visible { outline: 2px solid var(--lagune); outline-offset: 2px; } +.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; } +h1, h2, strong, .v, .big .in { font-family: var(--display); font-weight: 500; } +h1, h2, p, ul, ol, fieldset { margin: 0; padding: 0; border: 0; } +ul, ol { list-style: none; } +i { font-family: Arial, sans-serif; font-style: normal; } +a { color: var(--lagune); } +.ic { flex: none; width: 18px; height: 18px; } +.bar, main { width: 100%; max-width: 1312px; margin: 0 auto; padding: 0 32px; } +.bar { display: flex; align-items: center; gap: 14px; padding-top: 22px; padding-bottom: 22px; } +.brand { display: inline-flex; align-items: center; gap: 12px; font: 500 26px/1.5 var(--display); color: var(--ink); text-decoration: none; } +.brand em { font-style: normal; color: var(--lagune); } +.mark { position: relative; width: 34px; height: 34px; border-radius: 10px; background: var(--lagune); } +.mark::after { content: ''; position: absolute; right: 6px; top: 7px; width: 8px; height: 8px; border-radius: 50%; background: var(--safran); } +.tag { display: inline-flex; align-items: center; gap: 7px; min-height: 30px; padding: 0 13px; border-radius: 999px; background: var(--safran-50); color: var(--safran-text); font-size: 13px; font-weight: 600; } +.tag .ic { width: 15px; height: 15px; } +.out { margin-left: auto; display: inline-flex; align-items: center; min-height: 44px; font-size: 14px; font-weight: 600; color: var(--ink-2); text-decoration: none; } +main { display: flex; flex-direction: column; gap: 24px; padding-bottom: 80px; } +.head { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; flex-wrap: wrap; } +.head h1 { font-size: 56px; line-height: 1.02; letter-spacing: -.025em; } +.tabs { display: flex; gap: 4px; padding: 5px; border-radius: 999px; background: var(--creux); } +.tabs a { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 0 18px; border-radius: 999px; font-size: 15px; font-weight: 600; color: var(--ink-2); text-decoration: none; } +.tabs .on { background: var(--surface); box-shadow: var(--shadow); color: var(--ink); } +.list, .main { display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.item, .card .top { display: grid; align-items: center; gap: 18px; } +.item { grid-template-columns: 54px minmax(0, 1.2fr) minmax(0, 1fr) 190px 20px; padding: 16px 22px 16px 16px; border-radius: 22px; background: var(--surface); box-shadow: var(--shadow); color: var(--ink); text-decoration: none; } +.item:hover { background: #fff; } +.m { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; overflow-wrap: anywhere; } +.m strong { font-size: 24px; line-height: 1.1; } +.s { font-size: 14px; color: var(--ink-2); } +.v { font-size: 21px; line-height: 1.2; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow-wrap: anywhere; } +.v s, .tile s { color: var(--ink-2); } +.v b { font-weight: 500; color: var(--ok); } +.w { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; font-size: 14px; color: var(--ink-2); } +.item > i { color: var(--lagune); } +.chip { padding: 3px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; } +.chip.ok { background: var(--ok-bg); color: var(--ok); } +.logo-box { display: grid; place-items: center; flex: none; width: 54px; height: 54px; border-radius: 17px; overflow: hidden; background: #fff; } +.logo-box img { width: 100%; height: 100%; object-fit: contain; } +.letter { background: #fff; color: var(--lagune); font: 500 26px/1 var(--display); } +.card { display: flex; flex-direction: column; gap: 16px; padding: 20px 24px; border-radius: 24px; background: var(--surface); box-shadow: var(--shadow); } +.card .top { grid-template-columns: 54px minmax(0, 1.2fr) minmax(0, 1fr) auto; } +.foot { display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; } +.track { display: flex; gap: 8px; } +.track li { flex: 1; display: flex; align-items: center; gap: 9px; padding: 10px 14px; border-radius: 14px; background: var(--creux); font-size: 14px; font-weight: 600; color: var(--ink-2); } +.track .past { background: var(--ok-bg); color: var(--ok); } +.track .on { background: var(--safran-50); color: var(--safran-text); } +.track .bad { background: var(--bad-bg); color: var(--bad); } +.open { display: inline-flex; align-items: center; gap: 7px; flex: none; min-height: 44px; font-size: 14px; font-weight: 600; text-decoration: none; white-space: nowrap; } +.opens { display: flex; flex-direction: column; } +.back { display: inline-flex; align-items: center; gap: 9px; align-self: flex-start; min-height: 44px; margin-bottom: -10px; font-size: 15px; font-weight: 600; color: var(--ink-2); text-decoration: none; } +.notice { display: flex; align-items: center; gap: 12px; padding: 12px 20px; min-height: 56px; border-radius: 18px; } +.notice a { display: inline-flex; gap: 7px; align-items: center; min-height: 44px; margin-left: auto; color: inherit; font-weight: 600; white-space: nowrap; text-decoration: none; } +.notice.ok { background: var(--ok-bg); color: var(--ok); } +.notice.bad { background: var(--bad-bg); color: var(--bad); } +.grid { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 28px; align-items: start; } +.hero { display: flex; flex-direction: column; gap: 22px; padding: 26px; border-radius: 26px; background: var(--lagune-50); } +.hero .top { display: flex; align-items: center; gap: 16px; } +.hero h1 { font-size: 32px; line-height: 1.05; } +.tiles { display: flex; align-items: stretch; gap: 16px; } +.tiles > i { align-self: center; } +.tile { flex: 1 1 0; display: flex; flex-direction: column; gap: 6px; min-width: 0; padding: 18px 20px; border-radius: 20px; background: var(--surface); } +.tile.old s { font: 500 40px/1.15 var(--display); overflow-wrap: anywhere; } +.tile.new { background: var(--ok); color: #fff; transition: box-shadow .15s; } +.tile.new:focus-within { box-shadow: 0 0 0 3px var(--surface), 0 0 0 5px var(--ok); } +.tile.new .cap, .tile.new .was, .tile.new s { color: #dcebd2; } +.tile.new .was button { color: #fff; } +.cap { font-size: 13px; color: var(--ink-2); } +.in { width: 100%; min-width: 0; margin: 0; padding: 0; border: 0; outline: 0; background: none; color: inherit; font: 600 16px/1.4 var(--ui); resize: none; field-sizing: content; overflow-wrap: anywhere; } +select.in { appearance: none; cursor: pointer; } +.big { display: flex; align-items: center; gap: 12px; } +.big .in { font-size: 40px; line-height: 1.15; cursor: text; } +.big .in.long { font-size: 23px; line-height: 1.3; } +.big .ic { opacity: .75; } +.title-field .big .in { font-size: 32px; border-radius: 10px; } +.title-field:focus-within .big { box-shadow: 0 2px 0 var(--lagune); } +.row { display: flex; align-items: center; gap: 15px; min-height: 76px; padding: 12px 14px 12px 18px; border-radius: 20px; background: var(--surface); box-shadow: var(--shadow); min-width: 0; transition: box-shadow .15s; } +.row[data-edit]:hover .pen { background: var(--creux); color: var(--ink); } +.row:focus-within:has(.in:focus) { box-shadow: 0 0 0 2px var(--lagune), var(--shadow); } +.row .m { gap: 2px; } +.row .m b { font-weight: 600; } +.row.changed { box-shadow: inset 4px 0 0 var(--ok), var(--shadow); } +.row.changed:has(.in:focus) { box-shadow: 0 0 0 2px var(--ok), var(--shadow); } +.two { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +.disc { display: grid; place-items: center; flex: none; width: 40px; height: 40px; border-radius: 50%; } +.pen { display: grid; place-items: center; flex: none; width: 44px; height: 44px; border-radius: 14px; color: var(--ink-2); cursor: pointer; transition: background .15s; } +.was { display: flex; align-items: center; flex-wrap: wrap; gap: 4px 8px; font-size: 13px; color: var(--ok); } +.was button { display: inline-flex; align-items: center; gap: 5px; min-height: 44px; margin: -10px 0; padding: 0 6px; border: 0; background: none; font: 600 13px var(--ui); color: var(--ok); cursor: pointer; } +.was .ic { width: 15px; height: 15px; } +.group { display: flex; flex-direction: column; gap: 10px; } +.group legend { margin-bottom: 10px; } +.pills { display: flex; flex-wrap: wrap; gap: 8px; } +.pill { display: inline-flex; align-items: center; gap: 9px; min-height: 44px; padding: 0 15px; border-radius: 999px; background: none; box-shadow: inset 0 0 0 1.5px #bcd2cd; font-size: 15px; font-weight: 600; color: var(--ink-2); cursor: pointer; } +.pill input { position: absolute; opacity: 0; } +.pill img { border-radius: 50%; margin-left: -5px; } +.pill:not(:has(:checked)) img { filter: grayscale(1); opacity: .6; } +.pill:has(:checked) { background: var(--surface); box-shadow: var(--shadow); color: var(--ink); } +.pill:has(:checked)::after { content: '✓'; color: var(--ok); font-weight: 600; } +.pill:has(:focus-visible) { outline: 2px solid var(--lagune); outline-offset: 2px; } +.add { appearance: none; min-height: 44px; max-width: 170px; padding: 0 10px; border: 0; border-radius: 999px; background: none; font: 600 15px var(--ui); color: var(--lagune); cursor: pointer; } +.side { position: sticky; top: 20px; display: flex; flex-direction: column; gap: 12px; padding: 26px 24px; border-radius: 24px; background: var(--creux); } +.side h2 { font-size: 26px; line-height: 1.15; } +.side ul { display: flex; flex-direction: column; gap: 10px; margin: 4px 0 10px; font-size: 15px; } +.side li { display: flex; gap: 10px; color: var(--ink-2); } +.side li .ic { margin-top: 2px; color: var(--ok); } +.side li:last-child .ic { color: var(--safran-text); } +.btn { display: inline-flex; align-items: center; justify-content: center; gap: 9px; width: 100%; min-height: 52px; padding: 0 20px; border: 0; border-radius: 16px; font: 600 16px/1 var(--ui); cursor: pointer; list-style: none; white-space: nowrap; } +.btn::-webkit-details-marker { display: none; } +.btn.small { width: auto; min-height: 44px; padding: 0 18px; border-radius: 14px; font-size: 15px; } +.btn.ok { background: var(--ok); color: #fff; } +.btn.ok:hover { background: var(--ok-deep); } +.btn.plain { background: var(--surface); box-shadow: var(--shadow); color: var(--ok); } +.btn.bad { background: none; color: var(--bad); } +.btn.bad:hover { background: var(--bad-bg); } +.btn.badfull { margin-top: 10px; background: var(--bad); color: #fff; } +.refuse[open] { padding: 8px 18px 18px; border-radius: 18px; background: var(--surface); } +.refuse legend { font: 500 21px/1.2 var(--display); margin-bottom: 4px; } +.refuse[open] summary { display: none; } +.reason { display: flex; align-items: center; gap: 11px; min-height: 44px; font-size: 15px; font-weight: 600; cursor: pointer; } +.reason input { width: 20px; height: 20px; margin: 0; accent-color: var(--bad); } +.nothing { display: flex; flex-direction: column; align-items: flex-start; gap: 10px; padding: 36px; border-radius: 26px; background: var(--surface); box-shadow: var(--shadow); } +.nothing .ic { width: 34px; height: 34px; color: var(--ok); } +.nothing h1, .nothing h2 { font-size: 34px; line-height: 1.1; } +.nothing p { color: var(--ink-2); } + +@media (max-width: 899px) { + .bar, main { padding-left: 16px; padding-right: 16px; } + .bar { gap: 10px; padding-top: 14px; padding-bottom: 14px; } + .brand { gap: 8px; font-size: 21px; } + .mark { width: 30px; height: 30px; border-radius: 9px; } + .tag { padding: 0 10px; font-size: 12px; } + .out { font-size: 13px; } + main { gap: 14px; padding-bottom: 32px; } + .head { gap: 12px; } + .head h1 { font-size: 38px; } + .tabs { width: 100%; border-radius: 20px; overflow-x: auto; scrollbar-width: none; } + .tabs { padding: 4px; gap: 0; } + .tabs a { flex: auto; justify-content: center; padding: 0 7px; gap: 4px; font-size: 13px; white-space: nowrap; } + .item { grid-template-columns: 54px minmax(0, 1fr) 20px; gap: 4px 14px; padding: 14px; } + .item .m { grid-column: 2; } + .item .v, .item .w { grid-column: 2; } + .item .w { flex-direction: row; flex-wrap: wrap; align-items: center; } + .item > i { grid-column: 3; grid-row: 1; } + .card { padding: 16px; } + .card .top { grid-template-columns: 54px minmax(0, 1fr); gap: 6px 14px; } + .card .v, .card .open { grid-column: 2; } + .track { gap: 5px; } + .track li { flex: auto; gap: 5px; padding: 9px 8px; font-size: 12px; } + .track .ic { width: 14px; height: 14px; } + .foot .btn.small, .foot form { width: 100%; } + .grid { display: flex; flex-direction: column; align-items: stretch; gap: 14px; } + .hero { gap: 16px; padding: 18px; } + .hero .top { flex-wrap: wrap; gap: 8px 14px; } + .hero h1, .title-field .big .in { font-size: 26px; } + .tiles { gap: 8px; } + .tile { padding: 14px; } + .tile.old s, .big .in { font-size: 30px; } + .big .in.long { font-size: 19px; } + .tile .big { gap: 6px; } + .two { grid-template-columns: 1fr; } + .row { gap: 12px; padding: 10px 8px 10px 14px; flex-wrap: wrap; } + .row .m { flex: 1 1 60%; } + .row .open, .row .opens { order: 9; width: 100%; padding-left: 52px; margin-top: -8px; } + .row .opens .open { padding-left: 0; margin: 0; } + .side { position: static; padding: 22px 18px; } + .notice { flex-wrap: wrap; padding: 12px 16px; } + .notice span { flex: 1; } + .notice a { margin-left: 30px; } +} diff --git a/service/assets/review/review.js b/service/assets/review/review.js new file mode 100644 index 0000000..1b30d67 --- /dev/null +++ b/service/assets/review/review.js @@ -0,0 +1,76 @@ +// Corrections are marked as they are typed. Without this script the form still works. +const form = document.querySelector('[data-form]'); +if (form !== null) { + const save = form.querySelector('[data-save]'); + + const controls = (field) => [...field.querySelectorAll('[name]')]; + const values = (field) => + controls(field) + .filter((control) => control.type !== 'checkbox' || control.checked) + .map((control) => control.value.trim()) + .filter(Boolean); + const text = (list) => JSON.stringify([...list].sort()); + const received = (field) => JSON.parse(field.querySelector('[data-received]').dataset.received); + const start = new Map([...form.querySelectorAll('[data-edit]')].map((field) => [field, text(values(field))])); + + const refresh = () => { + let touched = false; + for (const [field, opened] of start) { + const now = text(values(field)); + const changed = now !== text(received(field).map((value) => value.trim())); + const was = field.querySelector('.was'); + field.classList.toggle('changed', changed); + was.hidden = !changed; + was.querySelector('[data-restore]').hidden = false; + touched ||= now !== opened; + } + save.hidden = !touched; + }; + + const tick = (field, code, on) => { + const box = controls(field).find((control) => control.value === code); + if (box !== undefined) box.checked = on; + }; + + form.addEventListener('input', refresh); + form.addEventListener('click', (event) => { + const button = event.target.closest('[data-restore]'); + if (button === null) return; + + const field = button.closest('[data-edit]'); + const back = received(field); + for (const control of controls(field)) { + if (control.type === 'checkbox') control.checked = back.includes(control.value); + else control.value = back[0] ?? ''; + } + refresh(); + controls(field)[0]?.focus(); + }); + + form.querySelector('[data-add-country]')?.addEventListener('change', (event) => { + const select = event.target; + const { value, selectedOptions } = select; + if (value === '') return; + + const field = select.closest('[data-edit]'); + if (controls(field).some((control) => control.value === value)) { + tick(field, value, true); + } else { + const pill = document.createElement('label'); + pill.className = 'pill'; + const box = Object.assign(document.createElement('input'), { type: 'checkbox', name: 'countries', value, checked: true }); + const flag = Object.assign(document.createElement('img'), { src: selectedOptions[0].dataset.flag, alt: '', width: 22, height: 22 }); + pill.append(box, flag, selectedOptions[0].textContent); + select.before(pill); + } + select.value = ''; + refresh(); + }); + + // Enter in a field must not send the contribution by accident. + form.addEventListener('keydown', (event) => { + if (event.key === 'Enter' && event.target.matches('input:not([type="checkbox"]):not([type="radio"])')) event.preventDefault(); + }); + + refresh(); +} diff --git a/service/challenge.ts b/service/challenge.ts new file mode 100644 index 0000000..f5ce1d6 --- /dev/null +++ b/service/challenge.ts @@ -0,0 +1,23 @@ +import { z } from 'zod'; + +import { VERIFY_URL } from './constants'; +import type { ChallengeCheck } from './types'; + +const answer = z.object({ success: z.boolean(), hostname: z.string().optional() }); + +/** Whether the challenge was solved by a person, on our own pages. An unreachable checker is a no. */ +export async function isHuman({ secret, host, token, address }: ChallengeCheck): Promise { + try { + const response = await fetch(VERIFY_URL, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ secret, response: token, remoteip: address }), + signal: AbortSignal.timeout(8000), + }); + const { success, hostname } = answer.parse(await response.json()); + + return success && hostname === host; + } catch { + return false; + } +} diff --git a/service/constants.ts b/service/constants.ts new file mode 100644 index 0000000..89cbcdf --- /dev/null +++ b/service/constants.ts @@ -0,0 +1,21 @@ +/** Largest request accepted, in bytes. The longest honest form is far below. */ +export const MAX_BODY = 32_768; + +/** Sends accepted from one address per hour. Mobile networks share an address between many people. */ +export const MAX_ATTEMPTS = 20; + +export const ATTEMPT_WINDOW_MS = 3_600_000; + +/** How long a sender digest is kept. */ +export const ATTEMPT_LIFE_MS = 86_400_000; + +/** How long an e-mail is kept once a maintainer has decided. */ +export const EMAIL_LIFE_MS = 30 * 86_400_000; + +/** How long an e-mail is kept when nobody has decided. */ +export const UNDECIDED_EMAIL_LIFE_MS = 180 * 86_400_000; + +export const VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; + +/** Longest challenge token, as its provider documents it. */ +export const MAX_TOKEN = 2048; diff --git a/service/migrations/0001_contributions.sql b/service/migrations/0001_contributions.sql new file mode 100644 index 0000000..b1bea56 --- /dev/null +++ b/service/migrations/0001_contributions.sql @@ -0,0 +1,34 @@ +-- Contributions and what a maintainer decided. The e-mail has its own column, so that it can be erased alone. +CREATE TABLE contributions ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('report', 'suggest')), + locale TEXT NOT NULL CHECK (locale IN ('en', 'fr')), + answers TEXT NOT NULL, + -- The answers as a maintainer corrected them. What was received stays above. + edited TEXT, + email TEXT, + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'checking', 'published', 'refused')), + reason TEXT, + issue INTEGER, + received_at TEXT NOT NULL, + -- Set while the public issue is being created, so that two clicks create one. + claimed_at TEXT, + decided_at TEXT, + published_at TEXT, + -- The erasure counts from this date: a decision always has one, in the one format it compares. + CHECK ((status = 'pending') = (decided_at IS NULL)), + CHECK (decided_at = strftime('%Y-%m-%dT%H:%M:%fZ', decided_at)), + CHECK ((status IN ('checking', 'published')) = (issue IS NOT NULL)), + CHECK ((status = 'published') = (published_at IS NOT NULL)), + CHECK ((status = 'refused') = (reason IS NOT NULL)) +) STRICT; + +CREATE INDEX contributions_by_status ON contributions (status, received_at); + +-- Recent sends, to slow a flood down. The sender is a keyed digest, never an address. +CREATE TABLE attempts ( + sender TEXT NOT NULL, + made_at TEXT NOT NULL +) STRICT; + +CREATE INDEX attempts_by_sender ON attempts (sender, made_at); diff --git a/service/moments.ts b/service/moments.ts new file mode 100644 index 0000000..d8c3926 --- /dev/null +++ b/service/moments.ts @@ -0,0 +1,4 @@ +/** The moment so many milliseconds earlier, written as the database writes it. */ +export function before(now: Date, milliseconds: number): string { + return new Date(now.getTime() - milliseconds).toISOString(); +} diff --git a/service/network.ts b/service/network.ts new file mode 100644 index 0000000..a484ae1 --- /dev/null +++ b/service/network.ts @@ -0,0 +1,30 @@ +const MAPPED_IPV4 = /^0:0:0:0:0:ffff:([0-9a-f]+):([0-9a-f]+)$/; + +/** What identifies a sender: an IPv4 address, or the /64 network that a single IPv6 subscriber owns. */ +export function network(address: string): string { + if (!address.includes(':')) return address; + + const full = expand(address); + const mapped = MAPPED_IPV4.exec(full); + if (mapped !== null) return [mapped[1], mapped[2]].flatMap(toBytes).join('.'); + + return `${full.split(':').slice(0, 4).join(':')}::/64`; +} + +/** The eight groups of an IPv6 address, or the text itself when it is not one. */ +function expand(address: string): string { + if (!URL.canParse(`http://[${address}]`)) return address; + + const [head = '', tail] = new URL(`http://[${address}]`).hostname.slice(1, -1).split('::'); + const left = head === '' ? [] : head.split(':'); + const right = tail === undefined || tail === '' ? [] : tail.split(':'); + const zeros = Array(8 - left.length - right.length).fill('0'); + + return [...left, ...zeros, ...right].join(':'); +} + +function toBytes(group: string | undefined): number[] { + const value = Number.parseInt(group ?? '', 16); + + return [value >> 8, value & 255]; +} diff --git a/service/read-submission.ts b/service/read-submission.ts new file mode 100644 index 0000000..6862382 --- /dev/null +++ b/service/read-submission.ts @@ -0,0 +1,77 @@ +import { z } from 'zod'; + +import { METHODS, STEPS } from '../src/contribute/constants'; +import type { Answers, ContributionKind, FieldError, Submission } from '../src/contribute/types'; +import { stepErrors } from '../src/contribute/validate'; +import { MAX_TOKEN } from './constants'; +import type { Contribution } from './types'; + +const one = (max: number) => z.array(z.string().max(max)).length(1).optional(); + +const you = { linked: one(3), email: one(254), credit: one(3), credit_name: one(60), licence: one(3) }; + +const report = z.strictObject({ + service: z.array(z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/)).length(1), + topic: one(20), + shown: one(600), + shown_rate: one(120), + value: one(500), + source: one(500), + seen_on: one(10), + ...you, +}); + +const suggest = z.strictObject({ + name: one(80), + website: one(300), + family: one(40), + countries: z.array(z.string().regex(/^[A-Z]{2}$/)).max(60).optional(), + methods: z.array(z.enum(METHODS)).max(METHODS.length).optional(), + links: one(2000), + ...you, +}); + +const envelope = { id: z.uuid().toLowerCase(), locale: z.enum(['en', 'fr']), challenge: z.string().min(1).max(MAX_TOKEN) }; + +const submission = z.discriminatedUnion('kind', [ + z.strictObject({ ...envelope, kind: z.literal('report'), answers: report }), + z.strictObject({ ...envelope, kind: z.literal('suggest'), answers: suggest }), +]); + +/** A complete and well-formed submission, or `null`. The rules are those the forms show. */ +export function readSubmission(body: unknown, now: Date): Submission | null { + const parsed = submission.safeParse(body); + if (!parsed.success) return null; + + const { id, kind, locale, challenge } = parsed.data; + const answers = given(parsed.data.answers); + + return answerErrors(kind, answers, now).length === 0 ? { id, kind, locale, challenge, answers } : null; +} + +/** What is wrong with the answers of a whole form. */ +export function answerErrors(kind: ContributionKind, answers: Answers, now: Date): FieldError[] { + // It may already be tomorrow where the visitor is. + const latest = new Date(now.getTime() + 14 * 3_600_000).toISOString().slice(0, 10); + + return STEPS.flatMap((step) => stepErrors(kind, step, answers, latest)); +} + +/** Answers whose fields have the expected shape, or `null`. */ +export function readAnswers(kind: ContributionKind, raw: unknown): Answers | null { + const parsed = (kind === 'report' ? report : suggest).safeParse(raw); + + return parsed.success ? given(parsed.data) : null; +} + +/** Takes the e-mail out of the answers, and the name of someone who did not ask to be named. */ +export function toContribution(submission: Submission): Contribution { + const { email, credit_name: creditName, ...rest } = submission.answers; + const named = submission.answers['credit']?.[0] === 'yes' && creditName !== undefined; + + return { ...submission, answers: named ? { ...rest, credit_name: creditName } : rest, email: email?.[0]?.trim() || null }; +} + +function given(fields: Readonly>): Answers { + return Object.fromEntries(Object.entries(fields).flatMap(([field, values]) => (values === undefined ? [] : [[field, values]]))); +} diff --git a/service/receive.ts b/service/receive.ts new file mode 100644 index 0000000..38480d3 --- /dev/null +++ b/service/receive.ts @@ -0,0 +1,61 @@ +import { CONTRIBUTIONS_URL } from '../src/contribute/constants'; +import { MAX_BODY } from './constants'; +import { network } from './network'; +import { readSubmission, toContribution } from './read-submission'; +import { senderDigest } from './sender'; +import { Store } from './store'; +import type { Environment, Tools } from './types'; + +/** Receives one contribution: checked, proven human, then kept for a maintainer. Nothing is published here. */ +export async function receive(request: Request, env: Environment, tools: Tools): Promise { + const url = new URL(request.url); + if (url.pathname !== CONTRIBUTIONS_URL) return reply(404); + if (request.method !== 'POST') return reply(405, { Allow: 'POST' }); + if (request.headers.get('Origin') !== url.origin) return reply(403); + if (request.headers.get('Content-Type')?.split(';')[0]?.trim() !== 'application/json') return reply(415); + + const now = tools.now(); + const submission = readSubmission(await readBody(request), now); + if (submission === null) return reply(400); + + const store = new Store(env.DB); + const address = request.headers.get('CF-Connecting-IP') ?? ''; + if (!(await store.allowAttempt(await senderDigest(network(address), env.SENDER_KEY), now))) return reply(429, { 'Retry-After': '3600' }); + + // The visitor tries again after a lost answer: the challenge is spent, the contribution is already here. + if (await store.has(submission.id)) return reply(201); + + if (!(await tools.isHuman({ secret: env.TURNSTILE_SECRET, host: env.CHALLENGE_HOST, token: submission.challenge, address }))) return reply(403); + + await store.add(toContribution(submission), now); + + return reply(201); +} + +/** The decoded body, or `null` when it is too large or is not JSON. */ +async function readBody(request: Request): Promise { + const reader = request.body?.getReader(); + if (reader === undefined) return null; + + const chunks: Uint8Array[] = []; + let size = 0; + for (let part = await reader.read(); !part.done; part = await reader.read()) { + size += part.value.byteLength; + if (size > MAX_BODY) { + await reader.cancel(); + + return null; + } + chunks.push(part.value); + } + + try { + return JSON.parse(await new Blob(chunks as BlobPart[]).text()); + } catch { + return null; + } +} + +function reply(status: number, headers: Readonly> = {}): Response { + return new Response(null, { status, headers: { 'Cache-Control': 'no-store', ...headers } }); +} diff --git a/service/review/access.ts b/service/review/access.ts new file mode 100644 index 0000000..a588d04 --- /dev/null +++ b/service/review/access.ts @@ -0,0 +1,45 @@ +import { z } from 'zod'; + +import type { ReviewEnvironment } from '../types'; + +const ALGORITHM = { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' }; + +const header = z.object({ alg: z.literal('RS256'), kid: z.string() }); + +const claims = z.object({ iss: z.string(), aud: z.array(z.string()), exp: z.number(), nbf: z.number().optional(), email: z.string(), type: z.literal('app') }); + +const keySet = z.object({ keys: z.array(z.looseObject({ kid: z.string(), kty: z.literal('RSA'), n: z.string(), e: z.string() })) }); + +type AccessSettings = Pick; + +/** Whether Access signed this request for the maintainer. Checked here too, in case a request ever goes around Access. */ +export async function admits(request: Request, env: AccessSettings, now: Date): Promise { + try { + const token = request.headers.get('Cf-Access-Jwt-Assertion') ?? ''; + const [head = '', body = '', signature = '', ...rest] = token.split('.'); + if (signature === '' || rest.length > 0 || env.ACCESS_AUD === '' || env.REVIEWER === '') return false; + + const { kid } = header.parse(decode(head)); + const response = await fetch(`${env.ACCESS_TEAM}/cdn-cgi/access/certs`, { signal: AbortSignal.timeout(8000) }); + const jwk = keySet.parse(await response.json()).keys.find((key) => key.kid === kid); + if (jwk === undefined) return false; + + const key = await crypto.subtle.importKey('jwk', { kty: jwk.kty, n: jwk.n, e: jwk.e }, ALGORITHM, false, ['verify']); + if (!(await crypto.subtle.verify(ALGORITHM, key, bytes(signature), new TextEncoder().encode(`${head}.${body}`)))) return false; + + const { iss, aud, exp, nbf, email } = claims.parse(decode(body)); + const seconds = now.getTime() / 1000; + + return iss === env.ACCESS_TEAM && aud.includes(env.ACCESS_AUD) && exp > seconds && (nbf ?? 0) <= seconds && email.toLowerCase() === env.REVIEWER.toLowerCase(); + } catch { + return false; + } +} + +function decode(part: string): unknown { + return JSON.parse(new TextDecoder().decode(bytes(part))); +} + +function bytes(part: string): Uint8Array { + return Uint8Array.from(atob(part.replace(/-/g, '+').replace(/_/g, '/')), (character) => character.charCodeAt(0)); +} diff --git a/service/review/constants.ts b/service/review/constants.ts new file mode 100644 index 0000000..1224c5c --- /dev/null +++ b/service/review/constants.ts @@ -0,0 +1,15 @@ +export const STATUSES = ['pending', 'checking', 'published', 'refused'] as const; + +export const REASONS = ['unconfirmed', 'up_to_date', 'duplicate', 'spam', 'other'] as const; + +/** Lines shown per list. */ +export const LIST_SIZE = 100; + +/** After this long, an issue that was being created is tried again. */ +export const CLAIM_LIFE_MS = 120_000; + +/** Fields of each form a maintainer may correct. What a person says of themselves is not one, except the name shown. */ +export const EDITABLE = { + report: ['topic', 'shown', 'value', 'source', 'seen_on', 'credit_name'], + suggest: ['name', 'website', 'family', 'countries', 'methods', 'links', 'credit_name'], +} as const; diff --git a/service/review/dates.ts b/service/review/dates.ts new file mode 100644 index 0000000..b9c8a4e --- /dev/null +++ b/service/review/dates.ts @@ -0,0 +1,21 @@ +/** `Aujourd’hui à 07h11`, `Hier à 07h11` or `28 octobre à 07h11`, in UTC. */ +export function moment(iso: string, now: Date): string { + const date = new Date(iso); + const hour = `${pad(date.getUTCHours())}h${pad(date.getUTCMinutes())}`; + const days = Math.round((dayStart(now) - dayStart(date)) / 86_400_000); + if (days === 0) return `Aujourd’hui à ${hour}`; + if (days === 1) return `Hier à ${hour}`; + + const year = date.getUTCFullYear() === now.getUTCFullYear() ? {} : { year: 'numeric' as const }; + const day = new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'long', timeZone: 'UTC', ...year }).format(date); + + return `${day} à ${hour}`; +} + +function dayStart(date: Date): number { + return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); +} + +function pad(value: number): string { + return String(value).padStart(2, '0'); +} diff --git a/service/review/directory.ts b/service/review/directory.ts new file mode 100644 index 0000000..8535a16 --- /dev/null +++ b/service/review/directory.ts @@ -0,0 +1,16 @@ +import { z } from 'zod'; + +import type { Directory } from './types'; + +const payload = z.object({ index: z.object({ entities: z.array(z.object({ id: z.string(), kind: z.string(), label: z.string() })) }) }); + +/** Names of the published providers, from the search data of the site. Empty when the site does not answer: slugs are shown instead. */ +export async function readDirectory(load: (path: string) => Promise): Promise { + try { + const { index } = payload.parse(await (await load('/search/fr.json')).json()); + + return new Map(index.entities.filter(({ kind }) => kind === 'provider').map(({ id, label }) => [id.replace('provider:', ''), label])); + } catch { + return new Map(); + } +} diff --git a/service/review/fields.ts b/service/review/fields.ts new file mode 100644 index 0000000..f94a518 --- /dev/null +++ b/service/review/fields.ts @@ -0,0 +1,125 @@ +import countries from '../../data/reference/countries.json'; +import { METHODS, TOPICS } from '../../src/contribute/constants'; +import { METHOD_ICON } from '../../src/contribute/icons'; +import { shortDay } from '../../src/contribute/moment'; +import type { Answers, MethodChoice } from '../../src/contribute/types'; +import { first, linkLines } from '../../src/contribute/validate'; +import { webAddress } from '../../src/contribute/web-address'; +import { countryName } from '../../src/i18n/country-names'; +import { catalogueStrings, contributeStrings } from '../../src/i18n/translate'; +import { FAMILY_ORDER } from '../../src/lib/catalogue-constants'; +import { flagUrl } from '../../src/lib/site-format'; +import { html, type Html } from './html'; +import { drawing, disc, type DrawingName } from './parts'; +import { TEXTS } from './texts'; +import type { Entry } from './types'; +import type { ContributeTone } from '../../src/contribute/icons'; + +const forms = contributeStrings('fr'); + +const families = catalogueStrings('fr').families; + +type Choice = readonly [value: string, label: string]; + +const TOPIC_CHOICES: readonly Choice[] = TOPICS.map((topic) => [topic, forms.report.topics[topic]]); + +const FAMILY_CHOICES: readonly Choice[] = [...FAMILY_ORDER.map((family): Choice => [family, families[family].one]), ['unknown', forms.suggest.unknown.label]]; + +const COUNTRY_CHOICES: readonly Choice[] = countries.map(({ code }): Choice => [code, countryName('fr', code)]).sort(([, a], [, b]) => a.localeCompare(b, 'fr')); + +/** How one field is shown. */ +interface Look { + readonly field: string; + readonly label: string; + readonly icon: DrawingName; + readonly tone: ContributeTone; +} + +/** A value read and corrected at the same place. */ +export function textField(entry: Entry, look: Look, type: 'text' | 'date' = 'text'): Html { + const value = first(entry.answers, look.field); + const address = type === 'text' && ['source', 'website'].includes(look.field) ? webAddress(value) : null; + const control = html``; + + return row(entry, look, control, address === null ? null : openLink(address, look.label)); +} + +export function areaField(entry: Entry, look: Look): Html { + const links = linkLines(entry.answers).flatMap((line) => webAddress(line) ?? []); + const control = html``; + + return row(entry, look, control, links.length === 0 ? null : html`${links.map((link, index) => openLink(link, `${look.label} ${index + 1}`))}`); +} + +export function choiceField(entry: Entry, look: Look, choices: 'topic' | 'family'): Html { + const current = first(entry.answers, look.field); + const options = (choices === 'topic' ? TOPIC_CHOICES : FAMILY_CHOICES).map(([value, label]) => html``); + + return row(entry, look, html``, null); +} + +/** Pills that can be taken off or put back, and a list to add a country. */ +export function countriesField(entry: Entry): Html { + const codes = [...new Set([...(entry.answers['countries'] ?? []), ...(entry.received['countries'] ?? [])])]; + const pills = codes.map((code) => pill('countries', code, countryName('fr', code), html``, entry.answers['countries']?.includes(code) === true)); + const options = COUNTRY_CHOICES.map(([code, name]) => html``); + + return group(entry, 'countries', TEXTS.places, html`${pills}`); +} + +export function methodsField(entry: Entry): Html { + const pills = METHODS.map((method) => pill('methods', method, methodName(method), drawing(METHOD_ICON[method]), entry.answers['methods']?.includes(method) === true)); + + return group(entry, 'methods', TEXTS.methods, html`${pills}`); +} + +/** The proposed value, large, in the tile where the change is read. */ +export function valueField(entry: Entry): Html { + const value = first(entry.answers, 'value'); + + return html`
${drawing('edit')}${was(entry, 'value')}
`; +} + +/** The name of a suggested provider, as a title. */ +export function nameField(entry: Entry): Html { + return html`
${drawing('edit')}${was(entry, 'name')}
`; +} + +/** How an answer reads in a sentence. */ +export function shown(answers: Answers, field: string): string { + const value = first(answers, field); + if (field === 'topic') return TOPIC_CHOICES.find(([key]) => key === value)?.[1] ?? value; + if (field === 'family') return FAMILY_CHOICES.find(([key]) => key === value)?.[1] ?? value; + if (field === 'countries') return (answers[field] ?? []).map((code) => countryName('fr', code)).join(', '); + if (field === 'methods') return (answers[field] ?? []).map((method) => METHODS.find((known) => known === method)).flatMap((method) => (method === undefined ? [] : methodName(method))).join(', '); + + return field === 'seen_on' ? shortDay(value) : value; +} + +function row(entry: Entry, { field, label, icon, tone }: Look, control: Html, end: Html | null): Html { + return html`
${disc(icon, tone)}${control}${was(entry, field)}${end}
`; +} + +function group(entry: Entry, field: string, label: string, pills: Html): Html { + return html`
${label}
${pills}
${was(entry, field)}
`; +} + +function pill(field: string, value: string, label: string, mark: Html, on: boolean): Html { + return html``; +} + +/** What was received, shown once the maintainer's version differs. */ +function was(entry: Entry, field: string): Html { + const values = entry.received[field] ?? []; + const same = JSON.stringify(values) === JSON.stringify(entry.answers[field] ?? []); + + return html`${TEXTS.received} ${shown(entry.received, field) || TEXTS.nothing}`; +} + +function openLink(href: string, label: string): Html { + return html`${TEXTS.open} →`; +} + +function methodName(method: MethodChoice): string { + return method === 'other' ? forms.suggest.otherMethod : catalogueStrings('fr').methods[method]; +} diff --git a/service/review/github.ts b/service/review/github.ts new file mode 100644 index 0000000..de3426e --- /dev/null +++ b/service/review/github.ts @@ -0,0 +1,39 @@ +import { z } from 'zod'; + +import type { Issue } from './types'; + +const API = 'https://api.github.com'; + +const INSIDERS: ReadonlySet = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); + +const created = z.object({ number: z.number().int() }); + +const listed = z.array(z.object({ number: z.number().int(), body: z.string().nullable(), author_association: z.string().optional(), pull_request: z.unknown().optional() })); + +/** + * Number of the issue that carries the marker, created when there is none. An issue whose answer was lost is + * found again instead of being created twice. `null` when GitHub does not answer as expected. + */ +export async function openIssue(issue: Issue, marker: string, repo: string, token: string): Promise { + const call = (path: string, init: RequestInit = {}): Promise => + fetch(`${API}/repos/${repo}/issues${path}`, { + ...init, + headers: { Accept: 'application/vnd.github+json', Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', 'User-Agent': 'paymap-contributions', 'X-GitHub-Api-Version': '2022-11-28' }, + signal: AbortSignal.timeout(10_000), + }); + + try { + const recent = await call('?state=all&sort=created&direction=desc&per_page=50'); + if (!recent.ok) return null; + + // Anyone can copy a marker into an issue of theirs: only the project's own count. + const known = listed.parse(await recent.json()).find((found) => found.pull_request === undefined && INSIDERS.has(found.author_association ?? '') && found.body?.endsWith(marker) === true); + if (known !== undefined) return known.number; + + const answer = await call('', { method: 'POST', body: JSON.stringify({ ...issue, body: `${issue.body}\n\n${marker}` }) }); + + return answer.status === 201 ? created.parse(await answer.json()).number : null; + } catch { + return null; + } +} diff --git a/service/review/html.ts b/service/review/html.ts new file mode 100644 index 0000000..3a6f017 --- /dev/null +++ b/service/review/html.ts @@ -0,0 +1,24 @@ +/** Markup that is safe to write as it is. */ +export class Html { + constructor(readonly text: string) {} +} + +type Part = Html | string | number | boolean | null | undefined | readonly Part[]; + +/** Builds markup. Every value is escaped unless it is markup itself. */ +export function html(strings: TemplateStringsArray, ...parts: readonly Part[]): Html { + return new Html(strings.reduce((text, string, index) => text + write(parts[index - 1]) + string)); +} + +/** Markup kept in this repository, never a visitor's text. */ +export function trusted(text: string): Html { + return new Html(text); +} + +function write(part: Part): string { + if (part instanceof Html) return part.text; + if (Array.isArray(part)) return part.map(write).join(''); + if (part === null || part === undefined || typeof part === 'boolean') return ''; + + return String(part).replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); +} diff --git a/service/review/issue-text.ts b/service/review/issue-text.ts new file mode 100644 index 0000000..fb178fa --- /dev/null +++ b/service/review/issue-text.ts @@ -0,0 +1,86 @@ +import { countryName } from '../../src/i18n/country-names'; +import type { Answers } from '../../src/contribute/types'; +import { first } from '../../src/contribute/validate'; +import { catalogueStrings, contributeStrings } from '../../src/i18n/translate'; +import type { Directory, Entry, Issue } from './types'; + +/** The public issue of a contribution. It is written field by field, so that nothing private can slip in. */ +export function issueText(entry: Entry, directory: Directory): Issue { + return entry.kind === 'report' ? reportIssue(entry, directory) : suggestIssue(entry); +} + +/** Hidden in the issue, so that the same contribution is never published twice. */ +export function issueMarker(id: string): string { + return ``; +} + +function reportIssue({ answers }: Entry, directory: Directory): Issue { + const slug = first(answers, 'service'); + const topic = topicName(first(answers, 'topic')); + + return { + title: `Correction: ${oneLine(directory.get(slug) ?? slug)}, ${topic}`, + body: sections([ + ['Service', slug], + ['What it is about', topic], + ['What Paymap shows', first(answers, 'shown')], + ['What it should be', first(answers, 'value')], + ['Official source', first(answers, 'source')], + ['Seen on', first(answers, 'seen_on')], + ...person(answers), + ]), + labels: ['correction', 'needs review'], + }; +} + +function suggestIssue({ answers }: Entry): Issue { + const family = first(answers, 'family'); + const families = catalogueStrings('en').families; + + return { + title: `New provider: ${oneLine(first(answers, 'name'))}`, + body: sections([ + ['Name', first(answers, 'name')], + ['Website', first(answers, 'website')], + ['Type', isFamily(family, families) ? families[family].one : 'Not known'], + ['Countries', (answers['countries'] ?? []).map((code) => countryName('en', code)).join(', ')], + ['Payment methods', (answers['methods'] ?? []).join(', ')], + ['Official links', first(answers, 'links')], + ...person(answers), + ]), + labels: ['new provider', 'needs review'], + }; +} + +function person(answers: Answers): (readonly [string, string])[] { + return [ + ['Works for this service', first(answers, 'linked')], + ['Credit', first(answers, 'credit') === 'yes' ? first(answers, 'credit_name') : 'Anonymous'], + ]; +} + +/** Each answer in a block of plain text: no mention, image or link a visitor wrote comes alive on GitHub. */ +function sections(rows: readonly (readonly [string, string])[]): string { + const filled = rows.filter(([, text]) => text !== '').map(([title, text]) => `### ${title}\n\n${block(text)}`); + + return ['Sent through the guided form of the site, read by a maintainer, not checked yet.', ...filled].join('\n\n'); +} + +function block(text: string): string { + const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map(([run]) => run.length)); + const fence = '`'.repeat(longest + 1); + + return `${fence}text\n${text}\n${fence}`; +} + +function oneLine(text: string): string { + return text.replace(/\s+/g, ' ').replace(/[@#<>`]/g, '').trim().slice(0, 80); +} + +function topicName(topic: string): string { + return Object.entries(contributeStrings('en').report.topics).find(([key]) => key === topic)?.[1] ?? topic; +} + +function isFamily(key: string, families: T): key is Extract { + return Object.hasOwn(families, key); +} diff --git a/service/review/pages.ts b/service/review/pages.ts new file mode 100644 index 0000000..33d7d1a --- /dev/null +++ b/service/review/pages.ts @@ -0,0 +1,128 @@ +import { first } from '../../src/contribute/validate'; +import { STATUSES } from './constants'; +import { moment } from './dates'; +import { areaField, choiceField, countriesField, methodsField, nameField, shown, textField, valueField } from './fields'; +import { html, type Html } from './html'; +import { disc, drawing, logo, nameOf, noticeBox } from './parts'; +import { ASK, TEXTS } from './texts'; +import type { Directory, Entry, Notice, ReviewTools, Status } from './types'; + +type Links = Pick; + +export interface ListView { + readonly status: Status; + readonly entries: readonly Entry[]; + readonly counts: Readonly>; + readonly notice: Notice | null; +} + +/** The lists: to read, being checked, published, refused. */ +export function listPage(view: ListView, directory: Directory, links: Links, now: Date): string { + const { status, entries, counts, notice } = view; + const tabs = STATUSES.map((key) => html`${TEXTS.tabs[key]} ${['pending', 'checking'].includes(key) && html`${counts[key]}`}`); + const items = entries.map((entry) => (status === 'pending' ? pendingItem(entry, directory, links, now) : decidedItem(entry, directory, links, now))); + const [title, text] = TEXTS.empty[status]; + const body = items.length > 0 ? html`
${items}
` : html`
${drawing('check')}

${title}

${text}

`; + + return frame(html`${notice && noticeBox(notice)}

${TEXTS.tabs[status]}

${body}`); +} + +/** One contribution. Every value is corrected where it is read. */ +export function entryPage(entry: Entry, directory: Directory, links: Links, notice: Notice | null): string { + const main = entry.kind === 'report' ? reportParts(entry, directory, links) : suggestParts(entry, directory, links); + + return frame(html`← ${TEXTS.tabs.pending}${notice && noticeBox(notice)}
${main}${personParts(entry, directory)}
${decision()}
`); +} + +export function messagePage(text: string): string { + return frame(html`
${drawing('lock')}

${text}

`); +} + +function frame(body: Html): string { + return html`${TEXTS.title}
Paymap${drawing('lock')}${TEXTS.private}${TEXTS.signOut}
${body}
`.text; +} + +function pendingItem(entry: Entry, directory: Directory, links: Links, now: Date): Html { + return html`${logo(entry, directory, links.siteUrl)}${nameOf(entry, directory)}${about(entry)}${change(entry)}${entry.edited && html`${TEXTS.editedByYou}`}${moment(entry.receivedAt, now)}→`; +} + +function decidedItem(entry: Entry, directory: Directory, links: Links, now: Date): Html { + const when = entry.status === 'published' ? `${TEXTS.publishedAt} · ${moment(entry.publishedAt ?? '', now)}` : `${entry.status === 'refused' ? TEXTS.refusedAt : TEXTS.sentAt} · ${moment(entry.decidedAt ?? '', now)}`; + const reason = entry.reason === null ? '' : ` · ${TEXTS.reasons[entry.reason]}`; + const issue = entry.issue !== null && html`${TEXTS.onGitHub} →`; + const publish = entry.status === 'checking' && html`
`; + + return html`
${logo(entry, directory, links.siteUrl)}${nameOf(entry, directory)}${about(entry)}${change(entry)}${issue}
${track(entry.status)}
${when}${reason}${entry.edited && ` · ${TEXTS.editedByYou}`}${publish}
`; +} + +function track(status: Status): Html { + const { received, checking, published, refused } = TEXTS.steps; + const step = (look: string, icon: 'tick' | 'clock' | 'alert', label: string): Html => html`
  • ${drawing(icon)}${label}
  • `; + if (status === 'refused') return html`
      ${step('past', 'tick', received)}${step('bad', 'alert', refused)}
    `; + + const done = status === 'published'; + + return html`
      ${step('past', 'tick', received)}${step(done ? 'past' : 'on', done ? 'tick' : 'clock', checking)}${step(done ? 'past' : '', done ? 'tick' : 'clock', published)}
    `; +} + +function about(entry: Entry): string { + if (entry.kind === 'suggest') return `${TEXTS.newProvider} · ${familyOf(entry)}`; + + return [shown(entry.answers, 'topic'), place(entry)].filter(Boolean).join(' · '); +} + +function familyOf(entry: Entry): string { + return first(entry.answers, 'family') === 'unknown' ? TEXTS.unknownFamily : shown(entry.answers, 'family'); +} + +function change(entry: Entry): Html { + if (entry.kind === 'suggest') return html`${TEXTS.countries(entry.answers['countries']?.length ?? 0)}`; + + const before = first(entry.answers, 'shown_rate'); + + return html`${before !== '' && html`${before} → `}${first(entry.answers, 'value')}`; +} + +function place(entry: Entry): string { + return first(entry.answers, 'shown').split(' · ').slice(0, 2).join(', '); +} + +function reportParts(entry: Entry, directory: Directory, links: Links): Html { + const slug = first(entry.answers, 'service'); + const before = first(entry.answers, 'shown_rate'); + const sheet = directory.has(slug) && html`${TEXTS.sheet} →`; + + return html`
    ${logo(entry, directory, links.siteUrl)}

    ${nameOf(entry, directory)}

    ${place(entry)}
    ${sheet}
    ${before !== '' && html`
    ${TEXTS.before}${before}
    →`}${valueField(entry)}
    + ${first(entry.received, 'shown') !== '' && textField(entry, { field: 'shown', label: TEXTS.shown, icon: 'percent', tone: 'money' })} + ${textField(entry, { field: 'source', label: TEXTS.source, icon: 'link', tone: 'rules' })} +
    ${choiceField(entry, { field: 'topic', label: TEXTS.topic, icon: 'ask', tone: 'plain' }, 'topic')}${textField(entry, { field: 'seen_on', label: TEXTS.seenOn, icon: 'clock', tone: 'methods' }, 'date')}
    `; +} + +function suggestParts(entry: Entry, directory: Directory, links: Links): Html { + return html`
    ${logo(entry, directory, links.siteUrl)}${nameField(entry)}${TEXTS.newProvider}
    ${countriesField(entry)}${methodsField(entry)}
    +
    ${textField(entry, { field: 'website', label: TEXTS.website, icon: 'globe', tone: 'methods' })}${choiceField(entry, { field: 'family', label: TEXTS.family, icon: 'shop', tone: 'actors' }, 'family')}
    + ${areaField(entry, { field: 'links', label: TEXTS.links, icon: 'link', tone: 'rules' })}`; +} + +function personParts(entry: Entry, directory: Directory): Html { + const named = first(entry.answers, 'credit') === 'yes'; + const tie = first(entry.answers, 'linked') === 'yes' ? TEXTS.linked : TEXTS.notLinked; + const person = named ? textField(entry, { field: 'credit_name', label: `${TEXTS.credit} · ${tie}`, icon: 'user', tone: 'actors' }) : html`
    ${disc('user', 'actors')}${tie}${TEXTS.anonymous}
    `; + const ask = entry.email !== null && html`${TEXTS.ask} →`; + + return html`${person}
    ${disc('mail', 'methods')}${entry.email === null ? TEXTS.noEmail : TEXTS.emailKept}${entry.email !== null && html`${entry.email}`}${ask}
    `; +} + +function mailto(entry: Entry, email: string, directory: Directory): string { + const { subject, body } = ASK[entry.locale]; + const text = body.replace('{name}', () => nameOf(entry, directory)); + + return `mailto:${encodeURIComponent(email)}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(text)}`; +} + +function decision(): Html { + const reasons = Object.entries(TEXTS.reasons).map(([key, label], index) => html``); + + return html``; +} + diff --git a/service/review/parts.ts b/service/review/parts.ts new file mode 100644 index 0000000..b73a705 --- /dev/null +++ b/service/review/parts.ts @@ -0,0 +1,52 @@ +import logos from '../../data/reference/logos.json'; +import { CONTRIBUTE_ICONS, CONTRIBUTE_TONES, type ContributeIconName, type ContributeTone } from '../../src/contribute/icons'; +import { first } from '../../src/contribute/validate'; +import { normalise } from '../../src/lib/search-match'; +import { html, trusted, type Html } from './html'; +import type { Directory, Entry, Notice } from './types'; + +const DRAWINGS = { + ...CONTRIBUTE_ICONS, + lock: '', + mail: '', + edit: '', + undo: '', + clock: '', + tick: '', +} as const; + +export type DrawingName = keyof typeof DRAWINGS; + +export function drawing(name: DrawingName): Html { + return html``; +} + +export function disc(name: ContributeIconName | DrawingName, tone: ContributeTone): Html { + const [background, colour] = CONTRIBUTE_TONES[tone]; + + return html`${drawing(name)}`; +} + +/** The square logo we hold, drafts included, or the initial of the name. */ +export function logo(entry: Entry, directory: Directory, siteUrl: string): Html { + const name = nameOf(entry, directory); + const key = entry.kind === 'report' ? first(entry.answers, 'service') : nameKey(name); + const mark = logos.find(({ provider, variant }) => variant === 'mark' && (provider === key || nameKey(provider) === key)); + if (mark !== undefined) return html``; + + return html``; +} + +export function nameOf(entry: Entry, directory: Directory): string { + const slug = first(entry.answers, 'service'); + + return entry.kind === 'suggest' ? first(entry.answers, 'name') : (directory.get(slug) ?? slug); +} + +export function noticeBox({ tone, title, text, link }: Notice): Html { + return html`
    ${drawing(tone === 'ok' ? 'check' : 'alert')}${title}${text === '' ? '' : ` ${text}`}${link && html`${link.label} →`}
    `; +} + +function nameKey(name: string): string { + return normalise(name).replace(/[^\p{L}\p{N}]/gu, ''); +} diff --git a/service/review/review-store.ts b/service/review/review-store.ts new file mode 100644 index 0000000..839ec22 --- /dev/null +++ b/service/review/review-store.ts @@ -0,0 +1,99 @@ +import { z } from 'zod'; + +import type { Answers } from '../../src/contribute/types'; +import { before } from '../moments'; +import type { Database } from '../types'; +import { CLAIM_LIFE_MS, LIST_SIZE, REASONS, STATUSES } from './constants'; +import type { Entry, Reason, Status } from './types'; + +const answers = z.string().transform((text) => z.record(z.string(), z.array(z.string())).parse(JSON.parse(text))); + +const row = z.object({ + id: z.string(), + kind: z.enum(['report', 'suggest']), + locale: z.enum(['en', 'fr']), + answers, + edited: answers.nullable(), + email: z.string().nullable(), + status: z.enum(STATUSES), + reason: z.enum(REASONS).nullable(), + issue: z.number().nullable(), + received_at: z.string(), + decided_at: z.string().nullable(), + published_at: z.string().nullable(), +}); + +/** What the maintainer reads and decides. Every change names the status it starts from. */ +export class ReviewStore { + constructor(private readonly db: Database) {} + + async list(status: Status): Promise { + const order = status === 'pending' ? 'received_at ASC' : 'decided_at DESC'; + const { results } = await this.db.prepare(`SELECT * FROM contributions WHERE status = ? ORDER BY ${order} LIMIT ?`).bind(status, LIST_SIZE).all(); + + return results.map(toEntry); + } + + async counts(): Promise>> { + const { results } = await this.db.prepare('SELECT status, COUNT(*) AS total FROM contributions GROUP BY status').all(); + const of = (status: Status): number => Number(results.find((line) => line['status'] === status)?.['total'] ?? 0); + + return { pending: of('pending'), checking: of('checking'), published: of('published'), refused: of('refused') }; + } + + async find(id: string): Promise { + const found = await this.db.prepare('SELECT * FROM contributions WHERE id = ?').bind(id).first(); + + return found === null ? null : toEntry(found); + } + + /** Keeps the maintainer's version. `null` goes back to what was received. */ + async edit(id: string, edited: Answers | null, now: Date): Promise { + return this.changed("UPDATE contributions SET edited = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", edited === null ? null : JSON.stringify(edited), id, before(now, CLAIM_LIFE_MS)); + } + + /** Keeps the maintainer's version and reserves the contribution while its issue is created. */ + async claim(id: string, edited: Answers | null, now: Date): Promise { + return this.changed("UPDATE contributions SET edited = ?, claimed_at = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", edited === null ? null : JSON.stringify(edited), now.toISOString(), id, before(now, CLAIM_LIFE_MS)); + } + + async release(id: string): Promise { + await this.changed("UPDATE contributions SET claimed_at = NULL WHERE id = ? AND status = 'pending' RETURNING id", id); + } + + async toChecking(id: string, issue: number, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'checking', issue = ?, decided_at = ?, claimed_at = NULL WHERE id = ? AND status = 'pending' RETURNING id", issue, now.toISOString(), id); + } + + async refuse(id: string, reason: Reason, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'refused', reason = ?, decided_at = ? WHERE id = ? AND status = 'pending' AND (claimed_at IS NULL OR claimed_at <= ?) RETURNING id", reason, now.toISOString(), id, before(now, CLAIM_LIFE_MS)); + } + + async publish(id: string, now: Date): Promise { + return this.changed("UPDATE contributions SET status = 'published', published_at = ? WHERE id = ? AND status = 'checking' RETURNING id", now.toISOString(), id); + } + + private async changed(query: string, ...values: (string | number | null)[]): Promise { + return (await this.db.prepare(query).bind(...values).first()) !== null; + } +} + +function toEntry(found: unknown): Entry { + const line = row.parse(found); + + return { + id: line.id, + kind: line.kind, + locale: line.locale, + received: line.answers, + answers: line.edited ?? line.answers, + edited: line.edited !== null, + email: line.email, + status: line.status, + reason: line.reason, + issue: line.issue, + receivedAt: line.received_at, + decidedAt: line.decided_at, + publishedAt: line.published_at, + }; +} diff --git a/service/review/review.ts b/service/review/review.ts new file mode 100644 index 0000000..7fdd3f6 --- /dev/null +++ b/service/review/review.ts @@ -0,0 +1,153 @@ +import type { Answers } from '../../src/contribute/types'; +import { contributeStrings } from '../../src/i18n/translate'; +import { answerErrors, readAnswers } from '../read-submission'; +import type { Database } from '../types'; +import { EDITABLE, REASONS, STATUSES } from './constants'; +import { issueMarker, issueText } from './issue-text'; +import { entryPage, listPage, messagePage } from './pages'; +import { ReviewStore } from './review-store'; +import { TEXTS } from './texts'; +import type { Directory, Entry, Notice, ReviewTools } from './types'; + +const ENTRY_PATH = /^\/c\/([0-9a-f-]{36})$/i; + +const MAX_FORM = 65_536; + +/** The private space of the maintainer: reads, corrects, sends to check, refuses. Nothing is published here. */ +export async function review(request: Request, db: Database, tools: ReviewTools): Promise { + if (!(await tools.admits(request))) return page(messagePage(TEXTS.closed), 403); + + const url = new URL(request.url); + if (request.method === 'GET' && url.pathname.startsWith('/review/')) return tools.asset(request); + + const store = new ReviewStore(db); + const id = ENTRY_PATH.exec(url.pathname)?.[1]; + if (request.method === 'GET' && url.pathname === '/') return showList(url, store, tools); + if (id === undefined) return page(messagePage(TEXTS.missing), 404); + + const entry = await store.find(id); + if (entry === null) return page(messagePage(TEXTS.missing), 404); + if (request.method === 'GET') return showEntry(entry, url, tools); + if (request.method !== 'POST') return page(messagePage(TEXTS.missing), 405); + if (request.headers.get('Origin') !== url.origin) return page(messagePage(TEXTS.closed), 403); + if (Number(request.headers.get('Content-Length') ?? Infinity) > MAX_FORM) return page(messagePage(TEXTS.missing), 413); + + return decide(await request.formData(), entry, store, tools); +} + +async function showList(url: URL, store: ReviewStore, tools: ReviewTools): Promise { + const status = STATUSES.find((known) => known === url.searchParams.get('list')) ?? 'pending'; + const [entries, counts, directory, notice] = await Promise.all([store.list(status), store.counts(), tools.directory(), doneNotice(url, store, tools)]); + + return page(listPage({ status, entries, counts, notice }, directory, tools, tools.now())); +} + +async function doneNotice(url: URL, store: ReviewStore, { repoUrl }: ReviewTools): Promise { + const done = url.searchParams.get('done'); + if (done === 'refused' || done === 'published') return { tone: 'ok', title: TEXTS.done[done], text: '' }; + if (done === 'moved') return failure(TEXTS.moved); + if (done !== 'sent') return null; + + const issue = (await store.find(url.searchParams.get('id') ?? ''))?.issue ?? null; + + return { tone: 'ok', title: TEXTS.done.sent, text: TEXTS.sentText, ...(issue === null ? {} : { link: { href: `${repoUrl}/issues/${issue}`, label: TEXTS.onGitHub } }) }; +} + +async function showEntry(entry: Entry, url: URL, tools: ReviewTools, notice: Notice | null = null, status = 200): Promise { + if (entry.status !== 'pending') return goTo(`/?list=${entry.status}`); + + const saved: Notice | null = url.searchParams.get('done') === 'saved' ? { tone: 'ok', title: TEXTS.done.saved, text: '' } : null; + + return page(entryPage(entry, await tools.directory(), tools, notice ?? saved), status); +} + +async function decide(form: FormData, entry: Entry, store: ReviewStore, tools: ReviewTools): Promise { + const { id } = entry; + const now = tools.now(); + const action = form.get('action'); + + if (action === 'publish') return goTo((await store.publish(id, now)) ? '/?list=checking&done=published' : '/?done=moved'); + if (action === 'refuse') { + const reason = REASONS.find((known) => known === form.get('reason')); + + return goTo(reason !== undefined && (await store.refuse(id, reason, now)) ? '/?done=refused' : '/?done=moved'); + } + if (action !== 'save' && action !== 'send') return page(messagePage(TEXTS.missing), 400); + + const corrected = readAnswers(entry.kind, withEdits(entry, form)); + const errors = corrected === null ? [{ code: 'too_long' } as const] : answerErrors(entry.kind, corrected, now); + if (corrected === null || errors.length > 0) { + const messages = [...new Set(errors.map(({ code }) => contributeStrings('fr').common.errors[code]))].join(' '); + const kept: Entry = { ...entry, answers: corrected ?? entry.answers }; + + return showEntry(kept, new URL('https://review.invalid/'), tools, { tone: 'bad', title: TEXTS.invalid, text: messages }, 422); + } + + const changed = !same(corrected, entry.received); + const edited = changed ? corrected : null; + if (action === 'save') return goTo((await store.edit(id, edited, now)) ? `/c/${id}?done=saved` : '/?done=moved'); + + // Read first: the reservation below is short. + const directory = await tools.directory(); + if (!(await store.claim(id, edited, now))) return goTo('/?done=moved'); + + return sendToCheck({ ...entry, answers: corrected, edited: changed }, directory, store, tools); +} + +async function sendToCheck(entry: Entry, directory: Directory, store: ReviewStore, tools: ReviewTools): Promise { + const issue = await tools.openIssue(issueText(entry, directory), issueMarker(entry.id)); + if (issue === null) { + await store.release(entry.id); + + return showEntry(entry, new URL('https://review.invalid/'), tools, failure(TEXTS.failed), 502); + } + + return goTo((await store.toChecking(entry.id, issue, tools.now())) ? `/?done=sent&id=${entry.id}` : '/?done=moved'); +} + +/** The received answers, with the fields the maintainer may correct taken from the form. */ +function withEdits(entry: Entry, form: FormData): Answers { + const answers: Record = { ...entry.received }; + for (const field of EDITABLE[entry.kind]) { + if (field === 'credit_name' && entry.received['credit']?.[0] !== 'yes') continue; + if (field === 'shown' && entry.received['shown'] === undefined) continue; + + const values = clean(form.getAll(field).filter((value) => typeof value === 'string')); + if (values.length > 0) answers[field] = values; + else delete answers[field]; + } + + return answers; +} + +function same(a: Answers, b: Answers): boolean { + const ordered = (answers: Answers): string => JSON.stringify(Object.entries(answers).map(([field, values]) => [field, clean(values).sort()] as const).filter(([, values]) => values.length > 0).sort(([x], [y]) => x.localeCompare(y))); + + return ordered(a) === ordered(b); +} + +/** Values as they are compared and kept: browsers send other line endings than they show. */ +function clean(values: readonly string[]): string[] { + return values.map((value) => value.trim().replace(/\r\n/g, '\n')).filter(Boolean); +} + +function failure([title, text]: readonly [string, string]): Notice { + return { tone: 'bad', title, text }; +} + +function goTo(path: string): Response { + return new Response(null, { status: 303, headers: { Location: path, 'Cache-Control': 'no-store' } }); +} + +function page(body: string, status = 200): Response { + return new Response(body, { + status, + headers: { + 'Content-Type': 'text/html; charset=utf-8', + 'Cache-Control': 'no-store', + 'Content-Security-Policy': "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; img-src https://paymap.africa https://cdn.jsdelivr.net; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", + 'Referrer-Policy': 'same-origin', + 'X-Content-Type-Options': 'nosniff', + }, + }); +} diff --git a/service/review/texts.ts b/service/review/texts.ts new file mode 100644 index 0000000..1033733 --- /dev/null +++ b/service/review/texts.ts @@ -0,0 +1,74 @@ +import type { Reason, Status } from './types'; + +/** Texts of the review space, in the language of its one reader. */ +export const TEXTS = { + title: 'Espace privé · Paymap', + private: 'Espace privé', + signOut: 'Se déconnecter', + tabs: { pending: 'À relire', checking: 'En vérification', published: 'Publiées', refused: 'Refusées' } satisfies Record, + empty: { + pending: ['Tout est relu', 'Les nouvelles propositions arriveront ici.'], + checking: ['Rien en vérification', 'Les propositions envoyées sur GitHub apparaîtront ici.'], + published: ['Rien de publié', 'Les propositions publiées apparaîtront ici.'], + refused: ['Rien de refusé', 'Les propositions refusées apparaîtront ici.'], + } satisfies Record, + steps: { received: 'Reçue', checking: 'En vérification', published: 'Publiée', refused: 'Refusée' }, + newProvider: 'Nouvelle solution', + countries: (count: number): string => (count === 0 ? 'Pays non précisés' : count === 1 ? '1 pays' : `${count} pays`), + unknownFamily: 'Type non précisé', + before: 'Sur Paymap', + after: 'Proposé', + sheet: 'Voir la fiche', + open: 'Ouvrir', + edit: 'Modifier', + received: 'Reçu :', + nothing: 'vide', + restore: 'Rétablir', + shown: 'Ce que Paymap affiche, selon la personne', + topic: 'Sujet', + source: 'Lien officiel', + seenOn: 'Vu le', + name: 'Nom', + website: 'Site officiel', + family: 'Type', + places: 'Pays', + addCountry: 'Ajouter un pays', + methods: 'Moyens de paiement', + links: 'Liens officiels, un par ligne', + credit: 'Nom à citer', + anonymous: 'Ne souhaite pas être cité', + linked: 'Travaille pour ce service', + notLinked: 'Sans lien avec le service', + emailKept: 'Privé, effacé 30 jours après la décision', + ask: 'Demander une précision', + noEmail: 'Pas d’e-mail laissé, ou déjà effacé', + decision: 'Votre décision', + sendTask: 'Une tâche publique est créée sur GitHub', + sendSheet: 'La fiche ne change pas encore', + sendPrivate: 'L’e-mail reste privé', + send: 'Envoyer en vérification', + save: 'Enregistrer mes corrections', + refuse: 'Refuser', + why: 'Pourquoi refuser ?', + reasons: { unconfirmed: 'La source ne confirme pas', up_to_date: 'Déjà à jour', duplicate: 'Déjà reçue', spam: 'Indésirable', other: 'Autre raison' } satisfies Record, + confirmRefuse: 'Confirmer le refus', + publish: 'Marquer comme publiée', + onGitHub: 'Voir sur GitHub', + editedByYou: 'Corrigée par vous', + sentAt: 'Envoyée en vérification', + publishedAt: 'Publiée', + refusedAt: 'Refusée', + invalid: 'Réponses à corriger', + done: { sent: 'Envoyée en vérification', saved: 'Corrections enregistrées', refused: 'Proposition refusée', published: 'Marquée comme publiée' }, + sentText: 'La fiche changera quand la source sera confirmée.', + failed: ['La tâche n’a pas été créée', 'GitHub n’a pas répondu. Vos corrections sont gardées, réessayez.'], + moved: ['Rien n’a changé', 'Cette proposition a déjà été traitée, ou l’est en ce moment.'], + missing: 'Cette proposition n’existe pas.', + closed: 'Accès refusé.', +} as const; + +/** Draft of the message asking for a detail, in the language of the person. */ +export const ASK = { + fr: { subject: 'Paymap : une précision sur votre proposition', body: 'Bonjour,\n\nMerci pour votre proposition sur Paymap à propos de {name}.\n\nPouvez-vous préciser : ' }, + en: { subject: 'Paymap: a question about your contribution', body: 'Hello,\n\nThank you for your contribution to Paymap about {name}.\n\nCould you tell us more about: ' }, +} as const; diff --git a/service/review/types.ts b/service/review/types.ts new file mode 100644 index 0000000..b0644ba --- /dev/null +++ b/service/review/types.ts @@ -0,0 +1,55 @@ +import type { Answers, ContributionKind } from '../../src/contribute/types'; +import type { Locale } from '../../src/i18n/locales'; +import type { REASONS, STATUSES } from './constants'; + +export type Status = (typeof STATUSES)[number]; + +export type Reason = (typeof REASONS)[number]; + +/** A contribution as the maintainer sees it. */ +export interface Entry { + readonly id: string; + readonly kind: ContributionKind; + readonly locale: Locale; + readonly received: Answers; + /** The received answers, or the maintainer's version of them. */ + readonly answers: Answers; + readonly edited: boolean; + readonly email: string | null; + readonly status: Status; + readonly reason: Reason | null; + readonly issue: number | null; + readonly receivedAt: string; + readonly decidedAt: string | null; + readonly publishedAt: string | null; +} + +/** Name of each published provider, by slug. */ +export type Directory = ReadonlyMap; + +export interface Issue { + readonly title: string; + readonly body: string; + readonly labels: readonly string[]; +} + +/** What the review space needs from outside, replaced in tests and locally. */ +export interface ReviewTools { + readonly now: () => Date; + /** Whether the request comes from the maintainer. */ + readonly admits: (request: Request) => Promise; + readonly directory: () => Promise; + /** Number of the issue that carries the marker, created when there is none. `null` when GitHub does not answer. */ + readonly openIssue: (issue: Issue, marker: string) => Promise; + readonly asset: (request: Request) => Promise; + readonly siteUrl: string; + readonly repoUrl: string; +} + +/** A message above the page: something was done, or could not be. */ +export interface Notice { + readonly tone: 'ok' | 'bad'; + readonly title: string; + readonly text: string; + readonly link?: { readonly href: string; readonly label: string }; +} diff --git a/service/sender.ts b/service/sender.ts new file mode 100644 index 0000000..4cdb8c2 --- /dev/null +++ b/service/sender.ts @@ -0,0 +1,8 @@ +/** Digest of a visitor's address. Useless without the key, and different once the key changes. */ +export async function senderDigest(address: string, key: string): Promise { + const encoder = new TextEncoder(); + const imported = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); + const signature = await crypto.subtle.sign('HMAC', imported, encoder.encode(address)); + + return [...new Uint8Array(signature)].map((byte) => byte.toString(16).padStart(2, '0')).join(''); +} diff --git a/service/store.ts b/service/store.ts new file mode 100644 index 0000000..77ba615 --- /dev/null +++ b/service/store.ts @@ -0,0 +1,37 @@ +import { ATTEMPT_LIFE_MS, ATTEMPT_WINDOW_MS, EMAIL_LIFE_MS, MAX_ATTEMPTS, UNDECIDED_EMAIL_LIFE_MS } from './constants'; +import { before } from './moments'; +import type { Contribution, Database } from './types'; + +/** The private database. Times are ISO texts in UTC, so that they compare as texts. */ +export class Store { + constructor(private readonly db: Database) {} + + async has(id: string): Promise { + return (await this.db.prepare('SELECT 1 AS found FROM contributions WHERE id = ?').bind(id).first()) !== null; + } + + /** Keeps a contribution. Sent twice, it is kept once. */ + async add({ id, kind, locale, answers, email }: Contribution, now: Date): Promise { + await this.db + .prepare('INSERT INTO contributions (id, kind, locale, answers, email, received_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (id) DO NOTHING') + .bind(id, kind, locale, JSON.stringify(answers), email, now.toISOString()) + .run(); + } + + /** Counts this attempt, unless the sender has made too many. A refused attempt is not counted. */ + async allowAttempt(sender: string, now: Date): Promise { + // One statement, so that requests sent together cannot all pass on the same count. + const counted = await this.db + .prepare('INSERT INTO attempts (sender, made_at) SELECT ?, ? WHERE (SELECT COUNT(*) FROM attempts WHERE sender = ? AND made_at > ?) < ? RETURNING 1 AS counted') + .bind(sender, now.toISOString(), sender, before(now, ATTEMPT_WINDOW_MS), MAX_ATTEMPTS) + .first(); + + return counted !== null; + } + + /** Erases what has been kept long enough. */ + async erase(now: Date): Promise { + await this.db.prepare('UPDATE contributions SET email = NULL WHERE email IS NOT NULL AND (decided_at <= ? OR received_at <= ?)').bind(before(now, EMAIL_LIFE_MS), before(now, UNDECIDED_EMAIL_LIFE_MS)).run(); + await this.db.prepare('DELETE FROM attempts WHERE made_at <= ?').bind(before(now, ATTEMPT_LIFE_MS)).run(); + } +} diff --git a/service/types.ts b/service/types.ts new file mode 100644 index 0000000..8f446e5 --- /dev/null +++ b/service/types.ts @@ -0,0 +1,55 @@ +import type { Submission } from '../src/contribute/types'; + +/** The part of a Cloudflare D1 database the service uses. */ +export interface Database { + prepare(query: string): Statement; +} + +export interface Statement { + bind(...values: (string | number | null)[]): Statement; + run(): Promise; + first(): Promise> | null>; + all(): Promise<{ readonly results: readonly Readonly>[] }>; +} + +/** What the service is given when it is deployed. */ +export interface Environment { + readonly DB: Database; + readonly TURNSTILE_SECRET: string; + /** Key of the sender digests. */ + readonly SENDER_KEY: string; + /** Host a solved challenge must come from. */ + readonly CHALLENGE_HOST: string; +} + +/** Names needed by the private review space only. */ +export interface ReviewEnvironment extends Environment { + readonly ASSETS: { fetch(request: Request): Promise }; + readonly REVIEW_HOST: string; + /** Address of the Access team, such as `https://team.cloudflareaccess.com`. */ + readonly ACCESS_TEAM: string; + readonly ACCESS_AUD: string; + /** The one e-mail let in. A secret: it is personal data. */ + readonly REVIEWER: string; + readonly GITHUB_REPO: string; + readonly GITHUB_TOKEN: string; +} + +/** A contribution as it is kept: the e-mail apart from the answers. */ +export interface Contribution extends Submission { + readonly email: string | null; +} + +/** A challenge answer to check. */ +export interface ChallengeCheck { + readonly secret: string; + readonly host: string; + readonly token: string; + readonly address: string; +} + +/** What a request needs from outside, replaced in tests. */ +export interface Tools { + readonly now: () => Date; + readonly isHuman: (check: ChallengeCheck) => Promise; +} diff --git a/service/worker.local.ts b/service/worker.local.ts new file mode 100644 index 0000000..ce7710a --- /dev/null +++ b/service/worker.local.ts @@ -0,0 +1,37 @@ +import { isHuman } from './challenge'; +import { receive } from './receive'; +import { readDirectory } from './review/directory'; +import { review } from './review/review'; +import type { ReviewEnvironment } from './types'; + +/** Local only, never deployed: the review space opens without Access, and issues are invented. */ +export default { + async fetch(request: Request, env: ReviewEnvironment): Promise { + const url = new URL(request.url); + if (url.hostname === 'review.localhost') { + const site = `http://localhost:${url.port}`; + + const answer = await review(request, env.DB, { + now: () => new Date(), + admits: async () => true, + directory: () => readDirectory((path) => env.ASSETS.fetch(new Request(`${site}${path}`))), + openIssue: async (issue) => { + console.log(issue.title, issue.body); + + return issue.title.includes('GitHub down') ? null : 999; + }, + asset: (incoming) => env.ASSETS.fetch(incoming), + siteUrl: site, + repoUrl: `https://github.com/${env.GITHUB_REPO}`, + }); + const local = new Response(answer.body, answer); + const policy = local.headers.get('Content-Security-Policy'); + if (policy !== null) local.headers.set('Content-Security-Policy', policy.replace('https://paymap.africa', site)); + + return local; + } + if (url.pathname.startsWith('/api/')) return receive(request, env, { now: () => new Date(), isHuman }); + + return env.ASSETS.fetch(request); + }, +}; diff --git a/service/worker.ts b/service/worker.ts new file mode 100644 index 0000000..baf571a --- /dev/null +++ b/service/worker.ts @@ -0,0 +1,40 @@ +import { isHuman } from './challenge'; +import { receive } from './receive'; +import { admits } from './review/access'; +import { readDirectory } from './review/directory'; +import { openIssue } from './review/github'; +import { review } from './review/review'; +import { Store } from './store'; +import type { Environment, ReviewEnvironment } from './types'; + +const SITE_URL = 'https://paymap.africa'; + +/** Entry of the private service: receives contributions, shows them to the maintainer, and erases old personal data once a day. */ +export default { + async fetch(request: Request, env: ReviewEnvironment): Promise { + try { + if (new URL(request.url).hostname === env.REVIEW_HOST) { + return await review(request, env.DB, { + now: () => new Date(), + admits: (incoming) => admits(incoming, env, new Date()), + directory: () => readDirectory((path) => fetch(`${SITE_URL}${path}`, { signal: AbortSignal.timeout(5000) })), + openIssue: (issue, marker) => openIssue(issue, marker, env.GITHUB_REPO, env.GITHUB_TOKEN), + asset: (incoming) => env.ASSETS.fetch(incoming), + siteUrl: SITE_URL, + repoUrl: `https://github.com/${env.GITHUB_REPO}`, + }); + } + + return await receive(request, env, { now: () => new Date(), isHuman }); + } catch (error) { + // The name only: a message could quote an answer. + console.error('Request not answered', error instanceof Error ? error.name : 'unknown'); + + return new Response(null, { status: 500, headers: { 'Cache-Control': 'no-store' } }); + } + }, + + async scheduled(_event: unknown, env: Environment): Promise { + await new Store(env.DB).erase(new Date()); + }, +}; diff --git a/service/wrangler.jsonc b/service/wrangler.jsonc new file mode 100644 index 0000000..5201822 --- /dev/null +++ b/service/wrangler.jsonc @@ -0,0 +1,20 @@ +{ + // Private service of ADR 0003. Deployed apart from the site, which stays static. + "name": "paymap-contributions", + "main": "worker.ts", + "compatibility_date": "2026-11-01", + "workers_dev": false, + "preview_urls": false, + "routes": [ + { "pattern": "paymap.africa/api/contributions", "zone_name": "paymap.africa" }, + // Behind an Access application that lets one e-mail in. + { "pattern": "review.paymap.africa", "custom_domain": true } + ], + // The worker answers first: nothing is served before the visitor is known. + "assets": { "directory": "assets", "binding": "ASSETS", "run_worker_first": true }, + "triggers": { "crons": ["17 3 * * *"] }, + // ACCESS_TEAM and ACCESS_AUD are filled when the Access application is created. Empty, they let nobody in. + "vars": { "CHALLENGE_HOST": "paymap.africa", "REVIEW_HOST": "review.paymap.africa", "GITHUB_REPO": "gausoft/paymap", "ACCESS_TEAM": "", "ACCESS_AUD": "" }, + // The deployed copy, wrangler.production.jsonc, adds the database id and the Access values. It is not versioned. Secrets: TURNSTILE_SECRET, SENDER_KEY, REVIEWER, GITHUB_TOKEN. + "d1_databases": [{ "binding": "DB", "database_name": "paymap-contributions", "migrations_dir": "migrations" }] +} diff --git a/service/wrangler.local.jsonc b/service/wrangler.local.jsonc new file mode 100644 index 0000000..8430ff5 --- /dev/null +++ b/service/wrangler.local.jsonc @@ -0,0 +1,10 @@ +{ + // The built site and the service on one local address. See README.md. + "name": "paymap-local", + "main": "worker.local.ts", + "compatibility_date": "2026-11-01", + "assets": { "directory": "../dist", "binding": "ASSETS", "html_handling": "drop-trailing-slash", "not_found_handling": "404-page", "run_worker_first": true }, + // Public test secret of Turnstile: it always passes, and always answers for example.com. + "vars": { "GITHUB_REPO": "gausoft/paymap", "CHALLENGE_HOST": "example.com", "TURNSTILE_SECRET": "1x0000000000000000000000000000000AA", "SENDER_KEY": "local-only" }, + "d1_databases": [{ "binding": "DB", "database_name": "paymap-local", "database_id": "local", "migrations_dir": "migrations" }] +} diff --git a/tests/review.test.ts b/tests/review.test.ts new file mode 100644 index 0000000..f165cef --- /dev/null +++ b/tests/review.test.ts @@ -0,0 +1,325 @@ +import { readFileSync } from 'node:fs'; +import { DatabaseSync, type SQLInputValue } from 'node:sqlite'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { admits } from '../service/review/access'; +import { moment } from '../service/review/dates'; +import { openIssue } from '../service/review/github'; +import { html } from '../service/review/html'; +import { review } from '../service/review/review'; +import { ReviewStore } from '../service/review/review-store'; +import type { Issue, ReviewTools } from '../service/review/types'; +import type { Database, Statement } from '../service/types'; + +const NOW = new Date('2026-12-03T09:20:00Z'); +const ID = '6f1d5f0e-5b0a-4c57-9a3e-0f6f0b1c2d3e'; +const URL_BASE = 'https://review.paymap.africa'; +const REPORT = { service: ['some-provider'], topic: ['fees'], shown: ['Card · Togo · 3 %'], shown_rate: ['3 %'], value: ['2 pourcent'], source: ['example.com/pricing'], linked: ['no'], credit: ['yes'], credit_name: ['Awa'], licence: ['yes'] }; +const SUGGESTION = { name: ['Example Pay'], website: ['example.com'], family: ['unknown'], countries: ['SN'], methods: ['card'], links: ['example.com/a'], linked: ['yes'], licence: ['yes'] }; +const FORM = { topic: 'fees', shown: 'Card · Togo · 3 %', value: '2 %', source: 'example.com/pricing', credit_name: 'Awa' }; + +let sqlite: DatabaseSync; +let db: Database; +let issues: Issue[]; + +beforeEach(() => { + sqlite = new DatabaseSync(':memory:'); + sqlite.exec(readFileSync('service/migrations/0001_contributions.sql', 'utf8')); + db = database(sqlite); + issues = []; +}); + +describe('the door', () => { + it('shows nothing to anyone else, files included', async () => { + keep(); + for (const path of ['/', `/c/${ID}`, '/review/review.css']) { + const response = await get(path, { admits: async () => false }); + + expect(response.status).toBe(403); + expect(await response.text()).not.toContain('someone@example.com'); + } + }); + + it('refuses a decision posted by another site', async () => { + keep(); + expect((await post({ ...FORM, action: 'send' }, {}, 'https://elsewhere.example')).status).toBe(403); + expect(line()).toMatchObject({ status: 'pending' }); + }); + + it('lets the maintainer in with a token signed for this application', async () => { + const { sign, jwk } = await signer(); + vi.stubGlobal('fetch', async () => Response.json({ keys: [jwk] })); + const env = { ACCESS_TEAM: 'https://team.example', ACCESS_AUD: 'aud', REVIEWER: 'me@example.com' }; + const good = { iss: env.ACCESS_TEAM, aud: ['aud'], exp: NOW.getTime() / 1000 + 60, email: 'Me@example.com', type: 'app' }; + const enter = async (claims: object, settings = env): Promise => admits(new Request(URL_BASE, { headers: { 'Cf-Access-Jwt-Assertion': await sign(claims) } }), settings, NOW); + + expect(await enter(good)).toBe(true); + expect(await enter({ ...good, email: 'other@example.com' })).toBe(false); + expect(await enter({ ...good, aud: ['other'] })).toBe(false); + expect(await enter({ ...good, iss: 'https://other.example' })).toBe(false); + expect(await enter({ ...good, exp: NOW.getTime() / 1000 - 1 })).toBe(false); + expect(await enter({ ...good, nbf: NOW.getTime() / 1000 + 60 })).toBe(false); + expect(await enter({ ...good, type: 'org' })).toBe(false); + expect(await enter(good, { ...env, REVIEWER: '' })).toBe(false); + expect(await admits(new Request(URL_BASE), env, NOW)).toBe(false); + + const [head, body] = (await sign(good)).split('.'); + const forged = new Request(URL_BASE, { headers: { 'Cf-Access-Jwt-Assertion': `${head}.${body}.${btoa('forged')}` } }); + expect(await admits(forged, env, NOW)).toBe(false); + }); +}); + +describe('reading', () => { + it('lists what waits, with the French time and the known name', async () => { + keep(); + const page = await (await get('/')).text(); + + expect(page).toContain('Some Provider'); + expect(page).toContain('Aujourd’hui à 08h05'); + expect(page).not.toContain('someone@example.com'); + }); + + it('never lets a visitor write markup', async () => { + keep({ ...REPORT, value: [''], credit_name: ['">'] }); + for (const path of ['/', `/c/${ID}`]) { + const page = await (await get(path)).text(); + + expect(page).not.toContain('