source: Klonkt/src/routes/guardian.js@ 1f640ff

main
Last change on this file since 1f640ff was d56d471, checked in by Robin <roboburr@โ€ฆ>, 6 weeks ago

Een voorstel krijgt een antwoord, een status en een zichtbare kring

Robin meldde drie dingen na de voorstelronde: er lijkt niets te gebeuren, de
status van een voorstel is nergens te volgen, en in /guardian zie je niet wie
de mede-guardians van een kind zijn. Onderzoek op beta wees de kern aan: de
ronde is aangekomen en geteld, maar elk voorstel was shaer:externalEmbeds, en
die stond al aan. Afspelen is nooit voorgesteld, en dat KON ook niet: de knop
"Afspelen voorstellen" verscheen alleen bij embeds === true, en voor een ward
op een andere server is die waarde onbekend, dus null, dus geen knop. Onbekend
is niet uit.

Drie reparaties, een per klacht.

Een: de lus sluit. De server van het kind beantwoordt de Offer die de
beslissing opende, terug naar de voorsteller: Accept als hij settelde op het
voorgestelde, Reject bij het tegendeel. Alleen de stem van het kind-account
telt als uitkomst; een vreemde die onze boeken wil sluiten wordt genegeerd.
Zonder dit kon het scherm van de voorsteller alleen maar eeuwig "wacht"
zeggen, wat er ook gebeurd was: de telling is het prive-grootboek van de
server van het kind.

Twee: de voorsteller houdt een eigen boek bij (ap_gated_sent) en het paneel
toont per ward de stand: wacht, aangenomen, afgewezen, of eerlijk verlopen als
het venster leegliep. Stilte na het venster is geen "loopt nog".

Drie: voor een ward op een andere server toont het paneel nu wel wie de
guardians zijn. Het lidmaatschap is publiek op het actordocument
(shaer:guardians, 2.1); de beschikbaarheid is en blijft het prive-grootboek
van hun server (3.6.1) en wordt alleen benoemd, niet getoond.

Changed files:
src/config/database.js

  • tabel ap_gated_sent (het boek van de voorsteller)
  • kolom proposer op ap_gated_offers, voor het antwoord naar huis

src/services/guardianship/gated.js

  • recordSent/recallSent/settleSent/listSent en sentStatus (puur, getest)
  • rememberGatedOffer onthoudt de voorsteller

src/services/guardianship/handshake.js

  • answerGatedProposer: het settle-antwoord naar de voorsteller
  • de inbox herkent dat antwoord en settelt het eigen boek; alleen het kind-account mag dat

src/routes/guardian.js

  • proposeGated schrijft het boek; dashboardState serveert per ward de voorstellen met status
  • GET /wards/guardians: lokaal met beschikbaarheid, remote de publieke lijst van hun actordocument

src/assets/js/guardian.js

  • de afspeel-knop verschijnt ook bij onbekende embeds-stand (de bug)
  • statusregels onder de instellingen-knoppen
  • remote guardians opgehaald bij het openen van het paneel

src/assets/css/guardian.css

  • g-prop-kleuren: de staat spreekt voor de woorden uit

src/services/i18n.js

  • prop_*- en panel_guards_far-strings, NL/EN/DE

test/gated-settings.test.js

  • de lus sluit: de voorsteller krijgt het antwoord, van alleen het kind
  • het boek: open, aangenomen, afgewezen, verlopen

remarks: 334 tests groen, server start op een schone database. De guardian-kant
(sound-fabrics) en de ward-kant (beta) hebben allebei deze commit nodig: de
knop en de status leven bij de guardian, het antwoord bij het kind.

-robo
Co-Authored-By: Claude Opus 5 <noreply@โ€ฆ>

  • Property mode set to 100644
