source: Klonkt/src/services/CircleService.js@ 7007d4c

main
Last change on this file since 7007d4c was 57929aa, checked in by roboburr <roboburr@…>, 3 months ago

Circles: lazy prepares in CircleService (fix crash on boot)

The module-level db.prepare() ran at import — before initializeDatabase()
created the remote_actors/remote_posts tables -> SQLITE_ERROR no such table
-> crash-loop. Now lazy via stmts() (prepare on first sync).

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

  • Property mode set to 100644
File size: 7.2 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 } 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// Robuuste, defensieve fetch: alleen https, timeout, body-cap, redirect-follow.
30async function fetchText(url) {
31 if (!/^https:\/\//i.test(url)) throw new Error('alleen https toegestaan');
32 const ac = new AbortController();
33 const timer = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
34 try {
35 const res = await fetch(url, {
36 signal: ac.signal,
37 redirect: 'follow',
38 headers: { Accept: 'application/activity+json, application/json' },
39 });
40 if (!res.ok) throw new Error(`HTTP ${res.status}`);
41 const buf = Buffer.from(await res.arrayBuffer());
42 if (buf.length > MAX_BODY_BYTES) throw new Error('body te groot');
43 return { text: buf.toString('utf8'), headers: res.headers, finalUrl: res.url };
44 } finally {
45 clearTimeout(timer);
46 }
47}
48
49// Lazy prepares — de tabellen bestaan pas ná initializeDatabase(); dit module
50// wordt geïmporteerd vóór die call, dus niet op module-niveau prepare'n.
51let _stmts = null;
52function stmts() {
53 if (_stmts) return _stmts;
54 _stmts = {
55 upsertActor: db.prepare(`
56 INSERT INTO remote_actors (id, url, name, summary, avatar, public_key, fetched_at)
57 VALUES (@id, @url, @name, @summary, @avatar, @public_key, CURRENT_TIMESTAMP)
58 ON CONFLICT(id) DO UPDATE SET
59 url=excluded.url, name=excluded.name, summary=excluded.summary,
60 avatar=excluded.avatar, public_key=excluded.public_key, fetched_at=CURRENT_TIMESTAMP
61 `),
62 upsertPost: db.prepare(`
63 INSERT INTO remote_posts (id, actor_id, published, title, summary, url, media_json, raw_json, fetched_at)
64 VALUES (@id, @actor_id, @published, @title, @summary, @url, @media_json, @raw_json, CURRENT_TIMESTAMP)
65 ON CONFLICT(id) DO UPDATE SET
66 published=excluded.published, title=excluded.title, summary=excluded.summary,
67 url=excluded.url, media_json=excluded.media_json, raw_json=excluded.raw_json, fetched_at=CURRENT_TIMESTAMP
68 `),
69 };
70 return _stmts;
71}
72
73export async function syncOne(link) {
74 const base = baseOf(link.remote_url);
75
76 // 1. Actor ophalen + valideren
77 const actorUrl = `${base}/.klonkt/actor.json`;
78 const a = await fetchText(actorUrl);
79 let actor;
80 try { actor = JSON.parse(a.text); } catch { throw new Error('actor: ongeldige JSON'); }
81 const actorId = actor.id;
82 const pubKey = actor.publicKey && actor.publicKey.publicKeyBase64;
83 if (!actorId || !pubKey) throw new Error('actor mist id/publicKey');
84 if (originOf(actorId) !== originOf(actorUrl)) throw new Error('actor.id heeft andere origin dan de actor-URL');
85
86 // TOFU: een sleutelwissel vereist expliciete herbevestiging (anti-hijack)
87 const existing = db.prepare('SELECT public_key FROM remote_actors WHERE id = ?').get(actorId);
88 if (existing && existing.public_key !== pubKey) {
89 throw new Error('publieke sleutel gewijzigd — herbevestiging vereist (TOFU)');
90 }
91
92 stmts().upsertActor.run({
93 id: actorId,
94 url: actor.url || base,
95 name: actor.name || null,
96 summary: actor.summary || null,
97 avatar: (actor.icon && actor.icon.url) || null,
98 public_key: pubKey,
99 });
100
101 // 2. Outbox ophalen + handtekening verifiëren
102 const outboxUrl = actor.outbox || `${base}/.klonkt/outbox.json`;
103 const o = await fetchText(outboxUrl);
104 const sigHeader = o.headers.get('klonkt-signature') || '';
105 const sig = (sigHeader.match(/ed25519=(.+)\s*$/) || [])[1];
106 if (!sig || !verifyBody(o.text, sig, pubKey)) {
107 throw new Error('outbox-handtekening ongeldig of ontbreekt');
108 }
109 let outbox;
110 try { outbox = JSON.parse(o.text); } catch { throw new Error('outbox: ongeldige JSON'); }
111 const items = Array.isArray(outbox.orderedItems) ? outbox.orderedItems.slice(0, MAX_ITEMS) : [];
112
113 // 3. Objecten sanitizen + cachen (same-origin als de actor = anti-impersonatie)
114 const actorOrigin = originOf(actorId);
115 const seen = new Set();
116 for (const it of items) {
117 const obj = it && it.object;
118 if (!obj || !obj.id) continue;
119 if (originOf(obj.id) !== actorOrigin) continue;
120 const media = [];
121 if (obj.image && obj.image.url) media.push({ type: 'image', url: obj.image.url });
122 if (Array.isArray(obj.attachment)) {
123 for (const att of obj.attachment) {
124 if (att && att.url) media.push({ type: String(att.type || 'link').toLowerCase(), url: att.url, name: att.name, duration: att.duration });
125 }
126 }
127 stmts().upsertPost.run({
128 id: obj.id,
129 actor_id: actorId,
130 published: iso(obj.published || it.published),
131 title: stripHtml(obj.name).slice(0, 300) || '(zonder titel)',
132 summary: stripHtml(obj.summary || obj.content).slice(0, 1000),
133 url: obj.url || obj.id,
134 media_json: media.length ? JSON.stringify(media) : null,
135 raw_json: JSON.stringify(obj).slice(0, 20000),
136 });
137 seen.add(obj.id);
138 }
139
140 // 4. Pruning: posts die niet meer in de outbox staan opruimen
141 const known = db.prepare('SELECT id FROM remote_posts WHERE actor_id = ?').all(actorId).map((r) => r.id);
142 const stale = known.filter((id) => !seen.has(id));
143 if (stale.length) {
144 const del = db.prepare('DELETE FROM remote_posts WHERE id = ?');
145 db.transaction((ids) => ids.forEach((id) => del.run(id)))(stale);
146 }
147
148 db.prepare(
149 "UPDATE circle_links SET remote_actor_id=?, last_synced=CURRENT_TIMESTAMP, status='active', last_error=NULL WHERE id=?"
150 ).run(actorId, link.id);
151
152 return { ok: true, actorId, items: seen.size, pruned: stale.length };
153}
154
155export async function sync() {
156 if (getTenancy() !== 'circle') return { skipped: 'tenancy != circle' };
157 const links = db.prepare("SELECT * FROM circle_links WHERE status != 'paused'").all();
158 const results = [];
159 for (const link of links) {
160 try {
161 results.push(await syncOne(link));
162 } catch (e) {
163 const msg = String((e && e.message) || e).slice(0, 300);
164 db.prepare("UPDATE circle_links SET status='error', last_error=?, last_synced=CURRENT_TIMESTAMP WHERE id=?")
165 .run(msg, link.id);
166 results.push({ ok: false, link: link.remote_url, error: msg });
167 }
168 }
169 return { synced: results.length, results };
170}
171
172let _timer = null;
173/** Periodieke achtergrond-sync (gated op tenancy='circle' binnen sync()). */
174export function startCircleSyncLoop(intervalMs = 15 * 60 * 1000) {
175 if (_timer) return;
176 const run = () => { sync().catch((e) => console.error('[cirkels] sync-fout:', e.message)); };
177 setTimeout(run, 30 * 1000); // korte delay na boot
178 _timer = setInterval(run, intervalMs);
179 if (_timer.unref) _timer.unref();
180}
Note: See TracBrowser for help on using the repository browser.