| 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)}`;
|
|---|
| 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 |
|
|---|
| 118 | export 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 |
|
|---|
| 132 | export 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 |
|
|---|
| 144 | export 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 | export default {
|
|---|
| 156 | getOrCreateKeys, apWants, sendAP, actorId, noteId,
|
|---|
| 157 | buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
|
|---|
| 158 | };
|
|---|