source: Klonkt/src/routes/activitypub.js@ 55bc7f9

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

feat(activitypub): reply back to the fediverse (Phase 4 outbound)

Site owner can reply to an inbound fediverse interaction from the post page. The
reply is sent as a signed Create(Note) with inReplyTo + @Mention to the remote
actor's inbox + our followers, stored in ap_outbox, shown in the thread, and
resolvable at /ap/notes/<id>.

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

  • Property mode set to 100644
File size: 5.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/notes/:id a single Note
9 * POST /ap/users/:slug/inbox, /ap/inbox → 202 (Follow/Accept + signature verify: next step)
10 *
11 * Mounted before resolveSite; resolves the site by slug itself.
12 */
13import express from 'express';
14import db from '../config/database.js';
15import AP from '../services/ActivityPubService.js';
16
17const router = express.Router();
18
19const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
20const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
21const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
22const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
23
24// ── WebFinger ─────────────────────────────────────────────────────
25router.get('/.well-known/webfinger', (req, res) => {
26 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
27 if (!m) return res.status(400).type('text/plain').send('bad resource');
28 const site = publicSite(m[1]);
29 if (!site) return res.status(404).end();
30 res.type('application/jrd+json; charset=utf-8');
31 res.set('Cache-Control', 'public, max-age=300');
32 res.send(JSON.stringify({
33 subject: `acct:${site.slug}@${hostOf(req)}`,
34 links: [{ rel: 'self', type: 'application/activity+json', href: AP.actorId(baseUrl(req), site.slug) }],
35 }));
36});
37
38// ── Actor ─────────────────────────────────────────────────────────
39router.get('/ap/users/:slug', (req, res) => {
40 const site = publicSite(req.params.slug);
41 if (!site) return res.status(404).end();
42 if (!AP.apWants(req)) {
43 // A browser hit the AP actor URL → send them to the human profile.
44 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
45 return res.redirect(302, baseUrl(req) + human);
46 }
47 site.primary_slug = primarySlug();
48 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
49});
50
51// ── Outbox ────────────────────────────────────────────────────────
52router.get('/ap/users/:slug/outbox', (req, res) => {
53 const site = publicSite(req.params.slug);
54 if (!site) return res.status(404).end();
55 const posts = db.prepare(
56 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
57 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
58 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
59 ).all(site.id);
60 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
61});
62
63// ── Followers (count only) ────────────────────────────────────────
64router.get('/ap/users/:slug/followers', (req, res) => {
65 const site = publicSite(req.params.slug);
66 if (!site) return res.status(404).end();
67 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
68 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
69});
70
71// ── Note ──────────────────────────────────────────────────────────
72router.get('/ap/notes/:id', (req, res) => {
73 const post = db.prepare(
74 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
75 ).get(req.params.id);
76 if (!post) {
77 // Could be one of OUR outbound replies (ap_outbox), not a post.
78 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
79 if (note) return AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...note });
80 return res.status(404).end();
81 }
82 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
83 if (!site) return res.status(404).end();
84 AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...AP.buildNote(baseUrl(req), site, post) });
85});
86
87// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
88const apJson = express.json({
89 type: ['application/activity+json', 'application/ld+json', 'application/json'],
90 limit: '1mb',
91 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
92});
93router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, async (req, res) => {
94 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
95 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
96});
97
98export default router;
Note: See TracBrowser for help on using the repository browser.