source: Klonkt/src/routes/activitypub.js@ 75bda38

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

feat(fediverse): expose pinned posts via the actor's featured collection

Adds actor.featured + GET /ap/users/:slug/featured (OrderedCollection of pinned,
published, non-fan_only posts as Notes, ordered by pin rank). Mastodon reads this
and shows them under the profile's Featured tab.

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

  • Property mode set to 100644
File size: 7.6 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 const posts = db.prepare(
80 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
81 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
82 AND pinned IS NOT NULL AND pinned > 0
83 ORDER BY pinned ASC, COALESCE(published_at, created_at) DESC LIMIT 20`
84 ).all(site.id);
85 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
86});
87
88// ── Note ──────────────────────────────────────────────────────────
89router.get('/ap/notes/:id', (req, res) => {
90 const post = db.prepare(
91 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
92 ).get(req.params.id);
93 if (!post) {
94 // Could be one of OUR outbound replies (ap_outbox), not a post.
95 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
96 if (note) return AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...note });
97 return res.status(404).end();
98 }
99 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
100 if (!site) return res.status(404).end();
101 AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...AP.buildNote(baseUrl(req), site, post) });
102});
103
104// ── Replies collection ── lets remote servers fetch a post's whole thread.
105router.get('/ap/notes/:id/replies', (req, res) => {
106 const base = baseUrl(req);
107 const items = AP.getReplyUris(base, req.params.id);
108 AP.sendAP(res, {
109 '@context': 'https://www.w3.org/ns/activitystreams',
110 id: `${base}/ap/notes/${req.params.id}/replies`,
111 type: 'OrderedCollection',
112 totalItems: items.length,
113 orderedItems: items,
114 });
115});
116
117// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
118router.get('/.well-known/nodeinfo', (req, res) => {
119 res.type('application/json');
120 res.set('Cache-Control', 'public, max-age=3600');
121 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
122});
123router.get('/nodeinfo/2.1', (req, res) => {
124 let users = 0; let posts = 0;
125 try { users = db.prepare('SELECT COUNT(*) c FROM users').get().c; } catch { /* */ }
126 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
127 res.type('application/json; charset=utf-8');
128 res.set('Cache-Control', 'public, max-age=600');
129 res.send(JSON.stringify({
130 version: '2.1',
131 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
132 protocols: ['activitypub'],
133 services: { inbound: [], outbound: [] },
134 openRegistrations: false,
135 usage: { users: { total: users }, localPosts: posts },
136 metadata: { nodeName: 'Klonkt' },
137 }));
138});
139
140// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
141const apJson = express.json({
142 type: ['application/activity+json', 'application/ld+json', 'application/json'],
143 limit: '1mb',
144 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
145});
146router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, async (req, res) => {
147 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
148 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
149});
150
151export default router;
Note: See TracBrowser for help on using the repository browser.