source: Klonkt/src/routes/activitypub.js@ 26c5f71

main
Last change on this file since 26c5f71 was 26c5f71, checked in by Bart <bart@โ€ฆ>, 5 weeks ago

WebFinger: een kale host vindt de primaire actor

acct:<host>@<host> is hoe Shaer een Ward adresseert zonder iemands slug te
kennen, maar WebFinger zocht het gebruikersdeel alleen op als site-slug. Een
kale host gaf dus altijd een 404, hoe je hem ook spelde.

Daarbovenop: ๐Ÿฉต.is.wildenvrij.nl en xn--zz9h.is.wildenvrij.nl zijn รฉรฉn host.
Een geplakte URL wordt door elke URL-parser stil gepunycode, een getypte
handle niet. asciiHost() vergelijkt via WHATWG URL, dus beide spellingen
komen bij dezelfde actor uit, en PUBLIC_BASE_URL mag ook beide vormen.

Zes tests, waarvan twee de terugval bewaken: een onbekende gebruiker blijft
404 en een kale host die niet van ons is ook. Anders koppelt een typefout een
kind stilletjes aan het verkeerde account.

Co-Authored-By: Claude Opus 5 <claude@โ€ฆ>

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