source: Klonkt/src/routes/guardian2.js@ e62f65d

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

Guardian 2: de zwaai (shaer:wave), warmte zonder publiceren

Een guardian kan met één tik naar een ward zwaaien: "denkt aan je". Het is een
prive direct-note met een shaer:wave-marker, spiegelbeeld van de reddingsboei
(shaer:helpRequest): nooit een feed-post, geen boosts, geen timeline. Niet-shaer
clients zien gewoon een DM; een shaer-client kan het als zacht seintje tonen. De
guardian publiceert dus niks.

Rijdt op het bestaande direct-note-pad (delivery.js), dus cross-instance en met
retry. De ward ontvangt 'm als prive-mention (marker opgeslagen in ap_mentions.wave
voor latere weergave).

Changed files:
src/services/guardianship/notes.js

  • waveProps/isWave naast de helpRequest-marker

src/services/guardianship/index.js

  • waveProps/isWave geexporteerd

src/services/guardianship/delivery.js

  • deliverDirectNote neemt een wave-vlag, stempelt ap_outbox.wave

src/services/ActivityPubService.js

  • buildReplyNote stempelt shaer:wave; inbound mention slaat wave op

src/config/database.js

  • ap_outbox.wave + ap_mentions.wave

src/routes/guardian2.js

  • POST /api/wave (alleen naar je eigen ward); wave/waved strings

src/views/pages/guardian2.ejs, src/assets/js/guardian2.js

  • Zwaai-knop op elke ward-kaart

src/services/i18n.js

  • guardian2 wave/waved (nl/en/de)

