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

main
Last change on this file since 7922694 was 7922694, checked in by Robin <roboburr@…>, 7 weeks ago

Feature: owner followers/following carry name + avatar (shaer-aa3)

The C2S owner view of followers and following returned bare actor
URIs, so a client could only show ids. Each entry is now an AS2 actor
reference { id, type: Person, name, preferredUsername, icon } built
from the best cached display Klonkt already holds: the follower's own
row (now cached at Follow time), then ap_following, interactions,
timeline, mentions, falling back to a handle derived from the URI.
Priority is the set display name, then the chosen username, then the
id. ap_followers gains name/handle/icon, populated when an inbound
Follow is accepted (fetchActor already runs there).

Changed files:
src/config/database.js

  • additive columns ap_followers.name/handle/icon

src/services/ActivityPubService.js

  • cache follower display on inbound Follow
  • actorDisplay(slug, uri): best cached display across the caches
  • buildActorRef(slug, uri): AS2 actor reference with display

src/routes/activitypub.js

  • owner followers/following map URIs through buildActorRef

New file:
test/c2s-contacts.test.js

  • name/username/id priority + interaction-cache fallback

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

  • Property mode set to 100644
File size: 16.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';
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// ── Inbox read (owner only, AP C2S) ───────────────────────────────
92// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
93// scoped to this site) reads recent inbound posts (the timeline: accounts
94// they follow) as Create(Note) items, so an app (Shaer) can build a unified
95// feed. Anyone else gets 403; the inbox stays write-only for the public.
96router.get('/ap/users/:slug/inbox', (req, res) => {
97 const auth = OAuth.verifyBearer(req.headers.authorization);
98 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
99 const base = baseUrl(req);
100 const items = AP.getTimeline(auth.site.slug, 60).map((t) => ({
101 id: `${t.id}#create`,
102 type: 'Create',
103 actor: t.author_uri,
104 published: t.published || t.created_at || undefined,
105 object: {
106 id: t.id,
107 type: 'Note',
108 attributedTo: t.author_uri,
109 content: t.content,
110 url: t.url || undefined,
111 published: t.published || t.created_at || undefined,
112 sensitive: !!t.nsfw,
113 summary: t.cw || undefined,
114 },
115 }));
116 AP.sendAP(res, {
117 '@context': AP.AP_CONTEXT,
118 id: `${base}/ap/users/${auth.site.slug}/inbox`,
119 type: 'OrderedCollection',
120 totalItems: items.length,
121 orderedItems: items,
122 });
123});
124
125// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
126// The actor advertises endpoints.uploadMedia; this implements it. A bearer
127// scoped to this site uploads one image/audio/video (multipart field "file",
128// AP convention) into the same store the reply editor uses, and gets back
129// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
130const AP_MEDIA_DIR = path.resolve(
131 process.env.REPLY_MEDIA_PATH ||
132 path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'storage', 'media', 'reply-media')
133);
134fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
135const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
136const apMediaUpload = multer({
137 storage: multer.diskStorage({
138 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
139 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
140 }),
141 limits: { fileSize: 32 * 1024 * 1024 },
142 fileFilter: (req, file, cb) => {
143 const ext = path.extname(file.originalname || '').toLowerCase();
144 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
145 cb(null, true);
146 },
147});
148router.post('/ap/users/:slug/uploadMedia', (req, res) => {
149 const auth = OAuth.verifyBearer(req.headers.authorization);
150 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
151 apMediaUpload.single('file')(req, res, (err) => {
152 if (err) return res.status(400).json({ error: err.message });
153 if (!req.file) return res.status(400).json({ error: 'No file' });
154 const mime = String(req.file.mimetype || '');
155 if (!/^(image|audio|video)\//.test(mime)) {
156 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
157 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
158 }
159 res.status(201).json({
160 url: '/media/reply-media/' + req.file.filename,
161 mediaType: mime,
162 name: String(req.file.originalname || '').slice(0, 120),
163 });
164 });
165});
166
167// ── Followers (count-only public, full for the owner) ─────────────
168// A C2S bearer scoped to this site (the account owner) gets the real actor
169// URIs so their own client can build a friends list; everyone else gets the
170// count only (privacy).
171router.get('/ap/users/:slug/followers', (req, res) => {
172 const auth = OAuth.verifyBearer(req.headers.authorization);
173 const owner = auth && auth.site.slug === req.params.slug;
174 const site = owner ? auth.site : publicSite(req.params.slug);
175 if (!site) return res.status(404).end();
176 if (owner) {
177 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
178 const items = uris.map((u) => AP.buildActorRef(site.slug, u)); // name + avatar (shaer-aa3)
179 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items));
180 }
181 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
182 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
183});
184
185// ── Following (count-only public, full for the owner) ─────────────
186router.get('/ap/users/:slug/following', (req, res) => {
187 const auth = OAuth.verifyBearer(req.headers.authorization);
188 const owner = auth && auth.site.slug === req.params.slug;
189 const site = owner ? auth.site : publicSite(req.params.slug);
190 if (!site) return res.status(404).end();
191 if (owner) {
192 let items = [];
193 try { items = db.prepare("SELECT actor_uri FROM ap_following WHERE slug = ? AND status = 'accepted' ORDER BY created_at").all(site.slug).map((r) => AP.buildActorRef(site.slug, r.actor_uri)); } catch { /* table may not exist */ }
194 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items));
195 }
196 let n = 0;
197 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
198 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
199});
200
201// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
202router.get('/ap/users/:slug/featured', (req, res) => {
203 const site = publicSite(req.params.slug);
204 if (!site) return res.status(404).end();
205 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
206 // last-processed-first). So we emit it reversed (lowest pin priority first,
207 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
208 const posts = db.prepare(
209 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
210 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
211 AND pinned IS NOT NULL AND pinned > 0
212 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
213 ).all(site.id);
214 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
215});
216
217// ── Note ──────────────────────────────────────────────────────────
218router.get('/ap/notes/:id', (req, res) => {
219 const post = db.prepare(
220 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
221 ).get(req.params.id);
222 if (!post) {
223 // Could be one of OUR outbound replies (ap_outbox), not a post.
224 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
225 if (!note) return res.status(404).end();
226 if (!AP.apWants(req)) {
227 // A browser hit a reply's AP URL → send them to the source it replies to
228 // (where the post + its reactions live), falling back to the site home.
229 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
230 ? note.inReplyTo : (baseUrl(req) + '/');
231 return res.redirect(302, src);
232 }
233 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
234 }
235 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
236 if (!site) return res.status(404).end();
237 const note = AP.buildNote(baseUrl(req), site, post);
238 if (!AP.apWants(req)) {
239 // A browser hit a post's AP note URL → send them to the human post page
240 // (which shows the post + its "from the fediverse" reactions).
241 return res.redirect(302, note.url || (baseUrl(req) + '/'));
242 }
243 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
244});
245
246// ── Replies collection ── lets remote servers fetch a post's whole thread.
247router.get('/ap/notes/:id/replies', (req, res) => {
248 const base = baseUrl(req);
249 const items = AP.getReplyUris(base, req.params.id);
250 AP.sendAP(res, {
251 '@context': AP.AP_CONTEXT,
252 id: `${base}/ap/notes/${req.params.id}/replies`,
253 type: 'OrderedCollection',
254 totalItems: items.length,
255 orderedItems: items,
256 });
257});
258
259// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
260router.get('/.well-known/nodeinfo', (req, res) => {
261 res.type('application/json');
262 res.set('Cache-Control', 'public, max-age=3600');
263 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
264});
265router.get('/nodeinfo/2.1', (req, res) => {
266 let users = 0; let posts = 0;
267 // "users" = public AP actors (sites), not the admin/member account rows.
268 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
269 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
270 res.type('application/json; charset=utf-8');
271 res.set('Cache-Control', 'public, max-age=600');
272 res.send(JSON.stringify({
273 version: '2.1',
274 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
275 protocols: ['activitypub'],
276 services: { inbound: [], outbound: [] },
277 openRegistrations: false,
278 usage: { users: { total: users }, localPosts: posts },
279 metadata: { nodeName: 'Klonkt' },
280 }));
281});
282
283// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
284const apJson = express.json({
285 type: ['application/activity+json', 'application/ld+json', 'application/json'],
286 limit: '1mb',
287 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
288});
289router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
290 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
291 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
292});
293
294// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
295// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
296// the normal delivery machinery. The token is scoped to one user+site (OAuth
297// consent), so it must match the slug in the URL. (Declared after apJson, which
298// this shares with the inbox handler.)
299router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
300 const auth = OAuth.verifyBearer(req.headers.authorization);
301 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
302 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
303 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
304
305 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
306 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
307 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
308 if (out.status === 201 && out.url) res.set('Location', out.url);
309 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
310});
311
312export default router;
Note: See TracBrowser for help on using the repository browser.