source: Klonkt/src/routes/activitypub.js@ 6bd25d1

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

feat(activitypub): phase 1 — discoverable/fetchable actor (WebFinger, Actor, Outbox, Notes)

First step of real ActivityPub federation: per-site RSA keys, WebFinger,
a content-negotiated Actor document (AP-JSON for servers, redirect to the HTML
profile for browsers), Outbox (Create/Note) and Note objects under /ap/*.
Inbox is a 202 stub for now; Follow/Accept + HTTP-signature verify + delivery
to followers land in the next step (tested live against Mastodon).

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

  • Property mode set to 100644
File size: 4.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/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, 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) return res.status(404).end();
77 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
78 if (!site) return res.status(404).end();
79 AP.sendAP(res, { '@context': 'https://www.w3.org/ns/activitystreams', ...AP.buildNote(baseUrl(req), site, post) });
80});
81
82// ── Inbox (Phase 1 stub: accept; Follow/Accept + sig verify next step) ──
83const apJson = express.json({ type: ['application/activity+json', 'application/ld+json', 'application/json'], limit: '1mb' });
84router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, (req, res) => {
85 try { console.log('[AP inbox]', (req.body && req.body.type) || 'unknown', '→', req.params.slug || 'shared'); } catch { /* ignore */ }
86 res.status(202).end();
87});
88
89export default router;
Note: See TracBrowser for help on using the repository browser.