source: Klonkt/src/services/CircleService.js@ 66cfbaa

main
Last change on this file since 66cfbaa was 221a209, checked in by roboburr <roboburr@…>, 3 months ago

Circle: carry over + display tags from the original post

Publisher puts tags as AS Hashtag array in the outbox (href pointing to the
source tag page). Consumer parses + caches them (remote_posts.tags). Feed
cards display them (post-card), and the reader shows tag chips that link to
the /tag page of the source.

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

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