source: Klonkt/src/services/CircleService.js@ 0b7ebbf

main
Last change on this file since 0b7ebbf was 25d4041, checked in by roboburr <roboburr@…>, 3 months ago

Circles v1 — step 3: pull side (CircleService.sync)

  • CircleService.js: fetches the remote actor + outbox per circle_link, verifies the Ed25519 Klonkt-Signature, sanitises (HTML -> plain text), caches in remote_actors/remote_posts. Defensive: https-only, fetch timeout, body cap, max items. Security: same-origin object.id vs actor (anti-impersonation), TOFU on the public key (key change = re-confirmation required), pruning of disappeared posts.
  • startCircleSyncLoop(): periodic background sync (15 min), no-op unless tenancy=circle.
  • server.js: loop started after initializeDatabase.

Consumer round-trip verified in isolation (verify ok / tamper fails / cross-origin
rejected).

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

  • Property mode set to 100644
File size: 6.9 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
49const 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`);
56const 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
64export 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
146export 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
163let _timer = null;
164/** Periodieke achtergrond-sync (gated op tenancy='circle' binnen sync()). */
165export 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}
Note: See TracBrowser for help on using the repository browser.