source: Klonkt/src/services/ActivityPubService.js@ 065452a

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

fix(activitypub): include post title in the Note content

Mastodon ignores a Note's name field, so prepend the title as a bold first line
in content (the standard blog->fediverse convention). Title is HTML-escaped.

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

  • Property mode set to 100644
File size: 12.3 KB
RevLine 
[6bd25d1]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)}`;
[065452a]103 // Mastodon ignores a Note's `name`, so put the title INTO the content (bold
104 // first line) — the standard blog→fediverse convention. post.content is
105 // already sanitized HTML; the title is plain text, so escape it.
106 const escTitle = String(post.title || '').replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]));
107 const titleHtml = post.title ? `<p><strong>${escTitle}</strong></p>` : '';
108 const html = titleHtml + (post.content || '');
[6bd25d1]109 return {
110 id,
111 type: 'Note',
112 attributedTo: aId,
113 content: html,
114 url: human,
115 published: new Date(post.published_at || post.created_at || Date.now()).toISOString(),
116 to: [PUBLIC],
117 cc: [`${aId}/followers`],
118 tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [],
119 };
120}
121
122export function buildCreate(base, site, post) {
123 const note = buildNote(base, site, post);
124 return {
125 '@context': 'https://www.w3.org/ns/activitystreams',
126 id: note.id + '#create',
127 type: 'Create',
128 actor: actorId(base, site.slug),
129 published: note.published,
130 to: note.to,
131 cc: note.cc,
132 object: note,
133 };
134}
135
136export function buildOutbox(base, site, posts) {
137 const id = `${actorId(base, site.slug)}/outbox`;
138 const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p));
139 return {
140 '@context': 'https://www.w3.org/ns/activitystreams',
141 id,
142 type: 'OrderedCollection',
143 totalItems: items.length,
144 orderedItems: items,
145 };
146}
147
148export function buildFollowers(base, site, count) {
149 const id = `${actorId(base, site.slug)}/followers`;
150 return {
151 '@context': 'https://www.w3.org/ns/activitystreams',
152 id,
153 type: 'OrderedCollection',
154 totalItems: count || 0,
155 orderedItems: [], // hidden for privacy; count only
156 };
157}
158
[5bf63b7]159// ── followers store (lazy stmts) ──────────────────────────────────
160let _insF, _delF, _listF, _cntF;
161function fStmts() {
162 if (!_insF) {
163 _insF = db.prepare('INSERT OR IGNORE INTO ap_followers (slug, actor_uri, inbox, shared_inbox, created_at) VALUES (?,?,?,?,CURRENT_TIMESTAMP)');
164 _delF = db.prepare('DELETE FROM ap_followers WHERE slug = ? AND actor_uri = ?');
165 _listF = db.prepare('SELECT inbox, shared_inbox FROM ap_followers WHERE slug = ?');
166 _cntF = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?');
167 }
168 return { ins: _insF, del: _delF, list: _listF, cnt: _cntF };
169}
170export function followerCount(slug) { return fStmts().cnt.get(slug).n; }
171
172// ── HTTP Signatures + delivery ────────────────────────────────────
173const slugFromActorUrl = (url) => { const m = String(url || '').match(/\/ap\/users\/([^/?#]+)/); return m ? decodeURIComponent(m[1]) : null; };
174
175// Sign + POST an activity to a remote inbox (draft-cavage HTTP Signatures, RSA-SHA256).
176export async function deliver(inboxUrl, bodyObj, keyId, privatePem) {
177 const body = JSON.stringify(bodyObj);
178 const u = new URL(inboxUrl);
179 const date = new Date().toUTCString();
180 const digest = 'SHA-256=' + crypto.createHash('sha256').update(body).digest('base64');
181 const signingString = `(request-target): post ${u.pathname}\nhost: ${u.host}\ndate: ${date}\ndigest: ${digest}`;
182 const signature = crypto.sign('sha256', Buffer.from(signingString), privatePem).toString('base64');
183 const sig = `keyId="${keyId}",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="${signature}"`;
184 const r = await fetch(inboxUrl, {
185 method: 'POST',
186 headers: { 'Content-Type': 'application/activity+json', Accept: 'application/activity+json', Date: date, Digest: digest, Signature: sig },
187 body,
188 signal: AbortSignal.timeout(8000),
189 });
190 return r.status;
191}
192
193export async function fetchActor(url) {
194 try {
195 const r = await fetch(url, { headers: { Accept: 'application/activity+json' }, redirect: 'follow', signal: AbortSignal.timeout(8000) });
196 if (!r.ok) return null;
197 return await r.json();
198 } catch { return null; }
199}
200
201// Best-effort verification of an incoming signed request. Returns the sender's
202// actor doc if the signature checks out, else null. (Not gating yet — MVP.)
203export async function verifyRequest(req) {
204 const sigH = req.headers['signature'];
205 if (!sigH) return null;
206 const p = Object.fromEntries([...sigH.matchAll(/([a-zA-Z]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
207 if (!p.keyId || !p.signature) return null;
208 const actor = await fetchActor(p.keyId.split('#')[0]);
209 const pem = actor && actor.publicKey && actor.publicKey.publicKeyPem;
210 if (!pem) return null;
211 const hs = (p.headers || '(request-target) host date').split(/\s+/);
212 const line = hs.map((h) => h === '(request-target)'
213 ? `(request-target): ${req.method.toLowerCase()} ${req.originalUrl}`
214 : `${h}: ${req.headers[h] || ''}`).join('\n');
215 let ok = false;
216 try { ok = crypto.verify('sha256', Buffer.from(line), pem, Buffer.from(p.signature, 'base64')); } catch { ok = false; }
217 if (ok && hs.includes('digest') && req.rawBody) {
218 const exp = 'SHA-256=' + crypto.createHash('sha256').update(req.rawBody).digest('base64');
219 if (req.headers['digest'] !== exp) ok = false;
220 }
221 return ok ? actor : null;
222}
223
224// Handle an incoming inbox POST. slugParam = null for the shared /ap/inbox.
225export async function handleInbox(req, slugParam) {
226 const act = req.body || {};
227 const type = act.type;
228 const base = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
229 const verified = await verifyRequest(req).catch(() => null); // best-effort; not gating (MVP)
230
231 if (type === 'Follow') {
232 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
233 const slug = slugParam || slugFromActorUrl(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
234 if (!who || !slug) return 400;
235 const remote = await fetchActor(who);
236 if (!remote || !remote.inbox) return 202; // can't reach them → drop quietly
237 fStmts().ins.run(slug, who, remote.inbox, (remote.endpoints && remote.endpoints.sharedInbox) || null);
238 const me = actorId(base, slug);
239 const keys = getOrCreateKeys(slug);
240 const accept = { '@context': 'https://www.w3.org/ns/activitystreams', id: `${me}#accept-${Date.now()}`, type: 'Accept', actor: me, object: act };
241 deliver(remote.inbox, accept, `${me}#main-key`, keys.private_pem).catch((e) => console.warn('[AP] Accept delivery failed:', e.message));
242 console.log('[AP] Follow', who, '→', slug, verified ? '(sig ok)' : '(sig unverified)');
243 return 202;
244 }
245 if (type === 'Undo' && act.object && act.object.type === 'Follow') {
246 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
247 const obj = act.object.object;
248 const slug = slugParam || slugFromActorUrl(typeof obj === 'string' ? obj : (obj && obj.id));
249 if (who && slug) { fStmts().del.run(slug, who); console.log('[AP] Unfollow', who, '→', slug); }
250 return 202;
251 }
252 console.log('[AP] inbox', type || 'unknown', '→', slugParam || 'shared', '(ignored)');
253 return 202;
254}
255
256// Deliver a new post as Create(Note) to all followers' inboxes (fire-and-forget).
257// Needs PUBLIC_BASE_URL (absolute URLs); no-op without followers or base.
258export async function deliverCreate(site, post) {
259 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
260 if (!base || !site || !site.slug) return;
261 const followers = fStmts().list.all(site.slug);
262 if (!followers.length) return;
263 const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
264 const keys = getOrCreateKeys(site.slug);
265 const keyId = `${actorId(base, site.slug)}#main-key`;
266 const create = buildCreate(base, site, post);
267 for (const inbox of inboxes) deliver(inbox, create, keyId, keys.private_pem).catch(() => { /* best-effort */ });
268}
269
[6bd25d1]270export default {
271 getOrCreateKeys, apWants, sendAP, actorId, noteId,
272 buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
[5bf63b7]273 followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate,
[6bd25d1]274};
Note: See TracBrowser for help on using the repository browser.