source: Klonkt/src/routes/activitypub.js@ 47a0d29

main
Last change on this file since 47a0d29 was 5a93ac0, checked in by Robin Genis <roboburr@…>, 3 months ago

feat(activitypub): federate images as attachments

Cover image + inline <img> are emitted as AP attachment (Document) with absolute
URLs + mediaType; <img> stripped from content (Mastodon strips it anyway). Outbox
+ post-create delivery now include cover_image_url.

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

  • Property mode set to 100644
File size: 5.0 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
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(
[5a93ac0]56 `SELECT id, slug, title, content, cover_image_url, published_at, created_at
[6bd25d1]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
[5bf63b7]82// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
83const apJson = express.json({
84 type: ['application/activity+json', 'application/ld+json', 'application/json'],
85 limit: '1mb',
86 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
87});
88router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apJson, async (req, res) => {
89 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
90 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
[6bd25d1]91});
92
93export default router;
Note: See TracBrowser for help on using the repository browser.