source: Klonkt/src/routes/activitypub.js

main
Last change on this file was 1d1fdc9, checked in by Robin <roboburr@…>, 4 days ago

Tijdstempels: de posts-kant ook, en de tijdbom ontmanteld (shaer-a937)

Correctie op mijn eigen sluitreden bij 9946a68: ik schreef daar dat de
posts-sorteringen door isoSql lopen, en dat was niet zo -- ik had ze juist
overgeslagen omdat ze vandaag nog niet scheef staan.

Twee dingen alsnog:

De TIJDBOM uit de bead. Scheduler zette published_at op CURRENT_TIMESTAMP,
dus zodra iemand een post inplant en die vanzelf publiceert, staat er SQL-
notatie tussen de ISO's en sorteert het hele archief door elkaar. Die schrijft
nu ISO, net als de andere zes schrijfwegen.

En het VANGNET voor wat er al staat: de zeven posts-sorteringen (outbox,
backfill, featured tweemaal, muziek tweemaal, beheeroverzicht) lopen nu ook
door isoSql. Half normaliseren is de verwarrendste toestand -- dan hangt het
per scherm af of een gemengde kolom goed valt.

Onderweg gecontroleerd dat elke gebruiker van isoSql en NU_ISO ze ook
importeert: admin.js gebruikte hem zonder import, en dat was pas omgevallen
op het moment dat iemand het beheeroverzicht opende. Alle aangeraakte
bestanden door node --check.

Volle suite 1255 groen.

  • Property mode set to 100644
