source: Klonkt/src/routes/activitypub.js@ 33e1dbd

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

Feature: C2S owner can read own followers/following (klonkt-demo-6kc)

The followers and following collections stay count-only for the public
(privacy), but a request carrying a C2S bearer scoped to that site (the account
owner) now returns the real actor URIs, so a client (Shaer) can build a friends
list. This was the one gap keeping the Shaer app's orbit empty against a real
Klonkt (it worked against the shaer-daemon, which serves the full lists).

  • buildFollowers/buildFollowing take an optional items array: when present, orderedItems carries the URIs and totalItems reflects them; otherwise count-only as before.
  • The two GET routes verify a bearer (OAuth.verifyBearer) and, when it is scoped to the requested slug, return the full list from ap_followers.actor_uri / ap_following.actor_uri (status=accepted); everyone else gets count-only. A private site's owner can read it even when it is not publicly listed.

3 new builder tests (count-only vs owner items vs empty owner list); 83 green.
Live-verified: owner bearer -> real URIs (alice/bob) in orderedItems; no bearer
-> orderedItems empty with the count intact; a token for another slug does not
unlock it.

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

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