source: Klonkt/src/routes/paid.js@ ec288dc

main
Last change on this file since ec288dc was ec288dc, checked in by Robin <roboburr@…>, 7 weeks ago

Debug: show why a patron is rejected on the "Nog geen supporter" page

We are debugging boiert.eu blind (it's a self-hosted instance we can't see
the logs of), so surface the non-identifying diagnosis on the result page
itself. verifyPatron now always returns { status, cents, diag } after it
reaches Patreon, where diag is a breadcrumb: the configured campaign_id, the
memberships Patreon returned (campaign:status:cents each), and what got
picked. The paid-result page prints it small under the buttons so the tester
can read it and report back. No identity (name/email) is included or stored.

Once the cause is known this can be removed again.

Changed files:
src/services/PaidPatreonService.js

  • verifyPatron returns {status,cents,diag}; null only on hard misconfig

src/routes/paid.js

  • pass diag as debug to the notpatron/tier result page

src/views/pages/paid-result.ejs

  • small "diagnose:" line when debug is present

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 7.3 KB
RevLine 
[9e9e6f9]1/**
2 * Paid posts (klonkt-demo-aki) slice 3: the patron link + passkey flow.
3 * Cookie-less throughout: the OAuth state and the WebAuthn challenge travel in
4 * signed blobs (CryptoBox), never a session.
5 *
6 * GET /paid/link?post=<slug> -> redirect to Patreon authorize
7 * GET /paid/callback -> verify patron, render the passkey page
8 * POST /paid/register -> verify the passkey, store the entitlement
9 */
10import express from 'express';
11import db from '../config/database.js';
12import { renderPage } from '../middleware/render.js';
13import { premiumUnlocked } from '../services/PatreonService.js';
14import { signBlob, verifyBlob, cryptoBoxReady } from '../services/CryptoBox.js';
15import PaidPatreon from '../services/PaidPatreonService.js';
16import Passkey from '../services/PasskeyService.js';
[6cbd014]17import { renderPostBodyHtml } from './posts.js';
[9e9e6f9]18
19const router = express.Router();
20const AUTHORIZE = 'https://www.patreon.com/oauth2/authorize';
21
22const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
23
24// The feature is only live when premium is on, secrets can be encrypted, and the
25// owner has connected a campaign.
26function ready(req, res) {
27 const site = res.locals.site;
28 if (!site) { res.status(404).end(); return null; }
29 if (!premiumUnlocked() || !cryptoBoxReady()) { res.status(404).end(); return null; }
30 const cfg = PaidPatreon.getOwnerConfig(site.id);
31 if (!cfg || !cfg.clientId || !cfg.campaignId) { res.status(404).end(); return null; }
32 return { site, cfg };
33}
34
35// Step 1: send the visitor to Patreon.
36router.get('/link', (req, res) => {
37 const r = ready(req, res); if (!r) return;
38 const slug = String(req.query.post || '').trim();
39 const post = slug ? db.prepare('SELECT slug, paid, paid_min_cents FROM posts WHERE site_id = ? AND slug = ?').get(r.site.id, slug) : null;
40 if (!post || !post.paid) return res.redirect((res.locals.siteUrlBase || '') + '/' + (slug || ''));
41 const cents = post.paid_min_cents || PaidPatreon.defaultMinCents(r.site.id);
42 const state = signBlob({ purpose: 'patron', siteId: r.site.id, cents, post: post.slug }, 900);
43 const url = `${AUTHORIZE}?response_type=code&client_id=${encodeURIComponent(r.cfg.clientId)}`
44 + `&redirect_uri=${encodeURIComponent(baseUrl(req) + '/paid/callback')}`
45 + `&scope=${encodeURIComponent('identity identity.memberships')}`
46 + `&state=${encodeURIComponent(state)}`;
47 res.redirect(url);
48});
49
50// Step 2: Patreon returns. Verify the patron; if a supporter at the right tier,
51// render the passkey-creation page.
52router.get('/callback', async (req, res) => {
53 const r = ready(req, res); if (!r) return;
54 const payload = verifyBlob(String(req.query.state || ''));
55 if (!payload || payload.purpose !== 'patron' || payload.siteId !== r.site.id) {
[c3d12a6]56 return renderPage(req, res, 'pages/paid-result', {
57 pageTitle: 'Ontgrendelen', bodyClass: 'on-special', ok: false, reason: 'expired',
58 });
[9e9e6f9]59 }
[c3d12a6]60 const patronUrl = PaidPatreon.patreonUrl(r.site.id);
[9e9e6f9]61 const code = String(req.query.code || '');
62 if (req.query.error || !code) {
[c3d12a6]63 return renderPage(req, res, 'pages/paid-result', { pageTitle: 'Ontgrendelen', bodyClass: 'on-special', ok: false, reason: 'declined', postSlug: payload.post, patronUrl });
[9e9e6f9]64 }
65 const membership = await PaidPatreon.verifyPatron(r.site.id, code, baseUrl(req) + '/paid/callback').catch(() => null);
66 const cents = membership ? (membership.cents || 0) : 0;
67 const active = membership && membership.status === 'active_patron';
68 if (!active || cents < payload.cents) {
69 return renderPage(req, res, 'pages/paid-result', {
70 pageTitle: 'Ontgrendelen', bodyClass: 'on-special', ok: false,
[c3d12a6]71 reason: active ? 'tier' : 'notpatron', neededCents: payload.cents, haveCents: cents, postSlug: payload.post, patronUrl,
[ec288dc]72 debug: membership ? membership.diag : 'no_response',
[9e9e6f9]73 });
74 }
75 // Supporter at the right tier. Hand out registration options + a signed blob
76 // carrying the challenge and the proven cents; the passkey page returns both.
77 const options = await Passkey.registrationOptions(baseUrl(req), r.site.slug);
78 const blob = signBlob({ purpose: 'reg', siteId: r.site.id, cents, challenge: options.challenge }, 900);
79 renderPage(req, res, 'pages/paid-passkey', {
80 pageTitle: 'Maak je passkey', bodyClass: 'on-special',
81 optionsJson: JSON.stringify(options), regBlob: blob, postSlug: payload.post,
82 });
83});
84
85// Step 3: verify the passkey and store the pseudonymous entitlement.
86router.post('/register', express.json({ limit: '64kb' }), async (req, res) => {
87 const r = ready(req, res); if (!r) return res.status(404).json({ error: 'unavailable' });
88 const { response, blob } = req.body || {};
89 const payload = verifyBlob(String(blob || ''));
90 if (!payload || payload.purpose !== 'reg' || payload.siteId !== r.site.id) {
91 return res.status(400).json({ error: 'bad_challenge' });
92 }
93 const cred = await Passkey.verifyRegistration(baseUrl(req), response, payload.challenge);
94 if (!cred) return res.status(400).json({ error: 'verify_failed' });
95 Passkey.storeEntitlement({
96 credentialId: cred.credentialId, siteId: r.site.id, publicKey: cred.publicKey,
97 counter: cred.counter, transports: cred.transports, minCents: payload.cents,
98 });
99 res.json({ ok: true });
100});
101
[6cbd014]102// Step 4 (unlock): hand out authentication options for a passkey assertion.
103router.get('/challenge', async (req, res) => {
104 const r = ready(req, res); if (!r) return;
105 const slug = String(req.query.post || '').trim();
106 const post = slug ? db.prepare('SELECT slug, paid, paid_min_cents FROM posts WHERE site_id = ? AND slug = ?').get(r.site.id, slug) : null;
107 if (!post || !post.paid) return res.status(404).json({ error: 'not_paid' });
108 const cents = post.paid_min_cents || PaidPatreon.defaultMinCents(r.site.id);
109 const options = await Passkey.authenticationOptions(baseUrl(req));
110 const blob = signBlob({ purpose: 'auth', siteId: r.site.id, cents, post: post.slug, challenge: options.challenge }, 300);
111 res.json({ options, blob });
112});
113
114// Verify the assertion, check the entitlement, and return the full post body in
115// the SAME response. No unlock token becomes state (design decision).
116router.post('/unlock', express.json({ limit: '64kb' }), async (req, res) => {
117 const r = ready(req, res); if (!r) return res.status(404).json({ error: 'unavailable' });
118 const { response, blob } = req.body || {};
119 const payload = verifyBlob(String(blob || ''));
120 if (!payload || payload.purpose !== 'auth' || payload.siteId !== r.site.id) return res.status(400).json({ error: 'bad_challenge' });
121 const credId = response && response.id;
122 const ent = credId ? Passkey.getEntitlement(credId, r.site.id) : null;
123 if (!ent) return res.status(403).json({ error: 'no_entitlement' }); // unknown/expired passkey
124 if ((ent.min_cents || 0) < payload.cents) return res.status(403).json({ error: 'tier' });
125 const vr = await Passkey.verifyAssertion(baseUrl(req), response, payload.challenge, ent);
126 if (!vr) return res.status(400).json({ error: 'verify_failed' });
127 Passkey.bumpCounter(credId, vr.newCounter);
128 const post = db.prepare("SELECT * FROM posts WHERE site_id = ? AND slug = ? AND status = 'published'").get(r.site.id, String(payload.post || ''));
129 if (!post || !post.paid) return res.status(404).json({ error: 'gone' });
130 res.json({ ok: true, title: post.title || '', html: renderPostBodyHtml(r.site, post, req) });
131});
132
[9e9e6f9]133export default router;
Note: See TracBrowser for help on using the repository browser.