source: Klonkt/src/routes/guardian.js@ 69bd747

main
Last change on this file since 69bd747 was 72ec6a4, checked in by Robin <roboburr@โ€ฆ>, 6 weeks ago

Hub-modus en guardian-lite eruit

Robins besluit (31-7): een instance is een eigenaar. Twee dingen weg.

HUB-MODUS was al dood: getTenancy() gaf sinds 24-6 hardcoded 'solo'
terug, dus elke tenancy === 'hub'-tak was onbereikbaar. Nu ook echt
verwijderd: getTenancy/setTenancy zelf, de /user/:slug-routing in
resolveSite, de hub-takken in admin, zoeken, audio, posts (neighbours
en related over alle sites), download, en de push-prefix. In de views
verdwijnen de hub-tagline, de hub-navigatie, de sites- en
users-tabellen (die kwamen alleen in hub-modus gevuld en verwezen nu
naar locals die niemand meer meegeeft), de eigenaar-toewijzing bij een
site, de /user/-slugprefix, het hub-brandblok en de hub-thuisknop.

GUARDIAN-LITE was de laatste multi-user-rest: /guardian/invite gaf een
link waarmee iemand via /guardian/join een echte user plus een site met
guardian_only=1 aanmaakte. Dat zette andermans wachtwoordhash, sessie
en PRIVATE actor-sleutel in jouw database, waardoor een verhuizing of
export nooit netjes kon (shaer-qw6q). Routes, formulier, kolom en
uitnodigingstabel zijn weg. Het guardian-DASHBOARD blijft: dat is
FEP-633c en werkt voor guardians met een eigen Klonkt. Bestaande
installaties houden kolom en tabel ongebruikt; nieuwe krijgen ze niet.

Changed files:
src/services/SettingsService.js

  • getTenancy/setTenancy verwijderd; kop herschreven

src/middleware/site.js, src/middleware/render.js

  • /user/:slug-routing weg; tenancy en hubTitle uit de locals

src/routes/admin.js, admin-settings.js, audio.js, download.js,
src/routes/posts.js, search.js

  • hub-takken en hub-queries weg; postNeighbors zonder isHub

src/services/ActivityPubService.js

  • pushPrefix is nu gewoon ; getTenancy-import weg

src/routes/guardian.js

  • /invite en /join verwijderd (dashboard blijft), imports opgeschoond

src/config/database.js

  • guardian_only-kolom en ap_guardian_invites-tabel niet meer aangemaakt

src/views/pages/admin.ejs, admin-users.ejs, admin-site-edit.ejs,
src/views/pages/guardian.ejs, partials/topnav.ejs, chrome.ejs, bottom-tab.ejs

  • alle hub-takken en de uitnodigingsknop weg

remarks: 320 regels weg, 63 erbij. Suite 372 groen; alle 85 templates
compileren; en met een wegwerp-kopie van de database daadwerkelijk
gedraaid en ingelogd: /, /admin, /admin/users, /admin/sites,
/admin/settings, /admin/sites/demo/edit, /admin/media en /guardian
geven alle 200 zonder fouten in het log, en /guardian/invite en
/guardian/join geven nu 404.

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

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