source: Klonkt/src/routes/activitypub.js@ d3b9f68

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

feat(federation): full JSON-LD @context on all AP objects (valid AS2)

Every object now carries a complete @context (AS2 + security/v1 + term definitions for the
Mastodon/toot + schema.org extensions we emit: sensitive, Hashtag, manuallyApprovesFollowers,
discoverable, featured, PropertyValue, embedUrl). Previously these were emitted under only the
bare AS2 context, so a strict JSON-LD processor dropped them — Mastodon tolerated it but it
wasn't valid AS2/JSON-LD. It is the same context shape Mastodon publishes, so Mastodon sees no
change while strict consumers now resolve every term.

  • src/services/ActivityPubService.js — shared AP_CONTEXT on every object/activity; removed the now-dead local AS2 string const
  • src/routes/activitypub.js — served objects (note/replies/notes route) use AP.AP_CONTEXT

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

  • Property mode set to 100644
File size: 10.2 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. CRITICAL: this router is mounted at root (app.use(apRoutes)), so a
25// blanket res.status(404) here ran for EVERY request and 404'd the whole site when AP was
26// off. Use next('router') to SKIP this router entirely and let the normal routes handle it
27// (the /ap/* paths then fall through to the app's normal 404, which is correct).
28router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
29// Generous per-IP baseline over all /ap/* (reads). The inbox POST gets an
30// additional, tighter cap inline (it triggers outbound fetches).
31router.use(apReadLimiter);
32let _ver = '1.0.0';
33try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
34
35const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
36const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
37const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
38const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
39
40// ── WebFinger ─────────────────────────────────────────────────────
41router.get('/.well-known/webfinger', (req, res) => {
42 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
43 if (!m) return res.status(400).type('text/plain').send('bad resource');
44 const site = publicSite(m[1]);
45 if (!site) return res.status(404).end();
46 res.type('application/jrd+json; charset=utf-8');
47 res.set('Cache-Control', 'public, max-age=300');
48 const actorUri = AP.actorId(baseUrl(req), site.slug);
49 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
50 res.send(JSON.stringify({
51 subject: `acct:${site.slug}@${hostOf(req)}`,
52 aliases: [actorUri, profileUrl],
53 links: [
54 { rel: 'self', type: 'application/activity+json', href: actorUri },
55 { rel: 'http://webfinger.net/rel/profile-page', type: 'text/html', href: profileUrl },
56 ],
57 }));
58});
59
60// ── Actor ─────────────────────────────────────────────────────────
61router.get('/ap/users/:slug', (req, res) => {
62 const site = publicSite(req.params.slug);
63 if (!site) return res.status(404).end();
64 if (!AP.apWants(req)) {
65 // A browser hit the AP actor URL → send them to the human profile.
66 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
67 return res.redirect(302, baseUrl(req) + human);
68 }
69 site.primary_slug = primarySlug();
70 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
71});
72
73// ── Outbox ────────────────────────────────────────────────────────
74router.get('/ap/users/:slug/outbox', (req, res) => {
75 const site = publicSite(req.params.slug);
76 if (!site) return res.status(404).end();
77 const posts = db.prepare(
78 `SELECT id, slug, title, content, cover_image_url, nsfw, content_warning, published_at, created_at
79 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
80 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
81 ).all(site.id);
82 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
83});
84
85// ── Followers (count only) ────────────────────────────────────────
86router.get('/ap/users/:slug/followers', (req, res) => {
87 const site = publicSite(req.params.slug);
88 if (!site) return res.status(404).end();
89 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
90 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
91});
92
93// ── Following (count only) ────────────────────────────────────────
94router.get('/ap/users/:slug/following', (req, res) => {
95 const site = publicSite(req.params.slug);
96 if (!site) return res.status(404).end();
97 let n = 0;
98 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
99 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
100});
101
102// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
103router.get('/ap/users/:slug/featured', (req, res) => {
104 const site = publicSite(req.params.slug);
105 if (!site) return res.status(404).end();
106 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
107 // last-processed-first). So we emit it reversed (lowest pin priority first,
108 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
109 const posts = db.prepare(
110 `SELECT id, slug, title, content, cover_image_url, nsfw, content_warning, published_at, created_at
111 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
112 AND pinned IS NOT NULL AND pinned > 0
113 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
114 ).all(site.id);
115 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
116});
117
118// ── Note ──────────────────────────────────────────────────────────
119router.get('/ap/notes/:id', (req, res) => {
120 const post = db.prepare(
121 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
122 ).get(req.params.id);
123 if (!post) {
124 // Could be one of OUR outbound replies (ap_outbox), not a post.
125 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
126 if (!note) return res.status(404).end();
127 if (!AP.apWants(req)) {
128 // A browser hit a reply's AP URL → send them to the source it replies to
129 // (where the post + its reactions live), falling back to the site home.
130 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
131 ? note.inReplyTo : (baseUrl(req) + '/');
132 return res.redirect(302, src);
133 }
134 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
135 }
136 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
137 if (!site) return res.status(404).end();
138 const note = AP.buildNote(baseUrl(req), site, post);
139 if (!AP.apWants(req)) {
140 // A browser hit a post's AP note URL → send them to the human post page
141 // (which shows the post + its "from the fediverse" reactions).
142 return res.redirect(302, note.url || (baseUrl(req) + '/'));
143 }
144 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
145});
146
147// ── Replies collection ── lets remote servers fetch a post's whole thread.
148router.get('/ap/notes/:id/replies', (req, res) => {
149 const base = baseUrl(req);
150 const items = AP.getReplyUris(base, req.params.id);
151 AP.sendAP(res, {
152 '@context': AP.AP_CONTEXT,
153 id: `${base}/ap/notes/${req.params.id}/replies`,
154 type: 'OrderedCollection',
155 totalItems: items.length,
156 orderedItems: items,
157 });
158});
159
160// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
161router.get('/.well-known/nodeinfo', (req, res) => {
162 res.type('application/json');
163 res.set('Cache-Control', 'public, max-age=3600');
164 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
165});
166router.get('/nodeinfo/2.1', (req, res) => {
167 let users = 0; let posts = 0;
168 // "users" = public AP actors (sites), not the admin/member account rows.
169 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
170 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
171 res.type('application/json; charset=utf-8');
172 res.set('Cache-Control', 'public, max-age=600');
173 res.send(JSON.stringify({
174 version: '2.1',
175 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
176 protocols: ['activitypub'],
177 services: { inbound: [], outbound: [] },
178 openRegistrations: false,
179 usage: { users: { total: users }, localPosts: posts },
180 metadata: { nodeName: 'Klonkt' },
181 }));
182});
183
184// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
185const apJson = express.json({
186 type: ['application/activity+json', 'application/ld+json', 'application/json'],
187 limit: '1mb',
188 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
189});
190router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
191 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
192 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
193});
194
195export default router;
Note: See TracBrowser for help on using the repository browser.