source: Klonkt/src/routes/guardian.js@ 5c373b8

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

Guardian-PWA: CSP-nonce injecteren zodat de JS laadt

DIT was de echte oorzaak van "guardian-PWA doet niks / hangt / niks functioneel",
en waarom cache legen en incognito nooit hielpen: het is geen caching.

De guardian-PWA wordt direct met res.render gerenderd, NIET via renderPage. Alleen
renderPage draait injectCspNonce over de HTML. Onze CSP is strict-dynamic + per-
request nonce, dus een <script src="/guardian/app.js"> zonder nonce wordt door de
browser geweigerd (precies de fout die Robin zag op boiert.eu). Gevolg: guardian.js
laadde nooit, dus alle knoppen deden niks. Dit gold ook al voor de oude
/assets/js/guardian.js; de no-cache-verhuizing veranderde daar niks aan.

Fix: de guardian-render door injectCspNonce halen, net als de rest van de app.
injectCspNonce is nu exporteerbaar. Geverifieerd: na injectie heeft het app.js-
script de per-request nonce.

Changed files:
src/middleware/render.js

  • injectCspNonce geexporteerd

src/routes/guardian.js

  • guardian-PWA gerenderd naar string en nonce geinjecteerd (anders blokkeert strict-dynamic de JS)

remarks: embed-player zet een eigen CSP (unsafe-inline) en is niet geraakt. Tests 6/6.

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

  • Property mode set to 100644
