source: Klonkt/src/services/ActivityPubService.js@ dd1028a

main
Last change on this file since dd1028a was 5bf63b7, checked in by Robin Genis <roboburr@…>, 3 months ago

feat(activitypub): phase 1b — Follow/Accept, HTTP Signatures, delivery

Inbox handles Follow (store follower + send signed Accept) and Undo Follow;
incoming requests are signature-verified (best-effort). Outgoing POSTs to inboxes
are signed (draft-cavage RSA-SHA256). New published public posts are delivered as
Create(Note) to followers' inboxes. Makes a Klonkt actor truly followable from
Mastodon; live interop test pending with Bart.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 11.9 KB
Line 
1/**
2 * ActivityPubService — Klonkt as a real ActivityPub actor (fediverse bridge).
3 *
4 * Phase 1 (this file): the PUBLISH/discoverable side.
5 * - per-site RSA keypair (Mastodon-compatible HTTP Signatures; separate from
6 * the Ed25519 keys used by the lighter Cirkels v1)
7 * - builders for the Actor document, Note objects and the Outbox collection
8 * - apWants(): HTTP content-negotiation helper (activity+json vs HTML)
9 *
10 * The interactive side (inbox: Follow/Accept, signature verify, delivery to
11 * followers) lands in the next step and is tested live against Mastodon.
12 *
13 * AP actor URLs live under /ap/* so they never clash with the human pages:
14 * actor = <base>/ap/users/<slug>
15 * inbox = <actor>/inbox outbox = <actor>/outbox
16 * note = <base>/ap/notes/<postId>
17 */
18import crypto from 'crypto';
19import db from '../config/database.js';
20
21const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
22const MAX_OUTBOX = 20;
23
24// ── RSA keys per actor (lazy, cached in DB) ───────────────────────
25// Prepared lazily (NOT at module load) — the ap_keys table is created in
26// initializeDatabase(), which runs after this module is imported.
27let _sel, _ins;
28function keyStmts() {
29 if (!_sel) {
30 _sel = db.prepare('SELECT public_pem, private_pem FROM ap_keys WHERE slug = ?');
31 _ins = db.prepare('INSERT OR IGNORE INTO ap_keys (slug, public_pem, private_pem, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)');
32 }
33 return { sel: _sel, ins: _ins };
34}
35
36export function getOrCreateKeys(slug) {
37 const { sel, ins } = keyStmts();
38 const row = sel.get(slug);
39 if (row) return row;
40 const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
41 modulusLength: 2048,
42 publicKeyEncoding: { type: 'spki', format: 'pem' },
43 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
44 });
45 ins.run(slug, publicKey, privateKey);
46 return sel.get(slug) || { public_pem: publicKey, private_pem: privateKey };
47}
48
49// ── content negotiation ───────────────────────────────────────────
50// True when the caller wants ActivityPub JSON rather than the HTML page.
51export function apWants(req) {
52 const a = String(req.headers.accept || '').toLowerCase();
53 return a.includes('application/activity+json') ||
54 (a.includes('application/ld+json') && a.includes('activitystreams'));
55}
56
57const AP_CONTENT_TYPE = 'application/activity+json; charset=utf-8';
58export function sendAP(res, obj) {
59 res.type(AP_CONTENT_TYPE);
60 res.set('Cache-Control', 'public, max-age=120');
61 res.send(JSON.stringify(obj));
62}
63
64// ── document builders ─────────────────────────────────────────────
65export function actorId(base, slug) { return `${base}/ap/users/${encodeURIComponent(slug)}`; }
66export function noteId(base, postId) { return `${base}/ap/notes/${encodeURIComponent(postId)}`; }
67
68export function buildActor(base, site) {
69 const id = actorId(base, site.slug);
70 const keys = getOrCreateKeys(site.slug);
71 const actor = {
72 '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'],
73 id,
74 type: 'Person',
75 preferredUsername: site.slug,
76 name: site.title || site.slug,
77 summary: site.tagline || site.description || '',
78 url: `${base}/${site.slug === site.primary_slug ? '' : 'user/' + encodeURIComponent(site.slug)}`,
79 manuallyApprovesFollowers: false,
80 discoverable: true,
81 inbox: `${id}/inbox`,
82 outbox: `${id}/outbox`,
83 followers: `${id}/followers`,
84 endpoints: { sharedInbox: `${base}/ap/inbox` },
85 publicKey: {
86 id: `${id}#main-key`,
87 owner: id,
88 publicKeyPem: keys.public_pem,
89 },
90 };
91 if (site.profile_photo) {
92 const u = /^https?:/.test(site.profile_photo) ? site.profile_photo : `${base}${site.profile_photo.startsWith('/') ? '' : '/'}${site.profile_photo}`;
93 actor.icon = { type: 'Image', url: u };
94 }
95 return actor;
96}
97
98// A single post as an AS2 Note (the object), and as a Create activity (for outbox/delivery).
99export function buildNote(base, site, post) {
100 const id = noteId(base, post.id);
101 const aId = actorId(base, site.slug);
102 const human = `${base}/${encodeURIComponent(post.slug)}`;
103 const html = post.content || ''; // posts store sanitized HTML
104 return {
105 id,
106 type: 'Note',
107 attributedTo: aId,
108 content: html,
109 name: post.title || undefined,
110 url: human,
111 published: new Date(post.published_at || post.created_at || Date.now()).toISOString(),
112 to: [PUBLIC],
113 cc: [`${aId}/followers`],
114 tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [],
115 };
116}
117
118export function buildCreate(base, site, post) {
119 const note = buildNote(base, site, post);
120 return {
121 '@context': 'https://www.w3.org/ns/activitystreams',
122 id: note.id + '#create',
123 type: 'Create',
124 actor: actorId(base, site.slug),
125 published: note.published,
126 to: note.to,
127 cc: note.cc,
128 object: note,
129 };
130}
131
132export function buildOutbox(base, site, posts) {
133 const id = `${actorId(base, site.slug)}/outbox`;
134 const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p));
135 return {
136 '@context': 'https://www.w3.org/ns/activitystreams',
137 id,
138 type: 'OrderedCollection',
139 totalItems: items.length,
140 orderedItems: items,
141 };
142}
143
144export function buildFollowers(base, site, count) {
145 const id = `${actorId(base, site.slug)}/followers`;
146 return {
147 '@context': 'https://www.w3.org/ns/activitystreams',
148 id,
149 type: 'OrderedCollection',
150 totalItems: count || 0,
151 orderedItems: [], // hidden for privacy; count only
152 };
153}
154
155// ── followers store (lazy stmts) ──────────────────────────────────
156let _insF, _delF, _listF, _cntF;
157function fStmts() {
158 if (!_insF) {
159 _insF = db.prepare('INSERT OR IGNORE INTO ap_followers (slug, actor_uri, inbox, shared_inbox, created_at) VALUES (?,?,?,?,CURRENT_TIMESTAMP)');
160 _delF = db.prepare('DELETE FROM ap_followers WHERE slug = ? AND actor_uri = ?');
161 _listF = db.prepare('SELECT inbox, shared_inbox FROM ap_followers WHERE slug = ?');
162 _cntF = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?');
163 }
164 return { ins: _insF, del: _delF, list: _listF, cnt: _cntF };
165}
166export function followerCount(slug) { return fStmts().cnt.get(slug).n; }
167
168// ── HTTP Signatures + delivery ────────────────────────────────────
169const slugFromActorUrl = (url) => { const m = String(url || '').match(/\/ap\/users\/([^/?#]+)/); return m ? decodeURIComponent(m[1]) : null; };
170
171// Sign + POST an activity to a remote inbox (draft-cavage HTTP Signatures, RSA-SHA256).
172export async function deliver(inboxUrl, bodyObj, keyId, privatePem) {
173 const body = JSON.stringify(bodyObj);
174 const u = new URL(inboxUrl);
175 const date = new Date().toUTCString();
176 const digest = 'SHA-256=' + crypto.createHash('sha256').update(body).digest('base64');
177 const signingString = `(request-target): post ${u.pathname}\nhost: ${u.host}\ndate: ${date}\ndigest: ${digest}`;
178 const signature = crypto.sign('sha256', Buffer.from(signingString), privatePem).toString('base64');
179 const sig = `keyId="${keyId}",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="${signature}"`;
180 const r = await fetch(inboxUrl, {
181 method: 'POST',
182 headers: { 'Content-Type': 'application/activity+json', Accept: 'application/activity+json', Date: date, Digest: digest, Signature: sig },
183 body,
184 signal: AbortSignal.timeout(8000),
185 });
186 return r.status;
187}
188
189export async function fetchActor(url) {
190 try {
191 const r = await fetch(url, { headers: { Accept: 'application/activity+json' }, redirect: 'follow', signal: AbortSignal.timeout(8000) });
192 if (!r.ok) return null;
193 return await r.json();
194 } catch { return null; }
195}
196
197// Best-effort verification of an incoming signed request. Returns the sender's
198// actor doc if the signature checks out, else null. (Not gating yet — MVP.)
199export async function verifyRequest(req) {
200 const sigH = req.headers['signature'];
201 if (!sigH) return null;
202 const p = Object.fromEntries([...sigH.matchAll(/([a-zA-Z]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
203 if (!p.keyId || !p.signature) return null;
204 const actor = await fetchActor(p.keyId.split('#')[0]);
205 const pem = actor && actor.publicKey && actor.publicKey.publicKeyPem;
206 if (!pem) return null;
207 const hs = (p.headers || '(request-target) host date').split(/\s+/);
208 const line = hs.map((h) => h === '(request-target)'
209 ? `(request-target): ${req.method.toLowerCase()} ${req.originalUrl}`
210 : `${h}: ${req.headers[h] || ''}`).join('\n');
211 let ok = false;
212 try { ok = crypto.verify('sha256', Buffer.from(line), pem, Buffer.from(p.signature, 'base64')); } catch { ok = false; }
213 if (ok && hs.includes('digest') && req.rawBody) {
214 const exp = 'SHA-256=' + crypto.createHash('sha256').update(req.rawBody).digest('base64');
215 if (req.headers['digest'] !== exp) ok = false;
216 }
217 return ok ? actor : null;
218}
219
220// Handle an incoming inbox POST. slugParam = null for the shared /ap/inbox.
221export async function handleInbox(req, slugParam) {
222 const act = req.body || {};
223 const type = act.type;
224 const base = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
225 const verified = await verifyRequest(req).catch(() => null); // best-effort; not gating (MVP)
226
227 if (type === 'Follow') {
228 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
229 const slug = slugParam || slugFromActorUrl(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
230 if (!who || !slug) return 400;
231 const remote = await fetchActor(who);
232 if (!remote || !remote.inbox) return 202; // can't reach them → drop quietly
233 fStmts().ins.run(slug, who, remote.inbox, (remote.endpoints && remote.endpoints.sharedInbox) || null);
234 const me = actorId(base, slug);
235 const keys = getOrCreateKeys(slug);
236 const accept = { '@context': 'https://www.w3.org/ns/activitystreams', id: `${me}#accept-${Date.now()}`, type: 'Accept', actor: me, object: act };
237 deliver(remote.inbox, accept, `${me}#main-key`, keys.private_pem).catch((e) => console.warn('[AP] Accept delivery failed:', e.message));
238 console.log('[AP] Follow', who, '→', slug, verified ? '(sig ok)' : '(sig unverified)');
239 return 202;
240 }
241 if (type === 'Undo' && act.object && act.object.type === 'Follow') {
242 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
243 const obj = act.object.object;
244 const slug = slugParam || slugFromActorUrl(typeof obj === 'string' ? obj : (obj && obj.id));
245 if (who && slug) { fStmts().del.run(slug, who); console.log('[AP] Unfollow', who, '→', slug); }
246 return 202;
247 }
248 console.log('[AP] inbox', type || 'unknown', '→', slugParam || 'shared', '(ignored)');
249 return 202;
250}
251
252// Deliver a new post as Create(Note) to all followers' inboxes (fire-and-forget).
253// Needs PUBLIC_BASE_URL (absolute URLs); no-op without followers or base.
254export async function deliverCreate(site, post) {
255 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
256 if (!base || !site || !site.slug) return;
257 const followers = fStmts().list.all(site.slug);
258 if (!followers.length) return;
259 const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
260 const keys = getOrCreateKeys(site.slug);
261 const keyId = `${actorId(base, site.slug)}#main-key`;
262 const create = buildCreate(base, site, post);
263 for (const inbox of inboxes) deliver(inbox, create, keyId, keys.private_pem).catch(() => { /* best-effort */ });
264}
265
266export default {
267 getOrCreateKeys, apWants, sendAP, actorId, noteId,
268 buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
269 followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate,
270};
Note: See TracBrowser for help on using the repository browser.