| 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 | */
|
|---|
| 11 | import express from 'express';
|
|---|
| 12 | import crypto from 'crypto';
|
|---|
| 13 | import bcrypt from 'bcryptjs';
|
|---|
| 14 | import path from 'path';
|
|---|
| 15 | import { fileURLToPath } from 'url';
|
|---|
| 16 | import db from '../config/database.js';
|
|---|
| 17 | import { requireAuth } from '../middleware/auth.js';
|
|---|
| 18 | import AP from '../services/ActivityPubService.js';
|
|---|
| 19 | import * as Guardianship from '../services/guardianship/index.js';
|
|---|
| 20 | import { t as i18nT, resolveLang } from '../services/i18n.js';
|
|---|
| 21 | import { injectCspNonce } from '../middleware/render.js';
|
|---|
| 22 |
|
|---|
| 23 | const router = express.Router();
|
|---|
| 24 | const __dir = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 25 |
|
|---|
| 26 | /** The acting site: ?site=slug when owned, else the user's first site. */
|
|---|
| 27 | function 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. */
|
|---|
| 38 | function 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 |
|
|---|
| 45 | function 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 ─────────────────────────────────────────────────────────
|
|---|
| 63 | router.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 ─────────────────────────────────────────────
|
|---|
| 84 | router.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 | // ── Meekijken (FEP-633c §5, interop-hoofdroute): a committed guardian FOLLOWS
|
|---|
| 91 | // its wards, so their posts (incl. followers-only) are DELIVERED to the
|
|---|
| 92 | // guardian's inbox → timeline. The follow is the mechanism; no new fetch.
|
|---|
| 93 | // First contact also backfills the ward's recent PUBLIC posts as a cold
|
|---|
| 94 | // start so the corner is not empty before delivery catches up.
|
|---|
| 95 | function ensureWardConnections(site) {
|
|---|
| 96 | let wards;
|
|---|
| 97 | try { wards = Guardianship.listWards(site.slug); } catch { return; }
|
|---|
| 98 | for (const w of wards) {
|
|---|
| 99 | const already = db.prepare('SELECT 1 FROM ap_following WHERE slug = ? AND actor_uri = ?')
|
|---|
| 100 | .get(site.slug, w.other_uri);
|
|---|
| 101 | if (already) continue;
|
|---|
| 102 | // Follow (guardian's server auto-accepts today; §5.3 gating is a later fase).
|
|---|
| 103 | AP.followActor(site, w.other_uri).catch(() => { /* retried by the queue */ });
|
|---|
| 104 | // Cold start: pull recent public posts now so oma sees something at once.
|
|---|
| 105 | AP.backfillFromOutbox(site.slug, w.other_uri).catch(() => { /* best-effort */ });
|
|---|
| 106 | }
|
|---|
| 107 | }
|
|---|
| 108 |
|
|---|
| 109 | // ── The wards' corner: your wards' posts, read-only. No reply, no share; a
|
|---|
| 110 | // guardian watches, it does not publish (Robins besluit).
|
|---|
| 111 | router.get('/api/feed', requireAuth, (req, res) => {
|
|---|
| 112 | const site = siteForUser(req);
|
|---|
| 113 | if (!site) return res.status(404).json({ error: 'no_site' });
|
|---|
| 114 | ensureWardConnections(site);
|
|---|
| 115 | const wardUris = new Set(Guardianship.listWards(site.slug).map((w) => w.other_uri));
|
|---|
| 116 | // Only show the wards you actually guard (the timeline can hold more).
|
|---|
| 117 | const items = AP.getTimeline(site.slug, 60, 0)
|
|---|
| 118 | .filter((p) => wardUris.has(p.author_uri))
|
|---|
| 119 | .map((p) => ({
|
|---|
| 120 | id: p.id,
|
|---|
| 121 | author: p.author_handle || p.author_name || p.author_uri,
|
|---|
| 122 | authorName: p.author_name,
|
|---|
| 123 | authorIcon: p.author_icon,
|
|---|
| 124 | content: p.content,
|
|---|
| 125 | url: p.url,
|
|---|
| 126 | published: p.published || p.created_at,
|
|---|
| 127 | cw: p.cw || null,
|
|---|
| 128 | media: p.media_json ? JSON.parse(p.media_json) : [],
|
|---|
| 129 | }));
|
|---|
| 130 | res.json({ items, following: wardUris.size });
|
|---|
| 131 | });
|
|---|
| 132 |
|
|---|
| 133 | // ── Adopt a ward: handle → resolve → C2S Offer through the same pipeline
|
|---|
| 134 | // the Shaer apps use (one path, one behavior).
|
|---|
| 135 | router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
|
|---|
| 136 | const site = siteForUser(req);
|
|---|
| 137 | if (!site) return res.status(404).json({ error: 'no_site' });
|
|---|
| 138 | const handle = String(req.body?.handle || '').trim();
|
|---|
| 139 | if (!handle) return res.status(400).json({ error: 'empty_handle' });
|
|---|
| 140 | const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null);
|
|---|
| 141 | if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account
|
|---|
| 142 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 143 | const me = AP.actorId(base, site.slug);
|
|---|
| 144 | const r = await AP.ingestOutboxActivity(site, req.session.user, {
|
|---|
| 145 | type: 'Offer',
|
|---|
| 146 | object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me },
|
|---|
| 147 | });
|
|---|
| 148 | // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the
|
|---|
| 149 | // offer is recorded and delivery is retried in the background.
|
|---|
| 150 | if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' });
|
|---|
| 151 | res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false });
|
|---|
| 152 | });
|
|---|
| 153 |
|
|---|
| 154 | // ── Answer an offer (co-guardian accept/reject, or the candidate's final
|
|---|
| 155 | // "complete"). All three are a C2S Accept/Reject on the offer id; the
|
|---|
| 156 | // handshake module decides when it commits (§3.1).
|
|---|
| 157 | router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
|
|---|
| 158 | const site = siteForUser(req);
|
|---|
| 159 | if (!site) return res.status(404).json({ error: 'no_site' });
|
|---|
| 160 | const offerId = String(req.body?.offer || '').trim();
|
|---|
| 161 | const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept';
|
|---|
| 162 | if (!offerId) return res.status(400).json({ error: 'empty_offer' });
|
|---|
| 163 | const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId });
|
|---|
| 164 | if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' });
|
|---|
| 165 | res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit });
|
|---|
| 166 | });
|
|---|
| 167 |
|
|---|
| 168 | // ── PWA assets served no-cache, so an update is never masked by the 1-year
|
|---|
| 169 | // /assets cache or a stuck install (that was the whole "nothing works after
|
|---|
| 170 | // a deploy" bug). Small files; the browser revalidates and gets a 304 when
|
|---|
| 171 | // unchanged, the fresh file when changed.
|
|---|
| 172 | function pwaAsset(rel, type) {
|
|---|
| 173 | return (req, res) => {
|
|---|
| 174 | res.set('Cache-Control', 'no-cache');
|
|---|
| 175 | res.type(type);
|
|---|
| 176 | res.sendFile(path.join(__dir, '..', 'assets', rel));
|
|---|
| 177 | };
|
|---|
| 178 | }
|
|---|
| 179 | router.get('/app.js', pwaAsset('js/guardian2.js', 'application/javascript'));
|
|---|
| 180 | router.get('/app.css', pwaAsset('css/guardian2.css', 'text/css'));
|
|---|
| 181 |
|
|---|
| 182 | // ── Manage: release a committed ward (local Undo; federation is Fase 4). ──
|
|---|
| 183 | router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), (req, res) => {
|
|---|
| 184 | const site = siteForUser(req);
|
|---|
| 185 | if (!site) return res.status(404).json({ error: 'no_site' });
|
|---|
| 186 | const uri = String(req.body?.uri || '').trim();
|
|---|
| 187 | if (!uri) return res.status(400).json({ error: 'empty_uri' });
|
|---|
| 188 | Guardianship.removeRelation(site.slug, 'guardian', uri);
|
|---|
| 189 | res.json({ ok: true });
|
|---|
| 190 | });
|
|---|
| 191 |
|
|---|
| 192 | // ── The installable identity: own scope so the Guardian corner installs as
|
|---|
| 193 | // its own app next to the site PWA.
|
|---|
| 194 | router.get('/manifest.webmanifest', (req, res) => {
|
|---|
| 195 | const site = res.locals.site;
|
|---|
| 196 | res.set('Cache-Control', 'no-cache');
|
|---|
| 197 | res.json({
|
|---|
| 198 | id: `klonkt-guardian2-${site?.slug || 'guardian'}`,
|
|---|
| 199 | name: 'Klonkt Guardian',
|
|---|
| 200 | short_name: 'Guardian 2',
|
|---|
| 201 | description: 'Ward management and help requests for guardians.',
|
|---|
| 202 | scope: '/guardian2/',
|
|---|
| 203 | start_url: '/guardian?source=pwa',
|
|---|
| 204 | display: 'standalone',
|
|---|
| 205 | display_override: ['standalone', 'minimal-ui'],
|
|---|
| 206 | orientation: 'any',
|
|---|
| 207 | background_color: '#141a24',
|
|---|
| 208 | theme_color: '#ff6b35',
|
|---|
| 209 | lang: site?.language || 'nl',
|
|---|
| 210 | icons: [
|
|---|
| 211 | { src: '/guardian2/icon.svg', sizes: 'any', type: 'image/svg+xml' },
|
|---|
| 212 | ],
|
|---|
| 213 | });
|
|---|
| 214 | });
|
|---|
| 215 |
|
|---|
| 216 | // The buoy mark, in the guardian accent (mirrors the site favicon pattern).
|
|---|
| 217 | router.get('/icon.svg', (req, res) => {
|
|---|
| 218 | const svg = `<?xml version="1.0" encoding="UTF-8"?>
|
|---|
| 219 | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|---|
| 220 | <rect width="64" height="64" rx="14" fill="#ff6b35"/>
|
|---|
| 221 | <text x="50%" y="50%" dy="0.35em" text-anchor="middle" font-size="36">🛟</text>
|
|---|
| 222 | </svg>`;
|
|---|
| 223 | res.set('Content-Type', 'image/svg+xml');
|
|---|
| 224 | res.set('Cache-Control', 'public, max-age=86400');
|
|---|
| 225 | res.send(svg);
|
|---|
| 226 | });
|
|---|
| 227 |
|
|---|
| 228 | // ── Losse guardians (Guardian 2): uitnodigen en aansluiten ───────────────
|
|---|
| 229 | // De familie nodigt oma uit; zij kiest naam + wachtwoord en heeft daarmee een
|
|---|
| 230 | // guardian-only account: user + minimale site (guardian_only=1). Alles wat al
|
|---|
| 231 | // per slug werkt (actor, inbox, offers, push, deze PWA) werkt dan meteen.
|
|---|
| 232 |
|
|---|
| 233 | router.post('/invite', requireAuth, (req, res) => {
|
|---|
| 234 | const token = crypto.randomBytes(16).toString('base64url');
|
|---|
| 235 | db.prepare('INSERT INTO ap_guardian_invites (token, created_by) VALUES (?,?)')
|
|---|
| 236 | .run(token, req.session.user.id);
|
|---|
| 237 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 238 | const url = `${base}/guardian2/join/${token}`;
|
|---|
| 239 | res.send(`<!doctype html><meta charset="utf-8"><body style="font-family:sans-serif;max-width:480px;margin:40px auto">
|
|---|
| 240 | <h2>Invite a guardian</h2>
|
|---|
| 241 | <p>Share this link. It lets one person create a guardian account here:</p>
|
|---|
| 242 | <p><a href="${url}">${url}</a></p>
|
|---|
| 243 | <p><a href="/guardian2">Back</a></p></body>`);
|
|---|
| 244 | });
|
|---|
| 245 |
|
|---|
| 246 | function joinForm(token, error) {
|
|---|
| 247 | return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|---|
| 248 | <body style="font-family:sans-serif;max-width:420px;margin:40px auto">
|
|---|
| 249 | <h2>Become a guardian</h2>
|
|---|
| 250 | <p>Watch over someone you care about. Pick a name and a password; that is all.</p>
|
|---|
| 251 | ${error ? `<p style="color:#b00">${error}</p>` : ''}
|
|---|
| 252 | <form method="post" action="/guardian2/join/${token}">
|
|---|
| 253 | <p><input name="name" placeholder="your name (grandma)" required pattern="[a-z0-9_-]{1,32}"
|
|---|
| 254 | style="width:100%;padding:10px" autocapitalize="none"></p>
|
|---|
| 255 | <p><input name="password" type="password" placeholder="password" required minlength="8"
|
|---|
| 256 | style="width:100%;padding:10px"></p>
|
|---|
| 257 | <p><button style="width:100%;padding:12px">Create my guardian account</button></p>
|
|---|
| 258 | </form></body>`;
|
|---|
| 259 | }
|
|---|
| 260 |
|
|---|
| 261 | router.get('/join/:token', (req, res) => {
|
|---|
| 262 | const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
|
|---|
| 263 | .get(req.params.token);
|
|---|
| 264 | if (!inv) return res.status(404).send('This invite is no longer valid.');
|
|---|
| 265 | res.send(joinForm(req.params.token));
|
|---|
| 266 | });
|
|---|
| 267 |
|
|---|
| 268 | router.post('/join/:token', express.urlencoded({ extended: false }), (req, res) => {
|
|---|
| 269 | const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
|
|---|
| 270 | .get(req.params.token);
|
|---|
| 271 | if (!inv) return res.status(404).send('This invite is no longer valid.');
|
|---|
| 272 | const name = String(req.body.name || '').trim().toLowerCase();
|
|---|
| 273 | const password = String(req.body.password || '');
|
|---|
| 274 | if (!/^[a-z0-9_-]{1,32}$/.test(name)) return res.status(400).send(joinForm(req.params.token, 'Only lowercase letters, digits, - and _.'));
|
|---|
| 275 | if (password.length < 8) return res.status(400).send(joinForm(req.params.token, 'Password: at least 8 characters.'));
|
|---|
| 276 | if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(name) || db.prepare('SELECT 1 FROM users WHERE username = ?').get(name)) {
|
|---|
| 277 | return res.status(409).send(joinForm(req.params.token, 'That name is taken, pick another.'));
|
|---|
| 278 | }
|
|---|
| 279 | const userId = crypto.randomUUID();
|
|---|
| 280 | db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)')
|
|---|
| 281 | .run(userId, name, `${name}@guardian.invalid`, bcrypt.hashSync(password, 10), 'member');
|
|---|
| 282 | db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, guardian_only) VALUES (?,?,?,?,0,1)')
|
|---|
| 283 | .run(crypto.randomUUID(), name, name, userId);
|
|---|
| 284 | db.prepare('UPDATE ap_guardian_invites SET used_by = ?, used_at = CURRENT_TIMESTAMP WHERE token = ?')
|
|---|
| 285 | .run(userId, req.params.token);
|
|---|
| 286 | req.session.user = { id: userId, username: name, role: 'member' };
|
|---|
| 287 | res.redirect('/guardian2');
|
|---|
| 288 | });
|
|---|
| 289 |
|
|---|
| 290 | export default router;
|
|---|