remarks: npm test 167/167; wave-api auth-gated. Ward-kant toont 'm nu als prive-
mention (de emoji draagt 'm); een wave-badge in Berichten + het DM-antwoord-draadje
zijn de volgende, kleine stap.

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

  • Property mode set to 100644
File size: 17.3 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 const s = Object.fromEntries(keys.map((k) => [k, i18nT(L, `guardian.${k}`)]));
43 s.wave = i18nT(L, 'guardian2.wave');
44 s.waved = i18nT(L, 'guardian2.waved');
45 return s;
46}
47
48function dashboardState(site, L) {
49 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
50 const me = AP.actorId(base, site.slug);
51 const help = db.prepare(
52 `SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, content, published, created_at
53 FROM ap_mentions WHERE slug = ? AND help_request = 1 ORDER BY created_at DESC LIMIT 50`
54 ).all(site.slug);
55 return {
56 site: site.slug,
57 me,
58 wards: Guardianship.listWards(site.slug), // committed wards
59 offers: Guardianship.offersCollection(`${me}/queues/offers`, site.slug, me).orderedItems,
60 help,
61 strings: uiStrings(L),
62 };
63}
64
65// ── The PWA page ─────────────────────────────────────────────────────────
66router.get('/', requireAuth, (req, res) => {
67 const site = siteForUser(req);
68 const L = resolveLang(req);
69 if (!site) return res.status(404).send('No site for this account.');
70 const sites = db.prepare('SELECT slug, title FROM sites WHERE owner_id = ? ORDER BY id').all(req.session.user.id);
71 // This standalone PWA page is rendered directly (not through renderPage), so
72 // the CSP nonce must be injected here — otherwise strict-dynamic blocks
73 // guardian.js and the whole dashboard is dead (buttons do nothing).
74 res.render('pages/guardian2', {
75 state: dashboardState(site, L),
76 sites,
77 lang: L,
78 t: (k, v) => i18nT(L, k, v),
79 cspNonce: res.locals.cspNonce,
80 }, (err, html) => {
81 if (err) { console.error('[guardian] render error', err); return res.status(500).send('Internal Server Error'); }
82 res.send(injectCspNonce(html, res.locals.cspNonce));
83 });
84});
85
86// ── JSON state for refreshes ─────────────────────────────────────────────
87router.get('/api/state', requireAuth, (req, res) => {
88 const site = siteForUser(req);
89 if (!site) return res.status(404).json({ error: 'no_site' });
90 res.json(dashboardState(site, resolveLang(req)));
91});
92
93// ── Meekijken (FEP-633c §5, interop-hoofdroute): a committed guardian FOLLOWS
94// its wards, so their posts (incl. followers-only) are DELIVERED to the
95// guardian's inbox → timeline. The follow is the mechanism; no new fetch.
96// First contact also backfills the ward's recent PUBLIC posts as a cold
97// start so the corner is not empty before delivery catches up.
98function ensureWardConnections(site) {
99 let wards;
100 try { wards = Guardianship.listWards(site.slug); } catch { return; }
101 for (const w of wards) {
102 const already = db.prepare('SELECT 1 FROM ap_following WHERE slug = ? AND actor_uri = ?')
103 .get(site.slug, w.other_uri);
104 if (already) continue;
105 // Follow (guardian's server auto-accepts today; §5.3 gating is a later fase).
106 AP.followActor(site, w.other_uri).catch(() => { /* retried by the queue */ });
107 // Cold start: pull recent public posts now so oma sees something at once.
108 AP.backfillFromOutbox(site.slug, w.other_uri).catch(() => { /* best-effort */ });
109 }
110}
111
112// ── The wards' corner: your wards' posts, read-only. No reply, no share; a
113// guardian watches, it does not publish (Robins besluit).
114router.get('/api/feed', requireAuth, (req, res) => {
115 const site = siteForUser(req);
116 if (!site) return res.status(404).json({ error: 'no_site' });
117 ensureWardConnections(site);
118 const wardUris = new Set(Guardianship.listWards(site.slug).map((w) => w.other_uri));
119 // Only show the wards you actually guard (the timeline can hold more).
120 const items = AP.getTimeline(site.slug, 60, 0)
121 .filter((p) => wardUris.has(p.author_uri))
122 .map((p) => ({
123 id: p.id,
124 author: p.author_handle || p.author_name || p.author_uri,
125 authorName: p.author_name,
126 authorIcon: p.author_icon,
127 content: p.content,
128 url: p.url,
129 published: p.published || p.created_at,
130 cw: p.cw || null,
131 media: p.media_json ? JSON.parse(p.media_json) : [],
132 }));
133 res.json({ items, following: wardUris.size });
134});
135
136// ── Follow-gating (FEP-633c §5.3): pending follows on MY wards, for me to
137// approve. Ward and guardian are co-located on the family Klonkt here, so
138// the guardian reads its wards' pending follows locally.
139function wardSlugsOf(site) {
140 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
141 return Guardianship.listWards(site.slug)
142 .map((w) => (w.other_uri.startsWith(base) ? w.other_uri.split('/').pop() : null))
143 .filter(Boolean);
144}
145
146router.get('/api/follow-requests', requireAuth, (req, res) => {
147 const site = siteForUser(req);
148 if (!site) return res.status(404).json({ error: 'no_site' });
149 const items = [];
150 for (const wardSlug of wardSlugsOf(site)) {
151 for (const f of Guardianship.follows.listForWard(wardSlug)) {
152 items.push({ id: f.id, ward: wardSlug, follower: f.follower_handle || f.follower_name || f.follower_uri, followerIcon: f.follower_icon, created: f.created_at });
153 }
154 }
155 res.json({ items });
156});
157
158router.post('/api/follow/:id', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
159 const site = siteForUser(req);
160 if (!site) return res.status(404).json({ error: 'no_site' });
161 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
162 const me = AP.actorId(base, site.slug);
163 const decision = req.body?.decision === 'reject' ? 'reject' : 'approve';
164 const pending = Guardianship.follows.getPending(req.params.id);
165 if (!pending) return res.status(404).json({ error: 'gone' });
166 // I must actually be a guardian of this ward.
167 const guardians = Guardianship.listGuardians(pending.ward_slug).map((g) => g.other_uri);
168 if (!guardians.includes(me)) return res.status(403).json({ error: 'not_a_guardian' });
169 const r = Guardianship.follows.decide(pending.id, me, decision, guardians);
170 try {
171 if (r.outcome === 'approved') { await AP.acceptGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); }
172 else if (r.outcome === 'rejected') { await AP.rejectGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); }
173 } catch (e) { return res.status(502).json({ error: 'delivery', outcome: r.outcome }); }
174 res.json({ ok: true, outcome: r.outcome });
175});
176
177// ── Wave (FEP-633c §5, shaer:wave): a gentle "thinking of you" from a
178// guardian to a ward. A private direct note, never a feed post. Warmth
179// without publishing (Robins besluit).
180router.post('/api/wave', requireAuth, express.json({ limit: '2kb' }), async (req, res) => {
181 const site = siteForUser(req);
182 if (!site) return res.status(404).json({ error: 'no_site' });
183 const wardUri = String(req.body?.ward || '').trim();
184 // Only wave at a ward you actually guard.
185 const isWard = Guardianship.listWards(site.slug).some((w) => w.other_uri === wardUri);
186 if (!wardUri || !isWard) return res.status(403).json({ error: 'not_your_ward' });
187 const text = String(req.body?.text || '').trim().slice(0, 200) || '👋 thinking of you';
188 const r = await AP.deliverDirectNote(site, { recipients: [wardUri], text, wave: true }).catch(() => null);
189 if (!r) return res.status(502).json({ error: 'delivery' });
190 res.json({ ok: true, delivered: r.delivered });
191});
192
193// ── Adopt a ward: handle → resolve → C2S Offer through the same pipeline
194// the Shaer apps use (one path, one behavior).
195router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
196 const site = siteForUser(req);
197 if (!site) return res.status(404).json({ error: 'no_site' });
198 const handle = String(req.body?.handle || '').trim();
199 if (!handle) return res.status(400).json({ error: 'empty_handle' });
200 const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null);
201 if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account
202 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
203 const me = AP.actorId(base, site.slug);
204 const r = await AP.ingestOutboxActivity(site, req.session.user, {
205 type: 'Offer',
206 object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me },
207 });
208 // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the
209 // offer is recorded and delivery is retried in the background.
210 if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' });
211 res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false });
212});
213
214// ── Answer an offer (co-guardian accept/reject, or the candidate's final
215// "complete"). All three are a C2S Accept/Reject on the offer id; the
216// handshake module decides when it commits (§3.1).
217router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
218 const site = siteForUser(req);
219 if (!site) return res.status(404).json({ error: 'no_site' });
220 const offerId = String(req.body?.offer || '').trim();
221 const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept';
222 if (!offerId) return res.status(400).json({ error: 'empty_offer' });
223 const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId });
224 if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' });
225 res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit });
226});
227
228// ── PWA assets served no-cache, so an update is never masked by the 1-year
229// /assets cache or a stuck install (that was the whole "nothing works after
230// a deploy" bug). Small files; the browser revalidates and gets a 304 when
231// unchanged, the fresh file when changed.
232function pwaAsset(rel, type) {
233 return (req, res) => {
234 res.set('Cache-Control', 'no-cache');
235 res.type(type);
236 res.sendFile(path.join(__dir, '..', 'assets', rel));
237 };
238}
239router.get('/app.js', pwaAsset('js/guardian2.js', 'application/javascript'));
240router.get('/app.css', pwaAsset('css/guardian2.css', 'text/css'));
241
242// ── Manage: release a committed ward (local Undo; federation is Fase 4). ──
243router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), (req, res) => {
244 const site = siteForUser(req);
245 if (!site) return res.status(404).json({ error: 'no_site' });
246 const uri = String(req.body?.uri || '').trim();
247 if (!uri) return res.status(400).json({ error: 'empty_uri' });
248 Guardianship.removeRelation(site.slug, 'guardian', uri);
249 res.json({ ok: true });
250});
251
252// ── The installable identity: own scope so the Guardian corner installs as
253// its own app next to the site PWA.
254router.get('/manifest.webmanifest', (req, res) => {
255 const site = res.locals.site;
256 res.set('Cache-Control', 'no-cache');
257 res.json({
258 id: `klonkt-guardian2-${site?.slug || 'guardian'}`,
259 name: 'Klonkt Guardian',
260 short_name: 'Guardian 2',
261 description: 'Ward management and help requests for guardians.',
262 scope: '/guardian2/',
263 start_url: '/guardian?source=pwa',
264 display: 'standalone',
265 display_override: ['standalone', 'minimal-ui'],
266 orientation: 'any',
267 background_color: '#141a24',
268 theme_color: '#ff6b35',
269 lang: site?.language || 'nl',
270 icons: [
271 { src: '/guardian2/icon.svg', sizes: 'any', type: 'image/svg+xml' },
272 ],
273 });
274});
275
276// The buoy mark, in the guardian accent (mirrors the site favicon pattern).
277router.get('/icon.svg', (req, res) => {
278 const svg = `<?xml version="1.0" encoding="UTF-8"?>
279<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
280 <rect width="64" height="64" rx="14" fill="#ff6b35"/>
281 <text x="50%" y="50%" dy="0.35em" text-anchor="middle" font-size="36">&#128735;</text>
282</svg>`;
283 res.set('Content-Type', 'image/svg+xml');
284 res.set('Cache-Control', 'public, max-age=86400');
285 res.send(svg);
286});
287
288// ── Losse guardians (Guardian 2): uitnodigen en aansluiten ───────────────
289// De familie nodigt oma uit; zij kiest naam + wachtwoord en heeft daarmee een
290// guardian-only account: user + minimale site (guardian_only=1). Alles wat al
291// per slug werkt (actor, inbox, offers, push, deze PWA) werkt dan meteen.
292
293router.post('/invite', requireAuth, (req, res) => {
294 const token = crypto.randomBytes(16).toString('base64url');
295 db.prepare('INSERT INTO ap_guardian_invites (token, created_by) VALUES (?,?)')
296 .run(token, req.session.user.id);
297 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
298 const url = `${base}/guardian2/join/${token}`;
299 res.send(`<!doctype html><meta charset="utf-8"><body style="font-family:sans-serif;max-width:480px;margin:40px auto">
300 <h2>Invite a guardian</h2>
301 <p>Share this link. It lets one person create a guardian account here:</p>
302 <p><a href="${url}">${url}</a></p>
303 <p><a href="/guardian2">Back</a></p></body>`);
304});
305
306function joinForm(token, error) {
307 return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
308 <body style="font-family:sans-serif;max-width:420px;margin:40px auto">
309 <h2>Become a guardian</h2>
310 <p>Watch over someone you care about. Pick a name and a password; that is all.</p>
311 ${error ? `<p style="color:#b00">${error}</p>` : ''}
312 <form method="post" action="/guardian2/join/${token}">
313 <p><input name="name" placeholder="your name (grandma)" required pattern="[a-z0-9_-]{1,32}"
314 style="width:100%;padding:10px" autocapitalize="none"></p>
315 <p><input name="password" type="password" placeholder="password" required minlength="8"
316 style="width:100%;padding:10px"></p>
317 <p><button style="width:100%;padding:12px">Create my guardian account</button></p>
318 </form></body>`;
319}
320
321router.get('/join/:token', (req, res) => {
322 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
323 .get(req.params.token);
324 if (!inv) return res.status(404).send('This invite is no longer valid.');
325 res.send(joinForm(req.params.token));
326});
327
328router.post('/join/:token', express.urlencoded({ extended: false }), (req, res) => {
329 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
330 .get(req.params.token);
331 if (!inv) return res.status(404).send('This invite is no longer valid.');
332 const name = String(req.body.name || '').trim().toLowerCase();
333 const password = String(req.body.password || '');
334 if (!/^[a-z0-9_-]{1,32}$/.test(name)) return res.status(400).send(joinForm(req.params.token, 'Only lowercase letters, digits, - and _.'));
335 if (password.length < 8) return res.status(400).send(joinForm(req.params.token, 'Password: at least 8 characters.'));
336 if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(name) || db.prepare('SELECT 1 FROM users WHERE username = ?').get(name)) {
337 return res.status(409).send(joinForm(req.params.token, 'That name is taken, pick another.'));
338 }
339 const userId = crypto.randomUUID();
340 db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)')
341 .run(userId, name, `${name}@guardian.invalid`, bcrypt.hashSync(password, 10), 'member');
342 db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, guardian_only) VALUES (?,?,?,?,0,1)')
343 .run(crypto.randomUUID(), name, name, userId);
344 db.prepare('UPDATE ap_guardian_invites SET used_by = ?, used_at = CURRENT_TIMESTAMP WHERE token = ?')
345 .run(userId, req.params.token);
346 req.session.user = { id: userId, username: name, role: 'member' };
347 res.redirect('/guardian2');
348});
349
350export default router;
Note: See TracBrowser for help on using the repository browser.