source: Klonkt/src/routes/activitypub.js@ 283f618

main
Last change on this file since 283f618 was 283f618, checked in by Robin Genis <roboburr@…>, 2 months ago

feat(fediverse): add an ActivityPub on/off toggle (off = no federation, no comments)

A solo site can now run without the fediverse. ap_enabled (default on, Beheer ->
Instellingen). When off: /ap/*, WebFinger and NodeInfo 404 (undiscoverable), the
'from the fediverse' reactions section is hidden on posts (= no comments, since
native comments were removed), the profile follow button and the fediverse admin
links disappear. Cirkels is separate (not gated here).

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

  • Property mode set to 100644
File size: 9.0 KB
Line 
1/**
2 * ActivityPub — public endpoints (Phase 1: discover + fetch).
3 *
4 * GET /.well-known/webfinger?resource=acct:<slug>@<host>
5 * GET /ap/users/:slug actor (content-negotiated: AP-JSON vs redirect to HTML profile)
6 * GET /ap/users/:slug/outbox OrderedCollection of Create(Note)
7 * GET /ap/users/:slug/followers count-only OrderedCollection
8 * GET /ap/users/:slug/featured pinned posts (Mastodon "Featured" tab)
9 * GET /ap/notes/:id a single Note
10 * POST /ap/users/:slug/inbox, /ap/inbox → 202 (Follow/Accept + signature verify: next step)
11 *
12 * Mounted before resolveSite; resolves the site by slug itself.
13 */
14import express from 'express';
15import { readFileSync } from 'fs';
16import db from '../config/database.js';
17import AP from '../services/ActivityPubService.js';
18import { apReadLimiter, apInboxLimiter } from '../middleware/rate-limit.js';
19import { apEnabled } from '../services/SettingsService.js';
20
21const router = express.Router();
22// The whole fediverse layer can be turned off (solo "no federation" mode):
23// then /ap/*, WebFinger and NodeInfo are simply gone — the site is undiscoverable
24// and unfederatable.
25router.use((req, res, next) => { if (!apEnabled()) return res.status(404).end(); next(); });
26// Generous per-IP baseline over all /ap/* (reads). The inbox POST gets an
27// additional, tighter cap inline (it triggers outbound fetches).
28router.use(apReadLimiter);
29let _ver = '1.0.0';
30try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
31
32const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
33const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
34const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
35const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
36
37// ── WebFinger ─────────────────────────────────────────────────────
38router.get('/.well-known/webfinger', (req, res) => {
39 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
40 if (!m) return res.status(400).type('text/plain').send('bad resource');
41 const site = publicSite(m[1]);
42 if (!site) return res.status(404).end();
43 res.type('application/jrd+json; charset=utf-8');
44 res.set('Cache-Control', 'public, max-age=300');
45 res.send(JSON.stringify({
46 subject: `acct:${site.slug}@${hostOf(req)}`,
47 links: [{ rel: 'self', type: 'application/activity+json', href: AP.actorId(baseUrl(req), site.slug) }],
48 }));
49});
50
51// ── Actor ─────────────────────────────────────────────────────────
52router.get('/ap/users/:slug', (req, res) => {
53 const site = publicSite(req.params.slug);
54 if (!site) return res.status(404).end();
55 if (!AP.apWants(req)) {
56 // A browser hit the AP actor URL → send them to the human profile.
57 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
58 return res.redirect(302, baseUrl(req) + human);
59 }
60 site.primary_slug = primarySlug();
61 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
62});
63
64// ── Outbox ────────────────────────────────────────────────────────
65router.get('/ap/users/:slug/outbox', (req, res) => {
66 const site = publicSite(req.params.slug);
67 if (!site) return res.status(404).end();
68 const posts = db.prepare(
69 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
70 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
71 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
72 ).all(site.id);
73 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
74});
75
76// ── Followers (count only) ────────────────────────────────────────
77router.get('/ap/users/:slug/followers', (req, res) => {
78 const site = publicSite(req.params.slug);
79 if (!site) return res.status(404).end();
80 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
81 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
82});
83
84// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
85router.get('/ap/users/:slug/featured', (req, res) => {
86 const site = publicSite(req.params.slug);
87 if (!site) return res.status(404).end();
88 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
89 // last-processed-first). So we emit it reversed (lowest pin priority first,
90 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
91 const posts = db.prepare(
92 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
93 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
94 AND pinned IS NOT NULL AND pinned > 0
95 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
96 ).all(site.id);
97 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
98});
99
100// ── Note ──────────────────────────────────────────────────────────
101router.get('/ap/notes/:id', (req, res) => {
102 const post = db.prepare(
103 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
104 ).get(req.params.id);
105 if (!post) {
106 // Could be one of OUR outbound replies (ap_outbox), not a post.
107 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
108 if (!note) return res.status(404).end();
109 if (!AP.apWants(req)) {
110 // A browser hit a reply's AP URL → send them to the source it replies to
111 // (where the post + its reactions live), falling back to the site home.
112 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
113 ? note.inReplyTo : (baseUrl(req) + '/');
114 return res.redirect(302, src);
115 }
116 return AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...note });
117 }
118 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
119 if (!site) return res.status(404).end();
120 const note = AP.buildNote(baseUrl(req), site, post);
121 if (!AP.apWants(req)) {
122 // A browser hit a post's AP note URL → send them to the human post page
123 // (which shows the post + its "from the fediverse" reactions).
124 return res.redirect(302, note.url || (baseUrl(req) + '/'));
125 }
126 AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...note });
127});
128
129// ── Replies collection ── lets remote servers fetch a post's whole thread.
130router.get('/ap/notes/:id/replies', (req, res) => {
131 const base = baseUrl(req);
132 const items = AP.getReplyUris(base, req.params.id);
133 AP.sendAP(res, {
134 '@context': 'https://www.w3.org/ns/activitystreams',
135 id: `${base}/ap/notes/${req.params.id}/replies`,
136 type: 'OrderedCollection',
137 totalItems: items.length,
138 orderedItems: items,
139 });
140});
141
142// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
143router.get('/.well-known/nodeinfo', (req, res) => {
144 res.type('application/json');
145 res.set('Cache-Control', 'public, max-age=3600');
146 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
147});
148router.get('/nodeinfo/2.1', (req, res) => {
149 let users = 0; let posts = 0;
150 try { users = db.prepare('SELECT COUNT(*) c FROM users').get().c; } catch { /* */ }
151 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
152 res.type('application/json; charset=utf-8');
153 res.set('Cache-Control', 'public, max-age=600');
154 res.send(JSON.stringify({
155 version: '2.1',
156 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
157 protocols: ['activitypub'],
158 services: { inbound: [], outbound: [] },
159 openRegistrations: false,
160 usage: { users: { total: users }, localPosts: posts },
161 metadata: { nodeName: 'Klonkt' },
162 }));
163});
164
165// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
166const apJson = express.json({
167 type: ['application/activity+json', 'application/ld+json', 'application/json'],
168 limit: '1mb',
169 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
170});
171router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
172 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
173 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
174});
175
176export default router;
Note: See TracBrowser for help on using the repository browser.