File size: 80.8 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, { isoSql } 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 // Waar dit een antwoord op is (Robins melding, 26-8). Zonder dit veld
546 // kwam elk antwoord binnen als het begin van een gesprek: de client kan
547 // een keten alleen teruglopen langs inReplyTo. De andere twee legs
548 // (replyItem uit ap_interactions, sentItem via buildNote) droegen hem
549 // al -- deze was de enige die hem niet eens opsloeg.
550 inReplyTo: m.in_reply_to || undefined,
551 published: AP.isoStamp(m.published || m.created_at),
552 // Addressed to us and to nobody we know of: the other recipients of a
553 // note to several people are not ours to see, so we serve what we know.
554 to: [me],
555 // The Mention is how the client recognises itself as the addressee and
556 // groups the note into a conversation. No FEP-e232 link tags here: a
557 // mention row keeps the resolved quote, not the raw tags.
558 tag: [{ type: 'Mention', href: me, name: myHandle }, ...(p.emojiAllowed ? (AP.timelineEmojis(m.emoji_json) || []) : [])],
559 attachment: AP.gateAttachments(AP.timelineAttachments(m.media_json), { images: p.imagesAllowed, audio: p.musicAllowed }),
560 // FEP-633c: what kind of message this is. The wave is a gentle nudge from
561 // a guardian; the help request is the buoy. Both render differently.
562 'shaer:wave': m.wave ? true : undefined,
563 'shaer:helpRequest': m.help_request ? true : undefined,
564 quote: p.quotesAllowed ? AP.quoteObject(m.quote_json) : undefined,
565 preview: p.embedsAllowed ? AP.previewObject(m.embed_json, { playback: p.playbackAllowed }) : undefined,
566 },
567 };
568}
569
570/** Een eigen verzonden note als AS2-item, zelfde vorm als de inbox-leg. */
571function sentItem(n, { me, mine }) {
572 return {
573 id: `${n.id}#create`,
574 type: 'Create',
575 actor: me,
576 published: n.published,
577 // The leading mention anchor is addressing, not prose (the DM leg strips
578 // it the same way); the Mention tags built from the full content stay.
579 object: {
580 ...n, content: AP.stripLeadingMentions(n.content),
581 attributedTo: AP.actorObject(typeof n.attributedTo === 'string' ? n.attributedTo : me, mine),
582 },
583 };
584}
585
586// ── Gesprekken: eerst wie, dan pas wat (shaer-frontend-yso) ──────
587//
588// Twee lezingen naast de bestaande inbox-lezing, niet in de plaats ervan: de
589// apps in het veld lezen die nog. /conversations geeft EEN rij per tegenpartij
590// -- compleet van vorm, dus de avatarhemel kan niemand kwijtraken doordat een
591// ander druk was -- en /messages geeft een gesprek met een cursor, zodat een
592// 'load more' eerlijk kan verschijnen in plaats van dat de geschiedenis stil
593// ophoudt.
594//
595// Beide lopen langs dezelfde poorten als de inbox-lezing (gatesFor) en
596// dezelfde kaartvorm (messageItem/sentItem). Messages dicht sluit ook
597// hier vreemden en vrienden, maar nooit het guardian-kanaal en nooit de boei.
598function conversationItems(req, auth, refs) {
599 const base = baseUrl(req);
600 const P = gatesFor(auth.site);
601 const me = AP.actorId(base, auth.site.slug);
602 const ctx = { base, me, myHandle: ownHandle(base, auth.site.slug), p: P };
603 const mine = AP.selfAuthor(base, auth.site);
604 const guardianUris = (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })();
605
606 const incoming = new Map(AP.messageRowsByUri(auth.site.slug, refs.filter((r) => r.direction === 'in').map((r) => r.ref))
607 .map((m) => [m.object_uri, m]));
608 // PAREN, geen losse lijst: een kop levert niet altijd een item op (dichte
609 // poort, ontbrekende rij), en dan zou de aanroeper op index koppelen en de
610 // telling aan het verkeerde gesprek hangen. Stil, en pas te zien als iemand
611 // een badge op de verkeerde naam ziet staan.
612 const pairs = [];
613 for (const r of refs) {
614 if (r.direction === 'in') {
615 const m = incoming.get(r.ref);
616 if (!m) continue;
617 if (!(P.messagesAllowed || m.help_request || guardianUris.has(m.actor_uri))) continue;
618 pairs.push({ head: r, item: messageItem(m, ctx) });
619 } else {
620 const n = AP.getOutboxNote(base, r.ref);
621 // Je eigen woorden blijven van jou: een dichte messages-poort verbergt
622 // niet wat je zelf gezegd hebt.
623 if (n) pairs.push({ head: r, item: sentItem(n, { me, mine }) });
624 }
625 }
626 return pairs;
627}
628
629router.get('/ap/users/:slug/conversations', (req, res) => {
630 const auth = OAuth.verifyBearer(req.headers.authorization);
631 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
632 const heads = AP.conversationHeads(auth.site.slug);
633 const pairs = conversationItems(req, auth, heads);
634 const items = pairs.map((x) => x.item);
635 // Ongelezen per gesprek (shaer-frontend-3tx): een COUNT, geen bijgehouden
636 // getal. Hij hangt aan het NIEUWSTE kopje van elke persoon -- er kunnen er
637 // twee zijn (zie conversationHeads) en het aantal hoort bij het gesprek, niet
638 // bij een bericht.
639 //
640 // AS2 heeft geen term voor ongelezen; dit is per-lezer-interactiestatus,
641 // dezelfde categorie als shaer:liked. Niet in totalItems persen: dat betekent
642 // 'hoeveel er zijn' en niet 'hoeveel jij nog niet zag'.
643 // De poorten van DEZE lezer, niet die van de inbox-handler: die leeft in een
644 // andere functie en heette hier per ongeluk P.
645 const poorten = gatesFor(auth.site);
646 const ongelezen = AP.unreadPerConversation(auth.site.slug, {
647 messagesAllowed: poorten.messagesAllowed,
648 guardians: (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })(),
649 });
650 const gezien = new Set();
651 for (const { head, item } of pairs) {
652 if (gezien.has(head.other)) continue;
653 gezien.add(head.other);
654 const u = ongelezen.get(head.other);
655 if (!u) continue;
656 item.object['shaer:unread'] = u.n;
657 // Een zwaai is geen aantal maar een zetje van een guardian: eigen teken.
658 if (u.wave) item.object['shaer:unreadWave'] = true;
659 }
660 AP.sendAP(res, {
661 '@context': AP.AP_CONTEXT,
662 id: `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/conversations`,
663 type: 'OrderedCollection',
664 totalItems: items.length,
665 orderedItems: items,
666 'shaer:cursor': AP.feedCursor(auth.site.slug),
667 }, 'private, no-store');
668});
669
670router.get('/ap/users/:slug/messages', (req, res) => {
671 const auth = OAuth.verifyBearer(req.headers.authorization);
672 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
673 const other = String(req.query.with || '');
674 if (!/^https?:\/\//i.test(other)) return res.status(400).json({ error: 'with must be an actor URI' });
675 const page = AP.conversationHistory(auth.site.slug, other, {
676 before: req.query.before ? String(req.query.before) : null,
677 limit: req.query.limit,
678 });
679 const items = conversationItems(req, auth, page.rows).map((x) => x.item);
680 // De paginagrootte reist mee in next: vroeg je om 30, dan hoort de volgende
681 // pagina er ook 30 te zijn. Zonder dit wordt hij stilletjes de standaard, en
682 // dan klopt het ritme van een 'load more' niet meer met wat de gebruiker ziet.
683 const size = req.query.limit ? `&limit=${encodeURIComponent(String(req.query.limit))}` : '';
684 const self = `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/messages?with=${encodeURIComponent(other)}`;
685 AP.sendAP(res, {
686 '@context': AP.AP_CONTEXT,
687 id: req.query.before ? `${self}${size}&before=${encodeURIComponent(String(req.query.before))}` : `${self}${size}`,
688 type: 'OrderedCollectionPage',
689 partOf: self,
690 orderedItems: items,
691 // De volgende pagina is de standaardvorm van 'er is meer' (AS2). Ontbreekt
692 // hij, dan is het gesprek op -- en dat mag de client weten zonder gokken,
693 // want anders kan een 'load more' niet eerlijk verschijnen.
694 next: page.more && page.oldest ? `${self}${size}&before=${encodeURIComponent(page.oldest)}` : undefined,
695 }, 'private, no-store');
696});
697
698// De bel (/inbox/wait) is weg (shaer-pq4, 10-8). Hij deed hetzelfde als de
699// WACHTENDE inbox-lezing hierboven, maar in twee rondjes in plaats van een:
700// eerst 'er is nieuws', dan alsnog de lezing. Die lezing kan het zelf, en
701// sinds ?changes=1 stuurt hij alleen nog het verschil.
702//
703// AP.onNews blijft bestaan: de Guardian-PWA hangt er ook aan.
704
705// The server blocklist is the source of truth for Shaer's "in Orbit":
706// clients read it here instead of keeping their own state. Actor-kind
707// blocks only (domain blocks are instance policy, not an Orbit member).
708//
709// FEP-1580 zet deze deur één spleet verder open: de bronkant MOET de blokkades
710// beschikbaar maken voor de instantie waar je NAARTOE verhuist, zodat je
711// zichtbaarheidsvoorkeuren meeverhuizen. De doelkant haalt ze als eerste op,
712// want ze bepalen wat de rest te zien krijgt. Geen nieuwe collectie: deze
713// bestond al en staat al op de actor, alleen de toegang verbreedt.
714router.get('/ap/users/:slug/blocked', async (req, res) => {
715 const auth = OAuth.verifyBearer(req.headers.authorization);
716 let slug = (auth && auth.site.slug === req.params.slug) ? auth.site.slug : null;
717 if (!slug && req.headers['signature']) {
718 const verified = await AP.verifyRequest(req).catch(() => null);
719 if (verified && verified.id && AP.isMoveTarget(req.params.slug, verified.id)) slug = req.params.slug;
720 }
721 if (!slug) return res.status(403).end();
722 const base = baseUrl(req);
723 const items = AP.listBlocks(slug)
724 .filter((b) => b.kind === 'actor')
725 .map((b) => b.target);
726 AP.sendAP(res, {
727 '@context': AP.AP_CONTEXT,
728 id: `${base}/ap/users/${slug}/blocked`,
729 type: 'OrderedCollection',
730 totalItems: items.length,
731 orderedItems: items,
732 }, 'private, no-store');
733});
734
735// ── Guardian queues (owner only, FEP-633c, shaer:queues) ──────────
736// The dashboard collections the Shaer clients read: pending adoption offers,
737// gated follows (empty in Klonkt for now) and the guardian's wards. Same
738// contract as the Shaer test daemon.
739function queueRoute(name, build) {
740 router.get(`/ap/users/:slug/queues/${name}`, (req, res) => {
741 const auth = OAuth.verifyBearer(req.headers.authorization);
742 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
743 const base = baseUrl(req);
744 const me = `${base}/ap/users/${auth.site.slug}`;
745 // 304 als er niets veranderde (Barts punt, 9-8). Zonder dit haalde een app
746 // bij elke actie de hele lijst opnieuw op -- een hulpvraag afvinken vroeg de
747 // honderd wards inclusief poorten terug.
748 AP.sendMaybe304(req, res, { '@context': AP.AP_CONTEXT, ...build(`${me}/queues/${name}`, auth.site.slug, me) });
749 });
750}
751queueRoute('offers', (id, slug, me) => Guardianship.offersCollection(id, slug, me));
752queueRoute('follows', (id, slug, me) => Guardianship.followsCollection(id, slug, me));
753// §5.3 turned around (shaer-p729): what this ward has asked to follow, still
754// waiting on its guardians. Owner-only like the rest — who a child wants to
755// follow is nobody else's business.
756queueRoute('outgoing-follows', (id, slug, me) => Guardianship.outgoingFollowsCollection(id, slug, me));
757queueRoute('wards', (id, slug) => Guardianship.wardsCollection(id, slug));
758// Availability (FEP-633c 3.6.1) is never public: the ward reads its
759// guardians' real states here and nowhere else.
760queueRoute('guardians', (id, slug) => Guardianship.guardiansCollection(id, slug));
761
762// ── Het logboek (FEP-633c §4.2, shaer:log) ────────────────────────────
763// NAAST de wachtrijen en niet erin: alles onder shaer:queues wacht op een
764// antwoord, dit is wat er al besloten is. Eigen pad, dezelfde eigenaar-only
765// bearer. Het bestaat omdat een weigering anders alleen te merken viel doordat
766// er iets uit een lijst verdween, en "het is weg" is geen reden.
767router.get('/ap/users/:slug/log', (req, res) => {
768 const auth = OAuth.verifyBearer(req.headers.authorization);
769 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
770 const me = `${baseUrl(req)}/ap/users/${auth.site.slug}`;
771 AP.sendAP(res, {
772 '@context': AP.AP_CONTEXT,
773 ...Guardianship.logCollection(`${me}/log`, auth.site.slug, (s) => AP.listGuardianEvents(s, 50)),
774 }, 'private, no-store');
775});
776// De hulpvragen MET hun staat (5.2.1, shaer-lgo). De apps lazen ze uit de feed
777// en wisten dus niet of er al iemand op af was -- daarom bleef een afgehandeld
778// verzoek daar staan (Barts melding, 8-8).
779queueRoute('help', (id, slug) => Guardianship.helpCollection(id, slug));
780
781// ── Inbox read (owner only, AP C2S) ───────────────────────────────
782// GET on the inbox is part of ActivityPub C2S: the account owner (a bearer
783// scoped to this site) reads recent inbound posts (the timeline: accounts
784// they follow) as Create(Note) items, so an app (Shaer) can build a unified
785// feed. Anyone else gets 403; the inbox stays write-only for the public.
786router.get('/ap/users/:slug/inbox', async (req, res) => {
787 const auth = OAuth.verifyBearer(req.headers.authorization);
788 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
789 const base = baseUrl(req);
790 // Wachten is een UITBREIDING van deze lezing, geen tweede endpoint (shaer-n05).
791 // Geef `since` (de shaer:cursor van je vorige antwoord) en `wait` mee, en het
792 // antwoord blijft hangen tot er iets is of de tijd om is. Zonder die twee
793 // gedraagt de route zich exact zoals altijd.
794 //
795 // Bewust hetzelfde antwoord in plaats van een "er is nieuws"-seintje: dan
796 // hoeft er niets nieuws geparsed te worden, is er geen tweede beschrijving van
797 // de kaartvorm die uit de pas kan lopen, en scheelt het de client een tweede
798 // ronde.
799 const wachtS = Math.min(Math.max(parseInt(req.query.wait, 10) || 0, 0), 50);
800 if (req.query.since && wachtS > 0) {
801 const afbreken = new AbortController();
802 res.on('close', () => afbreken.abort()); // client hing op: niet doorgaan met wachten
803 const uit = await AP.waitForFeedChange(auth.site.slug, {
804 since: String(req.query.since), waitMs: wachtS * 1000, signal: afbreken.signal,
805 });
806 if (res.writableEnded || afbreken.signal.aborted) return undefined;
807 // Niets veranderd? Dan een LEEG antwoord (Barts punt): de hele collectie
808 // terugsturen terwijl er niets gebeurd is, is elke 25 seconden een tijdlijn
809 // over de mobiele verbinding voor niets. Met 304 kost stilte niets en kost
810 // nieuws nog steeds maar één rondje -- beter dan een apart seintje-endpoint,
811 // dat voor nieuws twee rondjes nodig heeft.
812 //
813 // De '0'-uitzondering is geen franje. Ontbreekt ap_feed_state (een instance
814 // die de migratie nog niet draaide), dan geeft feedCursor altijd '0' terug,
815 // en zou een client hier eeuwig 304 krijgen en nooit meer inhoud zien. Bij
816 // een lege merksteen sturen we dus gewoon de collectie.
817 if (!uit.changed && uit.cursor !== '0') {
818 res.set('Vary', 'Authorization');
819 return res.status(304).end();
820 }
821 }
822 // Gated feature (FEP-633c): may this account see EXTERNAL embeds? A ward's
823 // world outside the fediverse is the guardians' call. The gate is applied
824 // here, at serialisation: a blocked embed is never sent, because an embed the
825 // client merely hides has still been delivered to the device.
826 // De poorten van deze lezer (gatesFor): een plek waar ze berekend worden,
827 // zodat de gesprekslezingen dezelfde stand eerbiedigen en niet hun eigen
828 // kopie krijgen die kan gaan afwijken.
829 const P = gatesFor(auth.site);
830 const {
831 embedsAllowed, playbackAllowed, imagesAllowed, musicAllowed, quotesAllowed,
832 emojiAllowed, messagesAllowed, composeAllowed, repliesAllowed, threadsAllowed,
833 followingAllowed, gateAuthor,
834 } = P;
835 // De rechten-lijst hieronder vraagt er nog een paar rechtstreeks op.
836 const gate = (col) => Guardianship.wardGateAllowed(auth.site[col], P.isWard);
837 // ── Standaardvormen naast het dialect (shaer-nmw) ────────────────
838 //
839 // Een lezer die AS2 kent heeft nu genoeg aan attributedTo (ingesloten
840 // actor), quote (FEP-044f als object), preview (AS2 core) en de
841 // Announce-wrapper. De shaer:-velden blijven er nog naast staan voor apps
842 // in het veld; die gaan eruit als de clients om zijn.
843 // Wie ik ben en wie mijn guardians zijn: allebei de lezingen hieronder
844 // hebben ze nodig, dus een keer, hierboven.
845 const me = AP.actorId(base, auth.site.slug);
846 const myHandle = AP.deriveHandle(me); // een naam, of de kale URI -- nooit een halve
847 const guardianUris = (() => { try { return new Set(Guardianship.listGuardians(auth.site.slug).map((g) => g.other_uri)); } catch { return new Set(); } })();
848 // ── Alleen het VERSCHIL, als de client daarom vraagt (shaer-pq4) ──
849 //
850 // De wachtende lezing zei tot nu toe alleen DAT er iets veranderde, waarna de
851 // client alles opnieuw las: vier legs van zestig met al hun media-, quote- en
852 // embed-JSON, voor een enkel nieuw bericht. ap_feed_state houdt per object al
853 // bij wat er wanneer veranderde, dus het verschil lag er klaar en werd alleen
854 // nooit uitgedeeld (feedChangesSince had geen enkele aanroeper).
855 //
856 // OPT-IN met ?changes=1, en dat is geen franje: een app in het veld stuurt
857 // `since` al mee en vervangt haar hele feed door wat er terugkomt. Zou
858 // `since` opeens een verschil betekenen, dan wist die app zichzelf leeg.
859 //
860 // Het antwoord is een OrderedCollectionPage met partOf, want dat is wat het
861 // IS -- een deel, geen collectie. Een generieke lezer ziet dat verschil ook.
862 if (req.query.changes && req.query.since) {
863 const veranderd = AP.feedChangesSince(auth.site.slug, String(req.query.since));
864 const levend = veranderd.filter((c) => c.kind !== 'deleted').map((c) => c.object_uri);
865 const tl = new Map(AP.timelineRowsByIds(auth.site.slug, levend).map((r) => [r.id, r]));
866 const mn = new Map(AP.messageRowsByUri(auth.site.slug, levend.filter((u) => !tl.has(u))).map((r) => [r.object_uri, r]));
867 const rp = new Map(AP.replyRowsByUri(auth.site.slug, levend.filter((u) => !tl.has(u) && !mn.has(u))).map((r) => [r.object_uri, r]));
868 const reacties = AP.getReactionsFor(auth.site.slug, [...tl.keys()]);
869 const ctx = { base, me, myHandle, p: P };
870 const items = [];
871 for (const c of veranderd) {
872 if (c.kind === 'deleted') {
873 // Een verwijdering reisde tot nu toe als AFWEZIGHEID mee: de volledige
874 // lezing bevatte hem simpelweg niet meer. Die volledigheid is precies
875 // wat hier wegvalt, dus zonder grafsteen zou een weggehaalde post voor
876 // altijd in de app blijven staan -- en dat faalt stil. AS2 heeft er een
877 // vorm voor, en de rij lag er al.
878 items.push({ type: 'Delete', actor: me, object: { id: c.object_uri, type: 'Tombstone' } });
879 continue;
880 }
881 const t = tl.get(c.object_uri);
882 if (t) { items.push(timelineItem(t, { p: P, reactions: reacties })); continue; }
883 const m = mn.get(c.object_uri);
884 if (m) {
885 if (messagesAllowed || m.help_request || guardianUris.has(m.actor_uri)) items.push(messageItem(m, ctx));
886 continue;
887 }
888 const r = rp.get(c.object_uri);
889 if (r) { items.push(replyItem(r, ctx)); continue; }
890 const n = AP.getOutboxNote(base, c.object_uri);
891 if (n) items.push(sentItem(n, { me, mine: AP.selfAuthor(base, auth.site) }));
892 }
893 return AP.sendAP(res, {
894 '@context': AP.AP_CONTEXT,
895 id: `${base}/ap/users/${encodeURIComponent(auth.site.slug)}/inbox?changes=1&since=${encodeURIComponent(String(req.query.since))}`,
896 type: 'OrderedCollectionPage',
897 partOf: `${base}/ap/users/${auth.site.slug}/inbox`,
898 orderedItems: items,
899 // De rechten gaan MEE. Zonder dit valt de client terug op zijn standaard,
900 // en die standaard is 'alles mag' -- dan zet een gesloten poort zichzelf
901 // stil open bij elke verschil-lezing. Dezelfde reden waarom een 304 de
902 // caps met rust laat.
903 'shaer:capabilities': capabilitiesOf(P, gate),
904 'shaer:cursor': AP.feedCursor(auth.site.slug),
905 }, 'private, no-store');
906 }
907 const rows = AP.getTimeline(auth.site.slug, 60);
908 // Eén query voor de hele pagina (shaer-9e9 fase 2): shaer:liked komt uit de
909 // tussentabel, de bron van waarheid, en niet meer uit de afgeleide kolom op
910 // ap_timeline. Per rij vragen zou hier een N+1 opleveren.
911 const reacties = AP.getReactionsFor(auth.site.slug, rows.map((t) => t.id));
912 const posts = rows.map((t) => timelineItem(t, { p: P, reactions: reacties }));
913 // The direct notes addressed to this account: a plain DM, a guardian's wave
914 // (§5), a ward's 🛟 help request (§5.2.1). Those are messages, not posts, so
915 // they are not in the timeline; without them the app's Berichten shows only
916 // what you said yourself. Same shape as a post, so one parser handles both.
917 // Messages dicht (shaer-3ow) sluit vreemden en vrienden, maar NOOIT het
918 // guardian-kanaal: de zwaai en het gesprek na een hulpvraag zijn precies
919 // het kanaal dat het kind veilig houdt, en een poort die dat afsnijdt
920 // beschermt niemand. De hulpvraag zelf gaat aan de innamekant al altijd voor.
921 const messageCtx = { base, me, myHandle, p: P };
922 const messages = AP.getDirectMessages(auth.site.slug, 60)
923 .filter((m) => messagesAllowed || m.help_request || guardianUris.has(m.actor_uri))
924 .map((m) => messageItem(m, messageCtx));
925 // Inbound REPLIES on your own posts: stored as interactions (the web's
926 // comment machinery), never as mentions, so this read missed them and a
927 // friend's reply arrived everywhere except in your app (Robins melding,
928 // 30-7). Same shape as the other legs; media/quotes ride the stored JSON.
929 const replies = AP.getReplyMessages(auth.site.slug, 60).map((m) => replyItem(m, messageCtx));
930 // Your OWN sent notes (replies and direct messages, ap_outbox): without
931 // them a reply existed everywhere except in your own app, Messages showed
932 // half a conversation, and a retry ran into the duplicate guard (Robins
933 // melding, 30-7). Served like the other legs: same shape, one parser.
934 const mine = AP.selfAuthor(base, auth.site);
935 const sent = AP.getSentNotes(base, auth.site, 60).map((n) => ({
936 id: `${n.id}#create`,
937 type: 'Create',
938 actor: me,
939 published: n.published,
940 // The leading mention anchor is addressing, not prose (the DM leg strips
941 // it the same way); the Mention tags built from the full content stay.
942 object: {
943 ...n, content: AP.stripLeadingMentions(n.content),
944 attributedTo: AP.actorObject(typeof n.attributedTo === 'string' ? n.attributedTo : me, mine),
945 },
946 }));
947 // Newest first over all legs, so the app can keep treating this as one feed.
948 const items = [...posts, ...messages, ...replies, ...sent].sort((a, b) => String(b.published || '').localeCompare(String(a.published || '')));
949 AP.sendAP(res, {
950 '@context': AP.AP_CONTEXT,
951 id: `${base}/ap/users/${auth.site.slug}/inbox`,
952 type: 'OrderedCollection',
953 // What this account may do with what is in here (FEP-633c 5.6). Owner-only
954 // by construction, and never on the public actor document: it says
955 // something about a child, and only the child and its guardians need it.
956 'shaer:capabilities': capabilitiesOf(P, gate),
957 // Het merk van wat hierin zit. Geef hem terug als `since` om op het
958 // volgende te wachten. NA het samenstellen bepaald, zodat hij precies dekt
959 // wat je in handen hebt en niet iets dat er ondertussen bij kwam.
960 'shaer:cursor': AP.feedCursor(auth.site.slug),
961 totalItems: items.length,
962 orderedItems: items,
963 });
964 return undefined;
965});
966
967// ── uploadMedia (owner only, AP C2S) ──────────────────────────────
968// The actor advertises endpoints.uploadMedia; this implements it. A bearer
969// scoped to this site uploads one image/audio/video (multipart field "file",
970// AP convention) into the same store the reply editor uses, and gets back
971// { url, mediaType, name } to attach on a note (e.g. the help-buoy capture).
972const AP_MEDIA_DIR = mediaDir('REPLY_MEDIA_PATH', 'reply-media');
973fs.mkdirSync(AP_MEDIA_DIR, { recursive: true });
974const AP_MEDIA_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp', '.gif', '.mp3', '.m4a', '.ogg', '.opus', '.flac', '.wav', '.mp4', '.webm', '.mov']);
975const apMediaUpload = multer({
976 storage: multer.diskStorage({
977 destination: (req, file, cb) => cb(null, AP_MEDIA_DIR),
978 filename: (req, file, cb) => cb(null, `${randomUUID()}${path.extname(file.originalname || '').toLowerCase()}`),
979 }),
980 limits: { fileSize: 32 * 1024 * 1024 },
981 fileFilter: (req, file, cb) => {
982 const ext = path.extname(file.originalname || '').toLowerCase();
983 if (!AP_MEDIA_EXT.has(ext)) return cb(new Error('Media must be an image, audio or video file'));
984 cb(null, true);
985 },
986});
987router.post('/ap/users/:slug/uploadMedia', (req, res) => {
988 const auth = OAuth.verifyBearer(req.headers.authorization);
989 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
990 apMediaUpload.single('file')(req, res, (err) => {
991 if (err) return res.status(400).json({ error: err.message });
992 if (!req.file) return res.status(400).json({ error: 'No file' });
993 const mime = String(req.file.mimetype || '');
994 if (!/^(image|audio|video)\//.test(mime)) {
995 try { fs.unlinkSync(req.file.path); } catch { /* best effort */ }
996 return res.status(400).json({ error: 'Media must be an image, audio or video file' });
997 }
998 // A video gets a poster frame next to it (shaer-zowq), best-effort and
999 // out of band: ffmpeg pulls one frame at 1s into <name>.poster.jpg. On a
1000 // machine without ffmpeg nothing happens and nothing breaks; the clients
1001 // fall back to extracting a frame natively.
1002 if (mime.startsWith('video/')) {
1003 // The bundled static build (ffmpeg-static) does the work, exactly like
1004 // VideoCoverService and AudioTranscoder already do: Klonkt SHIPS its
1005 // ffmpeg (Robins opmerking, 30-7), so nothing needs installing on any
1006 // machine. Soft dependency + best-effort: absent stays silent, and
1007 // FFMPEG_PATH can still override for an operator who wants a newer one.
1008 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
1009 const bin = process.env.FFMPEG_PATH || ff.default;
1010 if (!bin) return;
1011 const poster = req.file.path + '.poster.jpg';
1012 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-ss', '1', '-i', req.file.path, '-frames:v', '1', '-vf', "scale='min(640,iw)':-2", poster],
1013 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] poster failed:', e.message); });
1014 }).catch(() => { /* never blocks the upload */ });
1015 }
1016 // Audio gets the same courtesy (Robins vraag, 30-7: vrolijk de kale
1017 // audio-tegel op): ffmpeg draws the waveform into <name>.poster.png.
1018 // White on transparent, so the tile's own gradient stays the backdrop
1019 // and every audio post keeps its own hue. The shape is bars, not the
1020 // raw hairy wave (Robins tweede vraag): peak and average sampled into
1021 // 57 columns (soft tip over bright core), blown up nearest-neighbor to
1022 // 14px bars, and drawgrid ERASES 5px gaps (c=black@0 + replace=1 writes
1023 // transparent pixels; h=2*ih keeps horizontal grid lines out of frame).
1024 if (mime.startsWith('audio/')) {
1025 Promise.all([import('child_process'), import('ffmpeg-static')]).then(([{ execFile }, ff]) => {
1026 const bin = process.env.FFMPEG_PATH || ff.default;
1027 if (!bin) return;
1028 const poster = req.file.path + '.poster.png';
1029 const graph = '[0:a]aformat=channel_layouts=mono,asplit[a][b];'
1030 + '[a]showwavespic=s=57x256:colors=white@0.5:filter=peak:scale=sqrt:draw=full[pk];'
1031 + '[b]showwavespic=s=57x256:colors=white:filter=average:scale=sqrt:draw=full[av];'
1032 + '[pk][av]overlay=format=auto,scale=798:256:flags=neighbor,drawgrid=w=14:h=2*ih:t=5:c=black@0:replace=1';
1033 execFile(bin, ['-hide_banner', '-loglevel', 'error', '-y', '-i', req.file.path, '-filter_complex', graph, '-frames:v', '1', poster],
1034 { timeout: 30000 }, (e) => { if (e && e.code !== 'ENOENT') console.warn('[media] waveform failed:', e.message); });
1035 }).catch(() => { /* never blocks the upload */ });
1036 }
1037 res.status(201).json({
1038 url: '/media/reply-media/' + req.file.filename,
1039 mediaType: mime,
1040 name: String(req.file.originalname || '').slice(0, 120),
1041 });
1042 });
1043});
1044
1045// ── Followers (count-only public, full for the owner) ─────────────
1046// A C2S bearer scoped to this site (the account owner) gets the real actor
1047// URIs so their own client can build a friends list; everyone else gets the
1048// count only (privacy).
1049// FEP-9876: enrichment is opt-in via `Prefer: return=representation` (RFC 7240).
1050// Returns true and sets the response headers when the owner asked for it.
1051function wantsEnriched(req, res) {
1052 res.set('Vary', 'Prefer'); // enriched and bare are two representations
1053 if (AP.prefersEnriched(req.get('Prefer'))) {
1054 res.set('Preference-Applied', 'return=representation');
1055 return true;
1056 }
1057 return false;
1058}
1059
1060router.get('/ap/users/:slug/followers', (req, res) => {
1061 const auth = OAuth.verifyBearer(req.headers.authorization);
1062 const owner = auth && auth.site.slug === req.params.slug;
1063 const site = owner ? auth.site : publicSite(req.params.slug);
1064 if (!site) return res.status(404).end();
1065 if (owner) {
1066 const uris = db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ? ORDER BY created_at').all(site.slug).map((r) => r.actor_uri);
1067 // Default = bare references; enrich only when the client asks (FEP-9876).
1068 const items = wantsEnriched(req, res) ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
1069 return AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, items.length, items, { page: paginaNr(req) }));
1070 }
1071 const n = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?').get(site.slug).n;
1072 AP.sendAP(res, AP.buildFollowers(baseUrl(req), site, n, null, { page: paginaNr(req) }));
1073});
1074
1075// ── Following (count-only public, full for the owner) ─────────────
1076router.get('/ap/users/:slug/following', (req, res) => {
1077 const auth = OAuth.verifyBearer(req.headers.authorization);
1078 const owner = auth && auth.site.slug === req.params.slug;
1079 const site = owner ? auth.site : publicSite(req.params.slug);
1080 if (!site) return res.status(404).end();
1081 if (owner) {
1082 const enrich = wantsEnriched(req, res); // FEP-9876 opt-in
1083 let items = [];
1084 try {
1085 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);
1086 items = enrich ? uris.map((u) => AP.buildActorRef(site.slug, u)) : uris;
1087 } catch { /* table may not exist */ }
1088 return AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, items.length, items, { page: paginaNr(req) }));
1089 }
1090 let n = 0;
1091 try { n = db.prepare("SELECT COUNT(*) n FROM ap_following WHERE slug = ? AND status = 'accepted'").get(site.slug).n; } catch { /* table may not exist */ }
1092 AP.sendAP(res, AP.buildFollowing(baseUrl(req), site, n, null, { page: paginaNr(req) }));
1093});
1094
1095/**
1096 * Mag deze aanvrager alles van `slug` zien? Waar bij de eigenaar zelf, en waar
1097 * voor de actor waar `slug` naartoe verhuisd is (FEP-1580, Source Instance).
1098 *
1099 * Eén plek voor die vraag, want hij komt op meerdere collecties terug en twee
1100 * antwoorden op dezelfde vraag lopen vroeg of laat uiteen.
1101 */
1102async function magAlles(req, slug) {
1103 const auth = OAuth.verifyBearer(req.headers.authorization);
1104 if (auth && auth.site.slug === slug) return true;
1105 if (!req.headers['signature']) return false;
1106 const v = await AP.verifyRequest(req).catch(() => null);
1107 return !!(v && v.id && AP.isMoveTarget(slug, v.id));
1108}
1109
1110// ── FEP-1580: de vertaaltabel van een verhuizing ──────────────────
1111//
1112// Publiek leesbaar, want dat is het hele doel: een derde die een oude URI in
1113// zijn database heeft leest hier wat de nieuwe is. Zonder deze collectie blijft
1114// elke reactie op een verhuisd bericht naar een dood adres wijzen.
1115//
1116// Niet-publieke items komen er alleen in voor een lezer die ze mocht zien. De
1117// spec: Moves voor objecten die niet aan as:Public gericht zijn MOGEN NIET
1118// publiek getoond worden. Een lijst met de URIs van je fan-only posts is een
1119// lek, ook al staat de inhoud er niet bij.
1120router.get('/ap/users/:slug/migration', async (req, res) => {
1121 const site = publicSite(req.params.slug);
1122 if (!site) return res.status(404).end();
1123 let alles = false;
1124 const auth = OAuth.verifyBearer(req.headers.authorization);
1125 if (auth && auth.site.slug === site.slug) alles = true;
1126 else if (req.headers['signature']) {
1127 const v = await AP.verifyRequest(req).catch(() => null);
1128 // Een geverifieerde volger zat in het publiek van de fan-only posts, dus
1129 // die mag ook weten waar ze heen zijn.
1130 if (v && v.id && AP.outboxAudience(site.slug, { verifiedActor: v.id }) === 'friend') alles = true;
1131 }
1132 AP.sendAP(res, Migration.buildMigration(baseUrl(req), site, { page: paginaNr(req), alles }),
1133 alles ? 'private, no-store' : undefined);
1134});
1135
1136// De Moves die de vertaaltabel rechtvaardigen. Altijd publiek: een bewijs dat
1137// je moet kunnen nakijken heeft niets aan een slot.
1138//
1139// LET OP: zonder FEP-8b32 (shaer-j1v0) staat hier geen handtekening onder. De
1140// collectie is structureel goed en niet verifieerbaar, en een derde die de spec
1141// streng volgt mag hem daarom weigeren. Bewust geen leeg proof-veld erbij.
1142router.get('/ap/users/:slug/moves', (req, res) => {
1143 const site = publicSite(req.params.slug);
1144 if (!site) return res.status(404).end();
1145 AP.sendAP(res, Migration.buildMoves(baseUrl(req), site));
1146});
1147
1148// ── Featured (pinned posts → Mastodon "Featured" tab) ─────────────
1149router.get('/ap/users/:slug/featured', (req, res) => {
1150 const site = publicSite(req.params.slug);
1151 if (!site) return res.status(404).end();
1152 // NB: Mastodon DISPLAYS the featured collection in REVERSE (pins shown
1153 // last-processed-first). So we emit it reversed (lowest pin priority first,
1154 // rank 1 last) → Mastodon flips it back to pin-rank ascending on the profile.
1155 // fan_only, ap_visibility, paid en excerpt MOETEN mee, om dezelfde reden als
1156 // in outboxSlice en backfillNewFollower (shaer-6oth, en Barts melding van
1157 // 15-8). buildNote beslist op deze velden, en een ontbrekende kolom is daar
1158 // `undefined` -- wat stilletjes het ruimste gedrag oplevert:
1159 //
1160 // zonder `paid` slaat buildNote zijn redactie over en gaat de VOLLEDIGE
1161 // tekst van een betaalde post mee. Deze collectie is
1162 // publiek en onbetekend opvraagbaar, dus dat is de post
1163 // gewoon te lezen. `excerpt` hoort erbij, anders valt de
1164 // teaser terug op de eerste alinea van precies de tekst
1165 // die verborgen moet blijven.
1166 // zonder ap_vis krijgt een quiet/unlisted post `to: as:Public` in plaats
1167 // van zijn volgers -- luider dan de schrijver koos.
1168 //
1169 // Het filter erbij: fan_only stond er al, ap_visibility ontbrak. Een post die
1170 // niet publiek bedoeld is hoort niet in een publieke collectie, ook niet als
1171 // hij vastgezet is.
1172 const posts = db.prepare(
1173 `SELECT id, slug, title, content, cover_image_url, cover_video_url, nsfw, content_warning, c2s_attachments, published_at, created_at,
1174 fan_only, ap_visibility, paid, paid_min_cents, excerpt
1175 FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
1176 AND IFNULL(ap_visibility, 'public') IN ('public', 'quiet')
1177 AND pinned IS NOT NULL AND pinned > 0
1178 ORDER BY pinned DESC, ${isoSql('COALESCE(published_at, created_at)')} ASC LIMIT 20`
1179 ).all(site.id);
1180 AP.sendAP(res, AP.buildFeatured(baseUrl(req), site, posts, { page: paginaNr(req) }));
1181});
1182
1183// ── Playlist als dereferenceerbare AP-collectie (shaer-ayc) ───────
1184// De eerste stap van het Funkwhale-spoor: een playlist heeft een id, dus een
1185// stabiele URI. Alleen het fedi_open-deel staat erin (de poort is per bestand
1186// en eenrichtings; zie setAudioFediOpen in routes/posts.js) — een collectie
1187// zonder open tracks bestaat wel maar is leeg, want de playlist zelf is niet
1188// geheim, alleen de bestanden erachter.
1189// De lijst van alle playlist-collecties (shaer-ayc, stap 2). De actor wijst
1190// hierheen via AS2 `streams`. Kaal standaard; verrijkte stubs op verzoek
1191// (FEP-9876), dezelfde conventie als followers/following.
1192router.get('/ap/users/:slug/playlists', (req, res) => {
1193 const site = publicSite(req.params.slug);
1194 if (!site) return res.status(404).end();
1195 AP.sendAP(res, AP.listPlaylistsAP(baseUrl(req), site, wantsEnriched(req, res), { page: paginaNr(req) }));
1196});
1197
1198// De tracks van deze site: de kanonieke plek voor onze muziek (shaer-0nh,
1199// stap 3). Een playlist is een keuze hieruit; deze collectie is alles wat de
1200// artiest heeft opengezet, ook wat in geen enkele playlist staat.
1201router.get('/ap/users/:slug/tracks', async (req, res) => {
1202 const site = publicSite(req.params.slug);
1203 if (!site) return res.status(404).end();
1204 AP.sendAP(res, AP.buildTrackCollection(baseUrl(req), site, AP.siteOpenTracks(site.id, { alles: await magAlles(req, site.slug) }), { page: paginaNr(req) }));
1205});
1206
1207// De bibliotheek van deze site (shaer-0nh). Funkwhale's Audio draagt een
1208// `library`, en dat is bij hen het haakje waar een UPLOAD aan komt te hangen --
1209// zonder die bak blijft een binnengehaalde track daar een naam zonder geluid.
1210// Gemeten op 13-8: open.audio had onze vier tracks wel, met onze eigen AP-id's,
1211// maar uploads leeg en is_playable false.
1212//
1213// Openbaar, want alles erin is fedi_open. Er valt dus niets goed te keuren en de
1214// volgerslijst blijft leeg: wie ons volgt volgt de ACTOR, niet de bak.
1215//
1216// `?page=` MOET hier doorgegeven worden. Zonder dat adverteert de wortel een
1217// `first` die op zichzelf uitkomt: de lezer volgt hem, krijgt weer een `Library`
1218// in plaats van een pagina, en klapt eruit -- open.audio gaf op 15-8 een 500 op
1219// precies deze URL. Dezelfde les als bij de outbox (shaer-sk4): een `first`
1220// beloven is een pagina beloven.
1221router.get('/ap/users/:slug/library', (req, res) => {
1222 const site = publicSite(req.params.slug);
1223 if (!site) return res.status(404).end();
1224 AP.sendAP(res, AP.buildLibrary(baseUrl(req), site, AP.siteOpenTracks(site.id), { page: paginaNr(req) }));
1225});
1226
1227// De volgerscollectie die hun docs als vereist noemen. Leeg en eerlijk: er is
1228// geen goedkeuringspad omdat de bibliotheek openbaar is.
1229router.get('/ap/users/:slug/library/followers', (req, res) => {
1230 const site = publicSite(req.params.slug);
1231 if (!site) return res.status(404).end();
1232 AP.sendAP(res, AP.pagedCollection(`${AP.libraryId(baseUrl(req), site)}/followers`, [], { page: paginaNr(req) }));
1233});
1234
1235// Eén track, los op te halen. Een gesloten track is AFWEZIG, niet leeg: 404,
1236// dezelfde regel als in de collectie, zodat het bestaan van een gated nummer
1237// niet uit een ander antwoord af te leiden is.
1238router.get('/ap/users/:slug/tracks/:id', (req, res) => {
1239 const site = publicSite(req.params.slug);
1240 if (!site) return res.status(404).end();
1241 const row = AP.openTrack(site.id, req.params.id);
1242 if (!row) return res.status(404).end();
1243 AP.sendAP(res, AP.buildTrackAudio(baseUrl(req), site, row, { standalone: true }));
1244});
1245
1246// De losse tracks van een post als EEN uitgave (shaer-38y). Ze gingen tot nu
1247// toe los de deur uit -- Audio-objecten die een lezer nergens kon plaatsen. Ze
1248// horen bij elkaar omdat ze in dezelfde post staan, en die post leent zijn
1249// titel, tekst, hoes en tags uit. 404 als de post geen muzikale eenheid IS:
1250// dan is er niets om naar te wijzen, en dat is geen lege collectie maar een
1251// collectie die niet bestaat.
1252router.get('/ap/users/:slug/posts/:id/tracks', (req, res) => {
1253 const site = publicSite(req.params.slug);
1254 if (!site) return res.status(404).end();
1255 const post = db.prepare(
1256 "SELECT id, slug, title, excerpt, content, cover_image_url, tags FROM posts WHERE id = ? AND site_id = ? AND status = 'published'"
1257 ).get(req.params.id, site.id);
1258 if (!post) return res.status(404).end();
1259 const col = AP.buildPostTrackCollection(baseUrl(req), site, post);
1260 if (!col) return res.status(404).end();
1261 AP.sendAP(res, col);
1262});
1263
1264router.get('/ap/users/:slug/playlists/:id', async (req, res) => {
1265 const site = publicSite(req.params.slug);
1266 if (!site) return res.status(404).end();
1267 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 = ?')
1268 .get(req.params.id, site.id);
1269 if (!pl) return res.status(404).end();
1270 // De doel-actor van een verhuizing krijgt de VOLLEDIGE plaat, niet alleen de
1271 // nummers die voor de fediverse opengezet zijn (FEP-1580).
1272 const alles = await magAlles(req, site.slug);
1273 AP.sendAP(res, AP.buildPlaylistCollection(baseUrl(req), site, pl, AP.playlistOpenTracks(pl.id, { alles })));
1274});
1275
1276// ── Note ──────────────────────────────────────────────────────────
1277router.get('/ap/notes/:id', async (req, res) => {
1278 // No fan_only filter in the SELECT anymore: a friends-only post is not
1279 // absent, it is GATED. The old route hid it from EVERYONE, also from the
1280 // follower whose friendship earns it — so the signed resolution the reply
1281 // path performs knocked on a door that could never open, and every reply
1282 // to a friends-only post (Shaer's default!) died in
1283 // cannot_resolve_inReplyTo. Strangers still get the exact same 404, so a
1284 // note's existence stays as private as before.
1285 // EEN GEBLOKKEERDE KRIJGT DE DEUR DICHT (Robin, 21-8), net als bij de outbox:
1286 // wie ondertekend aanklopt, klopt met zijn naam erop, en een blokkade is een
1287 // gesloten deur. Dezelfde 404 als een vreemde, zodat het bestaan van een note
1288 // niets extra's verraadt. Onbetekende verzoeken kunnen we niet thuisbrengen
1289 // en houden de publieke weergave -- daarvoor is de Block-bezorging.
1290 if (req.headers['signature']) {
1291 const wie = await AP.verifyRequest(req).catch(() => null);
1292 if (wie && wie.id && AP.isBlockedAny(wie.id)) return res.status(404).end();
1293 }
1294 const post = db.prepare(
1295 "SELECT * FROM posts WHERE id = ? AND status = 'published'"
1296 ).get(req.params.id);
1297 if (post && AP.noteAudience(post) !== 'public') {
1298 // The whole gate in a try: this is the only async route in this file,
1299 // and Express 4 does not catch an async rejection — the request would
1300 // hang forever instead of failing (which is exactly how the missing
1301 // default-export entry manifested while building this). Any error here
1302 // reads as "not authorized", never as silence.
1303 try {
1304 if (AP.noteAudience(post) === 'direct') return res.status(404).end();
1305 const gsite = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
1306 const actor = await AP.verifyRequest(req).catch(() => null);
1307 if (!actor || !AP.mayReadNote(gsite, post, actor.id)) return res.status(404).end();
1308 } catch { return res.status(404).end(); }
1309 }
1310 if (!post) {
1311 // Could be one of OUR outbound replies (ap_outbox), not a post.
1312 const note = AP.getOutboxNote(baseUrl(req), req.params.id);
1313 if (!note) return res.status(404).end();
1314 if (!AP.apWants(req)) {
1315 // A browser hit a reply's AP URL → send them to the source it replies to
1316 // (where the post + its reactions live), falling back to the site home.
1317 const src = (typeof note.inReplyTo === 'string' && /^https?:\/\//i.test(note.inReplyTo))
1318 ? note.inReplyTo : (baseUrl(req) + '/');
1319 return res.redirect(302, src);
1320 }
1321 return AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
1322 }
1323 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
1324 if (!site) return res.status(404).end();
1325 const note = AP.buildNote(baseUrl(req), site, post);
1326 if (!AP.apWants(req)) {
1327 // A browser hit a post's AP note URL → send them to the human post page
1328 // (which shows the post + its "from the fediverse" reactions).
1329 return res.redirect(302, note.url || (baseUrl(req) + '/'));
1330 }
1331 AP.sendAP(res, { '@context': AP.AP_CONTEXT, ...note });
1332});
1333
1334// ── Replies collection ── lets remote servers fetch a post's whole thread.
1335// ── De composer-preview (shaer-k3f): een URL wordt alvast een kaart ──
1336//
1337// Bearer-only, net als de thread: dit is de eigen app die tijdens het typen
1338// vraagt wat een link gaat worden. Dezelfde pijplijn als publiceren, dus de
1339// preview kan niet iets beloven dat de post niet waarmaakt. De embed gaat
1340// langs de eigen poort van de lezer -- een ward zonder open embeds-poort
1341// krijgt in de composer geen kaart die zijn feed hem ook niet zou tonen.
1342router.get('/ap/users/:slug/card', 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 uit = await AP.previewCard(String(req.query.url || ''));
1346 const isWard = (() => { try { return Guardianship.listGuardians(auth.site.slug).length > 0; } catch { return false; } })();
1347 const embedsAllowed = Guardianship.externalEmbedsAllowed(auth.site.external_embeds, isWard);
1348 const playback = embedsAllowed && Guardianship.externalPlaybackAllowed(auth.site.external_playback, isWard);
1349 AP.sendAP(res, {
1350 '@context': AP.AP_CONTEXT,
1351 quote: AP.quoteObject(uit.quoteJson),
1352 preview: embedsAllowed ? AP.previewObject(uit.embedJson, { playback }) : undefined,
1353 }, 'private, no-store');
1354});
1355
1356// ── De thread onder een post (shaer-tqz): ophalen, niet bewaren ────
1357//
1358// Bearer-only: dit is de eigen app van deze account die vraagt, nooit een
1359// vreemde. Klonkt doet de ondertekende GET die de app zelf niet kan (de
1360// sleutel staat hier), loopt één pagina van de replies-collectie af en geeft
1361// genormaliseerde notes terug. Er wordt NIETS opgeslagen; zie getThread.
1362//
1363// Voor een ward geldt de veiligste stand tot shaer-vw4 beslist is: alleen
1364// antwoorden uit de kring die de guardians al kennen, en shaer:hidden telt wat
1365// er buiten viel. De telling staat er zodat de UI eerlijk kan zijn -- OF hij
1366// getoond wordt is onderdeel van datzelfde besluit.
1367router.get('/ap/users/:slug/thread', async (req, res) => {
1368 const auth = OAuth.verifyBearer(req.headers.authorization);
1369 if (!auth || auth.site.slug !== req.params.slug) return res.status(403).end();
1370 const objectUri = String(req.query.object || '');
1371 if (!/^https:\/\//i.test(objectUri)) return res.status(400).json({ error: 'object must be an https URI' });
1372 const isWard = (() => { try { return Guardianship.listGuardians(auth.site.slug).length > 0; } catch { return false; } })();
1373 const uit = await AP.getThread(auth.site.slug, objectUri);
1374 if (!uit.found) {
1375 // WIENS schuld is dit? De oude melding zei "jouw server kon het niet
1376 // laden" terwijl onze server het prima deed en de BRON weigerde -- dat
1377 // wees naar de verkeerde partij (Barts melding, 10-8: een post van een
1378 // account dat hij vanochtend nog volgde, en dat nu niet meer).
1379 // 401/403/404/410 is een besluit van die server; al het andere, inclusief
1380 // een status die we niet eens kregen, is een storing.
1381 const geweigerd = [401, 403, 404, 410].includes(uit.sourceStatus);
1382 return res.status(geweigerd ? 404 : 502)
1383 .json({ error: geweigerd ? 'not shared by source' : 'source unreachable', sourceStatus: uit.sourceStatus || undefined });
1384 }
1385 // De poortstand komt uit de kolom (shaer-9y2): expliciete 0/1 van de
1386 // guardians wint, de automatiek is dicht-voor-een-ward. Dicht is de KRING,
1387 // niet niets: antwoorden van al goedgekeurd volk blijven staan, en wat er
1388 // buiten valt wordt geteld. Beeld, muziek en emoji gaan door dezelfde
1389 // poorten als de tijdlijn -- per verzoek, buiten de threadcache om.
1390 const threadsOpen = Guardianship.wardGateAllowed(auth.site.external_threads, isWard);
1391 const gate2 = (col) => Guardianship.wardGateAllowed(auth.site[col], isWard);
1392 const kring = threadsOpen ? { notes: uit.notes, hidden: 0 } : AP.filterThreadToCircle(auth.site.slug, uit.notes);
1393 const imagesOk = gate2('gate_images'), musicOk = gate2('gate_music'), emojiOk = gate2('gate_custom_emoji');
1394 uit.notes = kring.notes.map((n) => ({
1395 ...n,
1396 attachment: AP.gateAttachments(n.attachment, { images: imagesOk, audio: musicOk }),
1397 tag: emojiOk ? n.tag : AP.stripEmojiTags(n.tag),
1398 // De emoji-poort knipt in de byline zelf: FEP-9098 zit in de tag van de
1399 // ingesloten actor, niet meer in een eigen emoji-kaart ernaast.
1400 attributedTo: (!emojiOk && n.attributedTo && typeof n.attributedTo === 'object')
1401 ? { ...n.attributedTo, tag: undefined } : n.attributedTo,
1402 }));
1403 uit.hidden = kring.hidden;
1404 // Liked/boosted per antwoord, BUITEN de cache om: de genormaliseerde notes
1405 // mogen twee minuten oud zijn, maar of JIJ iets geliked hebt hoort van nu te
1406 // zijn -- anders springt het hartje terug zodra de reader opnieuw opent.
1407 const reacties = AP.getReactionsFor(auth.site.slug, uit.notes.map((n) => n.id));
1408 // De thread heeft al een ?object= in zijn id, dus geen ?page= erachter: die
1409 // collectie is niet te pagineren zonder de vraag zelf te herhalen. Hij is
1410 // owner-only en wordt door Shaer gelezen, niet door de federatie.
1411 AP.sendAP(res, {
1412 '@context': AP.AP_CONTEXT,
1413 id: `${baseUrl(req)}/ap/users/${encodeURIComponent(auth.site.slug)}/thread?object=${encodeURIComponent(objectUri)}`,
1414 type: 'OrderedCollection',
1415 totalItems: uit.notes.length,
1416 orderedItems: uit.notes.map((n) => ({
1417 ...n,
1418 'shaer:liked': !!(reacties.get(n.id) || {}).liked,
1419 'shaer:boosted': !!(reacties.get(n.id) || {}).boosted,
1420 })),
1421 'shaer:hidden': uit.hidden || undefined,
1422 }, 'private, no-store');
1423});
1424
1425router.get('/ap/notes/:id/replies', (req, res) => {
1426 const base = baseUrl(req);
1427 const items = AP.getReplyUris(base, req.params.id);
1428 AP.sendAP(res, AP.pagedCollection(`${base}/ap/notes/${req.params.id}/replies`, items));
1429});
1430
1431// ── NodeInfo ── standard instance metadata so fediverse tools recognise Klonkt.
1432router.get('/.well-known/nodeinfo', (req, res) => {
1433 res.type('application/json');
1434 res.set('Cache-Control', 'public, max-age=3600');
1435 res.send(JSON.stringify({ links: [{ rel: 'http://nodeinfo.diaspora.software/ns/schema/2.1', href: `${baseUrl(req)}/nodeinfo/2.1` }] }));
1436});
1437router.get('/nodeinfo/2.1', (req, res) => {
1438 let users = 0; let posts = 0;
1439 // "users" = public AP actors (sites), not the admin/member account rows.
1440 try { users = db.prepare('SELECT COUNT(*) c FROM sites WHERE (is_public IS NULL OR is_public = 1)').get().c; } catch { /* */ }
1441 try { posts = db.prepare("SELECT COUNT(*) c FROM posts WHERE status = 'published'").get().c; } catch { /* */ }
1442 res.type('application/json; charset=utf-8');
1443 res.set('Cache-Control', 'public, max-age=600');
1444 res.send(JSON.stringify({
1445 version: '2.1',
1446 software: { name: 'klonkt', version: _ver, repository: 'https://github.com/roboburr/klonkt' },
1447 protocols: ['activitypub'],
1448 services: { inbound: [], outbound: [] },
1449 openRegistrations: false,
1450 usage: { users: { total: users }, localPosts: posts },
1451 metadata: { nodeName: 'Klonkt' },
1452 }));
1453});
1454
1455// ── Inbox — Follow→Accept, Undo Follow (best-effort signature verify) ──
1456const apJson = express.json({
1457 type: ['application/activity+json', 'application/ld+json', 'application/json'],
1458 limit: '1mb',
1459 verify: (req, _res, buf) => { req.rawBody = buf; }, // raw body for digest verification
1460});
1461router.post(['/ap/users/:slug/inbox', '/ap/inbox'], apInboxLimiter, apJson, async (req, res) => {
1462 try { return res.status(await AP.handleInbox(req, req.params.slug || null) || 202).end(); }
1463 // Met de STACK erbij. Hier stond alleen `e.message`, en op 15-8 leverde dat
1464 // zes keer "[AP inbox] error: slug is not defined" op zonder één aanwijzing
1465 // waar -- een ReferenceError in een handler van duizenden regels, met een
1466 // naam die overal voorkomt. Een fout die je niet kunt plaatsen is niet
1467 // gemeld. Het type en de activiteit erbij, want dat zegt welke tak liep.
1468 catch (e) {
1469 const soort = req.body && req.body.type;
1470 console.warn('[AP inbox] error:', e.message, '| type:', soort, '| slug:', req.params.slug || '(gedeeld)');
1471 console.warn(e.stack);
1472 return res.status(202).end();
1473 }
1474});
1475
1476// ── Outbox POST: ActivityPub Client-to-Server ─────────────────────
1477// A bearer-authenticated client (Shaer) POSTs an activity; we translate it onto
1478// the normal delivery machinery. The token is scoped to one user+site (OAuth
1479// consent), so it must match the slug in the URL. (Declared after apJson, which
1480// this shares with the inbox handler.)
1481router.post('/ap/users/:slug/outbox', apInboxLimiter, apJson, async (req, res) => {
1482 const auth = OAuth.verifyBearer(req.headers.authorization);
1483 if (!auth) { res.set('WWW-Authenticate', 'Bearer'); return res.status(401).json({ error: 'invalid_token' }); }
1484 if (auth.site.slug !== req.params.slug) return res.status(403).json({ error: 'wrong_site', detail: 'token is scoped to a different site' });
1485 if (auth.user.readonly) return res.status(403).json({ error: 'read_only_account' });
1486
1487 const out = await AP.ingestOutboxActivity(auth.site, auth.user, req.body);
1488 if (out.error) return res.status(out.status || 400).json({ error: out.error, detail: out.detail });
1489 // 201 Created → Location header (AP spec); 202 Accepted for side-effect verbs.
1490 if (out.status === 201 && out.url) res.set('Location', out.url);
1491 // `state` carries a third outcome the app must be able to tell apart from a
1492 // plain success: a ward's follow held for its guardians (§5.3, shaer-p729).
1493 return res.status(out.status || 202).json({ ok: true, id: out.id, url: out.url, ...(out.state ? { state: out.state } : {}) });
1494});
1495
1496export default router;
Note: See TracBrowser for help on using the repository browser.