/** * The Guardian PWA (FEP-633c): a separate, installable corner of Klonkt for * guardians. One place to add and manage wards, a message centre for * incoming help requests and adoption traffic, and its own push channel * (alert types 'help' and 'guardian', web-push slice reused). * * Everything is scoped to a site the logged-in user OWNS: the guardian acts * as one of their own actors (?site=slug picks one when they own several). * Views carry no inline scripts (CSP): logic lives in /assets/js/guardian.js. */ import express from 'express'; import crypto from 'crypto'; import bcrypt from 'bcryptjs'; import path from 'path'; import { fileURLToPath } from 'url'; import db from '../config/database.js'; import { requireAuth } from '../middleware/auth.js'; import AP from '../services/ActivityPubService.js'; import * as Guardianship from '../services/guardianship/index.js'; import { t as i18nT, resolveLang } from '../services/i18n.js'; import { injectCspNonce } from '../middleware/render.js'; const router = express.Router(); const __dir = path.dirname(fileURLToPath(import.meta.url)); /** The acting site: ?site=slug when owned, else the user's first site. */ function siteForUser(req) { const userId = req.session.user.id; const want = String(req.query.site || req.body?.site || '').trim(); if (want) { const s = db.prepare('SELECT * FROM sites WHERE slug = ? AND owner_id = ?').get(want, userId); if (s) return s; } return db.prepare('SELECT * FROM sites WHERE owner_id = ? ORDER BY id LIMIT 1').get(userId); } /** Everything the dashboard shows, one shape for page and API. */ function uiStrings(L) { const keys = ['sent', 'sent_retry', 'sending', 'not_found', 'failed', 'network', 'pending', 'active', 'retract', 'release', 'release_confirm', 'open', 'push_unavailable', 'embeds_on', 'embeds_off', 'accept', 'reject', 'complete', 'awaiting_others', 'coguard']; const s = Object.fromEntries(keys.map((k) => [k, i18nT(L, `guardian.${k}`)])); s.wave = i18nT(L, 'guardian.wave'); s.waved = i18nT(L, 'guardian.waved'); return s; } function dashboardState(site, L) { const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); const me = AP.actorId(base, site.slug); const help = db.prepare( `SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, content, published, created_at FROM ap_mentions WHERE slug = ? AND help_request = 1 ORDER BY created_at DESC LIMIT 50` ).all(site.slug); return { site: site.slug, me, // Committed wards, each carrying the gated settings a guardian may change. // `embeds` is null for a ward we do not host: that setting lives on the // ward's own server, so we show it as not-adjustable rather than lying. wards: Guardianship.listWards(site.slug).map((w) => ({ ...w, embeds: wardEmbedSetting(w.other_uri) })), offers: Guardianship.offersCollection(`${me}/queues/offers`, site.slug, me).orderedItems, help, strings: uiStrings(L), }; } // ── The PWA page ───────────────────────────────────────────────────────── router.get('/', requireAuth, (req, res) => { const site = siteForUser(req); const L = resolveLang(req); if (!site) return res.status(404).send('No site for this account.'); const sites = db.prepare('SELECT slug, title FROM sites WHERE owner_id = ? ORDER BY id').all(req.session.user.id); // This standalone PWA page is rendered directly (not through renderPage), so // the CSP nonce must be injected here — otherwise strict-dynamic blocks // guardian.js and the whole dashboard is dead (buttons do nothing). res.render('pages/guardian', { state: dashboardState(site, L), sites, lang: L, t: (k, v) => i18nT(L, k, v), cspNonce: res.locals.cspNonce, }, (err, html) => { if (err) { console.error('[guardian] render error', err); return res.status(500).send('Internal Server Error'); } res.send(injectCspNonce(html, res.locals.cspNonce)); }); }); // ── JSON state for refreshes ───────────────────────────────────────────── router.get('/api/state', requireAuth, (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); res.json(dashboardState(site, resolveLang(req))); }); // ── Meekijken (FEP-633c §5, interop-hoofdroute): a committed guardian FOLLOWS // its wards, so their posts (incl. followers-only) are DELIVERED to the // guardian's inbox → timeline. The follow is the mechanism; no new fetch. // First contact also backfills the ward's recent PUBLIC posts as a cold // start so the corner is not empty before delivery catches up. function ensureWardConnections(site) { let wards; try { wards = Guardianship.listWards(site.slug); } catch { return; } for (const w of wards) { const already = db.prepare('SELECT 1 FROM ap_following WHERE slug = ? AND actor_uri = ?') .get(site.slug, w.other_uri); if (already) continue; // Follow (guardian's server auto-accepts today; §5.3 gating is a later fase). AP.followActor(site, w.other_uri).catch(() => { /* retried by the queue */ }); // Cold start: pull recent public posts now so oma sees something at once. AP.backfillFromOutbox(site.slug, w.other_uri).catch(() => { /* best-effort */ }); } } // ── The wards' corner: your wards' posts, read-only. No reply, no share; a // guardian watches, it does not publish (Robins besluit). router.get('/api/feed', requireAuth, (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); ensureWardConnections(site); const wardUris = new Set(Guardianship.listWards(site.slug).map((w) => w.other_uri)); // Only show the wards you actually guard (the timeline can hold more). const items = AP.getTimeline(site.slug, 60, 0) .filter((p) => wardUris.has(p.author_uri)) .map((p) => ({ id: p.id, author: p.author_handle || p.author_name || p.author_uri, authorName: p.author_name, authorIcon: p.author_icon, content: p.content, url: p.url, published: p.published || p.created_at, cw: p.cw || null, media: p.media_json ? JSON.parse(p.media_json) : [], })); res.json({ items, following: wardUris.size }); }); // ── Follow-gating (FEP-633c §5.3): pending follows on MY wards, for me to // approve. Ward and guardian are co-located on the family Klonkt here, so // the guardian reads its wards' pending follows locally. function wardSlugsOf(site) { const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); return Guardianship.listWards(site.slug) .map((w) => (w.other_uri.startsWith(base) ? w.other_uri.split('/').pop() : null)) .filter(Boolean); } router.get('/api/follow-requests', requireAuth, (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const items = []; const host = (() => { try { return new URL(process.env.PUBLIC_BASE_URL || '').host; } catch { return ''; } })(); // Local wards (guardian co-located): read the pending follows directly. for (const wardSlug of wardSlugsOf(site)) { for (const f of Guardianship.follows.listForWard(wardSlug)) { items.push({ id: f.id, ward: `@${wardSlug}@${host}`, follower: f.follower_handle || f.follower_name || f.follower_uri, followerIcon: f.follower_icon, remote: false, created: f.created_at }); } } // Remote wards: the copies forwarded here as Offer(Follow) (cross-instance). for (const rev of Guardianship.follows.listReviews(site.slug)) { const wardName = (() => { try { const u = new URL(rev.ward_uri); return `@${u.pathname.split('/').pop()}@${u.host}`; } catch { return rev.ward_uri; } })(); items.push({ id: rev.id, ward: wardName, follower: rev.follower_handle || rev.follower_uri, followerIcon: rev.follower_icon, remote: true, created: rev.created_at }); } res.json({ items }); }); router.post('/api/follow/:id', requireAuth, express.json({ limit: '4kb' }), async (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); const me = AP.actorId(base, site.slug); const decision = req.body?.decision === 'reject' ? 'reject' : 'approve'; // Remote ward: a forwarded copy. Send my Accept/Reject back to the ward, // which tallies quorum and returns the Accept(Follow) to the follower. const review = Guardianship.follows.getReview(site.slug, req.params.id); if (review) { try { await AP.sendFollowDecision(site, review, decision); } catch { return res.status(502).json({ error: 'delivery' }); } Guardianship.follows.removeReview(site.slug, req.params.id); return res.json({ ok: true, outcome: decision === 'reject' ? 'rejected' : 'sent' }); } // Local ward: decide directly (quorum on this instance). const pending = Guardianship.follows.getPending(req.params.id); if (!pending) return res.status(404).json({ error: 'gone' }); const guardians = Guardianship.listGuardians(pending.ward_slug).map((g) => g.other_uri); if (!guardians.includes(me)) return res.status(403).json({ error: 'not_a_guardian' }); const r = Guardianship.follows.decide(pending.id, me, decision, guardians); try { if (r.outcome === 'approved') { await AP.acceptGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); } else if (r.outcome === 'rejected') { await AP.rejectGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); } } catch (e) { return res.status(502).json({ error: 'delivery', outcome: r.outcome }); } res.json({ ok: true, outcome: r.outcome }); }); // ── Wave (FEP-633c §5, shaer:wave): a gentle "thinking of you" from a // guardian to a ward. A private direct note, never a feed post. Warmth // without publishing (Robins besluit). router.post('/api/wave', requireAuth, express.json({ limit: '2kb' }), async (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const wardUri = String(req.body?.ward || '').trim(); // Only wave at a ward you actually guard. const isWard = Guardianship.listWards(site.slug).some((w) => w.other_uri === wardUri); if (!wardUri || !isWard) return res.status(403).json({ error: 'not_your_ward' }); const text = String(req.body?.text || '').trim().slice(0, 200) || '👋 thinking of you'; const r = await AP.deliverDirectNote(site, { recipients: [wardUri], text, wave: true }).catch(() => null); if (!r) return res.status(502).json({ error: 'delivery' }); res.json({ ok: true, delivered: r.delivered }); }); // ── Adopt a ward: handle → resolve → C2S Offer through the same pipeline // the Shaer apps use (one path, one behavior). router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const handle = String(req.body?.handle || '').trim(); if (!handle) return res.status(400).json({ error: 'empty_handle' }); const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null); if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); const me = AP.actorId(base, site.slug); const r = await AP.ingestOutboxActivity(site, req.session.user, { type: 'Offer', object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me }, }); // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the // offer is recorded and delivery is retried in the background. if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' }); res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false }); }); // ── Answer an offer (co-guardian accept/reject, or the candidate's final // "complete"). All three are a C2S Accept/Reject on the offer id; the // handshake module decides when it commits (§3.1). router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const offerId = String(req.body?.offer || '').trim(); const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept'; if (!offerId) return res.status(400).json({ error: 'empty_offer' }); const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId }); if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' }); res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit }); }); // ── PWA assets served no-cache, so an update is never masked by the 1-year // /assets cache or a stuck install (that was the whole "nothing works after // a deploy" bug). Small files; the browser revalidates and gets a 304 when // unchanged, the fresh file when changed. function pwaAsset(rel, type) { return (req, res) => { res.set('Cache-Control', 'no-cache'); res.type(type); res.sendFile(path.join(__dir, '..', 'assets', rel)); }; } router.get('/app.js', pwaAsset('js/guardian.js', 'application/javascript')); router.get('/app.css', pwaAsset('css/guardian.css', 'text/css')); // ── Manage: release a committed ward (local Undo; federation is Fase 4). ── router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const uri = String(req.body?.uri || '').trim(); if (!uri) return res.status(400).json({ error: 'empty_uri' }); Guardianship.removeRelation(site.slug, 'guardian', uri); res.json({ ok: true }); }); /** * The external-embeds setting of a ward we host: true/false when a guardian has * decided, null when it is still on auto (which means off for a ward) or when * the ward lives elsewhere and the setting is not ours to show. */ function wardEmbedSetting(uri) { const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); if (!base || !String(uri || '').startsWith(`${base}/`)) return null; const slug = String(uri).trim().replace(/\/+$/, '').split('/').pop(); const row = slug ? db.prepare('SELECT external_embeds FROM sites WHERE slug = ?').get(slug) : null; if (!row) return null; return row.external_embeds === null || row.external_embeds === undefined ? false : row.external_embeds === 1; } // ── Gated feature: may this ward see external (non-fediverse) embeds? ── // The first real gated setting (FEP-633c §5-style). The gate itself is applied // server-side when the feed is serialised, so this endpoint is the only way it // can move, and only a committed guardian of THAT ward may move it. router.post('/wards/embeds', requireAuth, express.json({ limit: '4kb' }), (req, res) => { const site = siteForUser(req); if (!site) return res.status(404).json({ error: 'no_site' }); const uri = String(req.body?.uri || '').trim(); const allow = req.body?.allow === true; if (!uri) return res.status(400).json({ error: 'empty_uri' }); // Only a guardian of this ward, and only for a ward we host: a setting on a // remote ward belongs to that ward's own server (federating it is Fase 4). const isMyWard = Guardianship.listWards(site.slug).some((w) => w.other_uri === uri); if (!isMyWard) return res.status(403).json({ error: 'not_your_ward' }); const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); const slug = (base && uri.startsWith(`${base}/`)) ? uri.trim().replace(/\/+$/, '').split('/').pop() : null; const ward = slug ? db.prepare('SELECT id, slug FROM sites WHERE slug = ?').get(slug) : null; if (!ward) return res.status(400).json({ error: 'remote_ward_not_supported' }); db.prepare('UPDATE sites SET external_embeds = ? WHERE id = ?').run(allow ? 1 : 0, ward.id); res.json({ ok: true, allow }); }); // ── The installable identity: own scope so the Guardian corner installs as // its own app next to the site PWA. router.get('/manifest.webmanifest', (req, res) => { const site = res.locals.site; res.set('Cache-Control', 'no-cache'); res.json({ id: `klonkt-guardian-${site?.slug || 'guardian'}`, name: 'Klonkt Guardian', short_name: 'Guardian', description: 'Ward management and help requests for guardians.', scope: '/guardian/', start_url: '/guardian?source=pwa', display: 'standalone', display_override: ['standalone', 'minimal-ui'], orientation: 'any', background_color: '#141a24', theme_color: '#ff6b35', lang: site?.language || 'nl', icons: [ { src: '/guardian/icon.svg', sizes: 'any', type: 'image/svg+xml' }, ], }); }); // The buoy mark, in the guardian accent (mirrors the site favicon pattern). router.get('/icon.svg', (req, res) => { const svg = ` `; res.set('Content-Type', 'image/svg+xml'); res.set('Cache-Control', 'public, max-age=86400'); res.send(svg); }); // ── Losse guardians (Guardian 2): uitnodigen en aansluiten ─────────────── // De familie nodigt oma uit; zij kiest naam + wachtwoord en heeft daarmee een // guardian-only account: user + minimale site (guardian_only=1). Alles wat al // per slug werkt (actor, inbox, offers, push, deze PWA) werkt dan meteen. router.post('/invite', requireAuth, (req, res) => { const token = crypto.randomBytes(16).toString('base64url'); db.prepare('INSERT INTO ap_guardian_invites (token, created_by) VALUES (?,?)') .run(token, req.session.user.id); const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''); const url = `${base}/guardian/join/${token}`; res.send(`
Share this link. It lets one person create a guardian account here:
`); }); function joinForm(token, error) { return `Watch over someone you care about. Pick a name and a password; that is all.
${error ? `${error}
` : ''} `; } router.get('/join/:token', (req, res) => { const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL') .get(req.params.token); if (!inv) return res.status(404).send('This invite is no longer valid.'); res.send(joinForm(req.params.token)); }); router.post('/join/:token', express.urlencoded({ extended: false }), (req, res) => { const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL') .get(req.params.token); if (!inv) return res.status(404).send('This invite is no longer valid.'); const name = String(req.body.name || '').trim().toLowerCase(); const password = String(req.body.password || ''); if (!/^[a-z0-9_-]{1,32}$/.test(name)) return res.status(400).send(joinForm(req.params.token, 'Only lowercase letters, digits, - and _.')); if (password.length < 8) return res.status(400).send(joinForm(req.params.token, 'Password: at least 8 characters.')); if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(name) || db.prepare('SELECT 1 FROM users WHERE username = ?').get(name)) { return res.status(409).send(joinForm(req.params.token, 'That name is taken, pick another.')); } const userId = crypto.randomUUID(); db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)') .run(userId, name, `${name}@guardian.invalid`, bcrypt.hashSync(password, 10), 'member'); db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, guardian_only) VALUES (?,?,?,?,0,1)') .run(crypto.randomUUID(), name, name, userId); db.prepare('UPDATE ap_guardian_invites SET used_by = ?, used_at = CURRENT_TIMESTAMP WHERE token = ?') .run(userId, req.params.token); req.session.user = { id: userId, username: name, role: 'member' }; res.redirect('/guardian'); }); export default router;