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

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

A block now leaves the house: Block out, Undo(Block) back

Blocking was purely local — row in ap_blocks, purge the cached content,
drop the follower — and the other side never heard about it. The hub
kept the channel and every post, because nothing told it and its
unsigned crawl kept reading the public outbox (seen on dev.klonkt.com,
21-8).

Now blocking delivers a Block to the blocked actor's inbox and
unblocking an Undo(Block), so the way back stays open. Delivery can
never hold up the block itself: the row is written first and a
failed delivery is swallowed. Domain blocks send nothing — no inbox to
address.

Second door: a signed reader we block gets the same 404 on /ap/notes/:id
that a stranger gets, matching what the outbox already did. Unsigned
callers stay anonymous to us and keep the public view; that is what the
Block delivery is for.

Co-Authored-By: Claude Fable 5 <noreply@…>

  • Property mode set to 100644
File size: 79.2 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 * as Migration from '../services/MigrationService.js';
23import { getPrimarySite } from '../middleware/site.js';
24import multer from 'multer';
25import path from 'path';
26import fs from 'fs';
27import { randomUUID } from 'crypto';
28import { mediaDir } from '../config/paths.js';
29
30const router = express.Router();
31
32/**
33 * Welke pagina vraagt de lezer? (shaer-sk4)
34 *
35 * Hier stond `!!req.query.page` -- of de parameter er STAAT, niet welke. Daardoor
36 * gaf ?page=2 en ?page=99 allemaal pagina 1, en noemde het antwoord zichzelf ook
37 * nog pagina 1. Onleesbaar getal of geen parameter: dan de wortel.
38 */
39function paginaNr(req) {
40 if (req.query.page === undefined) return false;
41 const n = Math.floor(Number(req.query.page));
42 return Number.isFinite(n) && n > 0 ? n : 1;
43}
44// The whole fediverse layer can be turned off (solo "no federation" mode):
45// then /ap/*, WebFinger and NodeInfo are simply gone — the site is undiscoverable
46// and unfederatable. CRITICAL: this router is mounted at root (app.use(apRoutes)), so a
47// blanket res.status(404) here ran for EVERY request and 404'd the whole site when AP was
48// off. Use next('router') to SKIP this router entirely and let the normal routes handle it
49// (the /ap/* paths then fall through to the app's normal 404, which is correct).
50router.use((req, res, next) => { if (!apEnabled()) return next('router'); next(); });
51// Generous per-IP baseline over the AP-READ paths. The inbox POST gets an
52// additional, tighter cap inline (it triggers outbound fetches).
53//
54// PADGEBONDEN, niet router.use kaal (Barts 429-jacht, 9-8): deze router is op
55// de ROOT gemonteerd, dus een kale use() draait voor ELKE request van de hele
56// site -- pagina's, media, avatars, de PWA. De guardian-PWA met honderd
57// ward-avatars leegde zo in seconden een emmer die "voor /ap-reads" heette,
58// en hield hem leeg: vandaar een Too many requests die niet overging. De
59// kijkbuis die dit vond: een lege /ap-teller naast remaining: 0.
60router.use(['/ap', '/.well-known', '/nodeinfo'], apReadLimiter);
61let _ver = '1.0.0';
62try { _ver = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url))).version || _ver; } catch { /* keep default */ }
63
64const baseUrl = (req) => (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
65const hostOf = (req) => { try { return new URL(baseUrl(req)).host; } catch { return req.get('host'); } };
66const publicSite = (slug) => db.prepare('SELECT * FROM sites WHERE slug = ? AND (is_public IS NULL OR is_public = 1)').get(slug);
67// The primary site, via the one source of truth in middleware/site.js — which
68// falls back to the oldest site when nothing carries the is_primary flag. This
69// route used to keep its own is_primary-only copy, so a fresh instance whose
70// site was never flagged served its HTML at / (that resolver falls back) while
71// WebFinger and the actor route insisted it had no primary at all.
72const primarySlug = () => { const s = getPrimarySite(); return s && s.slug; };
73// A hostname as a human types it and as DNS stores it are the same host:
74// `🩵.is.wildenvrij.nl` IS `xn--zz9h.is.wildenvrij.nl`. WHATWG URL does the IDNA,
75// so compare the ASCII form and never the bytes the client happened to send.
76const asciiHost = (h) => {
77 try { return new URL(`https://${h}`).host.toLowerCase(); } catch { return String(h).trim().toLowerCase(); }
78};
79
80// ── host-meta ─────────────────────────────────────────────────────
81// De klassieke eerste stap van WebFinger (RFC 6415): een client die het
82// webfinger-pad niet wil raden, vraagt hier de sjabloon op. Mastodon serveert
83// dit ook, en een client die ermee begint kreeg bij ons een 404 en gaf het dan
84// op -- terwijl de webfinger eronder gewoon werkte.
85//
86// Twee vormen, want beide worden in het wild gevraagd: XRD (het origineel) en
87// JRD (de JSON-variant, RFC 6415 §3).
88const lrddSjabloon = (req) => `${baseUrl(req)}/.well-known/webfinger?resource={uri}`;
89
90router.get('/.well-known/host-meta', (req, res) => {
91 res.type('application/xrd+xml; charset=utf-8');
92 res.set('Cache-Control', 'public, max-age=86400');
93 res.send(`<?xml version="1.0" encoding="UTF-8"?>
94<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
95 <Link rel="lrdd" template="${lrddSjabloon(req)}"/>
96</XRD>`);
97});
98
99router.get('/.well-known/host-meta.json', (req, res) => {
100 res.type('application/jrd+json; charset=utf-8');
101 res.set('Cache-Control', 'public, max-age=86400');
102 res.send(JSON.stringify({ links: [{ rel: 'lrdd', template: lrddSjabloon(req) }] }));
103});
104
105// ── WebFinger ─────────────────────────────────────────────────────
106/**
107 * De `resource` uitpakken tot de gebruiker die bedoeld wordt.
108 *
109 * RFC 7033 schrijft een URI voor, en `acct:` is de nette vorm -- maar in het
110 * wild komen er vier spellingen langs, en drie daarvan wezen we af met een 400
111 * terwijl we prima wisten wie er bedoeld werd:
112 *
113 * acct:naam@host de nette vorm (Mastodon stuurt altijd deze)
114 * naam@host zonder schema
115 * @naam@host met het apenstaartje dat mensen intypen
116 *
117 * Coulant zijn kost hier niets: het antwoord noemt altijd de canonieke
118 * `acct:`-vorm terug, dus een slordige vraag levert geen slordig antwoord.
119 *
120 * De ACTOR-URI als resource (die Mastodon ook accepteert) hoort hier NIET bij,
121 * bewust: test/webfinger-bare-host.test.js legt vast dat die een 400 geeft.
122 * Dat is een uitgesproken keuze van eerder en geen vergetelheid, dus die draai
123 * ik niet om als bijvangst van een coulance-fix.
124 */
125function webfingerGebruiker(resource) {
126 const r = String(resource || '').trim();
127 if (!r) return null;
128 const acct = r.match(/^(?:acct:)?@?([^@/]+)@(.+)$/i);
129 return acct ? acct[1] : null;
130}
131
132/**
133 * Is dit een vraag naar de WORTEL van deze server?
134 *
135 * FEP-61cf laat de home instance webfingeren op "the root URL of the destination
136 * site" om ons token-endpoint te vinden. Dat is een URL en geen `acct:`, dus hij
137 * strandde hierboven op de 400 -- terwijl een ACTOR-URI met een pad wel degelijk
138 * een 400 hoort te blijven (dat legt test/webfinger-bare-host.test.js vast, en
139 * dat is een uitgesproken keuze van eerder). Vandaar: alleen origin + '/' telt,
140 * alles met een pad niet.
141 */
142function isEigenWortel(resource, req) {
143 const r = String(resource || '').trim();
144 if (!/^https?:\/\//i.test(r)) return false;
145 try {
146 const u = new URL(r);
147 if (u.pathname && u.pathname !== '/') return false;
148 if (u.search || u.hash) return false;
149 return asciiHost(u.host) === asciiHost(hostOf(req));
150 } catch { return false; }
151}
152
153router.get('/.well-known/webfinger', (req, res) => {
154 if (isEigenWortel(req.query.resource, req)) {
155 res.type('application/jrd+json; charset=utf-8');
156 res.set('Cache-Control', 'public, max-age=300');
157 return res.send(JSON.stringify({
158 subject: baseUrl(req) + '/',
159 links: [
160 // Waar een home instance ondertekend een token mag ophalen (FEP-61cf
161 // stap 2/3). Host-niveau en niet per site: het token zegt WIE er binnen
162 // is, niet waar hij binnen mag -- dat besluit valt bij de poort.
163 { rel: 'http://purl.org/openwebauth/v1', href: baseUrl(req) + '/owa/token' },
164 ],
165 }));
166 }
167 const user = webfingerGebruiker(req.query.resource);
168 if (!user) return res.status(400).type('text/plain').send('bad resource');
169 let site = publicSite(user);
170 // `acct:<host>@<host>` asks for this server's primary actor — the convention
171 // Shaer's Handle relies on so a Ward is reachable without knowing anyone's
172 // slug. Typing `🩵.is.wildenvrij.nl`, pasting `https://🩵.is.wildenvrij.nl`
173 // (which the client's URL parser silently punycodes) and sending the xn--
174 // form by hand are three spellings of one address; all arrive here with the
175 // host sitting in the user position, and all must find the same actor.
176 if (!site && asciiHost(user) === asciiHost(hostOf(req))) {
177 const slug = primarySlug();
178 if (slug) site = publicSite(slug);
179 }
180 if (!site) return res.status(404).end();
181 res.type('application/jrd+json; charset=utf-8');
182 res.set('Cache-Control', 'public, max-age=300');
183 const actorUri = AP.actorId(baseUrl(req), site.slug);
184 const profileUrl = baseUrl(req) + (site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`);
185 res.send(JSON.stringify({
186 subject: `acct:${site.slug}@${hostOf(req)}`,
187 aliases: [actorUri, profileUrl],
188 links: [
189 { rel: 'self', type: 'application/activity+json', href: actorUri },
190 { rel: 'http://webfinger.net/rel/profile-page', type: 'text/html', href: profileUrl },
191 // FEP-61cf: hier stuurt een doelsite deze gebruiker heen om zich te
192 // bewijzen. Zonder deze regel valt zo'n site terug op /magic geraden --
193 // wat toevallig klopt, maar raden is geen afspraak.
194 { rel: 'http://purl.org/openwebauth/v1#redirect', href: baseUrl(req) + '/magic' },
195 ],
196 }));
197});
198
199// ── Actor ─────────────────────────────────────────────────────────
200router.get('/ap/users/:slug', (req, res) => {
201 const site = publicSite(req.params.slug);
202 if (!site) return res.status(404).end();
203 if (!AP.apWants(req)) {
204 // A browser hit the AP actor URL → send them to the human profile.
205 const human = site.slug === primarySlug() ? '/' : `/user/${encodeURIComponent(site.slug)}`;
206 return res.redirect(302, baseUrl(req) + human);
207 }
208 site.primary_slug = primarySlug();
209 AP.sendAP(res, AP.buildActor(baseUrl(req), site));
210});
211
212// ── Outbox ────────────────────────────────────────────────────────
213router.get('/ap/users/:slug/outbox', async (req, res) => {
214 const site = publicSite(req.params.slug);
215 if (!site) return res.status(404).end();
216 // Authorized fetch (30-7): who is asking decides what they see.
217 // - the owner's own app (bearer) and a verified accepted follower or
218 // guardian get the friends-only history too, so a NEW friend's backfill
219 // brings the past along (Robins besluit: vrienden krijgen de
220 // geschiedenis mee);
221 // - a verified caller this instance BLOCKS gets an EMPTY collection, not
222 // even the public set: a block is a closed door, and a signed fetch is
223 // the caller knocking with their name on it;
224 // - everyone else gets the public collection, exactly as before.
225 const bearer = OAuth.verifyBearer(req.headers.authorization);
226 let verifiedActor = null;
227 if (!bearer && req.headers['signature']) {
228 const verified = await AP.verifyRequest(req).catch(() => null);
229 verifiedActor = verified && verified.id;
230 }
231 const audience = AP.outboxAudience(req.params.slug, {
232 bearerSlug: bearer ? bearer.site.slug : null,
233 verifiedActor,
234 });
235 if (audience === 'blocked') {
236 return AP.sendAP(res, AP.buildOutbox(baseUrl(req), site, [], [], { page: paginaNr(req) }), 'private, no-store');
237 }
238 // ECHT DOORBLADEREN (shaer-sk4). Hier stonden twintig posts uit SQL met een
239 // tweede kap van twintig eroverheen: alles daarvoor was niet op een volgende
240 // pagina maar helemaal onbereikbaar. outboxSlice pagineert over de UNION van
241 // posts en tracks, want die vlechten op datum en zijn met twee losse queries
242 // niet te offsetten.
243 //
244 // De tracks gaan mee voor iedereen die de deur door mag; de blocked-tak
245 // hierboven levert bewust een outbox ZONDER posts en zonder tracks.
246 const nr = paginaNr(req);
247 const { posts, tracks, totaal } = AP.outboxSlice(site.id, {
248 fanOnly: audience === 'friend',
249 offset: (Math.max(1, nr || 1) - 1) * AP.PAGINA_GROOTTE,
250 limit: AP.PAGINA_GROOTTE,
251 });
252 // FEP-1580: de instantie waar dit account naartoe verhuisd is krijgt de
253 // RAUWE inhoud, met [[track:]] en [[playlist:]] er nog in. Zij is een
254 // Klonkt en rendert die zelf tot een speler. De gebakken variant komt
255 // daar aan als tekstlink, en is bovendien onherstelbaar afgeknot: het
256 // bakken plakt hooguit vier titels aan.
257 const rauweInhoud = verifiedActor ? AP.isMoveTarget(site.slug, verifiedActor) : false;
258 const ob = AP.buildOutbox(baseUrl(req), site, posts, tracks, { page: nr, totalItems: totaal, alGesneden: true, rauweInhoud });
259 if (audience === 'friend') {
260 // The owner's app builds its feed from this leg, and every note here is
261 // by the site itself, so give it a byline too (avatar + name): de
262 // ingesloten actor in attributedTo, net als de tijdlijn.
263 const me = AP.selfAuthor(baseUrl(req), site);
264 // De kaart op je eigen post (shaer-k3f): dezelfde quote/preview die de
265 // tijdlijn voor andermans posts draagt, uit de snapshots die
266 // deliverCreate bij het publiceren opsloeg. Op note-id gekoppeld, want
267 // buildOutbox sorteert en mengt tracks erdoorheen. De embed alleen voor de
268 // BEARER en langs zijn eigen poort: een remote vriend krijgt hem niet
269 // (diens server resolvet en gate zelf bij ontvangst), en een ward zonder
270 // open embeds-poort krijgt hem hier net zo min als in de tijdlijn.
271 const byNote = new Map(posts.map((p) => [AP.noteId(baseUrl(req), p.id), p]));
272 const bearerEmbeds = bearer ? (() => {
273 const isWard = (() => { try { return Guardianship.listGuardians(bearer.site.slug).length > 0; } catch { return false; } })();
274 return Guardianship.externalEmbedsAllowed(bearer.site.external_embeds, isWard)
275 ? { playback: Guardianship.externalPlaybackAllowed(bearer.site.external_playback, isWard) } : null;
276 })() : null;
277 for (const it of ob.orderedItems) {
278 if (it && it.object && typeof it.object === 'object') {
279 it.object.attributedTo = AP.actorObject(
280 (typeof it.object.attributedTo === 'string' ? it.object.attributedTo : undefined) || AP.actorId(baseUrl(req), site.slug),
281 me,
282 );
283 const row = byNote.get(it.object.id);
284 if (row) {
285 it.object.quote = AP.quoteObject(row.quote_json);
286 if (bearerEmbeds) {
287 it.object.preview = AP.previewObject(row.embed_json, { playback: bearerEmbeds.playback });
288 }
289 }
290 }
291 }
292 }
293 AP.sendAP(res, ob, audience === 'friend' ? 'private, no-store' : undefined);
294});
295
296// ── Follow-QR (Robins verzoek, 31-7) ──────────────────────────────
297// The QR carries an HTTPS url, not the share: scheme: camera apps (Google
298// Lens voorop) treat unknown schemes as plain text and only offer to OPEN
299// https links (Robins melding, 31-7). The url lands on the interstitial
300// below, whose one big button fires the share: scheme — from a browser the
301// custom scheme DOES work (BROWSABLE intent-filter; Safari prompts).
302// Public on purpose: it encodes only the public handle, and the app's plain
303// image loaders carry no bearer.
304router.get('/ap/users/:slug/follow-qr.png', async (req, res) => {
305 const site = db.prepare('SELECT slug FROM sites WHERE slug = ?').get(req.params.slug);
306 if (!site) return res.status(404).end();
307 try {
308 const { default: QRCode } = await import('qrcode');
309 const png = await QRCode.toBuffer(`${baseUrl(req)}/ap/users/${encodeURIComponent(site.slug)}/follow`, { width: 600, margin: 1 });
310 res.set('Content-Type', 'image/png');
311 res.set('Cache-Control', 'public, max-age=86400');
312 res.send(png);
313 } catch (e) {
314 console.warn('[AP] follow-qr failed:', e && e.message);
315 res.status(500).end();
316 }
317});
318
319// The interstitial the QR opens: one big button into Shaer, and the handle
320// in plain sight for whoever has no Shaer (yet).
321router.get('/ap/users/:slug/follow', (req, res) => {
322 const site = db.prepare('SELECT slug, title FROM sites WHERE slug = ?').get(req.params.slug);
323 if (!site) return res.status(404).end();
324 const host = new URL(baseUrl(req)).host;
325 const esc = (t) => String(t).replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]));
326 const handle = `@${site.slug}@${host}`;
327 const name = esc(site.title || site.slug);
328 res.set('Cache-Control', 'public, max-age=3600');
329 res.send(`<!doctype html><html lang="en"><head><meta charset="utf-8">
330<meta name="viewport" content="width=device-width, initial-scale=1">
331<title>Follow ${name}</title>
332<style>
333 body { font-family: system-ui, sans-serif; margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
334 background: linear-gradient(160deg, #5A32E6, #2a1a5e); color: #fff; text-align: center; }
335 main { padding: 32px; max-width: 420px; }
336 h1 { font-size: 1.5rem; margin: 0 0 .4rem; }
337 .handle { opacity: .85; font-family: ui-monospace, monospace; word-break: break-all; }
338 a.go { display: block; margin: 28px auto 14px; padding: 16px 28px; border-radius: 999px; background: #fff; color: #2a1a5e;
339 font-weight: 700; font-size: 1.15rem; text-decoration: none; }
340 p.small { font-size: .85rem; opacity: .75; line-height: 1.5; }
341</style></head><body><main>
342 <h1>Follow ${name}</h1>
343 <div class="handle">${esc(handle)}</div>
344 <a class="go" href="share:social/follow/AP/${esc(handle)}">Open in Shaer</a>
345 <p class="small">No Shaer? Any fediverse app can follow ${esc(handle)}.</p>
346</main></body></html>`);
347});
348
349/** De byline-gegevens uit een tijdlijnrij, langs de emoji-poort. */
350function authorInfoFrom(r, prefix, gates) {
351 const info = {
352 name: r[`${prefix}name`] || undefined, handle: r[`${prefix}handle`] || undefined,
353 icon: r[`${prefix}icon`] || undefined, url: r[`${prefix}url`] || undefined,
354 emojis: (() => { try { return r[`${prefix}emoji_json`] ? JSON.parse(r[`${prefix}emoji_json`]) : undefined; } catch { return undefined; } })(),
355 };
356 return (info.name || info.handle || info.icon) ? gates.gateAuthor(info) : undefined;
357}
358
359// ── Een tijdlijnpost als AS2-item: EEN beschrijving van de kaartvorm ──
360//
361// Zelfde reden als messageItem hieronder: de volledige lezing en de
362// verschil-lezing bouwen dezelfde kaart, en twee beschrijvingen lopen uit de
363// pas zonder dat iemand het merkt.
364function timelineItem(t, { p, reactions }) {
365 const authorInfo = (r, prefix) => authorInfoFrom(r, prefix, p);
366 const {
367 embedsAllowed, playbackAllowed, imagesAllowed, musicAllowed, quotesAllowed, emojiAllowed,
368 } = p;
369 const reacties = reactions || new Map();
370 const auteur = authorInfo(t, 'author_');
371 const booster = authorInfo(t, 'reblog_');
372 const boosterUri = t.reblog_url || t.reblog_handle || undefined;
373 return {
374 id: `${t.id}#create`,
375 // EEN BOOST IS EEN ANNOUNCE (shaer-nmw): een Create met een
376 // zijkanaal-property was onze uitvinding; de wrapper is de standaard, en
377 // elke AP-client leest hem al.
378 type: booster ? 'Announce' : 'Create',
379 actor: booster ? (AP.actorObject(boosterUri || t.author_uri, booster)) : t.author_uri,
380 published: t.published || t.created_at || undefined,
381 object: {
382 id: t.id,
383 type: 'Note',
384 // AS2 staat een INGESLOTEN actor toe; dan heeft elke client de byline,
385 // niet alleen de onze (shaer-nmw).
386 attributedTo: AP.actorObject(t.author_uri, auteur),
387 content: t.content,
388 url: t.url || undefined,
389 published: t.published || t.created_at || undefined,
390 sensitive: !!t.nsfw,
391 summary: t.cw || undefined,
392 // Friends' media travels along (media_json → AS2 attachment), so the
393 // client renders their images/audio like own outbox posts.
394 attachment: AP.gateAttachments(AP.timelineAttachments(t.media_json), { images: imagesAllowed, audio: musicAllowed }),
395 // The note's preserved tags, so the client can render them: FEP-9098
396 // Emoji tags (:shortcode: → image) and FEP-e232 Link tags (quotes /
397 // inline object references). Combined into one `tag` array; omitted
398 // when the note has neither.
399 tag: (() => {
400 const tags = [...(emojiAllowed ? (AP.timelineEmojis(t.emoji_json) || []) : []), ...(AP.timelineObjectLinks(t.link_json) || [])];
401 return tags.length ? tags : undefined;
402 })(),
403 // Whether THIS account already liked/boosted the note, so the app's
404 // detail-view buttons show the current state (and can toggle/undo).
405 'shaer:liked': !!(reacties.get(t.id) || {}).liked,
406 'shaer:boosted': !!(reacties.get(t.id) || {}).boosted,
407 // FEP-044f: de geciteerde post als object, zodat de client een kaart
408 // rendert in plaats van een kale link. AS2 preview is diezelfde kaart
409 // voor een EXTERNE link: thumbnail, nooit de iframe van de aanbieder.
410 // Allebei weg zodra hun poort dicht staat; de speler in preview hangt
411 // aan de playback-poort.
412 quote: quotesAllowed ? AP.quoteObject(t.quote_json) : undefined,
413 preview: embedsAllowed ? AP.previewObject(t.embed_json, { playback: playbackAllowed }) : undefined,
414 },
415 };
416}
417
418/** Een inkomend antwoord op je eigen post als AS2-item. */
419function replyItem(m, { base, me, myHandle, p }) {
420 return {
421 id: `${m.object_uri}#create`,
422 type: 'Create',
423 actor: m.actor_uri,
424 published: AP.isoStamp(m.published || m.created_at),
425 object: {
426 id: m.object_uri,
427 type: 'Note',
428 attributedTo: AP.actorObject(m.actor_uri, (m.actor_name || m.actor_handle || m.actor_icon) ? p.gateAuthor({
429 name: m.actor_name || undefined, handle: m.actor_handle || undefined,
430 icon: m.actor_icon || undefined, url: m.actor_url || undefined,
431 emojis: (() => { try { return m.actor_emoji_json ? JSON.parse(m.actor_emoji_json) : undefined; } catch { return undefined; } })(),
432 }) : undefined),
433 content: AP.stripLeadingMentions(m.content),
434 inReplyTo: m.parent_uri || `${base}/ap/notes/${m.post_id}`,
435 published: AP.isoStamp(m.published || m.created_at),
436 to: [me],
437 tag: [{ type: 'Mention', href: me, name: myHandle }, ...(AP.timelineEmojis(m.emoji_json) || [])],
438 attachment: AP.timelineAttachments(m.media_json),
439 quote: p.quotesAllowed ? AP.quoteObject(m.quote_json) : undefined,
440 preview: p.embedsAllowed ? AP.previewObject(m.embed_json, { playback: p.playbackAllowed }) : undefined,
441 },
442 };
443}
444
445/** Wat deze lezer mag (FEP-633c 5.6), op EEN plek.
446 *
447 * De verschil-lezing draagt ze net zo goed: een antwoord zonder rechten zou
448 * de client naar zijn standaard laten terugvallen, en die standaard is
449 * 'alles mag'. Dan zet een gesloten poort zichzelf stil open. Dezelfde reden
450 * waarom een 304 de caps met rust laat.
451 */
452function capabilitiesOf(p, gate) {
453 return {
454 'shaer:externalEmbeds': p.embedsAllowed,
455 'shaer:externalPlayback': p.playbackAllowed,
456 // Leaving the app is the same decision as playing inside it: with the
457 // gate shut a link is shown but not followed, so the door is closed too
458 // and not just the picture over it.
459 'shaer:externalLinks': p.playbackAllowed,
460 // De rest van de familie (8-8): de app hoort VOORAF te weten wat hij mag
461 // aanbieden in plaats van het bij de eerste weigering te ontdekken. De
462 // (+) kaart leest shaer:compose al (Barts gate); de rest is er voor de
463 // schermen die nog komen. Serveren wat waar is kost hier niets.
464 'shaer:compose': p.composeAllowed,
465 'shaer:replies': p.repliesAllowed,
466 'shaer:messages': p.messagesAllowed,
467 'shaer:images': p.imagesAllowed,
468 'shaer:music': p.musicAllowed,
469 'shaer:quoteCards': p.quotesAllowed,
470 'shaer:customEmoji': p.emojiAllowed,
471 'shaer:externalThreads': p.threadsAllowed,
472 'shaer:following': p.followingAllowed,
473 // Stond in de catalogus mét kolom, en ontbrak hier: de guardian zag de
474 // poort in zijn paneel en de app van het kind heeft er nooit van gehoord.
475 // Gevonden door de pariteitstest, niet door iemand die het toevallig zag.
476 'shaer:accountMove': gate('gate_account_move'),
477 };
478}
479
480// ── De poorten van een lezer, op EEN plek (FEP-633c) ─────────────
481//
482// De inbox-lezing rekende ze inline uit. Nu er meer lezingen zijn die
483// dezelfde poorten moeten eerbiedigen (de gesprekken, de geschiedenis), zou
484// dat evenveel kopieen worden -- en een poort die op een van die plekken
485// vergeten wordt, levert stil iets uit dat dicht hoorde te staan.
486function gatesFor(site) {
487 const isWard = (() => { try { return Guardianship.listGuardians(site.slug).length > 0; } catch { return false; } })();
488 const embeds = Guardianship.externalEmbedsAllowed(site.external_embeds, isWard);
489 const gate = (col) => Guardianship.wardGateAllowed(site[col], isWard);
490 const emoji = gate('gate_custom_emoji');
491 return {
492 isWard,
493 embedsAllowed: embeds,
494 playbackAllowed: embeds && Guardianship.externalPlaybackAllowed(site.external_playback, isWard),
495 imagesAllowed: gate('gate_images'),
496 musicAllowed: gate('gate_music'),
497 quotesAllowed: gate('gate_quote_cards'),
498 emojiAllowed: emoji,
499 messagesAllowed: gate('gate_messages'),
500 composeAllowed: gate('gate_compose'),
501 repliesAllowed: gate('gate_replies'),
502 threadsAllowed: gate('external_threads'),
503 followingAllowed: gate('gate_following'),
504 // Emoji dicht raakt ook de bylines: de plaatjes in een naam komen net zo
505 // goed van een vreemde server. De naam zelf blijft, met :shortcode: als tekst.
506 gateAuthor: (a) => (a && !emoji ? { ...a, emojis: undefined } : a),
507 };
508}
509
510/**
511 * De naam waaronder deze lezer zichzelf herkent in een Mention.
512 *
513 * Via deriveHandle op de actor-URI, niet uit de slug hier opgebouwd. Dit stond
514 * er als `@${slug}@${host}` met `@${slug}` als terugval, en die terugval is een
515 * HALVE naam: zonder host zegt @dev niets op een oppervlak waar iedereen @dev
516 * kan heten. Hij ging alleen af bij een onparseerbare PUBLIC_BASE_URL -- maar
517 * dan klopt elke URI die we bouwen al niet, en is de kale actor-URI (wat
518 * deriveHandle dan teruggeeft) eerlijker dan een naam die compleet lijkt.
519 */
520function ownHandle(base, slug) {
521 return AP.deriveHandle(AP.actorId(base, slug));
522}
523
524// ── Een bericht als AS2-item: EEN beschrijving van de kaartvorm ──
525//
526// Gebruikt door de inbox-lezing en door de gesprekslezingen. Twee keer
527// opschrijven is twee vormen die uit de pas kunnen lopen, en dat merk je pas
528// als een kaart ergens anders rendert dan waar je keek.
529function messageItem(m, { base, me, myHandle, p }) {
530 return {
531 id: `${m.object_uri}#create`,
532 type: 'Create',
533 actor: m.actor_uri,
534 published: AP.isoStamp(m.published || m.created_at),
535 object: {
536 id: m.object_uri,
537 type: 'Note',
538 attributedTo: AP.actorObject(m.actor_uri, (m.actor_name || m.actor_handle || m.actor_icon) ? p.gateAuthor({
539 name: m.actor_name || undefined, handle: m.actor_handle || undefined,
540 icon: m.actor_icon || undefined, url: m.actor_url || undefined,
541 emojis: (() => { try { return m.actor_emoji_json ? JSON.parse(m.actor_emoji_json) : undefined; } catch { return undefined; } })(),
542 }) : undefined),
543 content: AP.stripLeadingMentions(m.content),
544 url: m.note_url || undefined,
545 published: AP.isoStamp(m.published || m.created_at),
546 // Addressed to us and to nobody we know of: the other recipients of a
547 // note to several people are not ours to see, so we serve what we know.
548 to: [me],
549 // The Mention is how the client recognises itself as the addressee and
550 // groups the note into a conversation. No FEP-e232 link tags here: a
551 // mention row keeps the resolved quote, not the raw tags.
552 tag: [{ type: 'Mention', href: me, name: myHandle }, ...(p.emojiAllowed ? (AP.timelineEmojis(m.emoji_json) || []) : [])],
553 attachment: AP.gateAttachments(AP.timelineAttachments(m.media_json), { images: p.imagesAllowed, audio: p.musicAllowed }),
554 // FEP-633c: what kind of message this is. The wave is a gentle nudge from
555 // a guardian; the help request is the buoy. Both render differently.
556 'shaer:wave': m.wave ? true : undefined,
557 'shaer:helpRequest': m.help_request ? true : undefined,
558 quote: p.quotesAllowed ? AP.quoteObject(m.quote_json) : undefined,
559 preview: p.embedsAllowed ? AP.previewObject(m.embed_json, { playback: p.playbackAllowed }) : undefined,
560 },
561 };
562}
563
564/** Een eigen verzonden note als AS2-item, zelfde vorm als de inbox-leg. */
565function sentItem(n, { me, mine }) {
566 return {
567 id: `${n.id}#create`,
568 type: 'Create',
569 actor: me,
570 published: n.published,
571 // The leading mention anchor is addressing, not prose (the DM leg strips
572 // it the same way); the Mention tags built from the full content stay.
573 object: {
574 ...n, content: AP.stripLeadingMentions(n.content),
575 attributedTo: AP.actorObject(typeof n.attributedTo === 'string' ? n.attributedTo : me, mine),
576 },
577 };
578}
579
580// ── Gesprekken: eerst wie, dan pas wat (shaer-frontend-yso) ──────
581//
582// Twee lezingen naast de bestaande inbox-lezing, niet in de plaats ervan: de
583// apps in het veld lezen die nog. /conversations geeft EEN rij per tegenpartij
584// -- compleet van vorm, dus de avatarhemel kan niemand kwijtraken doordat een
585// ander druk was -- en /messages geeft een gesprek met een cursor, zodat een
586// 'load more' eerlijk kan verschijnen in plaats van dat de geschiedenis stil
587// ophoudt.
588//
589// Beide lopen langs dezelfde poorten als de inbox-lezing (gatesFor) en
590// dezelfde kaartvorm (messageItem/sentItem). Messages dicht sluit ook
591// hier vreemden en vrienden, maar nooit het guardian-kanaal en nooit de boei.
592function conversationItems(req, auth, refs) {
593 const base = baseUrl(req);
594 const P = gatesFor(auth.site);
595 const me = AP.actorId(base, auth.site.slug);
596 const ctx = { base, me, myHandle: ownHandle(base, auth.site.slug), p: P };
597 const mine = AP.selfAuthor(base, auth.site);
598 const guardianUris = (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })();
599
600 const incoming = new Map(AP.messageRowsByUri(auth.site.slug, refs.filter((r) => r.direction === 'in').map((r) => r.ref))
601 .map((m) => [m.object_uri, m]));
602 // PAREN, geen losse lijst: een kop levert niet altijd een item op (dichte
603 // poort, ontbrekende rij), en dan zou de aanroeper op index koppelen en de
604 // telling aan het verkeerde gesprek hangen. Stil, en pas te zien als iemand
605 // een badge op de verkeerde naam ziet staan.
606 const pairs = [];
607 for (const r of refs) {
608 if (r.direction === 'in') {
609 const m = incoming.get(r.ref);
610 if (!m) continue;
611 if (!(P.messagesAllowed || m.help_request || guardianUris.has(m.actor_uri))) continue;
612 pairs.push({ head: r, item: messageItem(m, ctx) });
613 } else {
614 const n = AP.getOutboxNote(base, r.ref);
615 // Je eigen woorden blijven van jou: een dichte messages-poort verbergt
616 // niet wat je zelf gezegd hebt.
617 if (n) pairs.push({ head: r, item: sentItem(n, { me, mine }) });
618 }
619 }
620 return pairs;
621}
622
623router.get('/ap/users/:slug/conversations', (req, res) => {
624 const auth = OAuth.verifyBearer(req.headers.authorization);
625 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
626 const heads = AP.conversationHeads(auth.site.slug);
627 const pairs = conversationItems(req, auth, heads);
628 const items = pairs.map((x) => x.item);
629 // Ongelezen per gesprek (shaer-frontend-3tx): een COUNT, geen bijgehouden
630 // getal. Hij hangt aan het NIEUWSTE kopje van elke persoon -- er kunnen er
631 // twee zijn (zie conversationHeads) en het aantal hoort bij het gesprek, niet
632 // bij een bericht.
633 //
634 // AS2 heeft geen term voor ongelezen; dit is per-lezer-interactiestatus,
635 // dezelfde categorie als shaer:liked. Niet in totalItems persen: dat betekent
636 // 'hoeveel er zijn' en niet 'hoeveel jij nog niet zag'.
637 // De poorten van DEZE lezer, niet die van de inbox-handler: die leeft in een
638 // andere functie en heette hier per ongeluk P.
639 const poorten = gatesFor(auth.site);
640 const ongelezen = AP.unreadPerConversation(auth.site.slug, {
641 messagesAllowed: poorten.messagesAllowed,
642 guardians: (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })(),
643 });
644 const gezien = new Set();
645 for (const { head, item } of pairs) {
646 if (gezien.has(head.other)) continue;
647 gezien.add(head.other);
648 const u = ongelezen.get(head.other);
649 if (!u) continue;
650 item.object['shaer:unread'] = u.n;
651 // Een zwaai is geen aantal maar een zetje van een guardian: eigen teken.
652 if (u.wave) item.object['shaer:unreadWave'] = true;
653 }
654 AP.sendAP(res, {
655 '@context': AP.AP_CONTEXT,
656 id: `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/conversations`,
657 type: 'OrderedCollection',
658 totalItems: items.length,
659 orderedItems: items,
660 'shaer:cursor': AP.feedCursor(auth.site.slug),
661 }, 'private, no-store');
662});
663
664router.get('/ap/users/:slug/messages', (req, res) => {
665 const auth = OAuth.verifyBearer(req.headers.authorization);
666 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
667 const other = String(req.query.with || '');
668 if (!/^https?:\/\//i.test(other)) return res.status(400).json({ error: 'with must be an actor URI' });
669 const page = AP.conversationHistory(auth.site.slug, other, {
670 before: req.query.before ? String(req.query.before) : null,
671 limit: req.query.limit,
672 });
673 const items = conversationItems(req, auth, page.rows).map((x) => x.item);
674 // De paginagrootte reist mee in next: vroeg je om 30, dan hoort de volgende
675 // pagina er ook 30 te zijn. Zonder dit wordt hij stilletjes de standaard, en
676 // dan klopt het ritme van een 'load more' niet meer met wat de gebruiker ziet.
677 const size = req.query.limit ? `&limit=${encodeURIComponent(String(req.query.limit))}` : '';
678 const self = `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/messages?with=${encodeURIComponent(other)}`;
679 AP.sendAP(res, {
680 '@context': AP.AP_CONTEXT,
681 id: req.query.before ? `${self}${size}&before=${encodeURIComponent(String(req.query.before))}` : `${self}${size}`,
682 type: 'OrderedCollectionPage',
683 partOf: self,
684 orderedItems: items,
685 // De volgende pagina is de standaardvorm van 'er is meer' (AS2). Ontbreekt
686 // hij, dan is het gesprek op -- en dat mag de client weten zonder gokken,
687 // want anders kan een 'load more' niet eerlijk verschijnen.
688 next: page.more && page.oldest ? `${self}${size}&before=${encodeURIComponent(page.oldest)}` : undefined,
689 }, 'private, no-store');
690});
691
692// De bel (/inbox/wait) is weg (shaer-pq4, 10-8). Hij deed hetzelfde als de
693// WACHTENDE inbox-lezing hierboven, maar in twee rondjes in plaats van een:
694// eerst 'er is nieuws', dan alsnog de lezing. Die lezing kan het zelf, en
695// sinds ?changes=1 stuurt hij alleen nog het verschil.
696//
697// AP.onNews blijft bestaan: de Guardian-PWA hangt er ook aan.
698
699// The server blocklist is the source of truth for Shaer's "in Orbit":
700// clients read it here instead of keeping their own state. Actor-kind
701// blocks only (domain blocks are instance policy, not an Orbit member).
702//
703// FEP-1580 zet deze deur één spleet verder open: de bronkant MOET de blokkades
704// beschikbaar maken voor de instantie waar je NAARTOE verhuist, zodat je
705// zichtbaarheidsvoorkeuren meeverhuizen. De doelkant haalt ze als eerste op,
706// want ze bepalen wat de rest te zien krijgt. Geen nieuwe collectie: deze
707// bestond al en staat al op de actor, alleen de toegang verbreedt.
708router.get('/ap/users/:slug/blocked', async (req, res) => {
709 const auth = OAuth.verifyBearer(req.headers.authorization);
710 let slug = (auth && auth.site.slug === req.params.slug) ? auth.site.slug : null;
711 if (!slug && req.headers['signature']) {
712 const verified = await AP.verifyRequest(req).catch(() => null);
713 if (verified && verified.id && AP.isMoveTarget(req.params.slug, verified.id)) slug = req.params.slug;
714 }
715 if (!slug) return res.status(403).end();
716 const base = baseUrl(req);
717 const items = AP.listBlocks(slug)
718 .filter((b) => b.kind === 'actor')
719 .map((b) => b.target);
720 AP.sendAP(res, {
721 '@context': AP.AP_CONTEXT,
722 id: `${base}/ap/users/${slug}/blocked`,
723 type: 'OrderedCollection',
724 totalItems: items.length,
725 orderedItems: items,
726 }, 'private, no-store');
727});
728
729// ── Guardian queues (owner only, FEP-633c, shaer:queues) ──────────
730// The dashboard collections the Shaer clients read: pending adoption offers,
731// gated follows (empty in Klonkt for now) and the guardian's wards. Same
732// contract as the Shaer test daemon.
733function queueRoute(name, build) {
734 router.get(`/ap/users/:slug/queues/${name}`, (req, res) => {
735 const auth = OAuth.verifyBearer(req.headers.authorization);
736 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
737 const base = baseUrl(req);
738 const me = `${base}/ap/users/${auth.site.slug}`;
739 // 304 als er niets veranderde (Barts punt, 9-8). Zonder dit haalde een app
740 // bij elke actie de hele lijst opnieuw op -- een hulpvraag afvinken vroeg de
741 // honderd wards inclusief poorten terug.
742 AP.sendMaybe304(req, res, { '@context': AP.AP_CONTEXT, ...build(`${me}/queues/${name}`, auth.site.slug, me) });
743 });
744}
745queueRoute('offers', (id, slug, me) => Guardianship.offersCollection(id, slug, me));
746queueRoute('follows', (id, slug, me) => Guardianship.followsCollection(id, slug, me));
747// §5.3 turned around (shaer-p729): what this ward has asked to follow, still
748// waiting on its guardians. Owner-only like the rest — who a child wants to
749// follow is nobody else's business.
750queueRoute('outgoing-follows', (id, slug, me) => Guardianship.outgoingFollowsCollection(id, slug, me));
751queueRoute('wards', (id, slug) => Guardianship.wardsCollection(id, slug));
752// Availability (FEP-633c 3.6.1) is never public: the ward reads its
753// guardians' real states here and nowhere else.
754queueRoute('guardians', (id, slug) => Guardianship.guardiansCollection(id, slug));
755
756// ── Het logboek (FEP-633c §4.2, shaer:log) ────────────────────────────
757// NAAST de wachtrijen en niet erin: alles onder shaer:queues wacht op een
758// antwoord, dit is wat er al besloten is. Eigen pad, dezelfde eigenaar-only
759// bearer. Het bestaat omdat een weigering anders alleen te merken viel doordat
760// er iets uit een lijst verdween, en "het is weg" is geen reden.
761router.get('/ap/users/:slug/log', (req, res) => {
762 const auth = OAuth.verifyBearer(req.headers.authorization);
763 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
764 const me = `${baseUrl(req)}/ap/users/${auth.site.slug}`;
765 AP.sendAP(res, {
766 '@context': AP.AP_CONTEXT,
767 ...Guardianship.logCollection(`${me}/log`, auth.site.slug, (s) => AP.listGuardianEvents(s, 50)),
768 }, 'private, no-store');
769});
770// De hulpvragen MET hun staat (5.2.1, shaer-lgo). De apps lazen ze uit de feed
771// en wisten dus niet of er al iemand op af was -- daarom bleef een afgehandeld
772// verzoek daar staan (Barts melding, 8-8).
773queueRoute('help', (id, slug) => Guardianship.helpCollection(id, slug));
774
775// ── Inbox read (owner only, AP C2S) ───────────────────────────────
776// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
777// scoped to this site) reads recent inbound posts (the timeline: accounts
778// they follow) as Create(Note) items, so an app (Shaer) can build a unified
779// feed. Anyone else gets 403; the inbox stays write-only for the public.
780router.get('/ap/users/:slug/inbox', async (req, res) => {
781 const auth = OAuth.verifyBearer(req.headers.authorization);
782 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
783 const base = baseUrl(req);
784 // Wachten is een UITBREIDING van deze lezing, geen tweede endpoint (shaer-n05).
785 // Geef `since` (de shaer:cursor van je vorige antwoord) en `wait` mee, en het
786 // antwoord blijft hangen tot er iets is of de tijd om is. Zonder die twee
787 // gedraagt de route zich exact zoals altijd.
788 //
789 // Bewust hetzelfde antwoord in plaats van een "er is nieuws"-seintje: dan
790 // hoeft er niets nieuws geparsed te worden, is er geen tweede beschrijving van
791 // de kaartvorm die uit de pas kan lopen, en scheelt het de client een tweede
792 // ronde.
793 const wachtS = Math.min(Math.max(parseInt(req.query.wait, 10) || 0, 0), 50);
794 if (req.query.since && wachtS > 0) {
795 const afbreken = new AbortController();
796 res.on('close', () => afbreken.abort()); // client hing op: niet doorgaan met wachten
797 const uit = await AP.waitForFeedChange(auth.site.slug, {
798 since: String(req.query.since), waitMs: wachtS * 1000, signal: afbreken.signal,
799 });
800 if (res.writableEnded || afbreken.signal.aborted) return undefined;
801 // Niets veranderd? Dan een LEEG antwoord (Barts punt): de hele collectie
802 // terugsturen terwijl er niets gebeurd is, is elke 25 seconden een tijdlijn
803 // over de mobiele verbinding voor niets. Met 304 kost stilte niets en kost
804 // nieuws nog steeds maar één rondje -- beter dan een apart seintje-endpoint,
805 // dat voor nieuws twee rondjes nodig heeft.
806 //
807 // De '0'-uitzondering is geen franje. Ontbreekt ap_feed_state (een instance
808 // die de migratie nog niet draaide), dan geeft feedCursor altijd '0' terug,
809 // en zou een client hier eeuwig 304 krijgen en nooit meer inhoud zien. Bij
810 // een lege merksteen sturen we dus gewoon de collectie.
811 if (!uit.changed && uit.cursor !== '0') {
812 res.set('Vary', 'Authorization');
813 return res.status(304).end();
814 }
815 }
816 // Gated feature (FEP-633c): may this account see EXTERNAL embeds? A ward's
817 // world outside the fediverse is the guardians' call. The gate is applied
818 // here, at serialisation: a blocked embed is never sent, because an embed the
819 // client merely hides has still been delivered to the device.
820 // De poorten van deze lezer (gatesFor): een plek waar ze berekend worden,
821 // zodat de gesprekslezingen dezelfde stand eerbiedigen en niet hun eigen
822 // kopie krijgen die kan gaan afwijken.
823 const P = gatesFor(auth.site);
824 const {
825 embedsAllowed, playbackAllowed, imagesAllowed, musicAllowed, quotesAllowed,
826 emojiAllowed, messagesAllowed, composeAllowed, repliesAllowed, threadsAllowed,
827 followingAllowed, gateAuthor,
828 } = P;
829 // De rechten-lijst hieronder vraagt er nog een paar rechtstreeks op.
830 const gate = (col) => Guardianship.wardGateAllowed(auth.site[col], P.isWard);
831 // ── Standaardvormen naast het dialect (shaer-nmw) ────────────────
832 //
833 // Een lezer die AS2 kent heeft nu genoeg aan attributedTo (ingesloten
834 // actor), quote (FEP-044f als object), preview (AS2 core) en de
835 // Announce-wrapper. De shaer:-velden blijven er nog naast staan voor apps
836 // in het veld; die gaan eruit als de clients om zijn.
837 // Wie ik ben en wie mijn guardians zijn: allebei de lezingen hieronder
838 // hebben ze nodig, dus een keer, hierboven.
839 const me = AP.actorId(base, auth.site.slug);
840 const myHandle = AP.deriveHandle(me); // een naam, of de kale URI -- nooit een halve
841 const guardianUris = (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })();
842 // ── Alleen het VERSCHIL, als de client daarom vraagt (shaer-pq4) ──
843 //
844 // De wachtende lezing zei tot nu toe alleen DAT er iets veranderde, waarna de
845 // client alles opnieuw las: vier legs van zestig met al hun media-, quote- en
846 // embed-JSON, voor een enkel nieuw bericht. ap_feed_state houdt per object al
847 // bij wat er wanneer veranderde, dus het verschil lag er klaar en werd alleen
848 // nooit uitgedeeld (feedChangesSince had geen enkele aanroeper).
849 //
850 // OPT-IN met ?changes=1, en dat is geen franje: een app in het veld stuurt
851 // `since` al mee en vervangt haar hele feed door wat er terugkomt. Zou
852 // `since` opeens een verschil betekenen, dan wist die app zichzelf leeg.
853 //
854 // Het antwoord is een OrderedCollectionPage met partOf, want dat is wat het
855 // IS -- een deel, geen collectie. Een generieke lezer ziet dat verschil ook.
856 if (req.query.changes && req.query.since) {
857 const veranderd = AP.feedChangesSince(auth.site.slug, String(req.query.since));
858 const levend = veranderd.filter((c) => c.kind !== 'deleted').map((c) => c.object_uri);
859 const tl = new Map(AP.timelineRowsByIds(auth.site.slug, levend).map((r) => [r.id, r]));
860 const mn = new Map(AP.messageRowsByUri(auth.site.slug, levend.filter((u) => !tl.has(u))).map((r) => [r.object_uri, r]));
861 const rp = new Map(AP.replyRowsByUri(auth.site.slug, levend.filter((u) => !tl.has(u) && !mn.has(u))).map((r) => [r.object_uri, r]));
862 const reacties = AP.getReactionsFor(auth.site.slug, [...tl.keys()]);
863 const ctx = { base, me, myHandle, p: P };
864 const items = [];
865 for (const c of veranderd) {
866 if (c.kind === 'deleted') {
867 // Een verwijdering reisde tot nu toe als AFWEZIGHEID mee: de volledige
868 // lezing bevatte hem simpelweg niet meer. Die volledigheid is precies
869 // wat hier wegvalt, dus zonder grafsteen zou een weggehaalde post voor
870 // altijd in de app blijven staan -- en dat faalt stil. AS2 heeft er een
871 // vorm voor, en de rij lag er al.
872 items.push({ type: 'Delete', actor: me, object: { id: c.object_uri, type: 'Tombstone' } });
873 continue;
874 }
875 const t = tl.get(c.object_uri);
876 if (t) { items.push(timelineItem(t, { p: P, reactions: reacties })); continue; }
877 const m = mn.get(c.object_uri);
878 if (m) {
879 if (messagesAllowed || m.help_request || guardianUris.has(m.actor_uri)) items.push(messageItem(m, ctx));
880 continue;
881 }
882 const r = rp.get(c.object_uri);
883 if (r) { items.push(replyItem(r, ctx)); continue; }
884 const n = AP.getOutboxNote(base, c.object_uri);
885 if (n) items.push(sentItem(n, { me, mine: AP.selfAuthor(base, auth.site) }));
886 }
887 return AP.sendAP(res, {
888 '@context': AP.AP_CONTEXT,
889 id: `${base}/ap/users/${encodeURIComponent(auth.site.slug)}/inbox?changes=1&since=${encodeURIComponent(String(req.query.since))}`,
890 type: 'OrderedCollectionPage',
891 partOf: `${base}/ap/users/${auth.site.slug}/inbox`,
892 orderedItems: items,
893 // De rechten gaan MEE. Zonder dit valt de client terug op zijn standaard,
894 // en die standaard is 'alles mag' -- dan zet een gesloten poort zichzelf
895 // stil open bij elke verschil-lezing. Dezelfde reden waarom een 304 de
896 // caps met rust laat.
897 'shaer:capabilities': capabilitiesOf(P, gate),
898 'shaer:cursor': AP.feedCursor(auth.site.slug),
899 }, 'private, no-store');
900 }
901 const rows = AP.getTimeline(auth.site.slug, 60);
902 // Eén query voor de hele pagina (shaer-9e9 fase 2): shaer:liked komt uit de
903 // tussentabel, de bron van waarheid, en niet meer uit de afgeleide kolom op
904 // ap_timeline. Per rij vragen zou hier een N+1 opleveren.
905 const reacties = AP.getReactionsFor(auth.site.slug, rows.map((t) => t.id));
906 const posts = rows.map((t) => timelineItem(t, { p: P, reactions: reacties }));
907 // The direct notes addressed to this account: a plain DM, a guardian's wave
908 // (§5), a ward's 🛟 help request (§5.2.1). Those are messages, not posts, so
909 // they are not in the timeline; without them the app's Berichten shows only
910 // what you said yourself. Same shape as a post, so one parser handles both.
911 // Messages dicht (shaer-3ow) sluit vreemden en vrienden, maar NOOIT het
912 // guardian-kanaal: de zwaai en het gesprek na een hulpvraag zijn precies
913 // het kanaal dat het kind veilig houdt, en een poort die dat afsnijdt
914 // beschermt niemand. De hulpvraag zelf gaat aan de innamekant al altijd voor.
915 const messageCtx = { base, me, myHandle, p: P };
916 const messages = AP.getDirectMessages(auth.site.slug, 60)
917 .filter((m) => messagesAllowed || m.help_request || guardianUris.has(m.actor_uri))
918 .map((m) => messageItem(m, messageCtx));
919 // Inbound REPLIES on your own posts: stored as interactions (the web's
920 // comment machinery), never as mentions, so this read missed them and a
921 // friend's reply arrived everywhere except in your app (Robins melding,
922 // 30-7). Same shape as the other legs; media/quotes ride the stored JSON.
923 const replies = AP.getReplyMessages(auth.site.slug, 60).map((m) => replyItem(m, messageCtx));
924 // Your OWN sent notes (replies and direct messages, ap_outbox): without
925 // them a reply existed everywhere except in your own app, Messages showed
926 // half a conversation, and a retry ran into the duplicate guard (Robins
927 // melding, 30-7). Served like the other legs: same shape, one parser.
928 const mine = AP.selfAuthor(base, auth.site);
929 const sent = AP.getSentNotes(base, auth.site, 60).map((n) => ({
930 id: `${n.id}#create`,
931 type: 'Create',
932 actor: me,
933 published: n.published,
934 // The leading mention anchor is addressing, not prose (the DM leg strips
935 // it the same way); the Mention tags built from the full content stay.
936 object: {
937 ...n, content: AP.stripLeadingMentions(n.content),
938 attributedTo: AP.actorObject(typeof n.attributedTo === 'string' ? n.attributedTo : me, mine),
939 },
940 }));
941 // Newest first over all legs, so the app can keep treating this as one feed.
942 const items = [...posts, ...messages, ...replies, ...sent].sort((a, b) => String(b.published || '').localeCompare(String(a.published || '')));
943 AP.sendAP(res, {
944 '@context': AP.AP_CONTEXT,
945 id: `${base}/ap/users/${auth.site.slug}/inbox`,
946 type: 'OrderedCollection',
947 // What this account may do with what is in here (FEP-633c 5.6). Owner-only
948 // by construction, and never on the public actor document: it says
949 // something about a child, and only the child and its guardians need it.
950 'shaer:capabilities': capabilitiesOf(P, gate),
951 // Het merk van wat hierin zit. Geef hem terug als `since` om op het
952 // volgende te wachten. NA het samenstellen bepaald, zodat hij precies dekt
953 // wat je in handen hebt en niet iets dat er ondertussen bij kwam.
954 'shaer:cursor': AP.feedCursor(auth.site.slug),
955 totalItems: items.length,
956 orderedItems: items,
957 });
958 return undefined;
959});
960
961// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
962// The actor advertises endpoints.uploadMedia; this implements it. A bearer
963// scoped to this site uploads one image/audio/video (multipart field "file",
964// AP convention) into the same store the reply editor uses, and gets back
965// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
966const AP_MEDIA_DIR = mediaDir('REPLY_MEDIA_PATH', 'reply-media');
967fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
968const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
969const apMediaUpload = multer({
970 storage: multer.diskStorage({
971 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
972 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
973 }),
974 limits: { fileSize: 32 * 1024 * 1024 },
975 fileFilter: (req, file, cb) => {
976 const ext = path.extname(file.originalname || '').toLowerCase();
977 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
978 cb(null, true);
979 },
980});
981router.post('/ap/users/:slug/uploadMedia', (req, res) => {
982 const auth = OAuth.verifyBearer(req.headers.authorization);
983 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
984 apMediaUpload.single('file')(req, res, (err) => {
985 if (err) return res.status(400).json({ error: err.message });
986 if (!req.file) return res.status(400).json({ error: 'No file' });
987 const mime = String(req.file.mimetype || '');
988 if (!/^(image|audio|video)\//.test(mime)) {
989 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
990 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
991 }
992 // A video gets a poster frame next to it (shaer-zowq), best-effort and
993 // out of band: ffmpeg pulls one frame at 1s into <name>.poster.jpg. On a
994 // machine without ffmpeg nothing happens and nothing breaks; the clients
995 // fall back to extracting a frame natively.
996 if (mime.startsWith('video/')) {
997 // The bundled static build (ffmpeg-static) does the work, exactly like
998 // VideoCoverService and AudioTranscoder already do: Klonkt SHIPS its
999 // ffmpeg (Robins opmerking, 30-7), so nothing needs installing on any
1000 // machine. Soft dependency + best-effort: absent stays silent, and
1001 // FFMPEG_PATH can still override for an operator who wants a newer one.
1002 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
1003 const bin = process.env.FFMPEG_PATH || ff.default;
1004 if (!bin) return;
1005 const poster = req.file.path + '.poster.jpg';
1006 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-ss', '1', '-i', req.file.path, '-frames:v', '1', '-vf', "scale='min(640,iw)':-2", poster],
1007 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] poster failed:', e.message); });
1008 }).catch(() => { /* never blocks the upload */ });
1009 }
1010 // Audio gets the same courtesy (Robins vraag, 30-7: vrolijk de kale
1011 // audio-tegel op): ffmpeg draws the waveform into <name>.poster.png.
1012 // White on transparent, so the tile's own gradient stays the backdrop
1013 // and every audio post keeps its own hue. The shape is bars, not the
1014 // raw hairy wave (Robins tweede vraag): peak and average sampled into
1015 // 57 columns (soft tip over bright core), blown up nearest-neighbor to
1016 // 14px bars, and drawgrid ERASES 5px gaps (c=black@0 + replace=1 writes
1017 // transparent pixels; h=2*ih keeps horizontal grid lines out of frame).
1018 if (mime.startsWith('audio/')) {
1019 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
1020 const bin = process.env.FFMPEG_PATH || ff.default;
1021 if (!bin) return;
1022 const poster = req.file.path + '.poster.png';
1023 const graph = '[0:a]aformat=channel_layouts=mono,asplit[a][b];'
1024 + '[a]showwavespic=s=57x256:colors=white@0.5:filter=peak:scale=sqrt:draw=full[pk];'
1025 + '[b]showwavespic=s=57x256:colors=white:filter=average:scale=sqrt:draw=full[av];'
1026 + '[pk][av]overlay=format=auto,scale=798:256:flags=neighbor,drawgrid=w=14:h=2*ih:t=5:c=black@0:replace=1';
1027 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-i', req.file.path, '-filter_complex', graph, '-frames:v', '1', poster],
1028 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] waveform failed:', e.message); });
1029 }).catch(() => { /* never blocks the upload */ });
1030 }
1031 res.status(201).json({
1032 url: '/media/reply-media/' + req.file.filename,
1033 mediaType: mime,
1034 name: String(req.file.originalname || '').slice(0, 120),
1035 });
1036 });
1037});
1038
1039// ── Followers (count-only public, full for the owner) ─────────────
1040// A C2S bearer scoped to this site (the account owner) gets the real actor
1041// URIs so their own client can build a friends list; everyone else gets the
1042// count only (privacy).
1043// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
1044// Returns true and sets the response headers when the owner asked for it.
1045function wantsEnriched(req, res) {
1046 res.set('Vary', 'Prefer'); // enriched and bare are two representations
1047 if (AP.prefersEnriched(req.get('Prefer'))) {
1048 res.set('Preference-Applied', 'return=representation');
1049 return true;
1050 }
1051 return false;
1052}
1053
1054router.get('/ap/users/:slug/followers', (req, res) => {
1055 const auth = OAuth.verifyBearer(req.headers.authorization);
1056 const owner = auth && auth.site.slug === req.params.slug;
1057 const site = owner ? auth.site : publicSite(req.params.slug);
1058 if (!site) return res.status(404).end();
1059 if (owner) {
1060 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
1061 // Default = bare references; enrich only when the client asks (FEP-9876).
1062 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
1063 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items, { page: paginaNr(req) }));
1064 }
1065 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
1066 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n, null, { page: paginaNr(req) }));
1067});
1068
1069// ── Following (count-only public, full for the owner) ─────────────
1070router.get('/ap/users/:slug/following', (req, res) => {
1071 const auth = OAuth.verifyBearer(req.headers.authorization);
1072 const owner = auth && auth.site.slug === req.params.slug;
1073 const site = owner ? auth.site : publicSite(req.params.slug);
1074 if (!site) return res.status(404).end();
1075 if (owner) {
1076 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
1077 let items = [];
1078 try {
1079 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);
1080 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
1081 } catch { /* table may not exist */ }
1082 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items, { page: paginaNr(req) }));
1083 }
1084 let n = 0;
1085 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
1086 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n, null, { page: paginaNr(req) }));
1087});
1088
1089/**
1090 * Mag deze aanvrager alles van `slug` zien? Waar bij de eigenaar zelf, en waar
1091 * voor de actor waar `slug` naartoe verhuisd is (FEP-1580, Source Instance).
1092 *
1093 * Eén plek voor die vraag, want hij komt op meerdere collecties terug en twee
1094 * antwoorden op dezelfde vraag lopen vroeg of laat uiteen.
1095 */
1096async function magAlles(req, slug) {
1097 const auth = OAuth.verifyBearer(req.headers.authorization);
1098 if (auth && auth.site.slug === slug) return true;
1099 if (!req.headers['signature']) return false;
1100 const v = await AP.verifyRequest(req).catch(() => null);
1101 return !!(v && v.id && AP.isMoveTarget(slug, v.id));
1102}
1103
1104// ── FEP-1580: de vertaaltabel van een verhuizing ──────────────────
1105//
1106// Publiek leesbaar, want dat is het hele doel: een derde die een oude URI in
1107// zijn database heeft leest hier wat de nieuwe is. Zonder deze collectie blijft
1108// elke reactie op een verhuisd bericht naar een dood adres wijzen.
1109//
1110// Niet-publieke items komen er alleen in voor een lezer die ze mocht zien. De
1111// spec: Moves voor objecten die niet aan as:Public gericht zijn MOGEN NIET
1112// publiek getoond worden. Een lijst met de URIs van je fan-only posts is een
1113// lek, ook al staat de inhoud er niet bij.
1114router.get('/ap/users/:slug/migration', async (req, res) => {
1115 const site = publicSite(req.params.slug);
1116 if (!site) return res.status(404).end();
1117 let alles = false;
1118 const auth = OAuth.verifyBearer(req.headers.authorization);
1119 if (auth && auth.site.slug === site.slug) alles = true;
1120 else if (req.headers['signature']) {
1121 const v = await AP.verifyRequest(req).catch(() => null);
1122 // Een geverifieerde volger zat in het publiek van de fan-only posts, dus
1123 // die mag ook weten waar ze heen zijn.
1124 if (v && v.id && AP.outboxAudience(site.slug, { verifiedActor: v.id }) === 'friend') alles = true;
1125 }
1126 AP.sendAP(res, Migration.buildMigration(baseUrl(req), site, { page: paginaNr(req), alles }),
1127 alles ? 'private, no-store' : undefined);
1128});
1129
1130// De Moves die de vertaaltabel rechtvaardigen. Altijd publiek: een bewijs dat
1131// je moet kunnen nakijken heeft niets aan een slot.
1132//
1133// LET OP: zonder FEP-8b32 (shaer-j1v0) staat hier geen handtekening onder. De
1134// collectie is structureel goed en niet verifieerbaar, en een derde die de spec
1135// streng volgt mag hem daarom weigeren. Bewust geen leeg proof-veld erbij.
1136router.get('/ap/users/:slug/moves', (req, res) => {
1137 const site = publicSite(req.params.slug);
1138 if (!site) return res.status(404).end();
1139 AP.sendAP(res, Migration.buildMoves(baseUrl(req), site));
1140});
1141
1142// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
1143router.get('/ap/users/:slug/featured', (req, res) => {
1144 const site = publicSite(req.params.slug);
1145 if (!site) return res.status(404).end();
1146 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
1147 // last-processed-first). So we emit it reversed (lowest pin priority first,
1148 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
1149 const posts = db.prepare(
1150 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, c2s_attachments, published_at, created_at
1151 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
1152 AND pinned IS NOT NULL AND pinned > 0
1153 ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
1154 ).all(site.id);
1155 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts, { page: paginaNr(req) }));
1156});
1157
1158// ── Playlist als dereferenceerbare AP-collectie (shaer-ayc) ───────
1159// De eerste stap van het Funkwhale-spoor: een playlist heeft een id, dus een
1160// stabiele URI. Alleen het fedi_open-deel staat erin (de poort is per bestand
1161// en eenrichtings; zie setAudioFediOpen in routes/posts.js) — een collectie
1162// zonder open tracks bestaat wel maar is leeg, want de playlist zelf is niet
1163// geheim, alleen de bestanden erachter.
1164// De lijst van alle playlist-collecties (shaer-ayc, stap 2). De actor wijst
1165// hierheen via AS2 `streams`. Kaal standaard; verrijkte stubs op verzoek
1166// (FEP-9876), dezelfde conventie als followers/following.
1167router.get('/ap/users/:slug/playlists', (req, res) => {
1168 const site = publicSite(req.params.slug);
1169 if (!site) return res.status(404).end();
1170 AP.sendAP(res, AP.listPlaylistsAP(baseUrl(req), site, wantsEnriched(req, res), { page: paginaNr(req) }));
1171});
1172
1173// De tracks van deze site: de kanonieke plek voor onze muziek (shaer-0nh,
1174// stap 3). Een playlist is een keuze hieruit; deze collectie is alles wat de
1175// artiest heeft opengezet, ook wat in geen enkele playlist staat.
1176router.get('/ap/users/:slug/tracks', async (req, res) => {
1177 const site = publicSite(req.params.slug);
1178 if (!site) return res.status(404).end();
1179 AP.sendAP(res, AP.buildTrackCollection(baseUrl(req), site, AP.siteOpenTracks(site.id, { alles: await magAlles(req, site.slug) }), { page: paginaNr(req) }));
1180});
1181
1182// De bibliotheek van deze site (shaer-0nh). Funkwhale's Audio draagt een
1183// `library`, en dat is bij hen het haakje waar een UPLOAD aan komt te hangen --
1184// zonder die bak blijft een binnengehaalde track daar een naam zonder geluid.
1185// Gemeten op 13-8: open.audio had onze vier tracks wel, met onze eigen AP-id's,
1186// maar uploads leeg en is_playable false.
1187//
1188// Openbaar, want alles erin is fedi_open. Er valt dus niets goed te keuren en de
1189// volgerslijst blijft leeg: wie ons volgt volgt de ACTOR, niet de bak.
1190//
1191// `?page=` MOET hier doorgegeven worden. Zonder dat adverteert de wortel een
1192// `first` die op zichzelf uitkomt: de lezer volgt hem, krijgt weer een `Library`
1193// in plaats van een pagina, en klapt eruit -- open.audio gaf op 15-8 een 500 op
1194// precies deze URL. Dezelfde les als bij de outbox (shaer-sk4): een `first`
1195// beloven is een pagina beloven.
1196router.get('/ap/users/:slug/library', (req, res) => {
1197 const site = publicSite(req.params.slug);
1198 if (!site) return res.status(404).end();
1199 AP.sendAP(res, AP.buildLibrary(baseUrl(req), site, AP.siteOpenTracks(site.id), { page: paginaNr(req) }));
1200});
1201
1202// De volgerscollectie die hun docs als vereist noemen. Leeg en eerlijk: er is
1203// geen goedkeuringspad omdat de bibliotheek openbaar is.
1204router.get('/ap/users/:slug/library/followers', (req, res) => {
1205 const site = publicSite(req.params.slug);
1206 if (!site) return res.status(404).end();
1207 AP.sendAP(res, AP.pagedCollection(`${AP.libraryId(baseUrl(req), site)}/followers`, [], { page: paginaNr(req) }));
1208});
1209
1210// Eén track, los op te halen. Een gesloten track is AFWEZIG, niet leeg: 404,
1211// dezelfde regel als in de collectie, zodat het bestaan van een gated nummer
1212// niet uit een ander antwoord af te leiden is.
1213router.get('/ap/users/:slug/tracks/:id', (req, res) => {
1214 const site = publicSite(req.params.slug);
1215 if (!site) return res.status(404).end();
1216 const row = AP.openTrack(site.id, req.params.id);
1217 if (!row) return res.status(404).end();
1218 AP.sendAP(res, AP.buildTrackAudio(baseUrl(req), site, row, { standalone: true }));
1219});
1220
1221// De losse tracks van een post als EEN uitgave (shaer-38y). Ze gingen tot nu
1222// toe los de deur uit -- Audio-objecten die een lezer nergens kon plaatsen. Ze
1223// horen bij elkaar omdat ze in dezelfde post staan, en die post leent zijn
1224// titel, tekst, hoes en tags uit. 404 als de post geen muzikale eenheid IS:
1225// dan is er niets om naar te wijzen, en dat is geen lege collectie maar een
1226// collectie die niet bestaat.
1227router.get('/ap/users/:slug/posts/:id/tracks', (req, res) => {
1228 const site = publicSite(req.params.slug);
1229 if (!site) return res.status(404).end();
1230 const post = db.prepare(
1231 "SELECT id, slug, title, excerpt, content, cover_image_url, tags FROM posts WHERE id = ? AND site_id = ? AND status = 'published'"
1232 ).get(req.params.id, site.id);
1233 if (!post) return res.status(404).end();
1234 const col = AP.buildPostTrackCollection(baseUrl(req), site, post);
1235 if (!col) return res.status(404).end();
1236 AP.sendAP(res, col);
1237});
1238
1239router.get('/ap/users/:slug/playlists/:id', async (req, res) => {
1240 const site = publicSite(req.params.slug);
1241 if (!site) return res.status(404).end();
1242 const pl = db.prepare('SELECT id, title, artist, year, cover_url, kind, release_date, mb_release_id, created_at FROM playlists WHERE id = ? AND site_id = ?')
1243 .get(req.params.id, site.id);
1244 if (!pl) return res.status(404).end();
1245 // De doel-actor van een verhuizing krijgt de VOLLEDIGE plaat, niet alleen de
1246 // nummers die voor de fediverse opengezet zijn (FEP-1580).
1247 const alles = await magAlles(req, site.slug);
1248 AP.sendAP(res, AP.buildPlaylistCollection(baseUrl(req), site, pl, AP.playlistOpenTracks(pl.id, { alles })));
1249});
1250
1251// ── Note ──────────────────────────────────────────────────────────
1252router.get('/ap/notes/:id', async (req, res) => {
1253 // No fan_only filter in the SELECT anymore: a friends-only post is not
1254 // absent, it is GATED. The old route hid it from EVERYONE, also from the
1255 // follower whose friendship earns it — so the signed resolution the reply
1256 // path performs knocked on a door that could never open, and every reply
1257 // to a friends-only post (Shaer's default!) died in
1258 // cannot_resolve_inReplyTo. Strangers still get the exact same 404, so a
1259 // note's existence stays as private as before.
1260 // EEN GEBLOKKEERDE KRIJGT DE DEUR DICHT (Robin, 21-8), net als bij de outbox:
1261 // wie ondertekend aanklopt, klopt met zijn naam erop, en een blokkade is een
1262 // gesloten deur. Dezelfde 404 als een vreemde, zodat het bestaan van een note
1263 // niets extra's verraadt. Onbetekende verzoeken kunnen we niet thuisbrengen
1264 // en houden de publieke weergave -- daarvoor is de Block-bezorging.
1265 if (req.headers['signature']) {
1266 const wie = await AP.verifyRequest(req).catch(() => null);
1267 if (wie && wie.id && AP.isBlockedAny(wie.id)) return res.status(404).end();
1268 }
1269 const post = db.prepare(
1270 "SELECT * FROM posts WHERE id = ? AND status = 'published'"
1271 ).get(req.params.id);
1272 if (post && AP.noteAudience(post) !== 'public') {
1273 // The whole gate in a try: this is the only async route in this file,
1274 // and Express 4 does not catch an async rejection — the request would
1275 // hang forever instead of failing (which is exactly how the missing
1276 // default-export entry manifested while building this). Any error here
1277 // reads as "not authorized", never as silence.
1278 try {
1279 if (AP.noteAudience(post) === 'direct') return res.status(404).end();
1280 const gsite = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
1281 const actor = await AP.verifyRequest(req).catch(() => null);
1282 if (!actor || !AP.mayReadNote(gsite, post, actor.id)) return res.status(404).end();
1283 } catch { return res.status(404).end(); }
1284 }
1285 if (!post) {
1286 // Could be one of OUR outbound replies (ap_outbox), not a post.
1287 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
1288 if (!note) return res.status(404).end();
1289 if (!AP.apWants(req)) {
1290 // A browser hit a reply's AP URL → send them to the source it replies to
1291 // (where the post + its reactions live), falling back to the site home.
1292 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
1293 ? note.inReplyTo : (baseUrl(req) + '/');
1294 return res.redirect(302, src);
1295 }
1296 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
1297 }
1298 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
1299 if (!site) return res.status(404).end();
1300 const note = AP.buildNote(baseUrl(req), site, post);
1301 if (!AP.apWants(req)) {
1302 // A browser hit a post's AP note URL → send them to the human post page
1303 // (which shows the post + its "from the fediverse" reactions).
1304 return res.redirect(302, note.url || (baseUrl(req) + '/'));
1305 }
1306 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
1307});
1308
1309// ── Replies collection ── lets remote servers fetch a post's whole thread.
1310// ── De composer-preview (shaer-k3f): een URL wordt alvast een kaart ──
1311//
1312// Bearer-only, net als de thread: dit is de eigen app die tijdens het typen
1313// vraagt wat een link gaat worden. Dezelfde pijplijn als publiceren, dus de
1314// preview kan niet iets beloven dat de post niet waarmaakt. De embed gaat
1315// langs de eigen poort van de lezer -- een ward zonder open embeds-poort
1316// krijgt in de composer geen kaart die zijn feed hem ook niet zou tonen.
1317router.get('/ap/users/:slug/card', async (req, res) => {
1318 const auth = OAuth.verifyBearer(req.headers.authorization);
1319 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
1320 const uit = await AP.previewCard(String(req.query.url || ''));
1321 const isWard = (() => { try { return Guardianship.listGuardians(auth.site.slug).length > 0; } catch { return false; } })();
1322 const embedsAllowed = Guardianship.externalEmbedsAllowed(auth.site.external_embeds, isWard);
1323 const playback = embedsAllowed && Guardianship.externalPlaybackAllowed(auth.site.external_playback, isWard);
1324 AP.sendAP(res, {
1325 '@context': AP.AP_CONTEXT,
1326 quote: AP.quoteObject(uit.quoteJson),
1327 preview: embedsAllowed ? AP.previewObject(uit.embedJson, { playback }) : undefined,
1328 }, 'private, no-store');
1329});
1330
1331// ── De thread onder een post (shaer-tqz): ophalen, niet bewaren ────
1332//
1333// Bearer-only: dit is de eigen app van deze account die vraagt, nooit een
1334// vreemde. Klonkt doet de ondertekende GET die de app zelf niet kan (de
1335// sleutel staat hier), loopt één pagina van de replies-collectie af en geeft
1336// genormaliseerde notes terug. Er wordt NIETS opgeslagen; zie getThread.
1337//
1338// Voor een ward geldt de veiligste stand tot shaer-vw4 beslist is: alleen
1339// antwoorden uit de kring die de guardians al kennen, en shaer:hidden telt wat
1340// er buiten viel. De telling staat er zodat de UI eerlijk kan zijn -- OF hij
1341// getoond wordt is onderdeel van datzelfde besluit.
1342router.get('/ap/users/:slug/thread', async (req, res) => {
1343 const auth = OAuth.verifyBearer(req.headers.authorization);
1344 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
1345 const objectUri = String(req.query.object || '');
1346 if (!/^https:\/\//i.test(objectUri)) return res.status(400).json({ error: 'object must be an https URI' });
1347 const isWard = (() => { try { return Guardianship.listGuardians(auth.site.slug).length > 0; } catch { return false; } })();
1348 const uit = await AP.getThread(auth.site.slug, objectUri);
1349 if (!uit.found) {
1350 // WIENS schuld is dit? De oude melding zei "jouw server kon het niet
1351 // laden" terwijl onze server het prima deed en de BRON weigerde -- dat
1352 // wees naar de verkeerde partij (Barts melding, 10-8: een post van een
1353 // account dat hij vanochtend nog volgde, en dat nu niet meer).
1354 // 401/403/404/410 is een besluit van die server; al het andere, inclusief
1355 // een status die we niet eens kregen, is een storing.
1356 const geweigerd = [401, 403, 404, 410].includes(uit.sourceStatus);
1357 return res.status(geweigerd ? 404 : 502)
1358 .json({ error: geweigerd ? 'not shared by source' : 'source unreachable', sourceStatus: uit.sourceStatus || undefined });
1359 }
1360 // De poortstand komt uit de kolom (shaer-9y2): expliciete 0/1 van de
1361 // guardians wint, de automatiek is dicht-voor-een-ward. Dicht is de KRING,
1362 // niet niets: antwoorden van al goedgekeurd volk blijven staan, en wat er
1363 // buiten valt wordt geteld. Beeld, muziek en emoji gaan door dezelfde
1364 // poorten als de tijdlijn -- per verzoek, buiten de threadcache om.
1365 const threadsOpen = Guardianship.wardGateAllowed(auth.site.external_threads, isWard);
1366 const gate2 = (col) => Guardianship.wardGateAllowed(auth.site[col], isWard);
1367 const kring = threadsOpen ? { notes: uit.notes, hidden: 0 } : AP.filterThreadToCircle(auth.site.slug, uit.notes);
1368 const imagesOk = gate2('gate_images'), musicOk = gate2('gate_music'), emojiOk = gate2('gate_custom_emoji');
1369 uit.notes = kring.notes.map((n) => ({
1370 ...n,
1371 attachment: AP.gateAttachments(n.attachment, { images: imagesOk, audio: musicOk }),
1372 tag: emojiOk ? n.tag : AP.stripEmojiTags(n.tag),
1373 // De emoji-poort knipt in de byline zelf: FEP-9098 zit in de tag van de
1374 // ingesloten actor, niet meer in een eigen emoji-kaart ernaast.
1375 attributedTo: (!emojiOk && n.attributedTo && typeof n.attributedTo === 'object')
1376 ? { ...n.attributedTo, tag: undefined } : n.attributedTo,
1377 }));
1378 uit.hidden = kring.hidden;
1379 // Liked/boosted per antwoord, BUITEN de cache om: de genormaliseerde notes
1380 // mogen twee minuten oud zijn, maar of JIJ iets geliked hebt hoort van nu te
1381 // zijn -- anders springt het hartje terug zodra de reader opnieuw opent.
1382 const reacties = AP.getReactionsFor(auth.site.slug, uit.notes.map((n) => n.id));
1383 // De thread heeft al een ?object= in zijn id, dus geen ?page= erachter: die
1384 // collectie is niet te pagineren zonder de vraag zelf te herhalen. Hij is
1385 // owner-only en wordt door Shaer gelezen, niet door de federatie.
1386 AP.sendAP(res, {
1387 '@context': AP.AP_CONTEXT,
1388 id: `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/thread?object=${encodeURIComponent(objectUri)}`,
1389 type: 'OrderedCollection',
1390 totalItems: uit.notes.length,
1391 orderedItems: uit.notes.map((n) => ({
1392 ...n,
1393 'shaer:liked': !!(reacties.get(n.id) || {}).liked,
1394 'shaer:boosted': !!(reacties.get(n.id) || {}).boosted,
1395 })),
1396 'shaer:hidden': uit.hidden || undefined,
1397 }, 'private, no-store');
1398});
1399
1400router.get('/ap/notes/:id/replies', (req, res) => {
1401 const base = baseUrl(req);
1402 const items = AP.getReplyUris(base, req.params.id);
1403 AP.sendAP(res, AP.pagedCollection(`${base}/ap/notes/${req.params.id}/replies`, items));
1404});
1405
1406// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
1407router.get('/.well-known/nodeinfo', (req, res) => {
1408 res.type('application/json');
1409 res.set('Cache-Control', 'public, max-age=3600');
1410 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
1411});
1412router.get('/nodeinfo/2.1', (req, res) => {
1413 let users = 0; let posts = 0;
1414 // "users" = public AP actors (sites), not the admin/member account rows.
1415 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
1416 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
1417 res.type('application/json; charset=utf-8');
1418 res.set('Cache-Control', 'public, max-age=600');
1419 res.send(JSON.stringify({
1420 version: '2.1',
1421 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
1422 protocols: ['activitypub'],
1423 services: { inbound: [], outbound: [] },
1424 openRegistrations: false,
1425 usage: { users: { total: users }, localPosts: posts },
1426 metadata: { nodeName: 'Klonkt' },
1427 }));
1428});
1429
1430// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
1431const apJson = express.json({
1432 type: ['application/activity+json', 'application/ld+json', 'application/json'],
1433 limit: '1mb',
1434 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
1435});
1436router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
1437 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
1438 // Met de STACK erbij. Hier stond alleen `e.message`, en op 15-8 leverde dat
1439 // zes keer "[AP inbox] error: slug is not defined" op zonder één aanwijzing
1440 // waar -- een ReferenceError in een handler van duizenden regels, met een
1441 // naam die overal voorkomt. Een fout die je niet kunt plaatsen is niet
1442 // gemeld. Het type en de activiteit erbij, want dat zegt welke tak liep.
1443 catch (e) {
1444 const soort = req.body && req.body.type;
1445 console.warn('[AP inbox] error:', e.message, '| type:', soort, '| slug:', req.params.slug || '(gedeeld)');
1446 console.warn(e.stack);
1447 return res.status(202).end();
1448 }
1449});
1450
1451// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
1452// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
1453// the normal delivery machinery. The token is scoped to one user+site (OAuth
1454// consent), so it must match the slug in the URL. (Declared after apJson, which
1455// this shares with the inbox handler.)
1456router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
1457 const auth = OAuth.verifyBearer(req.headers.authorization);
1458 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
1459 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
1460 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
1461
1462 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
1463 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
1464 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
1465 if (out.status === 201 && out.url) res.set('Location', out.url);
1466 // `state` carries a third outcome the app must be able to tell apart from a
1467 // plain success: a ward's follow held for its guardians (§5.3, shaer-p729).
1468 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url, ...(out.state ? { state: out.state } : {}) });
1469});
1470
1471export default router;
Note: See TracBrowser for help on using the repository browser.