/** * ActivityPubService — Klonkt as a real ActivityPub actor (fediverse bridge). * * Phase 1 (this file): the PUBLISH/discoverable side. * - per-site RSA keypair (Mastodon-compatible HTTP Signatures; separate from * the Ed25519 keys used by the lighter Cirkels v1) * - builders for the Actor document, Note objects and the Outbox collection * - apWants(): HTTP content-negotiation helper (activity+json vs HTML) * * The interactive side (inbox: Follow/Accept, signature verify, delivery to * followers) lands in the next step and is tested live against Mastodon. * * AP actor URLs live under /ap/* so they never clash with the human pages: * actor = /ap/users/ * inbox = /inbox outbox = /outbox * note = /ap/notes/ */ import crypto from 'crypto'; import db from '../config/database.js'; const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public'; const MAX_OUTBOX = 20; // ── RSA keys per actor (lazy, cached in DB) ─────────────────────── // Prepared lazily (NOT at module load) — the ap_keys table is created in // initializeDatabase(), which runs after this module is imported. let _sel, _ins; function keyStmts() { if (!_sel) { _sel = db.prepare('SELECT public_pem, private_pem FROM ap_keys WHERE slug = ?'); _ins = db.prepare('INSERT OR IGNORE INTO ap_keys (slug, public_pem, private_pem, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)'); } return { sel: _sel, ins: _ins }; } export function getOrCreateKeys(slug) { const { sel, ins } = keyStmts(); const row = sel.get(slug); if (row) return row; const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); ins.run(slug, publicKey, privateKey); return sel.get(slug) || { public_pem: publicKey, private_pem: privateKey }; } // ── content negotiation ─────────────────────────────────────────── // True when the caller wants ActivityPub JSON rather than the HTML page. export function apWants(req) { const a = String(req.headers.accept || '').toLowerCase(); return a.includes('application/activity+json') || (a.includes('application/ld+json') && a.includes('activitystreams')); } const AP_CONTENT_TYPE = 'application/activity+json; charset=utf-8'; export function sendAP(res, obj) { res.type(AP_CONTENT_TYPE); res.set('Cache-Control', 'public, max-age=120'); res.send(JSON.stringify(obj)); } // ── document builders ───────────────────────────────────────────── export function actorId(base, slug) { return `${base}/ap/users/${encodeURIComponent(slug)}`; } export function noteId(base, postId) { return `${base}/ap/notes/${encodeURIComponent(postId)}`; } export function buildActor(base, site) { const id = actorId(base, site.slug); const keys = getOrCreateKeys(site.slug); const actor = { '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'], id, type: 'Person', preferredUsername: site.slug, name: site.title || site.slug, summary: site.tagline || site.description || '', url: `${base}/${site.slug === site.primary_slug ? '' : 'user/' + encodeURIComponent(site.slug)}`, manuallyApprovesFollowers: false, discoverable: true, inbox: `${id}/inbox`, outbox: `${id}/outbox`, followers: `${id}/followers`, endpoints: { sharedInbox: `${base}/ap/inbox` }, publicKey: { id: `${id}#main-key`, owner: id, publicKeyPem: keys.public_pem, }, }; if (site.profile_photo) { const u = /^https?:/.test(site.profile_photo) ? site.profile_photo : `${base}${site.profile_photo.startsWith('/') ? '' : '/'}${site.profile_photo}`; actor.icon = { type: 'Image', url: u }; } return actor; } // A single post as an AS2 Note (the object), and as a Create activity (for outbox/delivery). export function buildNote(base, site, post) { const id = noteId(base, post.id); const aId = actorId(base, site.slug); const human = `${base}/${encodeURIComponent(post.slug)}`; const html = post.content || ''; // posts store sanitized HTML return { id, type: 'Note', attributedTo: aId, content: html, name: post.title || undefined, url: human, published: new Date(post.published_at || post.created_at || Date.now()).toISOString(), to: [PUBLIC], cc: [`${aId}/followers`], tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [], }; } export function buildCreate(base, site, post) { const note = buildNote(base, site, post); return { '@context': 'https://www.w3.org/ns/activitystreams', id: note.id + '#create', type: 'Create', actor: actorId(base, site.slug), published: note.published, to: note.to, cc: note.cc, object: note, }; } export function buildOutbox(base, site, posts) { const id = `${actorId(base, site.slug)}/outbox`; const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p)); return { '@context': 'https://www.w3.org/ns/activitystreams', id, type: 'OrderedCollection', totalItems: items.length, orderedItems: items, }; } export function buildFollowers(base, site, count) { const id = `${actorId(base, site.slug)}/followers`; return { '@context': 'https://www.w3.org/ns/activitystreams', id, type: 'OrderedCollection', totalItems: count || 0, orderedItems: [], // hidden for privacy; count only }; } export default { getOrCreateKeys, apWants, sendAP, actorId, noteId, buildActor, buildNote, buildCreate, buildOutbox, buildFollowers, };