source: Klonkt/src/routes/activitypub.js@ 9a00f28

main
Last change on this file since 9a00f28 was 8b07c12, checked in by Robin Genis <roboburr@…>, 7 weeks ago

The AP blocked collection: the server blocklist drives Shaer's Orbit

Robins call: no separate client-side Orbit state; the block list on the
server is the source of truth. The actor now advertises the standard
ActivityPub blocked collection (spec 5.6) and the owner reads it over C2S;
Shaer hydrates "in Orbit" from it and keeps nothing locally.

Changed files:
src/services/ActivityPubService.js

  • buildActor: blocked: {id}/blocked (AP 5.6, owner-only GET)

src/routes/activitypub.js

  • GET /ap/users/:slug/blocked (bearer, owner-only): actor-kind blocks as an OrderedCollection of actor uris; domain blocks stay out (instance policy, not an Orbit member)

test/c2s-block.test.js

  • the actor advertises blocked; actor-kind items only

test/activitypub-as2.test.js

  • blocked added to the AS2 allowlist (a spec term, same family as liked/streams)

153 tests, all green.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 17.9 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';
20import OAuth from '../services/OAuthService.js';
21import multer from 'multer';
22import path from 'path';
23import fs from 'fs';
24import { fileURLToPath } from 'url';
25import { randomUUID } from 'crypto';
26
27const router = express.Router();
28// The whole fediverse layer can be turned off (solo "no federation" mode):
29// then /ap/*, WebFinger and NodeInfo are simply gone — the site is undiscoverable
30// and unfederatable. CRITICAL: this router is mounted at root (app.use(apRoutes)), so a
31// blanket res.status(404) here ran for EVERY request and 404'd the whole site when AP was
32// off. Use next('router') to SKIP this router entirely and let the normal routes handle it
33// (the /ap/* paths then fall through to the app's normal 404, which is correct).
34router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
35// Generous per-IP baseline over all /ap/* (reads). The inbox POST gets an
36// additional, tighter cap inline (it triggers outbound fetches).
37router.use(apReadLimiter);
38let _ver = '1.0.0';
39try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
40
41const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
42const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
43const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
44const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
45
46// ── WebFinger ─────────────────────────────────────────────────────
47router.get('/.well-known/webfinger', (req, res) => {
48 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
49 if (!m) return res.status(400).type('text/plain').send('bad resource');
50 const site = publicSite(m[1]);
51 if (!site) return res.status(404).end();
52 res.type('application/jrd+json; charset=utf-8');
53 res.set('Cache-Control', 'public, max-age=300');
54 const actorUri = AP.actorId(baseUrl(req), site.slug);
55 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
56 res.send(JSON.stringify({
57 subject: `acct:${site.slug}@${hostOf(req)}`,
58 aliases: [actorUri, profileUrl],
59 links: [
60 { rel: 'self', type: 'application/activity+json', href: actorUri },
61 { rel: 'http://webfinger.net/rel/profile-page', type: 'text/html', href: profileUrl },
62 ],
63 }));
64});
65
66// ── Actor ─────────────────────────────────────────────────────────
67router.get('/ap/users/:slug', (req, res) => {
68 const site = publicSite(req.params.slug);
69 if (!site) return res.status(404).end();
70 if (!AP.apWants(req)) {
71 // A browser hit the AP actor URL → send them to the human profile.
72 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
73 return res.redirect(302, baseUrl(req) + human);
74 }
75 site.primary_slug = primarySlug();
76 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
77});
78
79// ── Outbox ────────────────────────────────────────────────────────
80router.get('/ap/users/:slug/outbox', (req, res) => {
81 const site = publicSite(req.params.slug);
82 if (!site) return res.status(404).end();
83 const posts = db.prepare(
84 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
85 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
86 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
87 ).all(site.id);
88 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
89});
90
91// ── Blocked collection (owner only, AP §5.6) ──────────────────────
92// The server blocklist is the source of truth for Shaer's "in Orbit":
93// clients read it here instead of keeping their own state. Actor-kind
94// blocks only (domain blocks are instance policy, not an Orbit member).
95router.get('/ap/users/:slug/blocked', (req, res) => {
96 const auth = OAuth.verifyBearer(req.headers.authorization);
97 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
98 const base = baseUrl(req);
99 const items = AP.listBlocks(auth.site.slug)
100 .filter((b) => b.kind === 'actor')
101 .map((b) => b.target);
102 AP.sendAP(res, {
103 '@context': AP.AP_CONTEXT,
104 id: `${base}/ap/users/${auth.site.slug}/blocked`,
105 type: 'OrderedCollection',
106 totalItems: items.length,
107 orderedItems: items,
108 });
109});
110
111// ── Inbox read (owner only, AP C2S) ───────────────────────────────
112// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
113// scoped to this site) reads recent inbound posts (the timeline: accounts
114// they follow) as Create(Note) items, so an app (Shaer) can build a unified
115// feed. Anyone else gets 403; the inbox stays write-only for the public.
116router.get('/ap/users/:slug/inbox', (req, res) => {
117 const auth = OAuth.verifyBearer(req.headers.authorization);
118 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
119 const base = baseUrl(req);
120 const items = AP.getTimeline(auth.site.slug, 60).map((t) => ({
121 id: `${t.id}#create`,
122 type: 'Create',
123 actor: t.author_uri,
124 published: t.published || t.created_at || undefined,
125 object: {
126 id: t.id,
127 type: 'Note',
128 attributedTo: t.author_uri,
129 content: t.content,
130 url: t.url || undefined,
131 published: t.published || t.created_at || undefined,
132 sensitive: !!t.nsfw,
133 summary: t.cw || undefined,
134 // Friends' media travels along (media_json → AS2 attachment), so the
135 // client renders their images/audio like own outbox posts.
136 attachment: AP.timelineAttachments(t.media_json),
137 },
138 }));
139 AP.sendAP(res, {
140 '@context': AP.AP_CONTEXT,
141 id: `${base}/ap/users/${auth.site.slug}/inbox`,
142 type: 'OrderedCollection',
143 totalItems: items.length,
144 orderedItems: items,
145 });
146});
147
148// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
149// The actor advertises endpoints.uploadMedia; this implements it. A bearer
150// scoped to this site uploads one image/audio/video (multipart field "file",
151// AP convention) into the same store the reply editor uses, and gets back
152// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
153const AP_MEDIA_DIR = path.resolve(
154 process.env.REPLY_MEDIA_PATH ||
155 path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'storage', 'media', 'reply-media')
156);
157fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
158const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
159const apMediaUpload = multer({
160 storage: multer.diskStorage({
161 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
162 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
163 }),
164 limits: { fileSize: 32 * 1024 * 1024 },
165 fileFilter: (req, file, cb) => {
166 const ext = path.extname(file.originalname || '').toLowerCase();
167 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
168 cb(null, true);
169 },
170});
171router.post('/ap/users/:slug/uploadMedia', (req, res) => {
172 const auth = OAuth.verifyBearer(req.headers.authorization);
173 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
174 apMediaUpload.single('file')(req, res, (err) => {
175 if (err) return res.status(400).json({ error: err.message });
176 if (!req.file) return res.status(400).json({ error: 'No file' });
177 const mime = String(req.file.mimetype || '');
178 if (!/^(image|audio|video)\//.test(mime)) {
179 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
180 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
181 }
182 res.status(201).json({
183 url: '/media/reply-media/' + req.file.filename,
184 mediaType: mime,
185 name: String(req.file.originalname || '').slice(0, 120),
186 });
187 });
188});
189
190// ── Followers (count-only public, full for the owner) ─────────────
191// A C2S bearer scoped to this site (the account owner) gets the real actor
192// URIs so their own client can build a friends list; everyone else gets the
193// count only (privacy).
194// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
195// Returns true and sets the response headers when the owner asked for it.
196function wantsEnriched(req, res) {
197 res.set('Vary', 'Prefer'); // enriched and bare are two representations
198 if (AP.prefersEnriched(req.get('Prefer'))) {
199 res.set('Preference-Applied', 'return=representation');
200 return true;
201 }
202 return false;
203}
204
205router.get('/ap/users/:slug/followers', (req, res) => {
206 const auth = OAuth.verifyBearer(req.headers.authorization);
207 const owner = auth && auth.site.slug === req.params.slug;
208 const site = owner ? auth.site : publicSite(req.params.slug);
209 if (!site) return res.status(404).end();
210 if (owner) {
211 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
212 // Default = bare references; enrich only when the client asks (FEP-9876).
213 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
214 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items));
215 }
216 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
217 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
218});
219
220// ── Following (count-only public, full for the owner) ─────────────
221router.get('/ap/users/:slug/following', (req, res) => {
222 const auth = OAuth.verifyBearer(req.headers.authorization);
223 const owner = auth && auth.site.slug === req.params.slug;
224 const site = owner ? auth.site : publicSite(req.params.slug);
225 if (!site) return res.status(404).end();
226 if (owner) {
227 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
228 let items = [];
229 try {
230 const uris = db.prepare("SELECT actor_uri FROM ap_following WHERE slug = ? AND status = 'accepted' ORDER BY created_at").all(site.slug).map((r) => r.actor_uri);
231 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
232 } catch { /* table may not exist */ }
233 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items));
234 }
235 let n = 0;
236 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
237 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
238});
239
240// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
241router.get('/ap/users/:slug/featured', (req, res) => {
242 const site = publicSite(req.params.slug);
243 if (!site) return res.status(404).end();
244 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
245 // last-processed-first). So we emit it reversed (lowest pin priority first,
246 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
247 const posts = db.prepare(
248 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
249 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
250 AND pinned IS NOT NULL AND pinned > 0
251 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
252 ).all(site.id);
253 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
254});
255
256// ── Note ──────────────────────────────────────────────────────────
257router.get('/ap/notes/:id', (req, res) => {
258 const post = db.prepare(
259 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
260 ).get(req.params.id);
261 if (!post) {
262 // Could be one of OUR outbound replies (ap_outbox), not a post.
263 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
264 if (!note) return res.status(404).end();
265 if (!AP.apWants(req)) {
266 // A browser hit a reply's AP URL → send them to the source it replies to
267 // (where the post + its reactions live), falling back to the site home.
268 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
269 ? note.inReplyTo : (baseUrl(req) + '/');
270 return res.redirect(302, src);
271 }
272 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
273 }
274 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
275 if (!site) return res.status(404).end();
276 const note = AP.buildNote(baseUrl(req), site, post);
277 if (!AP.apWants(req)) {
278 // A browser hit a post's AP note URL → send them to the human post page
279 // (which shows the post + its "from the fediverse" reactions).
280 return res.redirect(302, note.url || (baseUrl(req) + '/'));
281 }
282 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
283});
284
285// ── Replies collection ── lets remote servers fetch a post's whole thread.
286router.get('/ap/notes/:id/replies', (req, res) => {
287 const base = baseUrl(req);
288 const items = AP.getReplyUris(base, req.params.id);
289 AP.sendAP(res, {
290 '@context': AP.AP_CONTEXT,
291 id: `${base}/ap/notes/${req.params.id}/replies`,
292 type: 'OrderedCollection',
293 totalItems: items.length,
294 orderedItems: items,
295 });
296});
297
298// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
299router.get('/.well-known/nodeinfo', (req, res) => {
300 res.type('application/json');
301 res.set('Cache-Control', 'public, max-age=3600');
302 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
303});
304router.get('/nodeinfo/2.1', (req, res) => {
305 let users = 0; let posts = 0;
306 // "users" = public AP actors (sites), not the admin/member account rows.
307 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
308 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
309 res.type('application/json; charset=utf-8');
310 res.set('Cache-Control', 'public, max-age=600');
311 res.send(JSON.stringify({
312 version: '2.1',
313 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
314 protocols: ['activitypub'],
315 services: { inbound: [], outbound: [] },
316 openRegistrations: false,
317 usage: { users: { total: users }, localPosts: posts },
318 metadata: { nodeName: 'Klonkt' },
319 }));
320});
321
322// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
323const apJson = express.json({
324 type: ['application/activity+json', 'application/ld+json', 'application/json'],
325 limit: '1mb',
326 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
327});
328router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
329 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
330 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
331});
332
333// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
334// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
335// the normal delivery machinery. The token is scoped to one user+site (OAuth
336// consent), so it must match the slug in the URL. (Declared after apJson, which
337// this shares with the inbox handler.)
338router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
339 const auth = OAuth.verifyBearer(req.headers.authorization);
340 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
341 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
342 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
343
344 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
345 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
346 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
347 if (out.status === 201 && out.url) res.set('Location', out.url);
348 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
349});
350
351export default router;
Note: See TracBrowser for help on using the repository browser.