source: Klonkt/src/routes/activitypub.js@ 1a2f206

main
Last change on this file since 1a2f206 was 1a2f206, checked in by Robin <roboburr@…>, 6 weeks ago

Follow: gesigneerd resolven, fouten naar de app, guardians ingelicht, volg-QR

Robins meldingen (31-7). Vier dingen aan de volg-kant.

Een: followActor haalde het actor-document anoniem op; een
authorized-fetch-instance weigert dat, waardoor volgen vanaf een boost
faalde. De fetch is nu gesigneerd als de eigen actor.

Twee: de C2S-ingest slikte followActor-fouten in en gaf altijd 202,
dus een mislukte follow zag er in de app uit als een gelukte. Fouten
komen nu als 502 follow_failed (met detail) bij de app aan, met test.

Drie: de guardians worden ingelicht als hun ward iemand gaat volgen:
een follow brengt nieuwe content het kind binnen, en het dorp hoort te
weten dat de deur openging. Een directe note per guardian,
best-effort. FEP-633c 5.3 gate't inkomende follows; deze uitgaande
melding is Shaer-beleid (spec-vraag als bead).

Vier: GET /ap/users/:slug/follow-qr.png serveert een QR-PNG van
share:social/follow/AP/@slug@host (npm qrcode, puur JS). Publiek met
opzet: er staat alleen de publieke handle in, en de plain image-loaders
van de apps dragen geen bearer.

Changed files:
src/services/ActivityPubService.js

  • followActor: signedGetJson voor het actor-doc; guardian-notice
  • C2S Follow-case: fouten door naar de app

src/routes/activitypub.js

  • follow-qr.png-route (cache 1 dag)

package.json / package-lock.json

  • qrcode-dependency

test/c2s-compose.test.js

  • onbereikbare follow geeft 502 follow_failed/unreachable

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

  • Property mode set to 100644
