| 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 |
|
|---|
| 7 | import db from '../config/database.js';
|
|---|
| 8 | import { verifyBody } from './CircleFederation.js';
|
|---|
| 9 | import { getTenancy } from './SettingsService.js';
|
|---|
| 10 |
|
|---|
| 11 | const FETCH_TIMEOUT_MS = 10000;
|
|---|
| 12 | const MAX_BODY_BYTES = 1024 * 1024; // 1 MB
|
|---|
| 13 | const MAX_ITEMS = 50;
|
|---|
| 14 |
|
|---|
| 15 | function stripHtml(s) {
|
|---|
| 16 | return String(s || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
|
|---|
| 17 | }
|
|---|
| 18 | function iso(d) {
|
|---|
| 19 | const t = d ? new Date(d) : null;
|
|---|
| 20 | return t && !isNaN(t.getTime()) ? t.toISOString() : null;
|
|---|
| 21 | }
|
|---|
| 22 | function originOf(u) {
|
|---|
| 23 | try { return new URL(u).origin; } catch { return null; }
|
|---|
| 24 | }
|
|---|
| 25 | function baseOf(remoteUrl) {
|
|---|
| 26 | return String(remoteUrl).replace(/\/+$/, '');
|
|---|
| 27 | }
|
|---|
| 28 |
|
|---|
| 29 | // Robuuste, defensieve fetch: alleen https, timeout, body-cap, redirect-follow.
|
|---|
| 30 | async 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 | const upsertActor = db.prepare(`
|
|---|
| 50 | INSERT INTO remote_actors (id, url, name, summary, avatar, public_key, fetched_at)
|
|---|
| 51 | VALUES (@id, @url, @name, @summary, @avatar, @public_key, CURRENT_TIMESTAMP)
|
|---|
| 52 | ON CONFLICT(id) DO UPDATE SET
|
|---|
| 53 | url=excluded.url, name=excluded.name, summary=excluded.summary,
|
|---|
| 54 | avatar=excluded.avatar, public_key=excluded.public_key, fetched_at=CURRENT_TIMESTAMP
|
|---|
| 55 | `);
|
|---|
| 56 | const upsertPost = db.prepare(`
|
|---|
| 57 | INSERT INTO remote_posts (id, actor_id, published, title, summary, url, media_json, raw_json, fetched_at)
|
|---|
| 58 | VALUES (@id, @actor_id, @published, @title, @summary, @url, @media_json, @raw_json, CURRENT_TIMESTAMP)
|
|---|
| 59 | ON CONFLICT(id) DO UPDATE SET
|
|---|
| 60 | published=excluded.published, title=excluded.title, summary=excluded.summary,
|
|---|
| 61 | url=excluded.url, media_json=excluded.media_json, raw_json=excluded.raw_json, fetched_at=CURRENT_TIMESTAMP
|
|---|
| 62 | `);
|
|---|
| 63 |
|
|---|
| 64 | export async function syncOne(link) {
|
|---|
| 65 | const base = baseOf(link.remote_url);
|
|---|
| 66 |
|
|---|
| 67 | // 1. Actor ophalen + valideren
|
|---|
| 68 | const actorUrl = `${base}/.klonkt/actor.json`;
|
|---|
| 69 | const a = await fetchText(actorUrl);
|
|---|
| 70 | let actor;
|
|---|
| 71 | try { actor = JSON.parse(a.text); } catch { throw new Error('actor: ongeldige JSON'); }
|
|---|
| 72 | const actorId = actor.id;
|
|---|
| 73 | const pubKey = actor.publicKey && actor.publicKey.publicKeyBase64;
|
|---|
| 74 | if (!actorId || !pubKey) throw new Error('actor mist id/publicKey');
|
|---|
| 75 | if (originOf(actorId) !== originOf(actorUrl)) throw new Error('actor.id heeft andere origin dan de actor-URL');
|
|---|
| 76 |
|
|---|
| 77 | // TOFU: een sleutelwissel vereist expliciete herbevestiging (anti-hijack)
|
|---|
| 78 | const existing = db.prepare('SELECT public_key FROM remote_actors WHERE id = ?').get(actorId);
|
|---|
| 79 | if (existing && existing.public_key !== pubKey) {
|
|---|
| 80 | throw new Error('publieke sleutel gewijzigd — herbevestiging vereist (TOFU)');
|
|---|
| 81 | }
|
|---|
| 82 |
|
|---|
| 83 | upsertActor.run({
|
|---|
| 84 | id: actorId,
|
|---|
| 85 | url: actor.url || base,
|
|---|
| 86 | name: actor.name || null,
|
|---|
| 87 | summary: actor.summary || null,
|
|---|
| 88 | avatar: (actor.icon && actor.icon.url) || null,
|
|---|
| 89 | public_key: pubKey,
|
|---|
| 90 | });
|
|---|
| 91 |
|
|---|
| 92 | // 2. Outbox ophalen + handtekening verifiëren
|
|---|
| 93 | const outboxUrl = actor.outbox || `${base}/.klonkt/outbox.json`;
|
|---|
| 94 | const o = await fetchText(outboxUrl);
|
|---|
| 95 | const sigHeader = o.headers.get('klonkt-signature') || '';
|
|---|
| 96 | const sig = (sigHeader.match(/ed25519=(.+)\s*$/) || [])[1];
|
|---|
| 97 | if (!sig || !verifyBody(o.text, sig, pubKey)) {
|
|---|
| 98 | throw new Error('outbox-handtekening ongeldig of ontbreekt');
|
|---|
| 99 | }
|
|---|
| 100 | let outbox;
|
|---|
| 101 | try { outbox = JSON.parse(o.text); } catch { throw new Error('outbox: ongeldige JSON'); }
|
|---|
| 102 | const items = Array.isArray(outbox.orderedItems) ? outbox.orderedItems.slice(0, MAX_ITEMS) : [];
|
|---|
| 103 |
|
|---|
| 104 | // 3. Objecten sanitizen + cachen (same-origin als de actor = anti-impersonatie)
|
|---|
| 105 | const actorOrigin = originOf(actorId);
|
|---|
| 106 | const seen = new Set();
|
|---|
| 107 | for (const it of items) {
|
|---|
| 108 | const obj = it && it.object;
|
|---|
| 109 | if (!obj || !obj.id) continue;
|
|---|
| 110 | if (originOf(obj.id) !== actorOrigin) continue;
|
|---|
| 111 | const media = [];
|
|---|
| 112 | if (obj.image && obj.image.url) media.push({ type: 'image', url: obj.image.url });
|
|---|
| 113 | if (Array.isArray(obj.attachment)) {
|
|---|
| 114 | for (const att of obj.attachment) {
|
|---|
| 115 | if (att && att.url) media.push({ type: String(att.type || 'link').toLowerCase(), url: att.url, name: att.name, duration: att.duration });
|
|---|
| 116 | }
|
|---|
| 117 | }
|
|---|
| 118 | upsertPost.run({
|
|---|
| 119 | id: obj.id,
|
|---|
| 120 | actor_id: actorId,
|
|---|
| 121 | published: iso(obj.published || it.published),
|
|---|
| 122 | title: stripHtml(obj.name).slice(0, 300) || '(zonder titel)',
|
|---|
| 123 | summary: stripHtml(obj.summary || obj.content).slice(0, 1000),
|
|---|
| 124 | url: obj.url || obj.id,
|
|---|
| 125 | media_json: media.length ? JSON.stringify(media) : null,
|
|---|
| 126 | raw_json: JSON.stringify(obj).slice(0, 20000),
|
|---|
| 127 | });
|
|---|
| 128 | seen.add(obj.id);
|
|---|
| 129 | }
|
|---|
| 130 |
|
|---|
| 131 | // 4. Pruning: posts die niet meer in de outbox staan opruimen
|
|---|
| 132 | const known = db.prepare('SELECT id FROM remote_posts WHERE actor_id = ?').all(actorId).map((r) => r.id);
|
|---|
| 133 | const stale = known.filter((id) => !seen.has(id));
|
|---|
| 134 | if (stale.length) {
|
|---|
| 135 | const del = db.prepare('DELETE FROM remote_posts WHERE id = ?');
|
|---|
| 136 | db.transaction((ids) => ids.forEach((id) => del.run(id)))(stale);
|
|---|
| 137 | }
|
|---|
| 138 |
|
|---|
| 139 | db.prepare(
|
|---|
| 140 | "UPDATE circle_links SET remote_actor_id=?, last_synced=CURRENT_TIMESTAMP, status='active', last_error=NULL WHERE id=?"
|
|---|
| 141 | ).run(actorId, link.id);
|
|---|
| 142 |
|
|---|
| 143 | return { ok: true, actorId, items: seen.size, pruned: stale.length };
|
|---|
| 144 | }
|
|---|
| 145 |
|
|---|
| 146 | export async function sync() {
|
|---|
| 147 | if (getTenancy() !== 'circle') return { skipped: 'tenancy != circle' };
|
|---|
| 148 | const links = db.prepare("SELECT * FROM circle_links WHERE status != 'paused'").all();
|
|---|
| 149 | const results = [];
|
|---|
| 150 | for (const link of links) {
|
|---|
| 151 | try {
|
|---|
| 152 | results.push(await syncOne(link));
|
|---|
| 153 | } catch (e) {
|
|---|
| 154 | const msg = String((e && e.message) || e).slice(0, 300);
|
|---|
| 155 | db.prepare("UPDATE circle_links SET status='error', last_error=?, last_synced=CURRENT_TIMESTAMP WHERE id=?")
|
|---|
| 156 | .run(msg, link.id);
|
|---|
| 157 | results.push({ ok: false, link: link.remote_url, error: msg });
|
|---|
| 158 | }
|
|---|
| 159 | }
|
|---|
| 160 | return { synced: results.length, results };
|
|---|
| 161 | }
|
|---|
| 162 |
|
|---|
| 163 | let _timer = null;
|
|---|
| 164 | /** Periodieke achtergrond-sync (gated op tenancy='circle' binnen sync()). */
|
|---|
| 165 | export function startCircleSyncLoop(intervalMs = 15 * 60 * 1000) {
|
|---|
| 166 | if (_timer) return;
|
|---|
| 167 | const run = () => { sync().catch((e) => console.error('[cirkels] sync-fout:', e.message)); };
|
|---|
| 168 | setTimeout(run, 30 * 1000); // korte delay na boot
|
|---|
| 169 | _timer = setInterval(run, intervalMs);
|
|---|
| 170 | if (_timer.unref) _timer.unref();
|
|---|
| 171 | }
|
|---|