source: Klonkt/src/services/CircleService.js@ 62b899d

main
Last change on this file since 62b899d was 62b899d, checked in by roboburr <roboburr@…>, 3 months ago

Circle: strip shortcodes from summary + "Sync all now" button

[[playlist:..]]/[[track:..]]/[[album:..]]-shortcodes survived stripHtml (not
HTML) → appeared raw in the circle summary (buggy). Now stripped on ingest
(consumer) and on publish. Also added a global sync button on
Admin → Circle.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@…>

  • Property mode set to 100644
File size: 9.0 KB
Line 
1// CircleService.js — pull-kant van Cirkels (v1).
2//
3// Haalt per circle_link de remote actor + outbox op, verifieert de Ed25519-
4// handtekening, sanitiseert en cachet publieke posts in remote_actors/remote_posts.
5// Alleen LEZEN van remote; nooit schrijven. Zie docs/cirkels-v1-spec.md §5b.
6
7import db from '../config/database.js';
8import { verifyBody, KLONKT_PROTO, MIN_PROTO } from './CircleFederation.js';
9import { getTenancy } from './SettingsService.js';
10
11const FETCH_TIMEOUT_MS = 10000;
12const MAX_BODY_BYTES = 1024 * 1024; // 1 MB
13const MAX_ITEMS = 50;
14
15function stripHtml(s) {
16 return String(s || '')
17 .replace(/<[^>]+>/g, ' ')
18 .replace(/\[\[[^\]]*\]\]/g, ' ') // [[playlist:..]]/[[track:..]]/[[album:..]]-shortcodes weg
19 .replace(/\s+/g, ' ')
20 .trim();
21}
22function iso(d) {
23 const t = d ? new Date(d) : null;
24 return t && !isNaN(t.getTime()) ? t.toISOString() : null;
25}
26function originOf(u) {
27 try { return new URL(u).origin; } catch { return null; }
28}
29function baseOf(remoteUrl) {
30 return String(remoteUrl).replace(/\/+$/, '');
31}
32
33// Bron buiten de cirkel zetten met een leesbare reden (geen stille mislukking).
34// Aparte status 'outdated' zodat de Beheer-UI er een nette "update vereist"-
35// melding van kan maken i.p.v. een generieke fout.
36function markOutdated(link, msg) {
37 // Gecachte posts van deze bron weghalen: we kunnen ze niet meer verifiëren of
38 // verversen (proto-mismatch), dus ze horen niet meer in de cirkel-feed.
39 if (link.remote_actor_id) {
40 try { db.prepare('DELETE FROM remote_posts WHERE actor_id = ?').run(link.remote_actor_id); } catch {}
41 }
42 db.prepare("UPDATE circle_links SET status='outdated', last_error=?, last_synced=CURRENT_TIMESTAMP WHERE id=?")
43 .run(String(msg).slice(0, 300), link.id);
44 return { ok: false, outdated: true, link: link.remote_url, error: msg };
45}
46
47// Robuuste, defensieve fetch: alleen https, timeout, body-cap, redirect-follow.
48async function fetchText(url) {
49 if (!/^https:\/\//i.test(url)) throw new Error('alleen https toegestaan');
50 const ac = new AbortController();
51 const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
52 try {
53 const res = await fetch(url, {
54 signal: ac.signal,
55 redirect: 'follow',
56 headers: {
57 Accept: 'application/activity+json, application/json',
58 // Vertel de publisher onze proto → die kan ons met 426 weren als we te oud zijn.
59 'Klonkt-Proto': String(KLONKT_PROTO),
60 },
61 });
62 if (!res.ok) throw new Error(`HTTP ${res.status}`);
63 const buf = Buffer.from(await res.arrayBuffer());
64 if (buf.length > MAX_BODY_BYTES) throw new Error('body te groot');
65 return { text: buf.toString('utf8'), headers: res.headers, finalUrl: res.url };
66 } finally {
67 clearTimeout(timer);
68 }
69}
70
71// Lazy prepares — de tabellen bestaan pas ná initializeDatabase(); dit module
72// wordt geïmporteerd vóór die call, dus niet op module-niveau prepare'n.
73let _stmts = null;
74function stmts() {
75 if (_stmts) return _stmts;
76 _stmts = {
77 upsertActor: db.prepare(`
78 INSERT INTO remote_actors (id, url, name, summary, avatar, public_key, fetched_at)
79 VALUES (@id, @url, @name, @summary, @avatar, @public_key, CURRENT_TIMESTAMP)
80 ON CONFLICT(id) DO UPDATE SET
81 url=excluded.url, name=excluded.name, summary=excluded.summary,
82 avatar=excluded.avatar, public_key=excluded.public_key, fetched_at=CURRENT_TIMESTAMP
83 `),
84 upsertPost: db.prepare(`
85 INSERT INTO remote_posts (id, actor_id, published, title, summary, url, media_json, raw_json, fetched_at)
86 VALUES (@id, @actor_id, @published, @title, @summary, @url, @media_json, @raw_json, CURRENT_TIMESTAMP)
87 ON CONFLICT(id) DO UPDATE SET
88 published=excluded.published, title=excluded.title, summary=excluded.summary,
89 url=excluded.url, media_json=excluded.media_json, raw_json=excluded.raw_json, fetched_at=CURRENT_TIMESTAMP
90 `),
91 };
92 return _stmts;
93}
94
95export async function syncOne(link) {
96 const base = baseOf(link.remote_url);
97
98 // 1. Actor ophalen + valideren
99 const actorUrl = `${base}/.klonkt/actor.json`;
100 const a = await fetchText(actorUrl);
101 let actor;
102 try { actor = JSON.parse(a.text); } catch { throw new Error('actor: ongeldige JSON'); }
103 const actorId = actor.id;
104 const pubKey = actor.publicKey && actor.publicKey.publicKeyBase64;
105 if (!actorId || !pubKey) throw new Error('actor mist id/publicKey');
106 if (originOf(actorId) !== originOf(actorUrl)) throw new Error('actor.id heeft andere origin dan de actor-URL');
107
108 // Protocol-versie-gate. De proto zit óók in de outbox-handtekening-grondslag,
109 // dus liegen in de (ongetekende) actor helpt niet: bij een echte mismatch faalt
110 // de verificatie verderop alsnog. Hier vooral voor een DUIDELIJKE melding +
111 // buitensluiten zonder stille mislukking.
112 const remoteProto = Number(actor.klonkt && actor.klonkt.proto) || 1;
113 if (remoteProto > KLONKT_PROTO) {
114 return markOutdated(link,
115 `Deze site draait een nieuwere Klonkt (proto ${remoteProto}); jouw instance is proto ${KLONKT_PROTO}. Werk je eigen Klonkt bij om te blijven federeren.`);
116 }
117 if (remoteProto < MIN_PROTO) {
118 return markOutdated(link,
119 `Draait een oudere Klonkt (proto ${remoteProto}; minimaal ${MIN_PROTO} vereist). Vraag ze te updaten.`);
120 }
121
122 // TOFU: een sleutelwissel vereist expliciete herbevestiging (anti-hijack)
123 const existing = db.prepare('SELECT public_key FROM remote_actors WHERE id = ?').get(actorId);
124 if (existing && existing.public_key !== pubKey) {
125 throw new Error('publieke sleutel gewijzigd — herbevestiging vereist (TOFU)');
126 }
127
128 stmts().upsertActor.run({
129 id: actorId,
130 url: actor.url || base,
131 name: actor.name || null,
132 summary: actor.summary || null,
133 avatar: (actor.icon && actor.icon.url) || null,
134 public_key: pubKey,
135 });
136
137 // 2. Outbox ophalen + handtekening verifiëren
138 const outboxUrl = actor.outbox || `${base}/.klonkt/outbox.json`;
139 const o = await fetchText(outboxUrl);
140 const sigHeader = o.headers.get('klonkt-signature') || '';
141 const sig = (sigHeader.match(/ed25519=(.+)\s*$/) || [])[1];
142 if (!sig || !verifyBody(o.text, sig, pubKey, remoteProto)) {
143 throw new Error('outbox-handtekening ongeldig of ontbreekt');
144 }
145 let outbox;
146 try { outbox = JSON.parse(o.text); } catch { throw new Error('outbox: ongeldige JSON'); }
147 const items = Array.isArray(outbox.orderedItems) ? outbox.orderedItems.slice(0, MAX_ITEMS) : [];
148
149 // 3. Objecten sanitizen + cachen (same-origin als de actor = anti-impersonatie)
150 const actorOrigin = originOf(actorId);
151 const seen = new Set();
152 for (const it of items) {
153 const obj = it && it.object;
154 if (!obj || !obj.id) continue;
155 if (originOf(obj.id) !== actorOrigin) continue;
156 const media = [];
157 if (obj.image && obj.image.url) media.push({ type: 'image', url: obj.image.url });
158 if (Array.isArray(obj.attachment)) {
159 for (const att of obj.attachment) {
160 if (att && att.url) media.push({ type: String(att.type || 'link').toLowerCase(), url: att.url, name: att.name, duration: att.duration });
161 }
162 }
163 stmts().upsertPost.run({
164 id: obj.id,
165 actor_id: actorId,
166 published: iso(obj.published || it.published),
167 title: stripHtml(obj.name).slice(0, 300) || '(zonder titel)',
168 summary: stripHtml(obj.summary || obj.content).slice(0, 1000),
169 url: obj.url || obj.id,
170 media_json: media.length ? JSON.stringify(media) : null,
171 raw_json: JSON.stringify(obj).slice(0, 20000),
172 });
173 seen.add(obj.id);
174 }
175
176 // 4. Pruning: posts die niet meer in de outbox staan opruimen
177 const known = db.prepare('SELECT id FROM remote_posts WHERE actor_id = ?').all(actorId).map((r) => r.id);
178 const stale = known.filter((id) => !seen.has(id));
179 if (stale.length) {
180 const del = db.prepare('DELETE FROM remote_posts WHERE id = ?');
181 db.transaction((ids) => ids.forEach((id) => del.run(id)))(stale);
182 }
183
184 db.prepare(
185 "UPDATE circle_links SET remote_actor_id=?, last_synced=CURRENT_TIMESTAMP, status='active', last_error=NULL WHERE id=?"
186 ).run(actorId, link.id);
187
188 return { ok: true, actorId, items: seen.size, pruned: stale.length };
189}
190
191export async function sync() {
192 if (getTenancy() !== 'circle') return { skipped: 'tenancy != circle' };
193 const links = db.prepare("SELECT * FROM circle_links WHERE status != 'paused'").all();
194 const results = [];
195 for (const link of links) {
196 try {
197 results.push(await syncOne(link));
198 } catch (e) {
199 const msg = String((e && e.message) || e).slice(0, 300);
200 db.prepare("UPDATE circle_links SET status='error', last_error=?, last_synced=CURRENT_TIMESTAMP WHERE id=?")
201 .run(msg, link.id);
202 results.push({ ok: false, link: link.remote_url, error: msg });
203 }
204 }
205 return { synced: results.length, results };
206}
207
208let _timer = null;
209/** Periodieke achtergrond-sync (gated op tenancy='circle' binnen sync()). */
210export function startCircleSyncLoop(intervalMs = 15 * 60 * 1000) {
211 if (_timer) return;
212 const run = () => { sync().catch((e) => console.error('[cirkels] sync-fout:', e.message)); };
213 setTimeout(run, 30 * 1000); // korte delay na boot
214 _timer = setInterval(run, intervalMs);
215 if (_timer.unref) _timer.unref();
216}
Note: See TracBrowser for help on using the repository browser.