source: Klonkt/src/routes/admin-circle.js@ 374fbe9

main
Last change on this file since 374fbe9 was 2fc9b7f, checked in by roboburr <roboburr@…>, 3 months ago

fix(circle): do not add hubs/non-circle sites as partner

A hub does not federate (its /.klonkt/actor.json returns 404), but it was
still added to the circle with a dead "error / HTTP 404" row. The add now
rolls back the insert on a 404 and shows a clear message ("a hub cannot be
a circle partner"). Temporary (non-404) errors still leave the link so it
can be refreshed later.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 5.7 KB
Line 
1/**
2 * Admin: Cirkel-beheer (god-only).
3 * GET /admin/circle -> lijst van cirkel-links + status
4 * POST /admin/circle/add -> Klonkt-URL toevoegen
5 * POST /admin/circle/:id/remove
6 * POST /admin/circle/:id/sync -> nu verversen (pull + verifieer)
7 * POST /admin/circle/allow -> toggle "mag in cirkels van anderen verschijnen"
8 *
9 * Zie docs/cirkels-v1-spec.md §5d.
10 */
11
12import express from 'express';
13import crypto from 'crypto';
14import { renderPage } from '../middleware/render.js';
15import { requireGod } from '../middleware/auth.js';
16import db from '../config/database.js';
17import { getTenancy } from '../services/SettingsService.js';
18import { syncOne, sync } from '../services/CircleService.js';
19
20const router = express.Router();
21
22function primarySite() {
23 return db.prepare('SELECT * FROM sites ORDER BY created_at ASC LIMIT 1').get();
24}
25
26router.get('/', requireGod, (req, res) => {
27 const site = primarySite();
28 const links = site
29 ? db.prepare('SELECT * FROM circle_links WHERE local_site_id = ? ORDER BY added_at DESC').all(site.id)
30 : [];
31 const counts = {};
32 for (const l of links) {
33 counts[l.id] = l.remote_actor_id
34 ? db.prepare('SELECT COUNT(*) AS n FROM remote_posts WHERE actor_id = ?').get(l.remote_actor_id).n
35 : 0;
36 }
37 renderPage(req, res, 'pages/admin-circle', {
38 pageTitle: 'Cirkel',
39 bodyClass: 'on-admin',
40 tenancy: getTenancy(),
41 site,
42 links,
43 counts,
44 allowCircle: site ? site.allow_circle !== 0 : true,
45 success: req.query.success || null,
46 error: req.query.error || null,
47 });
48});
49
50router.post('/add', requireGod, async (req, res) => {
51 const site = primarySite();
52 if (!site) return res.redirect('/admin/circle?error=' + encodeURIComponent('Geen site gevonden'));
53 const url = (req.body.remote_url || '').toString().trim().replace(/\/+$/, '');
54 if (!/^https:\/\/[^\s/]+(\/[^\s]*)?$/i.test(url)) {
55 return res.redirect('/admin/circle?error=' + encodeURIComponent('Voer een geldige https-URL in'));
56 }
57 const label = (req.body.label || '').toString().slice(0, 80).trim() || null;
58 const id = crypto.randomUUID();
59 try {
60 db.prepare("INSERT INTO circle_links (id, local_site_id, remote_url, label, status) VALUES (?, ?, ?, ?, 'active')")
61 .run(id, site.id, url, label);
62 } catch (e) {
63 return res.redirect('/admin/circle?error=' + encodeURIComponent('Deze site staat al in je cirkel'));
64 }
65 // Meteen ophalen i.p.v. wachten op de 15-min-loop.
66 try {
67 const link = db.prepare('SELECT * FROM circle_links WHERE id = ?').get(id);
68 await syncOne(link);
69 return res.redirect('/admin/circle?success=' + encodeURIComponent('Toegevoegd en gesynchroniseerd ✓'));
70 } catch (e) {
71 const msg = String((e && e.message) || e);
72 // 404 = geen cirkel-endpoint. Hubs federeren bewust NIET (hun /.klonkt/actor.json
73 // geeft 404), net als losse niet-Klonkt-sites. Niet toevoegen: rol de insert terug
74 // zodat er geen dode "fout"-rij in de cirkel blijft staan.
75 if (/\b404\b/.test(msg)) {
76 db.prepare('DELETE FROM circle_links WHERE id = ?').run(id);
77 return res.redirect('/admin/circle?error=' + encodeURIComponent('Niet toegevoegd: deze site doet niet mee aan cirkels. Een hub kan geen cirkel-partner zijn (en losse/niet-Klonkt-sites ook niet).'));
78 }
79 // Andere (mogelijk tijdelijke) fout → link blijft staan; later "Verversen".
80 return res.redirect('/admin/circle?success=' + encodeURIComponent('Toegevoegd — synchroniseren mislukte (klik "Verversen" om opnieuw te proberen)'));
81 }
82});
83
84router.post('/:id/remove', requireGod, (req, res) => {
85 const link = db.prepare('SELECT * FROM circle_links WHERE id = ?').get(req.params.id);
86 if (link) {
87 db.prepare('DELETE FROM circle_links WHERE id = ?').run(link.id);
88 // Gecachte content opruimen als geen andere link nog naar deze actor wijst.
89 if (link.remote_actor_id) {
90 const other = db.prepare('SELECT 1 FROM circle_links WHERE remote_actor_id = ? LIMIT 1').get(link.remote_actor_id);
91 if (!other) {
92 db.prepare('DELETE FROM remote_posts WHERE actor_id = ?').run(link.remote_actor_id);
93 db.prepare('DELETE FROM remote_actors WHERE id = ?').run(link.remote_actor_id);
94 }
95 }
96 }
97 res.redirect('/admin/circle?success=' + encodeURIComponent('Verwijderd'));
98});
99
100router.post('/:id/sync', requireGod, async (req, res) => {
101 const link = db.prepare('SELECT * FROM circle_links WHERE id = ?').get(req.params.id);
102 if (!link) return res.redirect('/admin/circle?error=' + encodeURIComponent('Niet gevonden'));
103 try {
104 const r = await syncOne(link);
105 res.redirect('/admin/circle?success=' + encodeURIComponent(`Bijgewerkt — ${r.items} posts opgehaald`));
106 } catch (e) {
107 const msg = String((e && e.message) || e).slice(0, 300);
108 db.prepare("UPDATE circle_links SET status='error', last_error=?, last_synced=CURRENT_TIMESTAMP WHERE id=?")
109 .run(msg, link.id);
110 res.redirect('/admin/circle?error=' + encodeURIComponent(msg));
111 }
112});
113
114// Alles in één keer verversen (handig "voor de zekerheid").
115router.post('/sync-all', requireGod, async (req, res) => {
116 try {
117 const r = await sync();
118 const n = (r && r.results) ? r.results.filter((x) => x && x.ok).length : 0;
119 res.redirect('/admin/circle?success=' + encodeURIComponent(`Cirkel gesynchroniseerd (${n} site(s) bijgewerkt)`));
120 } catch (e) {
121 res.redirect('/admin/circle?error=' + encodeURIComponent(String((e && e.message) || e).slice(0, 200)));
122 }
123});
124
125router.post('/allow', requireGod, (req, res) => {
126 const site = primarySite();
127 if (site) {
128 const v = (req.body.allow_circle === 'on' || req.body.allow_circle === '1') ? 1 : 0;
129 db.prepare('UPDATE sites SET allow_circle = ? WHERE id = ?').run(v, site.id);
130 }
131 res.redirect('/admin/circle?success=' + encodeURIComponent('Opgeslagen'));
132});
133
134export default router;
Note: See TracBrowser for help on using the repository browser.