source: Klonkt/src/routes/guardian2.js@ 05665bc

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

Guardian 2: losse guardians via uitnodiging (guardian-only accounts)

Stap 1 van het uitbouwplan op /guardian2. Een familie nodigt oma uit met een
link; zij kiest naam + wachtwoord en heeft daarmee een guardian-only account:
user + minimale site met guardian_only=1. Omdat alles in Klonkt al per slug
werkt (actor, WebFinger, inbox, offers, push, deze PWA) is zij daarmee meteen
een volwaardige guardian-actor, zonder CMS eromheen.

Changed files:
src/config/database.js

  • sites.guardian_only vlag; tabel ap_guardian_invites (token, eenmalig)

src/routes/guardian2.js

  • POST /invite (link minten, ingelogd), GET/POST /join/:token (naam+wachtwoord, user+site aanmaken, sessie, redirect naar de PWA)

src/views/pages/guardian2.ejs

  • Invite a guardian-knop in de header

remarks: npm test 164/164; join met ongeldig token geeft 404. Nog te doen op v2:
guardian-only sites uit listings houden, push per account, meekijken/follow-
goedkeuring.

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

  • Property mode set to 100644
File size: 12.2 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 crypto from 'crypto';
13import bcrypt from 'bcryptjs';
14import path from 'path';
15import { fileURLToPath } from 'url';
16import db from '../config/database.js';
17import { requireAuth } from '../middleware/auth.js';
18import AP from '../services/ActivityPubService.js';
19import * as Guardianship from '../services/guardianship/index.js';
20import { t as i18nT, resolveLang } from '../services/i18n.js';
21import { injectCspNonce } from '../middleware/render.js';
22
23const router = express.Router();
24const __dir = path.dirname(fileURLToPath(import.meta.url));
25
26/** The acting site: ?site=slug when owned, else the user's first site. */
27function siteForUser(req) {
28 const userId = req.session.user.id;
29 const want = String(req.query.site || req.body?.site || '').trim();
30 if (want) {
31 const s = db.prepare('SELECT * FROM sites WHERE slug = ? AND owner_id = ?').get(want, userId);
32 if (s) return s;
33 }
34 return db.prepare('SELECT * FROM sites WHERE owner_id = ? ORDER BY id LIMIT 1').get(userId);
35}
36
37/** Everything the dashboard shows, one shape for page and API. */
38function uiStrings(L) {
39 const keys = ['sent', 'sent_retry', 'sending', 'not_found', 'failed', 'network',
40 'pending', 'active', 'retract', 'release', 'open', 'push_unavailable',
41 'accept', 'reject', 'complete', 'awaiting_others', 'coguard'];
42 return Object.fromEntries(keys.map((k) => [k, i18nT(L, `guardian.${k}`)]));
43}
44
45function dashboardState(site, L) {
46 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
47 const me = AP.actorId(base, site.slug);
48 const help = db.prepare(
49 `SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, content, published, created_at
50 FROM ap_mentions WHERE slug = ? AND help_request = 1 ORDER BY created_at DESC LIMIT 50`
51 ).all(site.slug);
52 return {
53 site: site.slug,
54 me,
55 wards: Guardianship.listWards(site.slug), // committed wards
56 offers: Guardianship.offersCollection(`${me}/queues/offers`, site.slug, me).orderedItems,
57 help,
58 strings: uiStrings(L),
59 };
60}
61
62// ── The PWA page ─────────────────────────────────────────────────────────
63router.get('/', requireAuth, (req, res) => {
64 const site = siteForUser(req);
65 const L = resolveLang(req);
66 if (!site) return res.status(404).send('No site for this account.');
67 const sites = db.prepare('SELECT slug, title FROM sites WHERE owner_id = ? ORDER BY id').all(req.session.user.id);
68 // This standalone PWA page is rendered directly (not through renderPage), so
69 // the CSP nonce must be injected here — otherwise strict-dynamic blocks
70 // guardian.js and the whole dashboard is dead (buttons do nothing).
71 res.render('pages/guardian2', {
72 state: dashboardState(site, L),
73 sites,
74 lang: L,
75 t: (k, v) => i18nT(L, k, v),
76 cspNonce: res.locals.cspNonce,
77 }, (err, html) => {
78 if (err) { console.error('[guardian] render error', err); return res.status(500).send('Internal Server Error'); }
79 res.send(injectCspNonce(html, res.locals.cspNonce));
80 });
81});
82
83// ── JSON state for refreshes ─────────────────────────────────────────────
84router.get('/api/state', requireAuth, (req, res) => {
85 const site = siteForUser(req);
86 if (!site) return res.status(404).json({ error: 'no_site' });
87 res.json(dashboardState(site, resolveLang(req)));
88});
89
90// ── Adopt a ward: handle → resolve → C2S Offer through the same pipeline
91// the Shaer apps use (one path, one behavior).
92router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
93 const site = siteForUser(req);
94 if (!site) return res.status(404).json({ error: 'no_site' });
95 const handle = String(req.body?.handle || '').trim();
96 if (!handle) return res.status(400).json({ error: 'empty_handle' });
97 const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null);
98 if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account
99 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
100 const me = AP.actorId(base, site.slug);
101 const r = await AP.ingestOutboxActivity(site, req.session.user, {
102 type: 'Offer',
103 object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me },
104 });
105 // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the
106 // offer is recorded and delivery is retried in the background.
107 if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' });
108 res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false });
109});
110
111// ── Answer an offer (co-guardian accept/reject, or the candidate's final
112// "complete"). All three are a C2S Accept/Reject on the offer id; the
113// handshake module decides when it commits (§3.1).
114router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
115 const site = siteForUser(req);
116 if (!site) return res.status(404).json({ error: 'no_site' });
117 const offerId = String(req.body?.offer || '').trim();
118 const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept';
119 if (!offerId) return res.status(400).json({ error: 'empty_offer' });
120 const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId });
121 if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' });
122 res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit });
123});
124
125// ── PWA assets served no-cache, so an update is never masked by the 1-year
126// /assets cache or a stuck install (that was the whole "nothing works after
127// a deploy" bug). Small files; the browser revalidates and gets a 304 when
128// unchanged, the fresh file when changed.
129function pwaAsset(rel, type) {
130 return (req, res) => {
131 res.set('Cache-Control', 'no-cache');
132 res.type(type);
133 res.sendFile(path.join(__dir, '..', 'assets', rel));
134 };
135}
136router.get('/app.js', pwaAsset('js/guardian2.js', 'application/javascript'));
137router.get('/app.css', pwaAsset('css/guardian2.css', 'text/css'));
138
139// ── Manage: release a committed ward (local Undo; federation is Fase 4). ──
140router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), (req, res) => {
141 const site = siteForUser(req);
142 if (!site) return res.status(404).json({ error: 'no_site' });
143 const uri = String(req.body?.uri || '').trim();
144 if (!uri) return res.status(400).json({ error: 'empty_uri' });
145 Guardianship.removeRelation(site.slug, 'guardian', uri);
146 res.json({ ok: true });
147});
148
149// ── The installable identity: own scope so the Guardian corner installs as
150// its own app next to the site PWA.
151router.get('/manifest.webmanifest', (req, res) => {
152 const site = res.locals.site;
153 res.set('Cache-Control', 'no-cache');
154 res.json({
155 id: `klonkt-guardian2-${site?.slug || 'guardian'}`,
156 name: 'Klonkt Guardian',
157 short_name: 'Guardian 2',
158 description: 'Ward management and help requests for guardians.',
159 scope: '/guardian2/',
160 start_url: '/guardian?source=pwa',
161 display: 'standalone',
162 display_override: ['standalone', 'minimal-ui'],
163 orientation: 'any',
164 background_color: '#141a24',
165 theme_color: '#ff6b35',
166 lang: site?.language || 'nl',
167 icons: [
168 { src: '/guardian2/icon.svg', sizes: 'any', type: 'image/svg+xml' },
169 ],
170 });
171});
172
173// The buoy mark, in the guardian accent (mirrors the site favicon pattern).
174router.get('/icon.svg', (req, res) => {
175 const svg = `<?xml version="1.0" encoding="UTF-8"?>
176<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
177 <rect width="64" height="64" rx="14" fill="#ff6b35"/>
178 <text x="50%" y="50%" dy="0.35em" text-anchor="middle" font-size="36">&#128735;</text>
179</svg>`;
180 res.set('Content-Type', 'image/svg+xml');
181 res.set('Cache-Control', 'public, max-age=86400');
182 res.send(svg);
183});
184
185// ── Losse guardians (Guardian 2): uitnodigen en aansluiten ───────────────
186// De familie nodigt oma uit; zij kiest naam + wachtwoord en heeft daarmee een
187// guardian-only account: user + minimale site (guardian_only=1). Alles wat al
188// per slug werkt (actor, inbox, offers, push, deze PWA) werkt dan meteen.
189
190router.post('/invite', requireAuth, (req, res) => {
191 const token = crypto.randomBytes(16).toString('base64url');
192 db.prepare('INSERT INTO ap_guardian_invites (token, created_by) VALUES (?,?)')
193 .run(token, req.session.user.id);
194 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
195 const url = `${base}/guardian2/join/${token}`;
196 res.send(`<!doctype html><meta charset="utf-8"><body style="font-family:sans-serif;max-width:480px;margin:40px auto">
197 <h2>Invite a guardian</h2>
198 <p>Share this link. It lets one person create a guardian account here:</p>
199 <p><a href="${url}">${url}</a></p>
200 <p><a href="/guardian2">Back</a></p></body>`);
201});
202
203function joinForm(token, error) {
204 return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
205 <body style="font-family:sans-serif;max-width:420px;margin:40px auto">
206 <h2>Become a guardian</h2>
207 <p>Watch over someone you care about. Pick a name and a password; that is all.</p>
208 ${error ? `<p style="color:#b00">${error}</p>` : ''}
209 <form method="post" action="/guardian2/join/${token}">
210 <p><input name="name" placeholder="your name (grandma)" required pattern="[a-z0-9_-]{1,32}"
211 style="width:100%;padding:10px" autocapitalize="none"></p>
212 <p><input name="password" type="password" placeholder="password" required minlength="8"
213 style="width:100%;padding:10px"></p>
214 <p><button style="width:100%;padding:12px">Create my guardian account</button></p>
215 </form></body>`;
216}
217
218router.get('/join/:token', (req, res) => {
219 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
220 .get(req.params.token);
221 if (!inv) return res.status(404).send('This invite is no longer valid.');
222 res.send(joinForm(req.params.token));
223});
224
225router.post('/join/:token', express.urlencoded({ extended: false }), (req, res) => {
226 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
227 .get(req.params.token);
228 if (!inv) return res.status(404).send('This invite is no longer valid.');
229 const name = String(req.body.name || '').trim().toLowerCase();
230 const password = String(req.body.password || '');
231 if (!/^[a-z0-9_-]{1,32}$/.test(name)) return res.status(400).send(joinForm(req.params.token, 'Only lowercase letters, digits, - and _.'));
232 if (password.length < 8) return res.status(400).send(joinForm(req.params.token, 'Password: at least 8 characters.'));
233 if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(name) || db.prepare('SELECT 1 FROM users WHERE username = ?').get(name)) {
234 return res.status(409).send(joinForm(req.params.token, 'That name is taken, pick another.'));
235 }
236 const userId = crypto.randomUUID();
237 db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)')
238 .run(userId, name, `${name}@guardian.invalid`, bcrypt.hashSync(password, 10), 'member');
239 db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, guardian_only) VALUES (?,?,?,?,0,1)')
240 .run(crypto.randomUUID(), name, name, userId);
241 db.prepare('UPDATE ap_guardian_invites SET used_by = ?, used_at = CURRENT_TIMESTAMP WHERE token = ?')
242 .run(userId, req.params.token);
243 req.session.user = { id: userId, username: name, role: 'member' };
244 res.redirect('/guardian2');
245});
246
247export default router;
Note: See TracBrowser for help on using the repository browser.