source: Klonkt/src/routes/activitypub.js@ c1f5c23

main
Last change on this file since c1f5c23 was e61c289, checked in by Robin Genis <roboburr@…>, 7 weeks ago

Guardian-queues als C2S-routes + push-typen help/guardian

De drie shaer:queues-collecties uit het actor-doc zijn nu echte owner-only
routes (Bearer, zelfde patroon als /blocked): offers, follows (leeg tot
gated follows bestaan) en wards. Contract gelijk aan de Shaer test-daemon,
dus de iOS/Android-dashboards lezen ze ongewijzigd.

Web-push kent twee nieuwe alert-typen: 'help' (hulpvraag van een ward,
niet gethrottled, standaard aan) en 'guardian' (adoptieverkeer). Teksten in
nl/en/de.

Changed files:
src/routes/activitypub.js

  • GET /ap/users/:slug/queues/{offers,follows,wards}, owner-only

src/services/PushService.js

  • alert-typen help + guardian (defaults aan, throttle 0/30s)

src/services/i18n.js

  • push.n_help_*, push.n_guard_* in nl/en/de

New file:
test/guardianship.test.js

  • pint het module-oppervlak: actor-props, handshake C2S+S2S beide kanten, queue-shapes, ward-mag-niet-guarden, helpRequest-props

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 18.9 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';
18import { apReadLimiter, apInboxLimiter } from '../middleware/rate-limit.js';
19import { apEnabled } from '../services/SettingsService.js';
20import OAuth from '../services/OAuthService.js';
21import * as Guardianship from '../services/guardianship/index.js';
22import multer from 'multer';
23import path from 'path';
24import fs from 'fs';
25import { fileURLToPath } from 'url';
26import { randomUUID } from 'crypto';
27
28const router = express.Router();
29// The whole fediverse layer can be turned off (solo "no federation" mode):
30// then /ap/*, WebFinger and NodeInfo are simply gone — the site is undiscoverable
31// and unfederatable. CRITICAL: this router is mounted at root (app.use(apRoutes)), so a
32// blanket res.status(404) here ran for EVERY request and 404'd the whole site when AP was
33// off. Use next('router') to SKIP this router entirely and let the normal routes handle it
34// (the /ap/* paths then fall through to the app's normal 404, which is correct).
35router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
36// Generous per-IP baseline over all /ap/* (reads). The inbox POST gets an
37// additional, tighter cap inline (it triggers outbound fetches).
38router.use(apReadLimiter);
39let _ver = '1.0.0';
40try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
41
42const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
43const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
44const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
45const primarySlug = () => { const r = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get(); return r && r.slug; };
46
47// ── WebFinger ─────────────────────────────────────────────────────
48router.get('/.well-known/webfinger', (req, res) => {
49 const m = String(req.query.resource || '').match(/^acct:([^@]+)@(.+)$/i);
50 if (!m) return res.status(400).type('text/plain').send('bad resource');
51 const site = publicSite(m[1]);
52 if (!site) return res.status(404).end();
53 res.type('application/jrd+json; charset=utf-8');
54 res.set('Cache-Control', 'public, max-age=300');
55 const actorUri = AP.actorId(baseUrl(req), site.slug);
56 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
57 res.send(JSON.stringify({
58 subject: `acct:${site.slug}@${hostOf(req)}`,
59 aliases: [actorUri, profileUrl],
60 links: [
61 { rel: 'self', type: 'application/activity+json', href: actorUri },
62 { rel: 'http://webfinger.net/rel/profile-page', type: 'text/html', href: profileUrl },
63 ],
64 }));
65});
66
67// ── Actor ─────────────────────────────────────────────────────────
68router.get('/ap/users/:slug', (req, res) => {
69 const site = publicSite(req.params.slug);
70 if (!site) return res.status(404).end();
71 if (!AP.apWants(req)) {
72 // A browser hit the AP actor URL → send them to the human profile.
73 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
74 return res.redirect(302, baseUrl(req) + human);
75 }
76 site.primary_slug = primarySlug();
77 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
78});
79
80// ── Outbox ────────────────────────────────────────────────────────
81router.get('/ap/users/:slug/outbox', (req, res) => {
82 const site = publicSite(req.params.slug);
83 if (!site) return res.status(404).end();
84 const posts = db.prepare(
85 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
86 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
87 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
88 ).all(site.id);
89 AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, posts));
90});
91
92// ── Blocked collection (owner only, AP §5.6) ──────────────────────
93// The server blocklist is the source of truth for Shaer's "in Orbit":
94// clients read it here instead of keeping their own state. Actor-kind
95// blocks only (domain blocks are instance policy, not an Orbit member).
96router.get('/ap/users/:slug/blocked', (req, res) => {
97 const auth = OAuth.verifyBearer(req.headers.authorization);
98 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
99 const base = baseUrl(req);
100 const items = AP.listBlocks(auth.site.slug)
101 .filter((b) => b.kind === 'actor')
102 .map((b) => b.target);
103 AP.sendAP(res, {
104 '@context': AP.AP_CONTEXT,
105 id: `${base}/ap/users/${auth.site.slug}/blocked`,
106 type: 'OrderedCollection',
107 totalItems: items.length,
108 orderedItems: items,
109 });
110});
111
112// ── Guardian queues (owner only, FEP-633c, shaer:queues) ──────────
113// The dashboard collections the Shaer clients read: pending adoption offers,
114// gated follows (empty in Klonkt for now) and the guardian's wards. Same
115// contract as the Shaer test daemon.
116function queueRoute(name, build) {
117 router.get(`/ap/users/:slug/queues/${name}`, (req, res) => {
118 const auth = OAuth.verifyBearer(req.headers.authorization);
119 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
120 const base = baseUrl(req);
121 const me = `${base}/ap/users/${auth.site.slug}`;
122 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...build(`${me}/queues/${name}`, auth.site.slug, me) });
123 });
124}
125queueRoute('offers', (id, slug, me) => Guardianship.offersCollection(id, slug, me));
126queueRoute('follows', (id) => Guardianship.followsCollection(id));
127queueRoute('wards', (id, slug) => Guardianship.wardsCollection(id, slug));
128
129// ── Inbox read (owner only, AP C2S) ───────────────────────────────
130// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
131// scoped to this site) reads recent inbound posts (the timeline: accounts
132// they follow) as Create(Note) items, so an app (Shaer) can build a unified
133// feed. Anyone else gets 403; the inbox stays write-only for the public.
134router.get('/ap/users/:slug/inbox', (req, res) => {
135 const auth = OAuth.verifyBearer(req.headers.authorization);
136 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
137 const base = baseUrl(req);
138 const items = AP.getTimeline(auth.site.slug, 60).map((t) => ({
139 id: `${t.id}#create`,
140 type: 'Create',
141 actor: t.author_uri,
142 published: t.published || t.created_at || undefined,
143 object: {
144 id: t.id,
145 type: 'Note',
146 attributedTo: t.author_uri,
147 content: t.content,
148 url: t.url || undefined,
149 published: t.published || t.created_at || undefined,
150 sensitive: !!t.nsfw,
151 summary: t.cw || undefined,
152 // Friends' media travels along (media_json → AS2 attachment), so the
153 // client renders their images/audio like own outbox posts.
154 attachment: AP.timelineAttachments(t.media_json),
155 },
156 }));
157 AP.sendAP(res, {
158 '@context': AP.AP_CONTEXT,
159 id: `${base}/ap/users/${auth.site.slug}/inbox`,
160 type: 'OrderedCollection',
161 totalItems: items.length,
162 orderedItems: items,
163 });
164});
165
166// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
167// The actor advertises endpoints.uploadMedia; this implements it. A bearer
168// scoped to this site uploads one image/audio/video (multipart field "file",
169// AP convention) into the same store the reply editor uses, and gets back
170// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
171const AP_MEDIA_DIR = path.resolve(
172 process.env.REPLY_MEDIA_PATH ||
173 path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'storage', 'media', 'reply-media')
174);
175fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
176const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
177const apMediaUpload = multer({
178 storage: multer.diskStorage({
179 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
180 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
181 }),
182 limits: { fileSize: 32 * 1024 * 1024 },
183 fileFilter: (req, file, cb) => {
184 const ext = path.extname(file.originalname || '').toLowerCase();
185 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
186 cb(null, true);
187 },
188});
189router.post('/ap/users/:slug/uploadMedia', (req, res) => {
190 const auth = OAuth.verifyBearer(req.headers.authorization);
191 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
192 apMediaUpload.single('file')(req, res, (err) => {
193 if (err) return res.status(400).json({ error: err.message });
194 if (!req.file) return res.status(400).json({ error: 'No file' });
195 const mime = String(req.file.mimetype || '');
196 if (!/^(image|audio|video)\//.test(mime)) {
197 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
198 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
199 }
200 res.status(201).json({
201 url: '/media/reply-media/' + req.file.filename,
202 mediaType: mime,
203 name: String(req.file.originalname || '').slice(0, 120),
204 });
205 });
206});
207
208// ── Followers (count-only public, full for the owner) ─────────────
209// A C2S bearer scoped to this site (the account owner) gets the real actor
210// URIs so their own client can build a friends list; everyone else gets the
211// count only (privacy).
212// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
213// Returns true and sets the response headers when the owner asked for it.
214function wantsEnriched(req, res) {
215 res.set('Vary', 'Prefer'); // enriched and bare are two representations
216 if (AP.prefersEnriched(req.get('Prefer'))) {
217 res.set('Preference-Applied', 'return=representation');
218 return true;
219 }
220 return false;
221}
222
223router.get('/ap/users/:slug/followers', (req, res) => {
224 const auth = OAuth.verifyBearer(req.headers.authorization);
225 const owner = auth && auth.site.slug === req.params.slug;
226 const site = owner ? auth.site : publicSite(req.params.slug);
227 if (!site) return res.status(404).end();
228 if (owner) {
229 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
230 // Default = bare references; enrich only when the client asks (FEP-9876).
231 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
232 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items));
233 }
234 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
235 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
236});
237
238// ── Following (count-only public, full for the owner) ─────────────
239router.get('/ap/users/:slug/following', (req, res) => {
240 const auth = OAuth.verifyBearer(req.headers.authorization);
241 const owner = auth && auth.site.slug === req.params.slug;
242 const site = owner ? auth.site : publicSite(req.params.slug);
243 if (!site) return res.status(404).end();
244 if (owner) {
245 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
246 let items = [];
247 try {
248 const uris = db.prepare("SELECT actor_uri FROM ap_following WHERE slug = ? AND status = 'accepted' ORDER BY created_at").all(site.slug).map((r) => r.actor_uri);
249 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
250 } catch { /* table may not exist */ }
251 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items));
252 }
253 let n = 0;
254 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
255 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
256});
257
258// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
259router.get('/ap/users/:slug/featured', (req, res) => {
260 const site = publicSite(req.params.slug);
261 if (!site) return res.status(404).end();
262 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
263 // last-processed-first). So we emit it reversed (lowest pin priority first,
264 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
265 const posts = db.prepare(
266 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, published_at, created_at
267 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
268 AND pinned IS NOT NULL AND pinned > 0
269 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
270 ).all(site.id);
271 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
272});
273
274// ── Note ──────────────────────────────────────────────────────────
275router.get('/ap/notes/:id', (req, res) => {
276 const post = db.prepare(
277 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
278 ).get(req.params.id);
279 if (!post) {
280 // Could be one of OUR outbound replies (ap_outbox), not a post.
281 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
282 if (!note) return res.status(404).end();
283 if (!AP.apWants(req)) {
284 // A browser hit a reply's AP URL → send them to the source it replies to
285 // (where the post + its reactions live), falling back to the site home.
286 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
287 ? note.inReplyTo : (baseUrl(req) + '/');
288 return res.redirect(302, src);
289 }
290 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
291 }
292 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
293 if (!site) return res.status(404).end();
294 const note = AP.buildNote(baseUrl(req), site, post);
295 if (!AP.apWants(req)) {
296 // A browser hit a post's AP note URL → send them to the human post page
297 // (which shows the post + its "from the fediverse" reactions).
298 return res.redirect(302, note.url || (baseUrl(req) + '/'));
299 }
300 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
301});
302
303// ── Replies collection ── lets remote servers fetch a post's whole thread.
304router.get('/ap/notes/:id/replies', (req, res) => {
305 const base = baseUrl(req);
306 const items = AP.getReplyUris(base, req.params.id);
307 AP.sendAP(res, {
308 '@context': AP.AP_CONTEXT,
309 id: `${base}/ap/notes/${req.params.id}/replies`,
310 type: 'OrderedCollection',
311 totalItems: items.length,
312 orderedItems: items,
313 });
314});
315
316// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
317router.get('/.well-known/nodeinfo', (req, res) => {
318 res.type('application/json');
319 res.set('Cache-Control', 'public, max-age=3600');
320 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
321});
322router.get('/nodeinfo/2.1', (req, res) => {
323 let users = 0; let posts = 0;
324 // "users" = public AP actors (sites), not the admin/member account rows.
325 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
326 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
327 res.type('application/json; charset=utf-8');
328 res.set('Cache-Control', 'public, max-age=600');
329 res.send(JSON.stringify({
330 version: '2.1',
331 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
332 protocols: ['activitypub'],
333 services: { inbound: [], outbound: [] },
334 openRegistrations: false,
335 usage: { users: { total: users }, localPosts: posts },
336 metadata: { nodeName: 'Klonkt' },
337 }));
338});
339
340// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
341const apJson = express.json({
342 type: ['application/activity+json', 'application/ld+json', 'application/json'],
343 limit: '1mb',
344 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
345});
346router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
347 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
348 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
349});
350
351// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
352// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
353// the normal delivery machinery. The token is scoped to one user+site (OAuth
354// consent), so it must match the slug in the URL. (Declared after apJson, which
355// this shares with the inbox handler.)
356router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
357 const auth = OAuth.verifyBearer(req.headers.authorization);
358 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
359 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
360 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
361
362 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
363 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
364 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
365 if (out.status === 201 && out.url) res.set('Location', out.url);
366 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
367});
368
369export default router;
Note: See TracBrowser for help on using the repository browser.