source: Klonkt/src/services/CircleService.js@ 1be21ba

main
Last change on this file since 1be21ba was 151a72c, checked in by roboburr <roboburr@…>, 3 months ago

Circle UI: reason on its own line + clean word wrapping; message without duplicate URL

The outdated reason was pressed against the badge in a <small> with
word-break:break-all (intended for the URL) → broke in the middle of words.
Now a separate .circ-reason line with normal wrapping, and the proto message
no longer repeats the URL (the card already shows it).

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

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