File size: 35.6 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, renderNoteBody, formatDateTime } from '../middleware/render.js';
22import { emojiName } from '../services/NoteRender.js';
23
24const router = express.Router();
25const __dir = path.dirname(fileURLToPath(import.meta.url));
26
27/** The acting site: ?site=slug when owned, else the user's first site. */
28function siteForUser(req) {
29 const userId = req.session.user.id;
30 const want = String(req.query.site || req.body?.site || '').trim();
31 if (want) {
32 const s = db.prepare('SELECT * FROM sites WHERE slug = ? AND owner_id = ?').get(want, userId);
33 if (s) return s;
34 }
35 return db.prepare('SELECT * FROM sites WHERE owner_id = ? ORDER BY id LIMIT 1').get(userId);
36}
37
38/** Everything the dashboard shows, one shape for page and API. */
39function uiStrings(L) {
40 const keys = ['sent', 'sent_retry', 'sending', 'not_found', 'failed', 'network',
41 'pending', 'active', 'retract', 'release', 'release_confirm', 'open', 'push_unavailable',
42 'embeds_on', 'embeds_off', 'embeds_propose', 'embeds_waiting',
43 'accept', 'reject', 'complete', 'awaiting_others', 'coguard',
44 // The per-ward panel: everything about one child in one place.
45 'settings_title', 'panel_open', 'panel_close', 'panel_help', 'panel_help_empty',
46 'panel_follow', 'panel_follow_empty', 'panel_posts', 'panel_posts_empty',
47 'panel_actions', 'badge_help', 'badge_follow', 'badge_follow_one', 'help_empty',
48 // Releasing a ward: a deliberate two-step answer, never one click.
49 'release_title', 'release_effect', 'release_local', 'release_step_down',
50 'release_last', 'release_unknown', 'release_yes', 'release_no',
51 // Availability (FEP-633c 3.6): the dots, the step-away, the lapse.
52 'avail_available', 'avail_away', 'avail_dormant', 'panel_guards', 'panel_guards_remote',
53 'lapse_propose', 'lapse_line', 'lapse_tally', 'lapse_note', 'lapse_agree', 'lapse_disagree', 'voted',
54 'away_title', 'away_sub', 'away_week', 'away_month', 'away_done',
55 // A gated-setting proposal from a fellow guardian (5.6).
56 'gated_title', 'gated_line_on', 'gated_line_off', 'gated_agree', 'gated_disagree',
57 'play_propose', 'play_on', 'play_off',
58 // The status of a proposal this guardian sent (5.6).
59 'prop_line', 'prop_embeds', 'prop_play', 'prop_on', 'prop_off',
60 'prop_st_open', 'prop_st_accepted', 'prop_st_rejected', 'prop_st_expired',
61 'panel_guards_far'];
62 const s = Object.fromEntries(keys.map((k) => [k, i18nT(L, `guardian.${k}`)]));
63 s.wave = i18nT(L, 'guardian.wave');
64 s.waved = i18nT(L, 'guardian.waved');
65 return s;
66}
67
68function dashboardState(site, L) {
69 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
70 const me = AP.actorId(base, site.slug);
71 const help = db.prepare(
72 `SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, content, published, created_at,
73 emoji_json, actor_emoji_json, media_json, quote_json, embed_json
74 FROM ap_mentions WHERE slug = ? AND help_request = 1 ORDER BY created_at DESC LIMIT 50`
75 ).all(site.slug).map((h) => ({
76 ...h,
77 // The dashboard is built in the browser, so it gets the body finished: the
78 // same partial de Krant and Berichten use. A ๐Ÿ›Ÿ often carries a screenshot
79 // and a link to the post it is about; both belong in the card.
80 body_html: renderNoteBody(h, L),
81 name_html: emojiName(h.actor_name || '', h.actor_emoji_json),
82 // In the site's own timezone, the same as everywhere else in Klonkt. The
83 // PWA used to slice the raw UTC string, so a 20:20 call for help read 18:20.
84 when_text: formatDateTime(h.published || h.created_at),
85 }));
86 return {
87 site: site.slug,
88 me,
89 // Committed wards, each carrying the gated settings a guardian may change.
90 // `embeds` is null for a ward we do not host: that setting lives on the
91 // ward's own server, so we show it as not-adjustable rather than lying.
92 // `guardians` (FEP-633c 3.6): the fellow guardians of a LOCAL ward with
93 // their availability; null for a remote ward, whose server tracks it.
94 wards: Guardianship.listWards(site.slug).map((w) => ({
95 ...w,
96 embeds: wardEmbedSetting(w.other_uri),
97 playback: wardPlaybackSetting(w.other_uri),
98 guardians: wardGuardianStatuses(w.other_uri),
99 // What THIS guardian proposed for this ward and how it stands (5.6):
100 // open, accepted, rejected, or expired when the window ran out and the
101 // ward's server had nothing to write home. The answer is a real
102 // Accept/Reject from the ward's server, not a guess from here.
103 proposals: Guardianship.gated.listSent(site.slug, w.other_uri).map((p) => ({
104 feature: p.feature, value: !!p.value, created: p.created_at,
105 status: Guardianship.gated.sentStatus(p, Date.now()),
106 })),
107 })),
108 offers: Guardianship.offersCollection(`${me}/queues/offers`, site.slug, me).orderedItems,
109 // Running lapses (3.6.3) this guardian or its local wards are party to.
110 lapses: Guardianship.availability.lapseQueueItems(site.slug, me, Date.now()),
111 // Gated-setting proposals another guardian opened on a ward we share
112 // (5.6), forwarded here by the ward's server. Without answering these the
113 // threshold is never met and the proposal simply expires.
114 gatedReviews: Guardianship.gated.listGatedReviews(site.slug).map((r) => ({
115 id: r.id, ward: r.ward_uri, proposer: r.proposer, feature: r.feature, value: !!r.value,
116 })),
117 help,
118 strings: uiStrings(L),
119 };
120}
121
122/** The guardians of a ward WE host, with availability (3.6.1: owner-only in
123 * spirit; the co-guardians are among the owners of the relationship). Null
124 * for a remote ward: its server tracks availability, not us. */
125function wardGuardianStatuses(wardUri) {
126 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
127 if (!base || !String(wardUri || '').startsWith(`${base}/`)) return null;
128 const slug = String(wardUri).trim().replace(/\/+$/, '').split('/').pop();
129 try {
130 const uris = Guardianship.listGuardians(slug).map((g) => ({ uri: g.other_uri, handle: g.other_handle }));
131 const st = Object.fromEntries(
132 Guardianship.availability.statusesFor(slug, uris.map((u) => u.uri), Date.now()).map((s) => [s.id, s]),
133 );
134 return uris.map((u) => ({
135 uri: u.uri,
136 handle: u.handle,
137 availability: (st[u.uri] || {})['shaer:availability'] || 'active',
138 awayUntil: (st[u.uri] || {})['shaer:awayUntil'] || null,
139 lapse: (st[u.uri] || {})['shaer:lapse'] || null,
140 }));
141 } catch { return null; }
142}
143
144// โ”€โ”€ The PWA page โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
145router.get('/', requireAuth, (req, res) => {
146 const site = siteForUser(req);
147 const L = resolveLang(req);
148 if (!site) return res.status(404).send('No site for this account.');
149 const sites = db.prepare('SELECT slug, title FROM sites WHERE owner_id = ? ORDER BY id').all(req.session.user.id);
150 // This standalone PWA page is rendered directly (not through renderPage), so
151 // the CSP nonce must be injected here โ€” otherwise strict-dynamic blocks
152 // guardian.js and the whole dashboard is dead (buttons do nothing).
153 res.render('pages/guardian', {
154 state: dashboardState(site, L),
155 sites,
156 lang: L,
157 t: (k, v) => i18nT(L, k, v),
158 cspNonce: res.locals.cspNonce,
159 }, (err, html) => {
160 if (err) { console.error('[guardian] render error', err); return res.status(500).send('Internal Server Error'); }
161 res.send(injectCspNonce(html, res.locals.cspNonce));
162 });
163});
164
165// โ”€โ”€ JSON state for refreshes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
166router.get('/api/state', requireAuth, (req, res) => {
167 const site = siteForUser(req);
168 if (!site) return res.status(404).json({ error: 'no_site' });
169 res.json(dashboardState(site, resolveLang(req)));
170});
171
172// โ”€โ”€ Meekijken (FEP-633c ยง5, interop-hoofdroute): a committed guardian FOLLOWS
173// its wards, so their posts (incl. followers-only) are DELIVERED to the
174// guardian's inbox โ†’ timeline. The follow is the mechanism; no new fetch.
175// First contact also backfills the ward's recent PUBLIC posts as a cold
176// start so the corner is not empty before delivery catches up.
177function ensureWardConnections(site) {
178 let wards;
179 try { wards = Guardianship.listWards(site.slug); } catch { return; }
180 for (const w of wards) {
181 const already = db.prepare('SELECT 1 FROM ap_following WHERE slug = ? AND actor_uri = ?')
182 .get(site.slug, w.other_uri);
183 if (already) continue;
184 // Follow (guardian's server auto-accepts today; ยง5.3 gating is a later fase).
185 AP.followActor(site, w.other_uri).catch(() => { /* retried by the queue */ });
186 // Cold start: pull recent public posts now so oma sees something at once.
187 AP.backfillFromOutbox(site.slug, w.other_uri).catch(() => { /* best-effort */ });
188 }
189}
190
191// โ”€โ”€ The wards' corner: your wards' posts, read-only. No reply, no share; a
192// guardian watches, it does not publish (Robins besluit).
193router.get('/api/feed', requireAuth, (req, res) => {
194 const site = siteForUser(req);
195 if (!site) return res.status(404).json({ error: 'no_site' });
196 ensureWardConnections(site);
197 const wardUris = new Set(Guardianship.listWards(site.slug).map((w) => w.other_uri));
198 // Only show the wards you actually guard (the timeline can hold more).
199 const items = AP.getTimeline(site.slug, 60, 0)
200 .filter((p) => wardUris.has(p.author_uri))
201 .map((p) => ({
202 id: p.id,
203 author: p.author_handle || p.author_name || p.author_uri,
204 authorUri: p.author_uri, // the grouping key: which child's panel this belongs in
205 authorName: p.author_name,
206 authorIcon: p.author_icon,
207 content: p.content,
208 url: p.url,
209 published: p.published || p.created_at,
210 when_text: formatDateTime(p.published || p.created_at),
211 cw: p.cw || null,
212 media: p.media_json ? JSON.parse(p.media_json) : [],
213 }));
214 res.json({ items, following: wardUris.size });
215});
216
217// โ”€โ”€ Follow-gating (FEP-633c ยง5.3): pending follows on MY wards, for me to
218// approve. Ward and guardian are co-located on the family Klonkt here, so
219// the guardian reads its wards' pending follows locally.
220function wardSlugsOf(site) {
221 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
222 return Guardianship.listWards(site.slug)
223 .map((w) => (w.other_uri.startsWith(base) ? { slug: w.other_uri.split('/').pop(), uri: w.other_uri } : null))
224 .filter(Boolean);
225}
226
227router.get('/api/follow-requests', requireAuth, (req, res) => {
228 const site = siteForUser(req);
229 if (!site) return res.status(404).json({ error: 'no_site' });
230 const items = [];
231 const host = (() => { try { return new URL(process.env.PUBLIC_BASE_URL || '').host; } catch { return ''; } })();
232 // wardUri is the grouping key for the per-ward panel: the handle is for
233 // reading, the URI is what identifies the child across both cases below.
234 // Local wards (guardian co-located): read the pending follows directly.
235 for (const w of wardSlugsOf(site)) {
236 for (const f of Guardianship.follows.listForWard(w.slug)) {
237 items.push({ id: f.id, ward: `@${w.slug}@${host}`, wardUri: w.uri, follower: f.follower_handle || f.follower_name || f.follower_uri, followerIcon: f.follower_icon, remote: false, created: f.created_at });
238 }
239 }
240 // Remote wards: the copies forwarded here as Offer(Follow) (cross-instance).
241 for (const rev of Guardianship.follows.listReviews(site.slug)) {
242 const wardName = (() => { try { const u = new URL(rev.ward_uri); return `@${u.pathname.split('/').pop()}@${u.host}`; } catch { return rev.ward_uri; } })();
243 items.push({ id: rev.id, ward: wardName, wardUri: rev.ward_uri, follower: rev.follower_handle || rev.follower_uri, followerIcon: rev.follower_icon, remote: true, created: rev.created_at });
244 }
245 res.json({ items });
246});
247
248router.post('/api/follow/:id', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
249 const site = siteForUser(req);
250 if (!site) return res.status(404).json({ error: 'no_site' });
251 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
252 const me = AP.actorId(base, site.slug);
253 const decision = req.body?.decision === 'reject' ? 'reject' : 'approve';
254
255 // Remote ward: a forwarded copy. Send my Accept/Reject back to the ward,
256 // which tallies quorum and returns the Accept(Follow) to the follower.
257 const review = Guardianship.follows.getReview(site.slug, req.params.id);
258 if (review) {
259 try { await AP.sendFollowDecision(site, review, decision); }
260 catch { return res.status(502).json({ error: 'delivery' }); }
261 Guardianship.follows.removeReview(site.slug, req.params.id);
262 return res.json({ ok: true, outcome: decision === 'reject' ? 'rejected' : 'sent' });
263 }
264
265 // Local ward: decide directly (quorum on this instance).
266 const pending = Guardianship.follows.getPending(req.params.id);
267 if (!pending) return res.status(404).json({ error: 'gone' });
268 const allGuardians = Guardianship.listGuardians(pending.ward_slug).map((g) => g.other_uri);
269 if (!allGuardians.includes(me)) return res.status(403).json({ error: 'not_a_guardian' });
270 // Acting from the dashboard is an answer (3.6), and the quorum runs over
271 // the available set (3.5): both applied here, the same as over the wire.
272 Guardianship.availability.oneAnswer(me, Date.now());
273 const guardians = Guardianship.availability.availableSet(pending.ward_slug, allGuardians, Date.now());
274 const r = Guardianship.follows.decide(pending.id, me, decision, guardians);
275 try {
276 if (r.outcome === 'approved') { await AP.acceptGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); }
277 else if (r.outcome === 'rejected') { await AP.rejectGatedFollow(r.follow); Guardianship.follows.remove(r.follow.id); }
278 } catch (e) { return res.status(502).json({ error: 'delivery', outcome: r.outcome }); }
279 res.json({ ok: true, outcome: r.outcome });
280});
281
282// โ”€โ”€ Wave (FEP-633c ยง5, shaer:wave): a gentle "thinking of you" from a
283// guardian to a ward. A private direct note, never a feed post. Warmth
284// without publishing (Robins besluit).
285router.post('/api/wave', requireAuth, express.json({ limit: '2kb' }), async (req, res) => {
286 const site = siteForUser(req);
287 if (!site) return res.status(404).json({ error: 'no_site' });
288 const wardUri = String(req.body?.ward || '').trim();
289 // Only wave at a ward you actually guard.
290 const isWard = Guardianship.listWards(site.slug).some((w) => w.other_uri === wardUri);
291 if (!wardUri || !isWard) return res.status(403).json({ error: 'not_your_ward' });
292 const text = String(req.body?.text || '').trim().slice(0, 200) || '๐Ÿ‘‹ thinking of you';
293 const r = await AP.deliverDirectNote(site, { recipients: [wardUri], text, wave: true }).catch(() => null);
294 if (!r) return res.status(502).json({ error: 'delivery' });
295 res.json({ ok: true, delivered: r.delivered });
296});
297
298// โ”€โ”€ Adopt a ward: handle โ†’ resolve โ†’ C2S Offer through the same pipeline
299// the Shaer apps use (one path, one behavior).
300router.post('/adopt', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
301 const site = siteForUser(req);
302 if (!site) return res.status(404).json({ error: 'no_site' });
303 const handle = String(req.body?.handle || '').trim();
304 if (!handle) return res.status(400).json({ error: 'empty_handle' });
305 const wardUri = /^https?:\/\//i.test(handle) ? handle : await AP.webfingerResolve(handle).catch(() => null);
306 if (!wardUri) return res.status(404).json({ error: 'not_found' }); // the handle does not resolve to an account
307 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
308 const me = AP.actorId(base, site.slug);
309 const r = await AP.ingestOutboxActivity(site, req.session.user, {
310 type: 'Offer',
311 object: { type: 'Relationship', subject: wardUri, relationship: 'shaer:Guardian', object: me },
312 });
313 // 403/400 = a real refusal (e.g. you are a ward yourself); anything else the
314 // offer is recorded and delivery is retried in the background.
315 if (!r || (r.status >= 400 && r.status !== 502)) return res.status(r?.status || 500).json({ error: r?.error || 'offer_failed' });
316 res.json({ ok: true, ward: wardUri, delivered: r.delivered !== false });
317});
318
319// โ”€โ”€ Answer an offer (co-guardian accept/reject, or the candidate's final
320// "complete"). All three are a C2S Accept/Reject on the offer id; the
321// handshake module decides when it commits (ยง3.1).
322// โ”€โ”€ Step away (FEP-633c 3.6.1): the guardian declares itself unavailable โ”€โ”€
323// One direct note with shaer:away and an endTime to every ward, the same path
324// Shaer takes over C2S, and the only path: a ward on this instance receives
325// that note through the loopback and applies the absence in its own inbox
326// handler, exactly as a ward elsewhere does. This route used to write the
327// local wards itself as well, which meant the wire version could break without
328// anyone here noticing.
329router.post('/api/away', requireAuth, express.json({ limit: '2kb' }), async (req, res) => {
330 const site = siteForUser(req);
331 if (!site) return res.status(404).json({ error: 'no_site' });
332 const days = Math.min(365, Math.max(1, parseInt(req.body?.days, 10) || 0));
333 if (!days) return res.status(400).json({ error: 'away_needs_an_end' });
334 const wards = Guardianship.listWards(site.slug).map((w) => w.other_uri);
335 if (!wards.length) return res.status(409).json({ error: 'no_wards' });
336 const until = Date.now() + days * 24 * 3600 * 1000;
337 const L = resolveLang(req);
338 const text = i18nT(L, 'guardian.away_msg', { date: new Date(until).toLocaleDateString('nl-NL') });
339 const r = await AP.deliverDirectNote(site, { recipients: wards, text, awayUntil: until }).catch(() => null);
340 if (!(r && r.id)) return res.status(502).json({ error: 'away_failed' });
341 res.json({ ok: true, until });
342});
343
344// โ”€โ”€ Propose a lapse (FEP-633c 3.6.3) against a dormant co-guardian โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
345// The same C2S pipeline the Shaer apps would use: an Offer of shaer:Lapse.
346// A local ward opens directly; a remote ward gets the proposal delivered,
347// because the ward's server is the one that tallies and enforces.
348router.post('/api/lapse', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
349 const site = siteForUser(req);
350 if (!site) return res.status(404).json({ error: 'no_site' });
351 const ward = String(req.body?.ward || '').trim();
352 const target = String(req.body?.target || '').trim();
353 if (!ward || !target) return res.status(400).json({ error: 'missing_ward_or_target' });
354 if (!Guardianship.listWards(site.slug).some((w) => w.other_uri === ward)) {
355 return res.status(403).json({ error: 'not_my_ward' });
356 }
357 const r = await AP.ingestOutboxActivity(site, req.session.user, {
358 type: 'Offer', object: { type: 'shaer:Lapse', 'shaer:ward': ward, object: target },
359 });
360 if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'lapse_failed' });
361 res.json({ ok: true, lapse: r.id });
362});
363
364// โ”€โ”€ Answer a forwarded gated-setting proposal (FEP-633c 5.6) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
365// The decision belongs to the ward's server, so the answer travels there as an
366// Accept/Reject on the offer id, exactly like a gated follow's decision.
367router.post('/api/gated/:id', requireAuth, express.json({ limit: '2kb' }), async (req, res) => {
368 const site = siteForUser(req);
369 if (!site) return res.status(404).json({ error: 'no_site' });
370 const review = Guardianship.gated.getGatedReview(site.slug, req.params.id);
371 if (!review) return res.status(404).json({ error: 'gone' });
372 const agree = req.body?.answer !== 'reject';
373 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
374 const me = AP.actorId(base, site.slug);
375 const activity = {
376 id: `${me}#gated-${Date.now().toString(36)}`,
377 type: agree ? 'Accept' : 'Reject', actor: me, to: [review.ward_uri], object: review.id,
378 };
379 try { await AP.deliverToActor(site, review.ward_uri, activity); }
380 catch { return res.status(502).json({ error: 'delivery' }); }
381 Guardianship.gated.removeGatedReview(site.slug, review.id);
382 res.json({ ok: true, answer: agree ? 'accept' : 'reject' });
383});
384
385router.post('/offer', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
386 const site = siteForUser(req);
387 if (!site) return res.status(404).json({ error: 'no_site' });
388 const offerId = String(req.body?.offer || '').trim();
389 const answer = req.body?.answer === 'reject' ? 'Reject' : 'Accept';
390 if (!offerId) return res.status(400).json({ error: 'empty_offer' });
391 const r = await AP.ingestOutboxActivity(site, req.session.user, { type: answer, object: offerId });
392 if (!r || r.status >= 400) return res.status(r?.status || 500).json({ error: r?.error || 'answer_failed' });
393 res.json({ ok: true, committed: !!r.committed, readyToCommit: !!r.readyToCommit });
394});
395
396// โ”€โ”€ PWA assets served no-cache, so an update is never masked by the 1-year
397// /assets cache or a stuck install (that was the whole "nothing works after
398// a deploy" bug). Small files; the browser revalidates and gets a 304 when
399// unchanged, the fresh file when changed.
400function pwaAsset(rel, type) {
401 return (req, res) => {
402 res.set('Cache-Control', 'no-cache');
403 res.type(type);
404 res.sendFile(path.join(__dir, '..', 'assets', rel));
405 };
406}
407router.get('/app.js', pwaAsset('js/guardian.js', 'application/javascript'));
408router.get('/app.css', pwaAsset('css/guardian.css', 'text/css'));
409
410// โ”€โ”€ Manage: release a committed ward (local Undo; federation is Fase 4). โ”€โ”€
411/**
412 * What actually happens if this guardian releases this ward?
413 *
414 * Releasing is not one action but two very different ones, and the difference
415 * is the number of guardians the child has left (FEP-633c):
416 * - more than one โ†’ ยง3.3, you step down and the child stays a ward;
417 * - you are the last โ†’ ยง3.4, that is emancipation, and the FEP is explicit
418 * that no single guardian decides it alone (three consenting adults, or a
419 * majority plus two witnesses).
420 * On top of that, today's release is LOCAL: the Undo is not federated yet
421 * (relations.js, fase 4), so the ward's server keeps listing this guardian.
422 * A guardian pressing the button would otherwise believe the child is released.
423 *
424 * Answered on demand rather than in the dashboard state: for a ward we do not
425 * host this reaches out to that ward's server, and nobody should pay for that
426 * on every refresh.
427 */
428router.get('/wards/release-check', requireAuth, async (req, res) => {
429 const site = siteForUser(req);
430 if (!site) return res.status(404).json({ error: 'no_site' });
431 const uri = String(req.query.uri || '').trim();
432 if (!uri) return res.status(400).json({ error: 'empty_uri' });
433 if (!Guardianship.listWards(site.slug).some((w) => w.other_uri === uri)) {
434 return res.status(403).json({ error: 'not_my_ward' });
435 }
436 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
437 const local = !!base && uri.startsWith(`${base}/`);
438 let guardians = null; // null = we could not find out; say so rather than guess
439 if (local) {
440 const slug = uri.replace(/\/+$/, '').split('/').pop();
441 try { guardians = Guardianship.listGuardians(slug).length; } catch { /* stays null */ }
442 } else {
443 const doc = await AP.fetchActor(uri).catch(() => null);
444 const g = doc && doc['shaer:guardians'];
445 if (Array.isArray(g)) guardians = g.length;
446 else if (typeof g === 'string') guardians = 1;
447 else if (g && Array.isArray(g.items)) guardians = g.items.length;
448 else if (doc) guardians = 0; // the actor answered and names no guardians
449 }
450 res.json({
451 guardians,
452 last: guardians === null ? null : guardians <= 1,
453 local,
454 });
455});
456
457// โ”€โ”€ The fellow guardians of a ward, wherever it lives โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
458// A guardian looking at a ward's panel should see who else holds a seat: that
459// is the child's safety net, and "dit kind woont op een andere server" is not
460// an answer. For a local ward the availability rides along (we do that
461// bookkeeping). For a remote ward we read the PUBLIC membership from its
462// actor document (shaer:guardians, ยง2.1) and nothing more: availability is
463// the ward's server's private ledger (ยง3.6.1) and stays there. Fetched on
464// panel-open rather than into the dashboard, so one slow remote server does
465// not hold the whole screen hostage.
466router.get('/wards/guardians', requireAuth, async (req, res) => {
467 const site = siteForUser(req);
468 if (!site) return res.status(404).json({ error: 'no_site' });
469 const uri = String(req.query.uri || '').trim();
470 if (!Guardianship.listWards(site.slug).some((w) => w.other_uri === uri)) {
471 return res.status(403).json({ error: 'not_my_ward' });
472 }
473 const local = wardGuardianStatuses(uri);
474 if (local) return res.json({ local: true, guardians: local });
475 const doc = await AP.fetchActor(uri).catch(() => null);
476 let g = doc && doc['shaer:guardians'];
477 if (g && Array.isArray(g.items)) g = g.items; // a Collection
478 const guardians = (Array.isArray(g) ? g : (typeof g === 'string' ? [g] : []))
479 .filter((x) => typeof x === 'string')
480 .map((u) => {
481 try { const p = new URL(u); return { uri: u, handle: `@${p.pathname.replace(/\/+$/, '').split('/').pop()}@${p.host}` }; }
482 catch { return { uri: u, handle: u }; }
483 });
484 res.json({ local: false, guardians });
485});
486
487router.post('/wards/remove', requireAuth, express.json({ limit: '4kb' }), async (req, res) => {
488 const site = siteForUser(req);
489 if (!site) return res.status(404).json({ error: 'no_site' });
490 const uri = String(req.body?.uri || '').trim();
491 if (!uri) return res.status(400).json({ error: 'empty_uri' });
492 // Ending a guardianship is an Undo of the Relationship that travels to the
493 // ward and the other guardians (ยง3.2), not a local delete. Same call the
494 // Guardian apps reach over C2S, so the two cannot drift apart.
495 const r = await Guardianship.endGuardianship(site, uri);
496 if (r.status >= 400) return res.status(r.status).json({ error: r.error });
497 res.json({ ok: true, delivered: r.delivered, guardiansLeft: r.guardiansLeft });
498});
499
500/**
501 * The external-embeds setting of a ward we host: true/false when a guardian has
502 * decided, null when it is still on auto (which means off for a ward) or when
503 * the ward lives elsewhere and the setting is not ours to show.
504 */
505function wardEmbedSetting(uri) { return wardGateSetting(uri, 'external_embeds'); }
506/** The playback gate of a ward we host (5.6): the heavier sibling. */
507function wardPlaybackSetting(uri) { return wardGateSetting(uri, 'external_playback'); }
508function wardGateSetting(uri, column) {
509 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
510 if (!base || !String(uri || '').startsWith(`${base}/`)) return null;
511 const slug = String(uri).trim().replace(/\/+$/, '').split('/').pop();
512 const row = slug ? db.prepare(`SELECT ${column === 'external_playback' ? 'external_playback' : 'external_embeds'} AS v FROM sites WHERE slug = ?`).get(slug) : null;
513 if (!row) return null;
514 return row.v === null || row.v === undefined ? false : row.v === 1;
515}
516
517// โ”€โ”€ Gated feature: may this ward see external (non-fediverse) embeds? โ”€โ”€
518// The first real gated setting (FEP-633c ยง5-style). The gate itself is applied
519// server-side when the feed is serialised, so this endpoint is the only way it
520// can move, and only a committed guardian of THAT ward may move it.
521router.post('/wards/embeds', requireAuth, express.json({ limit: '4kb' }), (req, res) => {
522 req.body = { ...req.body, feature: req.body?.feature === 'shaer:externalPlayback' ? 'shaer:externalPlayback' : 'shaer:externalEmbeds' };
523 return proposeGated(req, res);
524});
525function proposeGated(req, res) {
526 const site = siteForUser(req);
527 if (!site) return res.status(404).json({ error: 'no_site' });
528 const uri = String(req.body?.uri || '').trim();
529 const allow = req.body?.allow === true;
530 if (!uri) return res.status(400).json({ error: 'empty_uri' });
531 // Only a guardian of this ward, and only for a ward we host: a setting on a
532 // remote ward belongs to that ward's own server (federating it is Fase 4).
533 const isMyWard = Guardianship.listWards(site.slug).some((w) => w.other_uri === uri);
534 if (!isMyWard) return res.status(403).json({ error: 'not_your_ward' });
535 // ยง5.6: propose it to the WARD'S server, wherever that is. The ward's server
536 // tallies (a majority of its guardians, ยง3.5) and enforces. Co-location is
537 // just the case where that server happens to be this one, so it takes the
538 // same road: propose, then let the tally decide. Anything else would make a
539 // guardian on the ward's own instance more powerful than one elsewhere.
540 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
541 const me = AP.actorId(base, site.slug);
542 const feature = req.body.feature; // normalised by the route above
543 const offerId = `${me}/gated/${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
544 const offer = Guardianship.gated.buildGatedOffer(offerId, me, uri, feature, allow);
545 // ONE path, whether the ward lives here or on the other side of the world
546 // (Robins regel, 29-7): propose over the wire and let the ward's server do
547 // what it does for everyone. deliverToActor loops a local recipient back
548 // into the same inbox handler, so co-location changes the transport and
549 // nothing else. The old shortcut recorded the vote here directly, which is
550 // how the remote path stayed broken for a month without anyone noticing.
551 // Our own record of what we sent (5.6): the ward's server answers this Offer
552 // once the decision settles, and that answer needs a row to land in. It is
553 // also the only way the proposer's screen can say more than a button caption.
554 Guardianship.gated.recordSent(offerId, site.slug, uri, feature, allow);
555 AP.deliverToActor(site, uri, offer).catch(() => { /* queued, best-effort */ });
556 const localSlug = (base && uri.startsWith(`${base}/`)) ? uri.replace(/\/+$/, '').split('/').pop() : null;
557 const progress = localSlug ? Guardianship.gated.gatedProgress(localSlug, feature) : null;
558 res.json({ ok: true, allow, state: 'open', ...(progress || { federated: true }) });
559}
560
561// โ”€โ”€ The installable identity: own scope so the Guardian corner installs as
562// its own app next to the site PWA.
563router.get('/manifest.webmanifest', (req, res) => {
564 const site = res.locals.site;
565 res.set('Cache-Control', 'no-cache');
566 res.json({
567 id: `klonkt-guardian-${site?.slug || 'guardian'}`,
568 name: 'Klonkt Guardian',
569 short_name: 'Guardian',
570 description: 'Ward management and help requests for guardians.',
571 scope: '/guardian/',
572 start_url: '/guardian?source=pwa',
573 display: 'standalone',
574 display_override: ['standalone', 'minimal-ui'],
575 orientation: 'any',
576 background_color: '#141a24',
577 theme_color: '#ff6b35',
578 lang: site?.language || 'nl',
579 icons: [
580 { src: '/guardian/icon.svg', sizes: 'any', type: 'image/svg+xml' },
581 ],
582 });
583});
584
585// The buoy mark, in the guardian accent (mirrors the site favicon pattern).
586router.get('/icon.svg', (req, res) => {
587 const svg = `<?xml version="1.0" encoding="UTF-8"?>
588<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
589 <rect width="64" height="64" rx="14" fill="#ff6b35"/>
590 <text x="50%" y="50%" dy="0.35em" text-anchor="middle" font-size="36">&#128735;</text>
591</svg>`;
592 res.set('Content-Type', 'image/svg+xml');
593 res.set('Cache-Control', 'public, max-age=86400');
594 res.send(svg);
595});
596
597// โ”€โ”€ Losse guardians (Guardian 2): uitnodigen en aansluiten โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
598// De familie nodigt oma uit; zij kiest naam + wachtwoord en heeft daarmee een
599// guardian-only account: user + minimale site (guardian_only=1). Alles wat al
600// per slug werkt (actor, inbox, offers, push, deze PWA) werkt dan meteen.
601
602router.post('/invite', requireAuth, (req, res) => {
603 const token = crypto.randomBytes(16).toString('base64url');
604 db.prepare('INSERT INTO ap_guardian_invites (token, created_by) VALUES (?,?)')
605 .run(token, req.session.user.id);
606 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
607 const url = `${base}/guardian/join/${token}`;
608 res.send(`<!doctype html><meta charset="utf-8"><body style="font-family:sans-serif;max-width:480px;margin:40px auto">
609 <h2>Invite a guardian</h2>
610 <p>Share this link. It lets one person create a guardian account here:</p>
611 <p><a href="${url}">${url}</a></p>
612 <p><a href="/guardian">Back</a></p></body>`);
613});
614
615function joinForm(token, error) {
616 return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
617 <body style="font-family:sans-serif;max-width:420px;margin:40px auto">
618 <h2>Become a guardian</h2>
619 <p>Watch over someone you care about. Pick a name and a password; that is all.</p>
620 ${error ? `<p style="color:#b00">${error}</p>` : ''}
621 <form method="post" action="/guardian/join/${token}">
622 <p><input name="name" placeholder="your name (grandma)" required pattern="[a-z0-9_-]{1,32}"
623 style="width:100%;padding:10px" autocapitalize="none"></p>
624 <p><input name="password" type="password" placeholder="password" required minlength="8"
625 style="width:100%;padding:10px"></p>
626 <p><button style="width:100%;padding:12px">Create my guardian account</button></p>
627 </form></body>`;
628}
629
630router.get('/join/:token', (req, res) => {
631 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
632 .get(req.params.token);
633 if (!inv) return res.status(404).send('This invite is no longer valid.');
634 res.send(joinForm(req.params.token));
635});
636
637router.post('/join/:token', express.urlencoded({ extended: false }), (req, res) => {
638 const inv = db.prepare('SELECT * FROM ap_guardian_invites WHERE token = ? AND used_at IS NULL')
639 .get(req.params.token);
640 if (!inv) return res.status(404).send('This invite is no longer valid.');
641 const name = String(req.body.name || '').trim().toLowerCase();
642 const password = String(req.body.password || '');
643 if (!/^[a-z0-9_-]{1,32}$/.test(name)) return res.status(400).send(joinForm(req.params.token, 'Only lowercase letters, digits, - and _.'));
644 if (password.length < 8) return res.status(400).send(joinForm(req.params.token, 'Password: at least 8 characters.'));
645 if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(name) || db.prepare('SELECT 1 FROM users WHERE username = ?').get(name)) {
646 return res.status(409).send(joinForm(req.params.token, 'That name is taken, pick another.'));
647 }
648 const userId = crypto.randomUUID();
649 db.prepare('INSERT INTO users (id, username, email, password_hash, role) VALUES (?,?,?,?,?)')
650 .run(userId, name, `${name}@guardian.invalid`, bcrypt.hashSync(password, 10), 'member');
651 db.prepare('INSERT INTO sites (id, slug, title, owner_id, is_primary, guardian_only) VALUES (?,?,?,?,0,1)')
652 .run(crypto.randomUUID(), name, name, userId);
653 db.prepare('UPDATE ap_guardian_invites SET used_by = ?, used_at = CURRENT_TIMESTAMP WHERE token = ?')
654 .run(userId, req.params.token);
655 req.session.user = { id: userId, username: name, role: 'member' };
656 res.redirect('/guardian');
657});
658
659export default router;
Note: See TracBrowser for help on using the repository browser.