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

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

Feature: OAuth C2S outbox POST — apps can drive the account (phase 1 done)

Second half of AP Client-to-Server: a bearer-authenticated POST to
/ap/users/:slug/outbox accepts activities and translates them onto the existing
delivery machinery (deliverReply / sendInteraction / followActor /
deliverCreate) rather than reimplementing federation.

  • ingestOutboxActivity(site, user, activity) dispatches Create(Note) (reply -> resolveRemoteNote + deliverReply; top-level -> a sanitized microblog post + deliverCreate), Like, Announce (+upsertBoostedNote), Follow, and Undo of Like/Announce/Follow. A bare Note is wrapped in a Create per AP section 6. Client "source" (plain) is preferred over "content" (HTML) for replies; top-level content is HtmlSanitizerService.sanitize()d. Unhandled verbs return a clear 400 rather than a silent no-op.
  • Route: bearer via OAuthService.verifyBearer; the token is scoped to one site, so a slug mismatch is 403 and a readonly account is 403; no token is 401 with WWW-Authenticate. 201+Location for created objects, 202 for side-effect verbs. Declared after apJson (shared with the inbox handler) to avoid a TDZ on the const.

Verified live end to end against a running server with a real OAuth token:
top-level Note -> 201 + Location, stored published + sanitized (script stripped)
+ served as a valid Note at /ap/notes/<id>; Like/Follow -> 202; unresolvable
reply -> honest 502; no-token 401, wrong-site 403, unsupported type 400. 7 new
unit tests for the deterministic dispatch paths (80 green).

Ivory and other Mastodon-API clients are NOT supported by this: they speak
Mastodon's REST API (/api/v1/apps, /api/v1/instance, secret-based OAuth), not AP
C2S. That's a separate track (klonkt-demo-mastapi). Delete/Update of arbitrary
objects deferred (klonkt-demo-c2sdel). Beads: klonkt-demo-1w4.

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

  • Property mode set to 100644
File size: 11.6 KB
RevLine 
[6bd25d1]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
[75bda38]8 * GET /ap/users/:slug/featured pinned posts (Mastodon "Featured" tab)
[6bd25d1]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';
[d7526bd]15import { readFileSync } from 'fs';
[6bd25d1]16import db from '../config/database.js';
17import AP from '../services/ActivityPubService.js';
[75ab393]18import { apReadLimiter, apInboxLimiter } from '../middleware/rate-limit.js';
[283f618]19import { apEnabled } from '../services/SettingsService.js';
[dd568e7]20import OAuth from '../services/OAuthService.js';
[6bd25d1]21
22const router = express.Router();
[283f618]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
[89cc8c4]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(); });
[75ab393]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);
[d7526bd]33let _ver = '1.0.0';
34try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
[6bd25d1]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');
[f2796d3]49 const actorUri = AP.actorId(baseUrl(req), site.slug);
50 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
[6bd25d1]51 res.send(JSON.stringify({
52 subject: `acct:${site.slug}@${hostOf(req)}`,
[f2796d3]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 ],
[6bd25d1]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(
[857a06f]79 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
[6bd25d1]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) ────────────────────────────────────────
87router.get('/ap/users/:slug/followers', (req, res) => {
88 const site = publicSite(req.params.slug);
89 if (!site) return res.status(404).end();
90 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
91 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
92});
93
[f2796d3]94// ── Following (count only) ────────────────────────────────────────
95router.get('/ap/users/:slug/following', (req, res) => {
96 const site = publicSite(req.params.slug);
97 if (!site) return res.status(404).end();
98 let n = 0;
99 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
100 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
101});
102
[75bda38]103// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
104router.get('/ap/users/:slug/featured', (req, res) => {
105 const site = publicSite(req.params.slug);
106 if (!site) return res.status(404).end();
[2af2e69]107 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
108 // last-processed-first). So we emit it reversed (lowest pin priority first,
109 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
[75bda38]110 const posts = db.prepare(
[857a06f]111 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
[75bda38]112 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
113 AND pinned IS NOT NULL AND pinned > 0
[2af2e69]114 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
[75bda38]115 ).all(site.id);
116 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
117});
118
[6bd25d1]119// ── Note ──────────────────────────────────────────────────────────
120router.get('/ap/notes/:id', (req, res) => {
121 const post = db.prepare(
122 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
123 ).get(req.params.id);
[55bc7f9]124 if (!post) {
125 // Could be one of OUR outbound replies (ap_outbox), not a post.
126 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
[49edc72]127 if (!note) return res.status(404).end();
128 if (!AP.apWants(req)) {
129 // A browser hit a reply's AP URL → send them to the source it replies to
130 // (where the post + its reactions live), falling back to the site home.
131 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
132 ? note.inReplyTo : (baseUrl(req) + '/');
133 return res.redirect(302, src);
134 }
[d3b9f68]135 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[55bc7f9]136 }
[6bd25d1]137 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
138 if (!site) return res.status(404).end();
[49edc72]139 const note = AP.buildNote(baseUrl(req), site, post);
140 if (!AP.apWants(req)) {
141 // A browser hit a post's AP note URL → send them to the human post page
142 // (which shows the post + its "from the fediverse" reactions).
143 return res.redirect(302, note.url || (baseUrl(req) + '/'));
144 }
[d3b9f68]145 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[6bd25d1]146});
147
[d7526bd]148// ── Replies collection ── lets remote servers fetch a post's whole thread.
149router.get('/ap/notes/:id/replies', (req, res) => {
150 const base = baseUrl(req);
151 const items = AP.getReplyUris(base, req.params.id);
152 AP.sendAP(res, {
[d3b9f68]153 '@context': AP.AP_CONTEXT,
[d7526bd]154 id: `${base}/ap/notes/${req.params.id}/replies`,
155 type: 'OrderedCollection',
156 totalItems: items.length,
157 orderedItems: items,
158 });
159});
160
161// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
162router.get('/.well-known/nodeinfo', (req, res) => {
163 res.type('application/json');
164 res.set('Cache-Control', 'public, max-age=3600');
165 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
166});
167router.get('/nodeinfo/2.1', (req, res) => {
168 let users = 0; let posts = 0;
[f2796d3]169 // "users" = public AP actors (sites), not the admin/member account rows.
170 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
[d7526bd]171 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
172 res.type('application/json; charset=utf-8');
173 res.set('Cache-Control', 'public, max-age=600');
174 res.send(JSON.stringify({
175 version: '2.1',
176 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
177 protocols: ['activitypub'],
178 services: { inbound: [], outbound: [] },
179 openRegistrations: false,
180 usage: { users: { total: users }, localPosts: posts },
181 metadata: { nodeName: 'Klonkt' },
182 }));
183});
184
[5bf63b7]185// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
186const apJson = express.json({
187 type: ['application/activity+json', 'application/ld+json', 'application/json'],
188 limit: '1mb',
189 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
190});
[75ab393]191router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
[5bf63b7]192 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
193 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
[6bd25d1]194});
195
[dd568e7]196// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
197// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
198// the normal delivery machinery. The token is scoped to one user+site (OAuth
199// consent), so it must match the slug in the URL. (Declared after apJson, which
200// this shares with the inbox handler.)
201router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
202 const auth = OAuth.verifyBearer(req.headers.authorization);
203 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
204 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
205 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
206
207 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
208 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
209 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
210 if (out.status === 201 && out.url) res.set('Location', out.url);
211 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
212});
213
[6bd25d1]214export default router;
Note: See TracBrowser for help on using the repository browser.