File size: 33.4 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
[75bda38]8 * GET /ap/users/:slug/featured pinned posts (Mastodon "Featured" tab)
[6bd25d1]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';
[d7526bd]15import { readFileSync } from 'fs';
[6bd25d1]16import db from '../config/database.js';
17import AP from '../services/ActivityPubService.js';
[75ab393]18import { apReadLimiter, apInboxLimiter } from '../middleware/rate-limit.js';
[283f618]19import { apEnabled } from '../services/SettingsService.js';
[dd568e7]20import OAuth from '../services/OAuthService.js';
[e61c289]21import * as Guardianship from '../services/guardianship/index.js';
[e6c6e6f]22import multer from 'multer';
23import path from 'path';
24import fs from 'fs';
25import { fileURLToPath } from 'url';
26import { randomUUID } from 'crypto';
[6bd25d1]27
28const router = express.Router();
[283f618]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
[89cc8c4]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(); });
[75ab393]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);
[d7526bd]39let _ver = '1.0.0';
40try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
[6bd25d1]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');
[f2796d3]55 const actorUri = AP.actorId(baseUrl(req), site.slug);
56 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
[6bd25d1]57 res.send(JSON.stringify({
58 subject: `acct:${site.slug}@${hostOf(req)}`,
[f2796d3]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 ],
[6bd25d1]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 ────────────────────────────────────────────────────────
[c66cbb4]81router.get('/ap/users/:slug/outbox', async (req, res) => {
[6bd25d1]82 const site = publicSite(req.params.slug);
83 if (!site) return res.status(404).end();
[73a10c2]84 // Authorized fetch (30-7): who is asking decides what they see.
85 // - the owner's own app (bearer) and a verified accepted follower or
86 // guardian get the friends-only history too, so a NEW friend's backfill
87 // brings the past along (Robins besluit: vrienden krijgen de
88 // geschiedenis mee);
89 // - a verified caller this instance BLOCKS gets an EMPTY collection, not
90 // even the public set: a block is a closed door, and a signed fetch is
91 // the caller knocking with their name on it;
92 // - everyone else gets the public collection, exactly as before.
93 const bearer = OAuth.verifyBearer(req.headers.authorization);
94 let verifiedActor = null;
95 if (!bearer && req.headers['signature']) {
[c66cbb4]96 const verified = await AP.verifyRequest(req).catch(() => null);
[73a10c2]97 verifiedActor = verified && verified.id;
[c66cbb4]98 }
[73a10c2]99 const audience = AP.outboxAudience(req.params.slug, {
100 bearerSlug: bearer ? bearer.site.slug : null,
101 verifiedActor,
102 });
103 if (audience === 'blocked') {
104 return AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, []), 'private, no-store');
105 }
106 const fanClause = audience === 'friend' ? '' : "AND (fan_only IS NULL OR fan_only = 0)";
[6bd25d1]107 const posts = db.prepare(
[a9da2c0]108 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, c2s_attachments, published_at, created_at
[c66cbb4]109 FROM posts WHERE site_id = ? AND status = 'published' ${fanClause}
[6bd25d1]110 ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
111 ).all(site.id);
[67f7150]112 const ob = AP.buildOutbox(baseUrl(req), site, posts);
113 if (audience === 'friend') {
114 // The owner's app builds its feed from this leg, and every note here is
115 // by the site itself: give it the same `shaer:author` byline the timeline
116 // entries carry, so your own cards get a header too (avatar + name).
117 const me = AP.selfAuthor(baseUrl(req), site);
118 for (const it of ob.orderedItems) {
119 if (it && it.object && typeof it.object === 'object') it.object['shaer:author'] = me;
120 }
121 }
122 AP.sendAP(res, ob, audience === 'friend' ? 'private, no-store' : undefined);
[6bd25d1]123});
124
[1a2f206]125// ── Follow-QR (Robins verzoek, 31-7) ──────────────────────────────
126// A PNG QR of share:social/follow/AP/@slug@host: the ward shows it in
127// Account, a friend scans the SCREEN with the ordinary camera app and their
128// Shaer opens with the follow question. Public on purpose: it encodes only
129// the public handle, and the app's plain image loaders carry no bearer.
130router.get('/ap/users/:slug/follow-qr.png', async (req, res) => {
131 const site = db.prepare('SELECT slug FROM sites WHERE slug = ?').get(req.params.slug);
132 if (!site) return res.status(404).end();
133 try {
134 const host = new URL(baseUrl(req)).host;
135 const { default: QRCode } = await import('qrcode');
136 const png = await QRCode.toBuffer(`share:social/follow/AP/@${site.slug}@${host}`, { width: 600, margin: 1 });
137 res.set('Content-Type', 'image/png');
138 res.set('Cache-Control', 'public, max-age=86400');
139 res.send(png);
140 } catch (e) {
141 console.warn('[AP] follow-qr failed:', e && e.message);
142 res.status(500).end();
143 }
144});
145
[8b07c12]146// ── Blocked collection (owner only, AP §5.6) ──────────────────────
147// The server blocklist is the source of truth for Shaer's "in Orbit":
148// clients read it here instead of keeping their own state. Actor-kind
149// blocks only (domain blocks are instance policy, not an Orbit member).
150router.get('/ap/users/:slug/blocked', (req, res) => {
151 const auth = OAuth.verifyBearer(req.headers.authorization);
152 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
153 const base = baseUrl(req);
154 const items = AP.listBlocks(auth.site.slug)
155 .filter((b) => b.kind === 'actor')
156 .map((b) => b.target);
157 AP.sendAP(res, {
158 '@context': AP.AP_CONTEXT,
159 id: `${base}/ap/users/${auth.site.slug}/blocked`,
160 type: 'OrderedCollection',
161 totalItems: items.length,
162 orderedItems: items,
163 });
164});
165
[e61c289]166// ── Guardian queues (owner only, FEP-633c, shaer:queues) ──────────
167// The dashboard collections the Shaer clients read: pending adoption offers,
168// gated follows (empty in Klonkt for now) and the guardian's wards. Same
169// contract as the Shaer test daemon.
170function queueRoute(name, build) {
171 router.get(`/ap/users/:slug/queues/${name}`, (req, res) => {
172 const auth = OAuth.verifyBearer(req.headers.authorization);
173 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
174 const base = baseUrl(req);
175 const me = `${base}/ap/users/${auth.site.slug}`;
176 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...build(`${me}/queues/${name}`, auth.site.slug, me) });
177 });
178}
179queueRoute('offers', (id, slug, me) => Guardianship.offersCollection(id, slug, me));
180queueRoute('follows', (id) => Guardianship.followsCollection(id));
181queueRoute('wards', (id, slug) => Guardianship.wardsCollection(id, slug));
[6eab7e9]182// Availability (FEP-633c 3.6.1) is never public: the ward reads its
183// guardians' real states here and nowhere else.
184queueRoute('guardians', (id, slug) => Guardianship.guardiansCollection(id, slug));
[e61c289]185
[0cea12b]186// ── Inbox read (owner only, AP C2S) ───────────────────────────────
187// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
188// scoped to this site) reads recent inbound posts (the timeline: accounts
189// they follow) as Create(Note) items, so an app (Shaer) can build a unified
190// feed. Anyone else gets 403; the inbox stays write-only for the public.
191router.get('/ap/users/:slug/inbox', (req, res) => {
192 const auth = OAuth.verifyBearer(req.headers.authorization);
193 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
194 const base = baseUrl(req);
[fc40410]195 // Gated feature (FEP-633c): may this account see EXTERNAL embeds? A ward's
196 // world outside the fediverse is the guardians' call. The gate is applied
197 // here, at serialisation: a blocked embed is never sent, because an embed the
198 // client merely hides has still been delivered to the device.
199 const isWard = (() => { try { return Guardianship.listGuardians(auth.site.slug).length > 0; } catch { return false; } })();
200 const embedsAllowed = Guardianship.externalEmbedsAllowed(auth.site.external_embeds, isWard);
[e27b8db]201 // The heavier sibling (5.6): may a third party's PLAYER run inside the app,
202 // and may a link hand the child over to a browser? Both are the guardians'
203 // call, both default to off for a ward, and both need the preview gate open
204 // first: you cannot play, or follow, what you may not see. Served here so
205 // the app knows what it may offer instead of guessing.
206 const playbackAllowed = embedsAllowed
207 && Guardianship.externalPlaybackAllowed(auth.site.external_playback, isWard);
[08ab8ad]208 const posts = AP.getTimeline(auth.site.slug, 60).map((t) => ({
[0cea12b]209 id: `${t.id}#create`,
210 type: 'Create',
211 actor: t.author_uri,
212 published: t.published || t.created_at || undefined,
213 object: {
214 id: t.id,
215 type: 'Note',
216 attributedTo: t.author_uri,
217 content: t.content,
218 url: t.url || undefined,
219 published: t.published || t.created_at || undefined,
220 sensitive: !!t.nsfw,
221 summary: t.cw || undefined,
[fb30b5d]222 // Friends' media travels along (media_json → AS2 attachment), so the
223 // client renders their images/audio like own outbox posts.
224 attachment: AP.timelineAttachments(t.media_json),
[eb36688]225 // The note's preserved tags, so the client can render them: FEP-9098
226 // Emoji tags (:shortcode: → image) and FEP-e232 Link tags (quotes /
227 // inline object references). Combined into one `tag` array; omitted
228 // when the note has neither.
229 tag: (() => {
230 const tags = [...(AP.timelineEmojis(t.emoji_json) || []), ...(AP.timelineObjectLinks(t.link_json) || [])];
231 return tags.length ? tags : undefined;
232 })(),
[6fd0e20]233 // FEP-044f: the resolved quoted post (author + content), so the client
234 // renders an embedded quote card instead of a bare link. Omitted when the
235 // note has no quote or the quoted post could not be resolved.
236 'shaer:quote': AP.timelineQuote(t.quote_json),
[46a30f0]237 // The post author's display info (name / @handle / avatar), so every card
238 // gets a byline header like the quote card. attributedTo stays the bare
239 // actor URI; this is the resolved presentation Klonkt already stored.
240 'shaer:author': (t.author_name || t.author_handle || t.author_icon) ? {
241 name: t.author_name || undefined, handle: t.author_handle || undefined,
242 icon: t.author_icon || undefined, url: t.author_url || undefined,
[a677616]243 // FEP-9098: emojis in the display name (":shortcode:"), if any.
244 emojis: (() => { try { return t.author_emoji_json ? JSON.parse(t.author_emoji_json) : undefined; } catch { return undefined; } })(),
[46a30f0]245 } : undefined,
246 // When a followed account boosted this, who did ("X boosted"). Omitted for
247 // ordinary posts.
248 'shaer:booster': (t.reblog_name || t.reblog_handle || t.reblog_icon) ? {
249 name: t.reblog_name || undefined, handle: t.reblog_handle || undefined,
250 icon: t.reblog_icon || undefined,
[f3caf19]251 // FEP-9098: emojis in the booster's display name (":shortcode:"), if any.
252 emojis: (() => { try { return t.reblog_emoji_json ? JSON.parse(t.reblog_emoji_json) : undefined; } catch { return undefined; } })(),
[46a30f0]253 } : undefined,
[de89079]254 // Whether THIS account already liked/boosted the note, so the app's
255 // detail-view buttons show the current state (and can toggle/undo).
256 'shaer:liked': !!t.liked,
257 'shaer:boosted': !!t.boosted,
[fc40410]258 // An external (non-fediverse) embed, thumbnail-only and never an iframe.
259 // Omitted entirely when the gate is closed (see above).
[e27b8db]260 // Carries shaer:playerUrl only when the playback gate is open too.
261 'shaer:embed': embedsAllowed ? AP.timelineEmbed(t.embed_json, { playback: playbackAllowed }) : undefined,
[0cea12b]262 },
263 }));
[08ab8ad]264 // The direct notes addressed to this account: a plain DM, a guardian's wave
265 // (§5), a ward's 🛟 help request (§5.2.1). Those are messages, not posts, so
266 // they are not in the timeline; without them the app's Berichten shows only
267 // what you said yourself. Same shape as a post, so one parser handles both.
268 const me = AP.actorId(base, auth.site.slug);
269 const myHandle = (() => { try { return `@${auth.site.slug}@${new URL(base).host}`; } catch { return `@${auth.site.slug}`; } })();
270 const messages = AP.getDirectMessages(auth.site.slug, 60).map((m) => ({
271 id: `${m.object_uri}#create`,
272 type: 'Create',
273 actor: m.actor_uri,
274 published: AP.isoStamp(m.published || m.created_at),
275 object: {
276 id: m.object_uri,
277 type: 'Note',
278 attributedTo: m.actor_uri,
279 content: AP.stripLeadingMentions(m.content),
280 url: m.note_url || undefined,
281 published: AP.isoStamp(m.published || m.created_at),
282 // Addressed to us and to nobody we know of: the other recipients of a
283 // note to several people are not ours to see, so we serve what we know.
284 to: [me],
285 // The Mention is how the client recognises itself as the addressee and
286 // groups the note into a conversation. No FEP-e232 link tags here: a
287 // mention row keeps the resolved quote, not the raw tags.
288 tag: [{ type: 'Mention', href: me, name: myHandle }, ...(AP.timelineEmojis(m.emoji_json) || [])],
289 attachment: AP.timelineAttachments(m.media_json),
290 // FEP-633c: what kind of message this is. The wave is a gentle nudge from
291 // a guardian; the help request is the buoy. Both render differently.
292 'shaer:wave': m.wave ? true : undefined,
293 'shaer:helpRequest': m.help_request ? true : undefined,
294 'shaer:quote': AP.timelineQuote(m.quote_json),
295 'shaer:author': (m.actor_name || m.actor_handle || m.actor_icon) ? {
296 name: m.actor_name || undefined, handle: m.actor_handle || undefined,
297 icon: m.actor_icon || undefined, url: m.actor_url || undefined,
298 emojis: (() => { try { return m.actor_emoji_json ? JSON.parse(m.actor_emoji_json) : undefined; } catch { return undefined; } })(),
299 } : undefined,
300 'shaer:embed': embedsAllowed ? AP.timelineEmbed(m.embed_json, { playback: playbackAllowed }) : undefined,
301 },
302 }));
[55eca8b]303 // Inbound REPLIES on your own posts: stored as interactions (the web's
304 // comment machinery), never as mentions, so this read missed them and a
305 // friend's reply arrived everywhere except in your app (Robins melding,
306 // 30-7). Same shape as the other legs; media/quotes ride the stored JSON.
307 const replies = AP.getReplyMessages(auth.site.slug, 60).map((m) => ({
308 id: `${m.object_uri}#create`,
309 type: 'Create',
310 actor: m.actor_uri,
311 published: AP.isoStamp(m.published || m.created_at),
312 object: {
313 id: m.object_uri,
314 type: 'Note',
315 attributedTo: m.actor_uri,
316 content: AP.stripLeadingMentions(m.content),
317 inReplyTo: m.parent_uri || `${base}/ap/notes/${m.post_id}`,
318 published: AP.isoStamp(m.published || m.created_at),
319 to: [me],
320 tag: [{ type: 'Mention', href: me, name: myHandle }, ...(AP.timelineEmojis(m.emoji_json) || [])],
321 attachment: AP.timelineAttachments(m.media_json),
322 'shaer:quote': AP.timelineQuote(m.quote_json),
323 'shaer:author': (m.actor_name || m.actor_handle || m.actor_icon) ? {
324 name: m.actor_name || undefined, handle: m.actor_handle || undefined,
325 icon: m.actor_icon || undefined, url: m.actor_url || undefined,
326 emojis: (() => { try { return m.actor_emoji_json ? JSON.parse(m.actor_emoji_json) : undefined; } catch { return undefined; } })(),
327 } : undefined,
328 'shaer:embed': embedsAllowed ? AP.timelineEmbed(m.embed_json, { playback: playbackAllowed }) : undefined,
329 },
330 }));
[6a99668]331 // Your OWN sent notes (replies and direct messages, ap_outbox): without
332 // them a reply existed everywhere except in your own app, Messages showed
333 // half a conversation, and a retry ran into the duplicate guard (Robins
334 // melding, 30-7). Served like the other legs: same shape, one parser.
335 const mine = AP.selfAuthor(base, auth.site);
336 const sent = AP.getSentNotes(base, auth.site, 60).map((n) => ({
337 id: `${n.id}#create`,
338 type: 'Create',
339 actor: me,
340 published: n.published,
341 // The leading mention anchor is addressing, not prose (the DM leg strips
342 // it the same way); the Mention tags built from the full content stay.
343 object: { ...n, content: AP.stripLeadingMentions(n.content), 'shaer:author': mine },
344 }));
345 // Newest first over all legs, so the app can keep treating this as one feed.
[55eca8b]346 const items = [...posts, ...messages, ...replies, ...sent].sort((a, b) => String(b.published || '').localeCompare(String(a.published || '')));
[0cea12b]347 AP.sendAP(res, {
348 '@context': AP.AP_CONTEXT,
349 id: `${base}/ap/users/${auth.site.slug}/inbox`,
350 type: 'OrderedCollection',
[e27b8db]351 // What this account may do with what is in here (FEP-633c 5.6). Owner-only
352 // by construction, and never on the public actor document: it says
353 // something about a child, and only the child and its guardians need it.
354 'shaer:capabilities': {
355 'shaer:externalEmbeds': embedsAllowed,
356 'shaer:externalPlayback': playbackAllowed,
357 // Leaving the app is the same decision as playing inside it: with the
358 // gate shut a link is shown but not followed, so the door is closed too
359 // and not just the picture over it.
360 'shaer:externalLinks': playbackAllowed,
361 },
[0cea12b]362 totalItems: items.length,
363 orderedItems: items,
364 });
365});
366
[e6c6e6f]367// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
368// The actor advertises endpoints.uploadMedia; this implements it. A bearer
369// scoped to this site uploads one image/audio/video (multipart field "file",
370// AP convention) into the same store the reply editor uses, and gets back
371// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
372const AP_MEDIA_DIR = path.resolve(
373 process.env.REPLY_MEDIA_PATH ||
374 path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'storage', 'media', 'reply-media')
375);
376fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
377const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
378const apMediaUpload = multer({
379 storage: multer.diskStorage({
380 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
381 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
382 }),
383 limits: { fileSize: 32 * 1024 * 1024 },
384 fileFilter: (req, file, cb) => {
385 const ext = path.extname(file.originalname || '').toLowerCase();
386 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
387 cb(null, true);
388 },
389});
390router.post('/ap/users/:slug/uploadMedia', (req, res) => {
391 const auth = OAuth.verifyBearer(req.headers.authorization);
392 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
393 apMediaUpload.single('file')(req, res, (err) => {
394 if (err) return res.status(400).json({ error: err.message });
395 if (!req.file) return res.status(400).json({ error: 'No file' });
396 const mime = String(req.file.mimetype || '');
397 if (!/^(image|audio|video)\//.test(mime)) {
398 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
399 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
400 }
[7d01696]401 // A video gets a poster frame next to it (shaer-zowq), best-effort and
402 // out of band: ffmpeg pulls one frame at 1s into <name>.poster.jpg. On a
403 // machine without ffmpeg nothing happens and nothing breaks; the clients
404 // fall back to extracting a frame natively.
405 if (mime.startsWith('video/')) {
[79f00c5]406 // The bundled static build (ffmpeg-static) does the work, exactly like
407 // VideoCoverService and AudioTranscoder already do: Klonkt SHIPS its
408 // ffmpeg (Robins opmerking, 30-7), so nothing needs installing on any
409 // machine. Soft dependency + best-effort: absent stays silent, and
410 // FFMPEG_PATH can still override for an operator who wants a newer one.
411 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
412 const bin = process.env.FFMPEG_PATH || ff.default;
413 if (!bin) return;
[7d01696]414 const poster = req.file.path + '.poster.jpg';
[79f00c5]415 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-ss', '1', '-i', req.file.path, '-frames:v', '1', '-vf', "scale='min(640,iw)':-2", poster],
[7d01696]416 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] poster failed:', e.message); });
417 }).catch(() => { /* never blocks the upload */ });
418 }
[6dd26e5]419 // Audio gets the same courtesy (Robins vraag, 30-7: vrolijk de kale
420 // audio-tegel op): ffmpeg draws the waveform into <name>.poster.png.
421 // White on transparent, so the tile's own gradient stays the backdrop
[1f640ff]422 // and every audio post keeps its own hue. The shape is bars, not the
423 // raw hairy wave (Robins tweede vraag): peak and average sampled into
424 // 57 columns (soft tip over bright core), blown up nearest-neighbor to
425 // 14px bars, and drawgrid ERASES 5px gaps (c=black@0 + replace=1 writes
426 // transparent pixels; h=2*ih keeps horizontal grid lines out of frame).
[6dd26e5]427 if (mime.startsWith('audio/')) {
428 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
429 const bin = process.env.FFMPEG_PATH || ff.default;
430 if (!bin) return;
431 const poster = req.file.path + '.poster.png';
[1f640ff]432 const graph = '[0:a]aformat=channel_layouts=mono,asplit[a][b];'
433 + '[a]showwavespic=s=57x256:colors=white@0.5:filter=peak:scale=sqrt:draw=full[pk];'
434 + '[b]showwavespic=s=57x256:colors=white:filter=average:scale=sqrt:draw=full[av];'
435 + '[pk][av]overlay=format=auto,scale=798:256:flags=neighbor,drawgrid=w=14:h=2*ih:t=5:c=black@0:replace=1';
436 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-i', req.file.path, '-filter_complex', graph, '-frames:v', '1', poster],
[6dd26e5]437 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] waveform failed:', e.message); });
438 }).catch(() => { /* never blocks the upload */ });
439 }
[e6c6e6f]440 res.status(201).json({
441 url: '/media/reply-media/' + req.file.filename,
442 mediaType: mime,
443 name: String(req.file.originalname || '').slice(0, 120),
444 });
445 });
446});
447
[4407c67]448// ── Followers (count-only public, full for the owner) ─────────────
449// A C2S bearer scoped to this site (the account owner) gets the real actor
450// URIs so their own client can build a friends list; everyone else gets the
451// count only (privacy).
[30871c1]452// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
453// Returns true and sets the response headers when the owner asked for it.
454function wantsEnriched(req, res) {
455 res.set('Vary', 'Prefer'); // enriched and bare are two representations
456 if (AP.prefersEnriched(req.get('Prefer'))) {
457 res.set('Preference-Applied', 'return=representation');
458 return true;
459 }
460 return false;
461}
462
[6bd25d1]463router.get('/ap/users/:slug/followers', (req, res) => {
[4407c67]464 const auth = OAuth.verifyBearer(req.headers.authorization);
465 const owner = auth && auth.site.slug === req.params.slug;
466 const site = owner ? auth.site : publicSite(req.params.slug);
[6bd25d1]467 if (!site) return res.status(404).end();
[4407c67]468 if (owner) {
[7922694]469 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
[30871c1]470 // Default = bare references; enrich only when the client asks (FEP-9876).
471 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
[4407c67]472 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items));
473 }
[6bd25d1]474 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
475 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n));
476});
477
[4407c67]478// ── Following (count-only public, full for the owner) ─────────────
[f2796d3]479router.get('/ap/users/:slug/following', (req, res) => {
[4407c67]480 const auth = OAuth.verifyBearer(req.headers.authorization);
481 const owner = auth && auth.site.slug === req.params.slug;
482 const site = owner ? auth.site : publicSite(req.params.slug);
[f2796d3]483 if (!site) return res.status(404).end();
[4407c67]484 if (owner) {
[30871c1]485 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
[4407c67]486 let items = [];
[30871c1]487 try {
488 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);
489 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
490 } catch { /* table may not exist */ }
[4407c67]491 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items));
492 }
[f2796d3]493 let n = 0;
494 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
495 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n));
496});
497
[75bda38]498// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
499router.get('/ap/users/:slug/featured', (req, res) => {
500 const site = publicSite(req.params.slug);
501 if (!site) return res.status(404).end();
[2af2e69]502 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
503 // last-processed-first). So we emit it reversed (lowest pin priority first,
504 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
[75bda38]505 const posts = db.prepare(
[a9da2c0]506 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, c2s_attachments, published_at, created_at
[75bda38]507 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
508 AND pinned IS NOT NULL AND pinned > 0
[2af2e69]509 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
[75bda38]510 ).all(site.id);
511 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts));
512});
513
[6bd25d1]514// ── Note ──────────────────────────────────────────────────────────
515router.get('/ap/notes/:id', (req, res) => {
516 const post = db.prepare(
517 "SELECT * FROM posts WHERE id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
518 ).get(req.params.id);
[55bc7f9]519 if (!post) {
520 // Could be one of OUR outbound replies (ap_outbox), not a post.
521 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
[49edc72]522 if (!note) return res.status(404).end();
523 if (!AP.apWants(req)) {
524 // A browser hit a reply's AP URL → send them to the source it replies to
525 // (where the post + its reactions live), falling back to the site home.
526 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
527 ? note.inReplyTo : (baseUrl(req) + '/');
528 return res.redirect(302, src);
529 }
[d3b9f68]530 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[55bc7f9]531 }
[6bd25d1]532 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
533 if (!site) return res.status(404).end();
[49edc72]534 const note = AP.buildNote(baseUrl(req), site, post);
535 if (!AP.apWants(req)) {
536 // A browser hit a post's AP note URL → send them to the human post page
537 // (which shows the post + its "from the fediverse" reactions).
538 return res.redirect(302, note.url || (baseUrl(req) + '/'));
539 }
[d3b9f68]540 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
[6bd25d1]541});
542
[d7526bd]543// ── Replies collection ── lets remote servers fetch a post's whole thread.
544router.get('/ap/notes/:id/replies', (req, res) => {
545 const base = baseUrl(req);
546 const items = AP.getReplyUris(base, req.params.id);
547 AP.sendAP(res, {
[d3b9f68]548 '@context': AP.AP_CONTEXT,
[d7526bd]549 id: `${base}/ap/notes/${req.params.id}/replies`,
550 type: 'OrderedCollection',
551 totalItems: items.length,
552 orderedItems: items,
553 });
554});
555
556// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
557router.get('/.well-known/nodeinfo', (req, res) => {
558 res.type('application/json');
559 res.set('Cache-Control', 'public, max-age=3600');
560 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
561});
562router.get('/nodeinfo/2.1', (req, res) => {
563 let users = 0; let posts = 0;
[f2796d3]564 // "users" = public AP actors (sites), not the admin/member account rows.
565 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
[d7526bd]566 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
567 res.type('application/json; charset=utf-8');
568 res.set('Cache-Control', 'public, max-age=600');
569 res.send(JSON.stringify({
570 version: '2.1',
571 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
572 protocols: ['activitypub'],
573 services: { inbound: [], outbound: [] },
574 openRegistrations: false,
575 usage: { users: { total: users }, localPosts: posts },
576 metadata: { nodeName: 'Klonkt' },
577 }));
578});
579
[5bf63b7]580// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
581const apJson = express.json({
582 type: ['application/activity+json', 'application/ld+json', 'application/json'],
583 limit: '1mb',
584 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
585});
[75ab393]586router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
[5bf63b7]587 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
588 catch (e) { console.warn('[AP inbox] error:', e.message); return res.status(202).end(); }
[6bd25d1]589});
590
[dd568e7]591// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
592// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
593// the normal delivery machinery. The token is scoped to one user+site (OAuth
594// consent), so it must match the slug in the URL. (Declared after apJson, which
595// this shares with the inbox handler.)
596router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
597 const auth = OAuth.verifyBearer(req.headers.authorization);
598 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
599 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
600 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
601
602 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
603 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
604 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
605 if (out.status === 201 && out.url) res.set('Location', out.url);
606 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url });
607});
608
[6bd25d1]609export default router;
Note: See TracBrowser for help on using the repository browser.