| [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 | */
|
|---|
| 18 | import crypto from 'crypto';
|
|---|
| 19 | import db from '../config/database.js';
|
|---|
| 20 |
|
|---|
| 21 | const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
|
|---|
| 22 | const 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.
|
|---|
| 27 | let _sel, _ins;
|
|---|
| 28 | function 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 |
|
|---|
| 36 | export 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.
|
|---|
| 51 | export 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 |
|
|---|
| 57 | const AP_CONTENT_TYPE = 'application/activity+json; charset=utf-8';
|
|---|
| 58 | export 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 ─────────────────────────────────────────────
|
|---|
| 65 | export function actorId(base, slug) { return `${base}/ap/users/${encodeURIComponent(slug)}`; }
|
|---|
| 66 | export function noteId(base, postId) { return `${base}/ap/notes/${encodeURIComponent(postId)}`; }
|
|---|
| 67 |
|
|---|
| 68 | export 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).
|
|---|
| 99 | export 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) => ({ '<': '<', '>': '>', '&': '&' }[c]));
|
|---|
| 107 | const titleHtml = post.title ? `<p><strong>${escTitle}</strong></p>` : '';
|
|---|
| [5a93ac0] | 108 |
|
|---|
| 109 | // Images travel as AP `attachment` (Mastodon strips <img> from content). Collect
|
|---|
| 110 | // the cover + any inline <img>, make absolute, then strip <img> from the content
|
|---|
| 111 | // to avoid duplicate rendering on clients that DO keep them.
|
|---|
| 112 | const abs = (u) => !u ? null : (/^https?:/i.test(u) ? u : `${base}${u.startsWith('/') ? '' : '/'}${u}`);
|
|---|
| 113 | const mediaType = (u) => {
|
|---|
| 114 | const e = ((u || '').split('?')[0].match(/\.(\w+)$/) || [])[1];
|
|---|
| 115 | return ({ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif' })[(e || '').toLowerCase()] || 'image/jpeg';
|
|---|
| 116 | };
|
|---|
| 117 | const urls = [];
|
|---|
| 118 | if (post.cover_image_url) urls.push(abs(post.cover_image_url));
|
|---|
| 119 | let body = post.content || '';
|
|---|
| 120 | for (const m of body.matchAll(/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/gi)) urls.push(abs(m[1]));
|
|---|
| 121 | body = body.replace(/<img\b[^>]*>/gi, '');
|
|---|
| 122 | const seen = new Set();
|
|---|
| 123 | const attachment = urls.filter(Boolean)
|
|---|
| 124 | .filter((u) => { if (seen.has(u)) return false; seen.add(u); return true; })
|
|---|
| 125 | .map((u) => ({ type: 'Document', mediaType: mediaType(u), url: u }));
|
|---|
| 126 |
|
|---|
| 127 | const note = {
|
|---|
| [6bd25d1] | 128 | id,
|
|---|
| 129 | type: 'Note',
|
|---|
| 130 | attributedTo: aId,
|
|---|
| [5a93ac0] | 131 | content: titleHtml + body,
|
|---|
| [6bd25d1] | 132 | url: human,
|
|---|
| 133 | published: new Date(post.published_at || post.created_at || Date.now()).toISOString(),
|
|---|
| 134 | to: [PUBLIC],
|
|---|
| 135 | cc: [`${aId}/followers`],
|
|---|
| 136 | tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [],
|
|---|
| 137 | };
|
|---|
| [5a93ac0] | 138 | if (attachment.length) note.attachment = attachment;
|
|---|
| 139 | return note;
|
|---|
| [6bd25d1] | 140 | }
|
|---|
| 141 |
|
|---|
| 142 | export function buildCreate(base, site, post) {
|
|---|
| 143 | const note = buildNote(base, site, post);
|
|---|
| 144 | return {
|
|---|
| 145 | '@context': 'https://www.w3.org/ns/activitystreams',
|
|---|
| 146 | id: note.id + '#create',
|
|---|
| 147 | type: 'Create',
|
|---|
| 148 | actor: actorId(base, site.slug),
|
|---|
| 149 | published: note.published,
|
|---|
| 150 | to: note.to,
|
|---|
| 151 | cc: note.cc,
|
|---|
| 152 | object: note,
|
|---|
| 153 | };
|
|---|
| 154 | }
|
|---|
| 155 |
|
|---|
| 156 | export function buildOutbox(base, site, posts) {
|
|---|
| 157 | const id = `${actorId(base, site.slug)}/outbox`;
|
|---|
| 158 | const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p));
|
|---|
| 159 | return {
|
|---|
| 160 | '@context': 'https://www.w3.org/ns/activitystreams',
|
|---|
| 161 | id,
|
|---|
| 162 | type: 'OrderedCollection',
|
|---|
| 163 | totalItems: items.length,
|
|---|
| 164 | orderedItems: items,
|
|---|
| 165 | };
|
|---|
| 166 | }
|
|---|
| 167 |
|
|---|
| 168 | export function buildFollowers(base, site, count) {
|
|---|
| 169 | const id = `${actorId(base, site.slug)}/followers`;
|
|---|
| 170 | return {
|
|---|
| 171 | '@context': 'https://www.w3.org/ns/activitystreams',
|
|---|
| 172 | id,
|
|---|
| 173 | type: 'OrderedCollection',
|
|---|
| 174 | totalItems: count || 0,
|
|---|
| 175 | orderedItems: [], // hidden for privacy; count only
|
|---|
| 176 | };
|
|---|
| 177 | }
|
|---|
| 178 |
|
|---|
| [5bf63b7] | 179 | // ── followers store (lazy stmts) ──────────────────────────────────
|
|---|
| 180 | let _insF, _delF, _listF, _cntF;
|
|---|
| 181 | function fStmts() {
|
|---|
| 182 | if (!_insF) {
|
|---|
| 183 | _insF = db.prepare('INSERT OR IGNORE INTO ap_followers (slug, actor_uri, inbox, shared_inbox, created_at) VALUES (?,?,?,?,CURRENT_TIMESTAMP)');
|
|---|
| 184 | _delF = db.prepare('DELETE FROM ap_followers WHERE slug = ? AND actor_uri = ?');
|
|---|
| 185 | _listF = db.prepare('SELECT inbox, shared_inbox FROM ap_followers WHERE slug = ?');
|
|---|
| 186 | _cntF = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?');
|
|---|
| 187 | }
|
|---|
| 188 | return { ins: _insF, del: _delF, list: _listF, cnt: _cntF };
|
|---|
| 189 | }
|
|---|
| 190 | export function followerCount(slug) { return fStmts().cnt.get(slug).n; }
|
|---|
| 191 |
|
|---|
| 192 | // ── HTTP Signatures + delivery ────────────────────────────────────
|
|---|
| 193 | const slugFromActorUrl = (url) => { const m = String(url || '').match(/\/ap\/users\/([^/?#]+)/); return m ? decodeURIComponent(m[1]) : null; };
|
|---|
| 194 |
|
|---|
| 195 | // Sign + POST an activity to a remote inbox (draft-cavage HTTP Signatures, RSA-SHA256).
|
|---|
| 196 | export async function deliver(inboxUrl, bodyObj, keyId, privatePem) {
|
|---|
| 197 | const body = JSON.stringify(bodyObj);
|
|---|
| 198 | const u = new URL(inboxUrl);
|
|---|
| 199 | const date = new Date().toUTCString();
|
|---|
| 200 | const digest = 'SHA-256=' + crypto.createHash('sha256').update(body).digest('base64');
|
|---|
| 201 | const signingString = `(request-target): post ${u.pathname}\nhost: ${u.host}\ndate: ${date}\ndigest: ${digest}`;
|
|---|
| 202 | const signature = crypto.sign('sha256', Buffer.from(signingString), privatePem).toString('base64');
|
|---|
| 203 | const sig = `keyId="${keyId}",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="${signature}"`;
|
|---|
| 204 | const r = await fetch(inboxUrl, {
|
|---|
| 205 | method: 'POST',
|
|---|
| 206 | headers: { 'Content-Type': 'application/activity+json', Accept: 'application/activity+json', Date: date, Digest: digest, Signature: sig },
|
|---|
| 207 | body,
|
|---|
| 208 | signal: AbortSignal.timeout(8000),
|
|---|
| 209 | });
|
|---|
| 210 | return r.status;
|
|---|
| 211 | }
|
|---|
| 212 |
|
|---|
| 213 | export async function fetchActor(url) {
|
|---|
| 214 | try {
|
|---|
| 215 | const r = await fetch(url, { headers: { Accept: 'application/activity+json' }, redirect: 'follow', signal: AbortSignal.timeout(8000) });
|
|---|
| 216 | if (!r.ok) return null;
|
|---|
| 217 | return await r.json();
|
|---|
| 218 | } catch { return null; }
|
|---|
| 219 | }
|
|---|
| 220 |
|
|---|
| 221 | // Best-effort verification of an incoming signed request. Returns the sender's
|
|---|
| 222 | // actor doc if the signature checks out, else null. (Not gating yet — MVP.)
|
|---|
| 223 | export async function verifyRequest(req) {
|
|---|
| 224 | const sigH = req.headers['signature'];
|
|---|
| 225 | if (!sigH) return null;
|
|---|
| 226 | const p = Object.fromEntries([...sigH.matchAll(/([a-zA-Z]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
|
|---|
| 227 | if (!p.keyId || !p.signature) return null;
|
|---|
| 228 | const actor = await fetchActor(p.keyId.split('#')[0]);
|
|---|
| 229 | const pem = actor && actor.publicKey && actor.publicKey.publicKeyPem;
|
|---|
| 230 | if (!pem) return null;
|
|---|
| 231 | const hs = (p.headers || '(request-target) host date').split(/\s+/);
|
|---|
| 232 | const line = hs.map((h) => h === '(request-target)'
|
|---|
| 233 | ? `(request-target): ${req.method.toLowerCase()} ${req.originalUrl}`
|
|---|
| 234 | : `${h}: ${req.headers[h] || ''}`).join('\n');
|
|---|
| 235 | let ok = false;
|
|---|
| 236 | try { ok = crypto.verify('sha256', Buffer.from(line), pem, Buffer.from(p.signature, 'base64')); } catch { ok = false; }
|
|---|
| 237 | if (ok && hs.includes('digest') && req.rawBody) {
|
|---|
| 238 | const exp = 'SHA-256=' + crypto.createHash('sha256').update(req.rawBody).digest('base64');
|
|---|
| 239 | if (req.headers['digest'] !== exp) ok = false;
|
|---|
| 240 | }
|
|---|
| 241 | return ok ? actor : null;
|
|---|
| 242 | }
|
|---|
| 243 |
|
|---|
| 244 | // Handle an incoming inbox POST. slugParam = null for the shared /ap/inbox.
|
|---|
| 245 | export async function handleInbox(req, slugParam) {
|
|---|
| 246 | const act = req.body || {};
|
|---|
| 247 | const type = act.type;
|
|---|
| 248 | const base = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
|
|---|
| 249 | const verified = await verifyRequest(req).catch(() => null); // best-effort; not gating (MVP)
|
|---|
| 250 |
|
|---|
| 251 | if (type === 'Follow') {
|
|---|
| 252 | const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
|
|---|
| 253 | const slug = slugParam || slugFromActorUrl(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
|
|---|
| 254 | if (!who || !slug) return 400;
|
|---|
| 255 | const remote = await fetchActor(who);
|
|---|
| 256 | if (!remote || !remote.inbox) return 202; // can't reach them → drop quietly
|
|---|
| 257 | fStmts().ins.run(slug, who, remote.inbox, (remote.endpoints && remote.endpoints.sharedInbox) || null);
|
|---|
| 258 | const me = actorId(base, slug);
|
|---|
| 259 | const keys = getOrCreateKeys(slug);
|
|---|
| 260 | const accept = { '@context': 'https://www.w3.org/ns/activitystreams', id: `${me}#accept-${Date.now()}`, type: 'Accept', actor: me, object: act };
|
|---|
| 261 | deliver(remote.inbox, accept, `${me}#main-key`, keys.private_pem).catch((e) => console.warn('[AP] Accept delivery failed:', e.message));
|
|---|
| 262 | console.log('[AP] Follow', who, '→', slug, verified ? '(sig ok)' : '(sig unverified)');
|
|---|
| 263 | return 202;
|
|---|
| 264 | }
|
|---|
| 265 | if (type === 'Undo' && act.object && act.object.type === 'Follow') {
|
|---|
| 266 | const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
|
|---|
| 267 | const obj = act.object.object;
|
|---|
| 268 | const slug = slugParam || slugFromActorUrl(typeof obj === 'string' ? obj : (obj && obj.id));
|
|---|
| 269 | if (who && slug) { fStmts().del.run(slug, who); console.log('[AP] Unfollow', who, '→', slug); }
|
|---|
| 270 | return 202;
|
|---|
| 271 | }
|
|---|
| 272 | console.log('[AP] inbox', type || 'unknown', '→', slugParam || 'shared', '(ignored)');
|
|---|
| 273 | return 202;
|
|---|
| 274 | }
|
|---|
| 275 |
|
|---|
| 276 | // Deliver a new post as Create(Note) to all followers' inboxes (fire-and-forget).
|
|---|
| 277 | // Needs PUBLIC_BASE_URL (absolute URLs); no-op without followers or base.
|
|---|
| 278 | export async function deliverCreate(site, post) {
|
|---|
| 279 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 280 | if (!base || !site || !site.slug) return;
|
|---|
| 281 | const followers = fStmts().list.all(site.slug);
|
|---|
| 282 | if (!followers.length) return;
|
|---|
| 283 | const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
|
|---|
| 284 | const keys = getOrCreateKeys(site.slug);
|
|---|
| 285 | const keyId = `${actorId(base, site.slug)}#main-key`;
|
|---|
| 286 | const create = buildCreate(base, site, post);
|
|---|
| 287 | for (const inbox of inboxes) deliver(inbox, create, keyId, keys.private_pem).catch(() => { /* best-effort */ });
|
|---|
| 288 | }
|
|---|
| 289 |
|
|---|
| [eb852c5] | 290 | // Tell followers a post is gone (Delete + Tombstone) so it's removed from their feeds.
|
|---|
| 291 | export async function deliverDelete(site, post) {
|
|---|
| 292 | const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
|
|---|
| 293 | if (!base || !site || !site.slug || !post || !post.id) return;
|
|---|
| 294 | const followers = fStmts().list.all(site.slug);
|
|---|
| 295 | if (!followers.length) return;
|
|---|
| 296 | const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
|
|---|
| 297 | const keys = getOrCreateKeys(site.slug);
|
|---|
| 298 | const me = actorId(base, site.slug);
|
|---|
| 299 | const nid = noteId(base, post.id);
|
|---|
| 300 | const del = {
|
|---|
| 301 | '@context': 'https://www.w3.org/ns/activitystreams',
|
|---|
| 302 | id: `${nid}#delete-${Date.now()}`,
|
|---|
| 303 | type: 'Delete',
|
|---|
| 304 | actor: me,
|
|---|
| 305 | to: [PUBLIC],
|
|---|
| 306 | object: { id: nid, type: 'Tombstone' },
|
|---|
| 307 | };
|
|---|
| 308 | for (const inbox of inboxes) deliver(inbox, del, `${me}#main-key`, keys.private_pem).catch(() => { /* best-effort */ });
|
|---|
| 309 | }
|
|---|
| 310 |
|
|---|
| [6bd25d1] | 311 | export default {
|
|---|
| 312 | getOrCreateKeys, apWants, sendAP, actorId, noteId,
|
|---|
| 313 | buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
|
|---|
| [eb852c5] | 314 | followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate, deliverDelete,
|
|---|
| [6bd25d1] | 315 | };
|
|---|