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

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

Volg-QR draagt een https-URL met een tussenpagina

Robins melding (31-7): de camera-app kan de QR wel lezen maar biedt een
onbekend scheme niet aan om te openen; Google Lens behandelt alles
behalve https als platte tekst. De QR codeert nu de https-URL van een
kleine tussenpagina (/ap/users/:slug/follow) met een grote Open in
Shaer-knop die alsnog share:social/follow/AP/@handle afvuurt: vanuit de
browser werkt het custom scheme wel (BROWSABLE intent-filter; Safari
prompt op iOS). Wie geen Shaer heeft ziet de handle gewoon staan.

Changed files:
src/routes/activitypub.js

  • follow-qr.png codeert de https-URL van de tussenpagina
  • /ap/users/:slug/follow: de tussenpagina (zelfstandige html, geen externe assets)

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

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