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