source: Klonkt/src/routes/activitypub.js@ 3dd99d3

main
Last change on this file since 3dd99d3 was 2af2e69, checked in by Robin Genis <roboburr@…>, 3 months ago

fediverse: emit featured collection reversed (Mastodon displays pins last-first)

Mastodon shows a remote actor's featured collection in reverse of the orderedItems
order (pins ordered by processed-time desc). So we now emit pin-rank DESCENDING →
Mastodon flips it back to rank 1 first on the profile.

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

  • Property mode set to 100644
File size: 7.8 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';
18
19const router = express.Router();
20let _ver = '1.0.0';
21try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
22
23const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
24const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
25const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
26const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
27
28// ── WebFinger ─────────────────────────────────────────────────────
29router.get('/.well-known/webfinger', (req, res) => {
30 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
31 if (!m) return res.status(400).type('text/plain').send('bad resource');
32 const site = publicSite(m[1]);
33 if (!site) return res.status(404).end();
34 res.type('application/jrd+json; charset=utf-8');
35 res.set('Cache-Control', 'public, max-age=300');
36 res.send(JSON.stringify({
37 subject: `acct:${site.slug}@${hostOf(req)}`,
38 links: [{ rel: 'self', type: 'application/activity+json', href: AP.actorId(baseUrl(req), site.slug) }],
39 }));
40});
41
42// ── Actor ─────────────────────────────────────────────────────────
43router.get('/ap/users/:slug', (req, res) => {
44 const site = publicSite(req.params.slug);
45 if (!site) return res.status(404).end();
46 if (!AP.apWants(req)) {
47 // A browser hit the AP actor URL → send them to the human profile.
48 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
49 return res.redirect(302, baseUrl(req) + human);
50 }
51 site.primary_slug = primarySlug();
52 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
53});
54
55// ── Outbox ────────────────────────────────────────────────────────
56router.get('/ap/users/:slug/outbox', (req, res) => {
57 const site = publicSite(req.params.slug);
58 if (!site) return res.status(404).end();
59 const posts = db.prepare(
60 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
61 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
62 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
63 ).all(site.id);
64 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
65});
66
67// ── Followers (count only) ────────────────────────────────────────
68router.get('/ap/users/:slug/followers', (req, res) => {
69 const site = publicSite(req.params.slug);
70 if (!site) return res.status(404).end();
71 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
72 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
73});
74
75// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
76router.get('/ap/users/:slug/featured', (req, res) => {
77 const site = publicSite(req.params.slug);
78 if (!site) return res.status(404).end();
79 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
80 // last-processed-first). So we emit it reversed (lowest pin priority first,
81 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
82 const posts = db.prepare(
83 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
84 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
85 AND pinned IS NOT NULL AND pinned > 0
86 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
87 ).all(site.id);
88 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
89});
90
91// ── Note ──────────────────────────────────────────────────────────
92router.get('/ap/notes/:id', (req, res) => {
93 const post = db.prepare(
94 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
95 ).get(req.params.id);
96 if (!post) {
97 // Could be one of OUR outbound replies (ap_outbox), not a post.
98 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
99 if (note) return AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...note });
100 return res.status(404).end();
101 }
102 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
103 if (!site) return res.status(404).end();
104 AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...AP.buildNote(baseUrl(req), site, post) });
105});
106
107// ── Replies collection ── lets remote servers fetch a post's whole thread.
108router.get('/ap/notes/:id/replies', (req, res) => {
109 const base = baseUrl(req);
110 const items = AP.getReplyUris(base, req.params.id);
111 AP.sendAP(res, {
112 '@context': 'https://www.w3.org/ns/activitystreams',
113 id: `${base}/ap/notes/${req.params.id}/replies`,
114 type: 'OrderedCollection',
115 totalItems: items.length,
116 orderedItems: items,
117 });
118});
119
120// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
121router.get('/.well-known/nodeinfo', (req, res) => {
122 res.type('application/json');
123 res.set('Cache-Control', 'public, max-age=3600');
124 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
125});
126router.get('/nodeinfo/2.1', (req, res) => {
127 let users = 0; let posts = 0;
128 try { users = db.prepare('SELECT COUNT(*) c FROM users').get().c; } catch { /* */ }
129 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
130 res.type('application/json; charset=utf-8');
131 res.set('Cache-Control', 'public, max-age=600');
132 res.send(JSON.stringify({
133 version: '2.1',
134 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
135 protocols: ['activitypub'],
136 services: { inbound: [], outbound: [] },
137 openRegistrations: false,
138 usage: { users: { total: users }, localPosts: posts },
139 metadata: { nodeName: 'Klonkt' },
140 }));
141});
142
143// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
144const apJson = express.json({
145 type: ['application/activity+json', 'application/ld+json', 'application/json'],
146 limit: '1mb',
147 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
148});
149router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, async (req, res) => {
150 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
151 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
152});
153
154export default router;
Note: See TracBrowser for help on using the repository browser.