File size: 8.5 KB
Line 
1/**
2 * The Guardian PWA (FEP-633c): a separate, installable corner of Klonkt for
3 * guardians. One place to add and manage wards, a message centre for
4 * incoming help requests and adoption traffic, and its own push channel
5 * (alert types 'help' and 'guardian', web-push slice reused).
6 *
7 * Everything is scoped to a site the logged-in user OWNS: the guardian acts
8 * as one of their own actors (?site=slug picks one when they own several).
9 * Views carry no inline scripts (CSP): logic lives in /assets/js/guardian.js.
10 */
11import express from 'express';
12import path from 'path';
13import { fileURLToPath } from 'url';
14import db from '../config/database.js';
15import { requireAuth } from '../middleware/auth.js';
16import AP from '../services/ActivityPubService.js';
17import * as Guardianship from '../services/guardianship/index.js';
18import { t as i18nT, resolveLang } from '../services/i18n.js';
19import { injectCspNonce } from '../middleware/render.js';
20
21const router = express.Router();
22const __dir = path.dirname(fileURLToPath(import.meta.url));
23
24/** The acting site: ?site=slug when owned, else the user's first site. */
25function siteForUser(req) {
26 const userId = req.session.user.id;
27 const want = String(req.query.site || req.body?.site || '').trim();
28 if (want) {
29 const s = db.prepare('SELECT * FROM sites WHERE slug = ? AND owner_id = ?').get(want, userId);
30 if (s) return s;
31 }
32 return db.prepare('SELECT * FROM sites WHERE owner_id = ? ORDER BY id LIMIT 1').get(userId);
33}
34
35/** Everything the dashboard shows, one shape for page and API. */
36function uiStrings(L) {
37 const keys = ['sent', 'sent_retry', 'sending', 'not_found', 'failed', 'network',
38 'pending', 'active', 'retract', 'release', 'open', 'push_unavailable',
39 'accept', 'reject', 'complete', 'awaiting_others', 'coguard'];
40 return Object.fromEntries(keys.map((k) => [k, i18nT(L, `guardian.${k}`)]));
41}
42
43function dashboardState(site, L) {
44 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
45 const me = AP.actorId(base, site.slug);
46 const help = db.prepare(
47 `SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, content, published, created_at
48 FROM ap_mentions WHERE slug = ? AND help_request = 1 ORDER BY created_at DESC LIMIT 50`
49 ).all(site.slug);
50 return {
51 site: site.slug,
52 me,
53 wards: Guardianship.listWards(site.slug), // committed wards
54 offers: Guardianship.offersCollection(`${me}/queues/offers`, site.slug, me).orderedItems,
55 help,
56 strings: uiStrings(L),
57 };
58}
59
60// ── The PWA page ─────────────────────────────────────────────────────────
61router.get('/', requireAuth, (req, res) => {
62 const site = siteForUser(req);
63 const L = resolveLang(req);
64 if (!site) return res.status(404).send('No site for this account.');
65 const sites = db.prepare('SELECT slug, title FROM sites WHERE owner_id = ? ORDER BY id').all(req.session.user.id);
66 // This standalone PWA page is rendered directly (not through renderPage), so
67 // the CSP nonce must be injected here — otherwise strict-dynamic blocks
68 // guardian.js and the whole dashboard is dead (buttons do nothing).
69 res.render('pages/guardian', {
70 state: dashboardState(site, L),
71 sites,
72 lang: L,
73 t: (k, v) => i18nT(L, k, v),
74 cspNonce: res.locals.cspNonce,
75 }, (err, html) => {
76 if (err) { console.error('[guardian] render error', err); return res.status(500).send('Internal Server Error'); }
77 res.send(injectCspNonce(html, res.locals.cspNonce));
78 });
79});
80
81// ── JSON state for refreshes ─────────────────────────────────────────────
82router.get('/api/state', requireAuth, (req, res) => {
83 const site = siteForUser(req);
84 if (!site) return res.status(404).json({ error: 'no_site' });
85 res.json(dashboardState(site, resolveLang(req)));
86});
87
88// ── Adopt a ward: handle → resolve → C2S Offer through the same pipeline
89// the Shaer apps use (one path, one behavior).
90router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
91 const site = siteForUser(req);
92 if (!site) return res.status(404).json({ error: 'no_site' });
93 const handle = String(req.body?.handle || '').trim();
94 if (!handle) return res.status(400).json({ error: 'empty_handle' });
95 const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null);
96 if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account
97 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
98 const me = AP.actorId(base, site.slug);
99 const r = await AP.ingestOutboxActivity(site, req.session.user, {
100 type: 'Offer',
101 object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me },
102 });
103 // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the
104 // offer is recorded and delivery is retried in the background.
105 if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' });
106 res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false });
107});
108
109// ── Answer an offer (co-guardian accept/reject, or the candidate's final
110// "complete"). All three are a C2S Accept/Reject on the offer id; the
111// handshake module decides when it commits (§3.1).
112router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
113 const site = siteForUser(req);
114 if (!site) return res.status(404).json({ error: 'no_site' });
115 const offerId = String(req.body?.offer || '').trim();
116 const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept';
117 if (!offerId) return res.status(400).json({ error: 'empty_offer' });
118 const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId });
119 if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' });
120 res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit });
121});
122
123// ── PWA assets served no-cache, so an update is never masked by the 1-year
124// /assets cache or a stuck install (that was the whole "nothing works after
125// a deploy" bug). Small files; the browser revalidates and gets a 304 when
126// unchanged, the fresh file when changed.
127function pwaAsset(rel, type) {
128 return (req, res) => {
129 res.set('Cache-Control', 'no-cache');
130 res.type(type);
131 res.sendFile(path.join(__dir, '..', 'assets', rel));
132 };
133}
134router.get('/app.js', pwaAsset('js/guardian.js', 'application/javascript'));
135router.get('/app.css', pwaAsset('css/guardian.css', 'text/css'));
136
137// ── Manage: release a committed ward (local Undo; federation is Fase 4). ──
138router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), (req, res) => {
139 const site = siteForUser(req);
140 if (!site) return res.status(404).json({ error: 'no_site' });
141 const uri = String(req.body?.uri || '').trim();
142 if (!uri) return res.status(400).json({ error: 'empty_uri' });
143 Guardianship.removeRelation(site.slug, 'guardian', uri);
144 res.json({ ok: true });
145});
146
147// ── The installable identity: own scope so the Guardian corner installs as
148// its own app next to the site PWA.
149router.get('/manifest.webmanifest', (req, res) => {
150 const site = res.locals.site;
151 res.set('Cache-Control', 'no-cache');
152 res.json({
153 id: `klonkt-guardian-${site?.slug || 'guardian'}`,
154 name: 'Klonkt Guardian',
155 short_name: 'Guardian',
156 description: 'Ward management and help requests for guardians.',
157 scope: '/guardian/',
158 start_url: '/guardian?source=pwa',
159 display: 'standalone',
160 display_override: ['standalone', 'minimal-ui'],
161 orientation: 'any',
162 background_color: '#141a24',
163 theme_color: '#ff6b35',
164 lang: site?.language || 'nl',
165 icons: [
166 { src: '/guardian/icon.svg', sizes: 'any', type: 'image/svg+xml' },
167 ],
168 });
169});
170
171// The buoy mark, in the guardian accent (mirrors the site favicon pattern).
172router.get('/icon.svg', (req, res) => {
173 const svg = `<?xml version="1.0" encoding="UTF-8"?>
174<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
175 <rect width="64" height="64" rx="14" fill="#ff6b35"/>
176 <text x="50%" y="50%" dy="0.35em" text-anchor="middle" font-size="36">&#128735;</text>
177</svg>`;
178 res.set('Content-Type', 'image/svg+xml');
179 res.set('Cache-Control', 'public, max-age=86400');
180 res.send(svg);
181});
182
183export default router;
Note: See TracBrowser for help on using the repository browser.