]*>\s*@[^<]+<\/a>[ ]*)+/i, (m, p) => p || '');
s = s.replace(/^(\s*]*>)?\s*(?:@[\w.-]+(?:@[\w.-]+)?[ ]+)+/i, (m, p) => p || '');
return s;
}
// View-ready threaded view of a post's fediverse activity (inbound replies +
// our outbound replies, nested), plus like/boost counts.
export function getInteractions(postId, base, site) {
const s = iStmts();
// Privacy: a followers-only or direct (DM) reply is addressed to people, not to the
// public web, so it must NOT render in the public thread. It still reaches the owner
// via notifications (post context + reference included there). Legacy rows without a
// visibility value are treated as public. Likes/boosts stay counted (count-only).
const rows = s.list.all(postId).filter((r) =>
r.kind !== 'reply' || !(r.visibility === 'followers' || r.visibility === 'direct'));
const baseClean = (base || process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const postNoteId = baseClean ? `${baseClean}/ap/notes/${postId}` : null;
// Our own (outbound) replies show the SITE identity for everyone (not "You").
let host = ''; try { host = new URL(baseClean).host; } catch { /* ignore */ }
const siteName = (site && (site.title || site.slug)) || '';
const siteHandle = (site && site.slug && host) ? `@${site.slug}@${host}` : '';
const siteUrl = baseClean ? `${baseClean}/` : '';
const siteIcon = (site && site.profile_photo) || null;
// Wat JIJ met deze reacties deed komt uit de tussentabel, niet meer uit
// acted_* (shaer-ipb). Eén batch-lookup, want een drukke thread zou anders een
// N+1 worden. De sleutel loopt door canonicalReactionUri, precies zoals aan de
// schrijfkant -- staat dezelfde note toevallig ook in je tijdlijn, dan is het
// één feit en niet twee knoppen die los van elkaar aan kunnen staan.
const mijnSleutel = new Map();
for (const r of rows) {
if (r.kind === 'reply' && r.object_uri) mijnSleutel.set(r.object_uri, canonicalReactionUri(site && site.slug, r.object_uri));
}
const mijn = getReactionsFor(site && site.slug, [...mijnSleutel.values()]);
const mijnReactie = (uri) => mijn.get(mijnSleutel.get(uri)) || { liked: false, boosted: false };
const nodes = [];
for (const r of rows) {
if (r.kind !== 'reply') continue;
const ik = mijnReactie(r.object_uri);
nodes.push({
noteId: r.object_uri, parent: r.parent_uri || null, mine: false, id: r.id,
actor_uri: r.actor_uri,
actor_name: r.actor_name, actor_handle: r.actor_handle, actor_url: r.actor_url,
actor_icon: r.actor_icon, content: stripLeadingMentions(r.content), created_at: r.published || r.created_at,
emoji_json: r.emoji_json, actor_emoji_json: r.actor_emoji_json, // FEP-9098 (thread render)
acted_boost: ik.boosted, acted_like: ik.liked,
children: [],
});
}
for (const o of s.listO.all(postId)) {
nodes.push({
noteId: baseClean ? `${baseClean}/ap/notes/${o.id}` : o.id, parent: o.in_reply_to || null,
mine: true, outboxId: o.id, content: stripLeadingMentions(o.content), created_at: o.created_at,
media: (() => { try { return o.attachments ? JSON.parse(o.attachments) : []; } catch { return []; } })(),
actor_name: siteName, actor_handle: siteHandle, actor_url: siteUrl, actor_icon: siteIcon,
children: [],
});
}
const byId = new Map(nodes.map((n) => [n.noteId, n]));
// Conversation partners per node (u02, the reply editor's mentions bar): the
// node's author plus the ancestor authors up the chain. Our own nodes are
// skipped (we do not mention ourselves), deduped by actor, capped at 8.
for (const n of nodes) {
const seen = new Set();
const list = [];
let cur = n, guard = 0;
while (cur && guard++ < 12 && list.length < 8) {
if (!cur.mine && cur.actor_uri && !seen.has(cur.actor_uri)) {
seen.add(cur.actor_uri);
list.push({
uri: cur.actor_uri,
url: cur.actor_url || cur.actor_uri,
handle: cur.actor_handle || deriveHandle(cur.actor_uri),
});
}
cur = cur.parent ? byId.get(cur.parent) : null;
}
n.participants = list;
}
const isTop = (n) => !n.parent || n.parent === postNoteId || !byId.has(n.parent);
const tops = [];
for (const n of nodes) {
if (isTop(n)) { tops.push(n); continue; }
let anc = n, guard = 0;
while (!isTop(anc) && guard++ < 12) anc = byId.get(anc.parent);
anc.children.push(n);
}
const byTime = (a, b) => new Date(a.created_at) - new Date(b.created_at);
tops.sort(byTime).forEach((t) => t.children.sort(byTime));
return {
thread: tops,
likeCount: rows.filter((r) => r.kind === 'like').length,
announceCount: rows.filter((r) => r.kind === 'announce').length,
total: nodes.length,
};
}
const slugFromActorUrl = (url) => { const m = String(url || '').match(/\/ap\/users\/([^/?#]+)/); return m ? decodeURIComponent(m[1]) : null; };
// Which of OUR sites are named in a note's Mention tags? Only hrefs on our own base count
// (an /ap/users/ path on a remote host is someone else's actor), and the slug must be
// an existing site. Deduped.
export function localMentionSlugs(tags, base) {
if (!base) return [];
const out = [], seen = new Set();
for (const t of (Array.isArray(tags) ? tags : (tags ? [tags] : []))) {
if (!t || t.type !== 'Mention' || typeof t.href !== 'string') continue;
if (!t.href.startsWith(base + '/ap/users/')) continue;
const slug = slugFromActorUrl(t.href);
if (!slug || seen.has(slug)) continue; seen.add(slug);
try { if (db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(slug)) out.push(slug); } catch { /* ignore */ }
}
return out;
}
// ── Authorized fetch for a single Note (2-8) ─────────────────────
// Who may read this post's Note over AP GET? 'public' needs nobody;
// friends-only (fan_only, Shaer's DEFAULT) needs a verified follower;
// 'direct' is addressed to people and is never served over a GET at all.
export function noteAudience(post) {
if (!post) return 'direct';
if (post.ap_visibility === 'direct') return 'direct';
if (post.fan_only || post.ap_visibility === 'friends') return 'followers';
return 'public';
}
// A follower earns the friends-only Note; a blocked actor gets the same
// nothing as a stranger (the standing rule: a blocked actor's signed fetch
// earns the empty set, gated server-side at serialisation).
export function mayReadNote(site, post, actorUri) {
const aud = noteAudience(post);
if (aud === 'public') return true;
if (aud === 'direct' || !site || !actorUri) return false;
// FEP-1580: dezelfde regel als in outboxAudience, en hier net zo hard nodig.
// De outbox geeft de LIJST vrij; zonder deze tak strandt de doelinstantie
// alsnog op elke losse Note die niet publiek is.
if (isMoveTarget(site.slug, actorUri)) return true;
try {
const blocked = db.prepare("SELECT 1 FROM ap_blocks WHERE slug = ? AND kind = 'actor' AND target = ?").get(site.slug, actorUri);
if (blocked) return false;
let host = null; try { host = new URL(actorUri).host; } catch { /* geen host, geen domein-block */ }
if (host) {
const dom = db.prepare("SELECT 1 FROM ap_blocks WHERE slug = ? AND kind = 'domain' AND target = ?").get(site.slug, host);
if (dom) return false;
}
return !!db.prepare('SELECT 1 FROM ap_followers WHERE slug = ? AND actor_uri = ?').get(site.slug, actorUri);
} catch { return false; }
}
// ── Web push to the owner (docs/webpush-design.md, slice 3) ─────────
// Fire-and-forget: a notification must never block or break inbox processing.
function pushEvent(slug, event) {
try { Push.notifySite(slug, event).catch(() => {}); } catch { /* never throw */ }
wakeNews(slug); // long-poll waiters (Robins verzoek, 31-7): same moments as push
}
// ── Long-poll on news (Robins verzoek, 31-7) ─────────────────────
// The app holds GET /ap/users/:slug/inbox/wait open; the moment anything
// push-worthy lands for that account (a message, a reply, a wave, a help
// request) every waiter is woken and the app re-reads its feed. In-process
// on purpose: one Klonkt is one process, and a waiter is one callback.
const _newsWaiters = new Map(); // slug -> Set
export function onNews(slug, cb) {
let set = _newsWaiters.get(slug);
if (!set) { set = new Set(); _newsWaiters.set(slug, set); }
set.add(cb);
return () => { set.delete(cb); if (!set.size) _newsWaiters.delete(slug); };
}
/**
* Wachters op het Guardian-paneel (Barts opdracht, 9-8).
*
* APART VAN onNews, en dat is met opzet. `news` gaat over de tijdlijn; dit gaat
* over alles wat een guardian te VERWERKEN krijgt -- een aanbod, een
* volgverzoek, een gate-voorstel, een hulpvraag, een lapse. De guardianship-
* module zendt daar al veertien soorten voor uit; die gingen alleen naar push,
* en push kiest bewust maar een handvol. Het paneel moet ze allemaal weten.
*
* Een wachter wordt EEN keer gewekt en daarna vergeten: het antwoord dat volgt
* is de nieuwe waarheid, en de client komt terug met een nieuwe wachter.
*/
const _guardWaiters = new Map(); // slug -> Set
export function onGuardian(slug, cb) {
let set = _guardWaiters.get(slug);
if (!set) { set = new Set(); _guardWaiters.set(slug, set); }
set.add(cb);
return () => { set.delete(cb); if (!set.size) _guardWaiters.delete(slug); };
}
export function wakeGuardian(slug) {
const set = _guardWaiters.get(slug);
if (!set || !set.size) return;
const cbs = [...set];
set.clear();
_guardWaiters.delete(slug);
for (const cb of cbs) { try { cb(); } catch { /* een wachter mag de rest nooit breken */ } }
}
export function wakeNews(slug) {
const set = _newsWaiters.get(slug);
if (!set || !set.size) return;
const cbs = [...set];
set.clear();
_newsWaiters.delete(slug);
for (const cb of cbs) { try { cb(); } catch { /* a waiter must never break the rest */ } }
}
// Path prefix for a site's pages. One instance is one owner, so the site
// lives at the root; kept as a function because the push URLs read like
// `${pushPrefix(slug)}/messages` all over this file.
function pushPrefix() { return ''; }
// Notification language: the site's content language (fallback: instance default).
function pushLang(slug) {
try { const r = db.prepare('SELECT language FROM sites WHERE slug = ?').get(slug); return (r && r.language) || process.env.KLONKT_DEFAULT_LANG || 'nl'; } catch { return 'nl'; }
}
// Site slug, target URL and title for a post-scoped notification.
function pushPostCtx(postId) {
try {
const r = db.prepare('SELECT p.slug AS post, p.title, s.slug AS site FROM posts p JOIN sites s ON s.id = p.site_id WHERE p.id = ?').get(postId);
if (!r) return null;
return { site: r.site, title: r.title || r.post, url: `${pushPrefix(r.site)}/${r.post}#fediverse` };
} catch { return null; }
}
/**
* Een DOORGESTUURDE activiteit alsnog verifiëren (shaer-s8k).
*
* Reageert iemand in een thread, dan stuurt de server van de oorspronkelijke
* poster die reactie door naar de deelnemers -- en ondertekent met zijn EIGEN
* sleutel. De handtekening klopt dan, maar de ondertekenaar is niet de auteur,
* dus de gate hieronder wees hem af. Gevolg: reacties van derden kwamen niet
* binnen, zonder dat iemand een fout zag.
*
* Mastodon lost dit op met een LD-Signature over de payload. Dat vraagt
* JSON-LD-canonicalisatie; wij doen het lichter en strenger: we geloven de
* bezorgde inhoud NIET en halen het object op bij de bron.
*
* Vier voorwaarden, en geen ervan is optioneel:
*
* 1. Alleen Create en Update. Een doorgestuurde Delete is per definitie niet te
* dereferencen -- het object is weg -- dus die blijft geweigerd.
* 2. De host van de object-id MOET die van de geclaimde actor zijn. Zonder dit
* anker wijst een doorsturer je naar een host die hij zelf beheert, waar
* attributedTo alles kan beweren.
* 3. Het OPGEHAALDE object wordt gebruikt, niet de bezorgde payload. Anders
* levert een doorsturer een echt id met verdraaide inhoud.
* 4. Mislukt het ophalen, of wijst het object zichzelf niet toe aan de
* geclaimde actor, dan blijft het een weigering. Geen twijfelgeval opslaan.
*/
/** Kennen we deze note? Een eigen post, een eigen outbox-antwoord, een
* gecachete post in de tijdlijn, of een reactie die al in een thread van ons
* staat. Alle vier zijn een geldige reden dat iemand ons een antwoord daarop
* doorstuurt; iets anders is dat niet. */
function knownNoteUri(uri) {
if (!uri || typeof uri !== 'string') return false;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
try {
if (base && uri.startsWith(`${base}/ap/notes/`)) {
const seg = decodeURIComponent(uri.slice(`${base}/ap/notes/`.length).split(/[?#]/)[0]);
if (db.prepare('SELECT 1 FROM ap_outbox WHERE id = ?').get(seg)) return true;
if (db.prepare('SELECT 1 FROM posts WHERE id = ?').get(seg)) return true;
}
if (db.prepare('SELECT 1 FROM ap_timeline WHERE id = ? LIMIT 1').get(uri)) return true;
if (db.prepare('SELECT 1 FROM ap_interactions WHERE object_uri = ? LIMIT 1').get(uri)) return true;
// Een antwoord dat we al bezorgd kregen van iemand die we volgen (shaer-e9g).
if (db.prepare('SELECT 1 FROM ap_seen_notes WHERE uri = ? LIMIT 1').get(uri)) return true;
} catch { /* bij twijfel niet ophalen */ }
return false;
}
/**
* Onthoud dat we dit bericht al eens bezorgd kregen.
*
* Alleen de URI. Geen inhoud, niets op het scherm, geen tweede weergave -- dit
* beantwoordt uitsluitend de vraag "kennen wij dit bericht?" die knownNoteUri
* stelt voordat er iets bij de bron wordt opgehaald.
*
* De beller bepaalt WIE er onthouden wordt, en dat is de hele veiligheidsvraag:
* onthouden we zomaar alles wat iemand aflevert, dan kan een vreemde eerst een
* bericht neerleggen en daarna met een doorgestuurd antwoord dáárop ons naar een
* adres van zijn keuze sturen. Vandaar dat handleInbox dit alleen doet voor
* schrijvers die je zelf volgt.
*/
const SEEN_NOTES_DAYS = 30;
let _seenSinceSnoei = 0;
function rememberNoteUri(uri) {
if (!uri || typeof uri !== 'string') return;
try {
db.prepare('INSERT OR IGNORE INTO ap_seen_notes (uri) VALUES (?)').run(uri);
// Af en toe opruimen, niet bij het opstarten: een server die weken doorloopt
// zou anders nooit snoeien. Doorsturen gebeurt kort na het antwoord, dus wat
// ouder is dan een maand beantwoordt geen enkele vraag meer.
if (++_seenSinceSnoei >= 500) {
_seenSinceSnoei = 0;
const r = db.prepare(`DELETE FROM ap_seen_notes WHERE created_at < datetime('now', '-${SEEN_NOTES_DAYS} days')`).run();
if (r.changes) console.log(`[AP] seen notes: ${r.changes} pruned`);
}
} catch { /* niet fataal */ }
}
const isFollowedActor = (uri) => {
try { return !!db.prepare('SELECT 1 FROM ap_following WHERE actor_uri = ? LIMIT 1').get(uri); } catch { return false; }
};
// Mislukte dereferences kort onthouden. Mastodon herhaalt een bezorging
// dagenlang; zonder dit doet elke herhaling de fetch opnieuw, ook als die de
// vorige twintig keer niets opleverde. Dempt meteen de scherpte van misbruik.
const _derefMiss = new Map();
const DEREF_MISS_MS = 30 * 60 * 1000;
function derefRecentlyFailed(uri) {
const t = _derefMiss.get(uri);
if (t === undefined) return false;
if (Date.now() - t > DEREF_MISS_MS) { _derefMiss.delete(uri); return false; }
return true;
}
function noteDerefFailure(uri) {
if (_derefMiss.size > 500) { // simpele begrenzing: oudste helft eruit
const oud = [..._derefMiss.entries()].sort((a, b) => a[1] - b[1]).slice(0, 250);
for (const [k] of oud) _derefMiss.delete(k);
}
_derefMiss.set(uri, Date.now());
}
async function dereferenceForwarded(act, claimedActor, type, slugParam) {
// Every exit states its reason. Five of the six used to return silently, so a
// rejection count could not be told apart from a narrowing that closed too far
// — and that is exactly the measurement shaer-drf is waiting for. Bounded by
// the signer-mismatch rate (tens per hour), so this is not a noisy log.
const skipped = (reason, detail) => {
console.log(`[AP] inbox forwarded, skipped (${reason}):`, claimedActor, detail || '');
return null;
};
if (type !== 'Create' && type !== 'Update') return skipped('not Create/Update', type);
const o = act && act.object;
const objId = typeof o === 'string' ? o : (o && o.id);
if (!objId || typeof objId !== 'string' || !/^https:\/\//i.test(objId)) return skipped('no https object id', objId || '(none)');
try {
if (new URL(objId).host !== new URL(claimedActor).host) return skipped('host anchor', objId); // ankereis
} catch { return skipped('unparsable id', objId); }
// Alleen dereferencen als het object beweert een antwoord te zijn op iets van
// ONS (shaer-drf). Zonder die eis zijn claimedActor en object.id allebei door
// de aanvaller gekozen en eist het host-anker alleen dat ze aan elkaar gelijk
// zijn -- dan kan iedereen met een werkende actor ons naar elke URL sturen.
// Doorsturen bestaat juist omdát wij in de thread zitten, dus deze eis kost
// niets aan legitiem verkeer waarvan we de ouder kennen.
const parent = typeof o === 'object' && o
? (typeof o.inReplyTo === 'string' ? o.inReplyTo : (o.inReplyTo && o.inReplyTo.id))
: null;
if (!knownNoteUri(parent)) return skipped('unknown inReplyTo', parent || '(none)');
if (derefRecentlyFailed(objId)) return skipped('recent failure', objId);
// Onbetekend eerst; tekenen alleen als terugval. Anders kan een ander ons een
// ONDERTEKEND verzoek naar een adres van zijn keuze laten sturen -- dezelfde
// reden als bij fetchActor sinds efe5633.
let fetched = await apGetJson(objId).catch(() => null);
if (!fetched || fetched.id !== objId) {
// The signer used to be slugParam, which is null on the shared inbox — and
// that is where forwarded traffic lands, because we advertise a sharedInbox.
// signedGetJson falls back to an unsigned GET for a null slug, so a source in
// secure mode could never be dereferenced at all. Same fix verifyRequest got
// in shaer-afq: any local actor is a valid signer.
const asSlug = slugParam || anySigningSlug();
if (asSlug) fetched = await signedGetJson(asSlug, objId).catch(() => null);
}
const attributed = fetched && (typeof fetched.attributedTo === 'string'
? fetched.attributedTo
: (fetched.attributedTo && fetched.attributedTo.id));
if (!fetched || fetched.id !== objId) {
noteDerefFailure(objId);
return skipped('fetch failed', objId);
}
if (attributed !== claimedActor) {
// Not a transport hiccup: the source itself says someone else wrote this.
noteDerefFailure(objId);
return skipped('attributedTo mismatch', `${objId} claims ${attributed || '(none)'}`);
}
return fetched;
}
// Handle an incoming inbox POST. slugParam = null for the shared /ap/inbox.
export async function handleInbox(req, slugParam, preVerified = null) {
const act = req.body || {};
const type = act.type;
// Real client IP (behind the proxy via `trust proxy`) — logged on dropped/rejected/
// ignored inbox hits so an operator can see who is probing their fediverse inbox.
const ip = req.ip || (req.connection && req.connection.remoteAddress) || '?';
const base = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
// preVerified is the loopback (see deliverToActor): a delivery between two
// actors on THIS instance never crosses a socket, so there is no signature to
// check — but we do know who signed, because we signed it. Handing that in
// keeps everything below identical, including the actor-versus-signer check,
// which is exactly the check that must not be skipped for being local.
const verified = preVerified || await verifyRequest(req, slugParam).catch(() => null);
// ENFORCE HTTP signatures: a data-affecting activity must be signed by the very
// actor it claims to be. No valid signature, or signer ≠ actor → reject (no
// forged replies/likes/follows/timeline posts). GET/discovery stays open.
const claimedActor = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
// Blocked actor/domain → silently drop (202, don't reveal the block).
if (claimedActor && isBlockedAny(claimedActor)) { console.log('[AP] inbox dropped (blocked)', claimedActor, 'from', ip); return 202; }
const GATED = ['Create', 'Like', 'Announce', 'Follow', 'Delete', 'Undo', 'Accept', 'Reject', 'Add', 'Remove', 'Update', 'Flag', 'Offer', 'Move'];
if (GATED.includes(type)) {
// Een geldige handtekening van iemand anders dan de auteur is doorsturen,
// geen vervalsing. Haal het object dan bij de bron op in plaats van het af
// te wijzen; lukt dat niet, dan valt het door naar de weigering hieronder.
let forwarded = null;
if (verified && claimedActor && verified.id !== claimedActor) {
forwarded = await dereferenceForwarded(act, claimedActor, type, slugParam).catch(() => null);
if (forwarded) {
act.object = forwarded; // de OPGEHAALDE inhoud, niet de bezorgde
console.log('[AP] inbox forwarded, verified at the source:', type, claimedActor, 'via', verified.id);
}
}
if (!forwarded && (!verified || !claimedActor || verified.id !== claimedActor)) {
// Drie verschillende oorzaken, die eerder allemaal "unsigned/invalid"
// heetten: geen handtekening meegestuurd, wel een handtekening maar niet
// te verifiëren (meestal een opgeheven account waarvan de sleutel weg is),
// of geldig ondertekend door iemand anders.
const reden = verified ? '(signer mismatch)'
: (req.headers && req.headers.signature) ? '(signature present, unverifiable)'
: '(no signature)';
console.warn('[AP] inbox REJECTED (signature)', type, claimedActor || '?', 'from', ip, reden);
return 401;
}
// One answer restores everything (FEP-633c 3.6): any VERIFIED activity
// from an actor that guards someone here restores it to active for those
// wards and cancels any lapse running against it, before the activity is
// even looked at. Signature-gated on purpose: an unverified claim of
// being gran must not wake gran up.
try {
const ev = Guardianship.availability.oneAnswer(claimedActor, Date.now());
if (ev.restored.length) console.log('[AP] guardian restored (one answer, 3.6):', claimedActor, '→', ev.restored.join(', '));
for (const c of ev.cancelledLapses) console.log('[AP] lapse cancelled by an answer from its target:', c.id);
} catch { /* availability is never load-bearing for delivery */ }
}
// FEP-633c §5.3 (modelled on the adoption offer): a gated follow forwarded to
// the guardians as an Offer(Follow), their Accept/Reject back to the ward.
if ((type === 'Offer' || type === 'Accept' || type === 'Reject') && act['shaer:followApproval'] === true) {
if (await handleFollowApprovalInbox(act, slugParam)) { console.log('[AP] follow-approval', type, 'from', claimedActor); return 202; }
}
// FEP-633c: the adoption handshake. An Offer lands at the local ward; an
// Accept/Reject answers an offer a local guardian sent. Anything the
// guardianship module does not recognize falls through to the old paths.
// An Undo of the guardianship Relationship (§3.2) is handled here too, and it
// must be seen BEFORE the generic Undo branch below, which only knows about
// Follow/Like/Announce and would swallow it with a 202.
if (type === 'Offer' || type === 'Accept' || type === 'Reject' || (type === 'Undo' && Guardianship.parseUndoRelationship(act))) {
// Every LOCAL party this activity is addressed to gets its own copy of the
// handshake (a ward and a co-guardian may both live here). Gather candidate
// local slugs from the inbox owner, the `to` list, and the ward.
// MET localSlugOf en niet met slugFromActorUrl. Dat laatste knipt alleen de
// staart van een pad af, zonder naar de HOST te kijken -- en deze uri's
// komen uit `to` en uit de relatie, dus van de afzender. Een Offer gericht
// aan https://elders.example/ap/users/dev leverde zo de slug "dev" op, en
// die bestaat hier. Dan draait onze dev de afhandeling van een activiteit
// die nooit aan hem geadresseerd was. localSlugOf eist dat de uri met onze
// eigen basis begint en dat de site echt bestaat.
const cand = new Set();
if (slugParam) cand.add(slugParam);
for (const t of (Array.isArray(act.to) ? act.to : (act.to ? [act.to] : []))) {
if (typeof t === 'string') { const s = localSlugOf(t); if (s) cand.add(s); }
}
if (type === 'Offer' || type === 'Undo') {
const rel = type === 'Undo' ? Guardianship.parseUndoRelationship(act) : Guardianship.parseRelationship(act.object);
if (rel) { const s = localSlugOf(rel.ward); if (s) cand.add(s); }
}
let consumed = false;
for (const slug of cand) {
const gsite = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
if (gsite && await Guardianship.handleGuardianshipInbox(gsite, act).catch(() => false)) consumed = true;
}
if (consumed) { console.log('[AP] guardianship', type, 'from', claimedActor); return 202; }
}
// A moderation report (Flag) about our content — store it for the targeted site's owner
// (each Klonkt site is moderated by its own owner). Signature is enforced (GATED).
if (type === 'Flag') {
const objs = Array.isArray(act.object) ? act.object : (act.object ? [act.object] : []);
const objectUris = objs.map((o) => (typeof o === 'string' ? o : (o && o.id))).filter(Boolean);
let targetSlug = null;
const noteIds = [];
for (const u of objectUris) {
const s = localSlugOf(u); // one of OURS -- host meegewogen
if (s) { targetSlug = targetSlug || s; continue; }
const pid = postIdFromNoteUrl(u, base); // one of our notes?
if (pid) noteIds.push(pid);
}
if (!targetSlug && noteIds.length) {
try { const r = db.prepare('SELECT s.slug FROM posts p JOIN sites s ON s.id = p.site_id WHERE p.id = ? LIMIT 1').get(noteIds[0]); if (r) targetSlug = r.slug; } catch { /* ignore */ }
}
if (!targetSlug) return 202; // not about us / can't tell → drop
// Flag is GATED, so `verified` is the signer's (reporter's) actor doc already.
const ai = actorInfo(verified || null, claimedActor);
try {
db.prepare('INSERT INTO ap_reports (slug, actor_uri, actor_name, actor_handle, actor_icon, content, objects, created_at) VALUES (?,?,?,?,?,?,?,CURRENT_TIMESTAMP)')
.run(targetSlug, claimedActor || null, ai.name, ai.handle, ai.icon, HtmlSanitizerService.toPlainText(act.content || '').slice(0, 3000), JSON.stringify(objectUris.slice(0, 20)));
console.log('[AP] report received for', targetSlug, 'from', claimedActor);
} catch { /* ignore */ }
return 202;
}
// FEP-7628 (DRAFT): an account moved house. Handled before Follow on purpose:
// a Move often arrives seconds before the new actor's re-Follow wave, and the
// swap below must not race our own outgoing Follow of the target.
if (type === 'Move') {
return handleMoveInbox(act, { verifiedActor: claimedActor });
}
if (type === 'Follow') {
const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
// EERST: volgt iemand onze BIBLIOTHEEK in plaats van onze actor? (shaer-0nh)
//
// Een luisteraar krijgt de muziek en NIET de gewone posts -- wie zich
// abonneert op een platenkast heeft niet om de Krant gevraagd. Vandaar een
// eigen tabel: zolang ze daar staan kan een postbezorging ze niet per
// ongeluk meenemen.
//
// De bibliotheek is openbaar (alles erin is fedi_open), dus dit accepteert
// meteen. Er valt niets goed te keuren, en dan is wachten oneerlijk.
const libSlug = libraryOwnerSlug(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
if (who && libSlug) {
const remote = await fetchActor(who);
if (!remote || !remote.inbox) return 202;
const fi = actorInfo(remote, who);
luisteraars.voegToe(libSlug, {
actorUri: who, inbox: remote.inbox,
sharedInbox: (remote.endpoints && remote.endpoints.sharedInbox) || null,
name: fi.name, handle: fi.handle, icon: fi.icon,
});
const keys = getOrCreateKeys(libSlug);
const accept = {
'@context': AP_CONTEXT,
id: `${actorId(base, libSlug)}#accept-library-${Date.now()}-${rid()}`,
type: 'Accept', actor: actorId(base, libSlug), object: act,
};
deliver(remote.inbox, accept, `${actorId(base, libSlug)}#main-key`, keys.privatePem)
.catch(() => { /* de volger staat er; een mislukte Accept mag dat niet omgooien */ });
console.log('[AP] library follow from', who, '->', libSlug);
return 202;
}
// slugParam is de eigenaar van een per-actor inbox; op de GEDEELDE inbox is
// die er niet en werd de slug uit act.object geraden. Zonder hostcontrole
// kon een Follow op andermans actor met dezelfde padstaart hier een volger
// opleveren.
const slug = slugParam || localSlugOf(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
if (!who || !slug) return 400;
const remote = await fetchActor(who);
if (!remote || !remote.inbox) return 202; // can't reach them → drop quietly
const sharedInbox = (remote.endpoints && remote.endpoints.sharedInbox) || null;
const fi = actorInfo(remote, who); // cache display for the friends list (shaer-aa3)
// FEP-633c §5.3: if the followed actor is a WARD (has guardians), the
// follow is gated. A committed guardian's own Follow is auto-accepted
// (it needs no gate); anyone else is held pending for guardian approval.
// Free actors / normal sites have no guardians → fall through, unchanged.
const wardGuardians = Guardianship.listGuardians(slug).map((g) => g.other_uri);
if (wardGuardians.length && !wardGuardians.includes(who)) {
const followId = (typeof act.id === 'string' && act.id) || `${who}#follow-${Date.now()}-${rid()}`;
Guardianship.follows.recordPending(slug, {
id: followId, follower: who, inbox: remote.inbox, sharedInbox,
name: fi.name, handle: fi.handle, icon: fi.icon, activity: act,
});
// FEP-633c §5.3, modelled on the guardian offer: the ward forwards the
// gated follow to its guardians for approval. A LOCAL guardian gets a
// push and reads /guardian directly; a REMOTE guardian gets an
// Offer(Follow) delivered so its instance stores a copy (same distributed
// pattern as the adoption offer). On quorum the ward returns Accept(Follow).
const wardActor = actorId(base, slug);
const wardKeys = getOrCreateKeys(slug);
const followObj = { id: followId, type: 'Follow', actor: who, object: wardActor };
// Dormancy evidence (FEP-633c 3.6.2): this decision directly addresses
// every guardian. The ONLY admissible evidence is a request like this
// one going unanswered; recordRequest itself skips a declared absence.
for (const g of wardGuardians) {
try { Guardianship.availability.recordRequest(slug, g, followId, Date.now()); } catch { /* never load-bearing */ }
}
for (const g of wardGuardians) {
// Local ONLY when the guardian lives on THIS instance: slugFromActorUrl
// ignores the host (an /ap/users/x path on a remote host is someone
// else's actor), so also require our base + an existing local site.
const gslug = g.startsWith(`${base}/`) ? slugFromActorUrl(g) : null;
const isLocal = gslug && db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(gslug);
if (isLocal) {
const L = pushLang(gslug);
// Een volgverzoek is geen mede-voogdij. Deze push leende de tekst van
// offer_for_ward en meldde dus een adoptie die niet gebeurde -- met de
// volger als onderwerp. Eigen woorden, en allebei de namen erin: wie
// er vraagt, en om wie het gaat (shaer-p729).
pushEvent(gslug, { type: 'guardian', title: i18nT(L, 'push.n_guard_folin_t'), body: i18nT(L, 'push.n_guard_folin_b', { who: fi.name || fi.handle || i18nT(L, 'notif.someone'), ward: slug }), url: `${pushPrefix(gslug)}/guardian` });
} else {
fetchActor(g).then((ga) => {
const inbox = ga && ((ga.endpoints && ga.endpoints.sharedInbox) || ga.inbox);
if (!inbox) return;
const beslissend2 = Guardianship.gated.isDecisive(0, Guardianship.follows.followThreshold(guardians.length));
const offer = { '@context': AP_CONTEXT, id: `${wardActor}#followoffer-${Date.now()}-${rid()}`, type: 'Offer', actor: wardActor, to: [g], object: followObj, 'shaer:followApproval': true, 'shaer:decisive': beslissend2 };
deliverWithRetry(slug, inbox, offer, `${wardActor}#main-key`, wardKeys.private_pem).catch(() => {});
}).catch(() => {});
}
}
console.log('[AP] Follow', who, '→ ward', slug, '(gated, awaiting guardians)');
return 202;
}
// De eigenaarspoort (Robins wens, 18-8): met approve_followers aan wordt
// een Follow niet automatisch geaccepteerd — hij wacht in dezelfde
// wachtrij als een ward-follow, maar hier beslist de EIGENAAR, op
// /connect. Zo kan niemand een klonkt zomaar aan een hub of ander
// verzamelplatform hangen zonder dat de eigenaar ja heeft gezegd.
// Wards vallen hier nooit: de guardianpoort hierboven gaat vóór.
const ownerGate = db.prepare('SELECT approve_followers FROM sites WHERE slug = ?').get(slug);
if (ownerGate && ownerGate.approve_followers) {
const followId = (typeof act.id === 'string' && act.id) || `${who}#follow-${Date.now()}-${rid()}`;
Guardianship.follows.recordPending(slug, {
id: followId, follower: who, inbox: remote.inbox, sharedInbox,
name: fi.name, handle: fi.handle, icon: fi.icon, activity: act, quorum: 'owner',
});
const L = pushLang(slug);
pushEvent(slug, {
type: 'follow',
title: i18nT(L, 'push.n_folreq_t'),
body: i18nT(L, 'push.n_folreq_b', { who: fi.name || fi.handle || i18nT(L, 'notif.someone') }),
url: `${pushPrefix(slug)}/connect`,
});
console.log('[AP] Follow', who, '→', slug, '(awaiting owner approval)');
return 202;
}
fStmts().ins.run(slug, who, remote.inbox, sharedInbox, fi.name, fi.handle, fi.icon);
try { _updFDisp.run(fi.name, fi.handle, fi.icon, slug, who); } catch { /* best effort */ }
{ const L = pushLang(slug); pushEvent(slug, { type: 'follow', title: i18nT(L, 'push.n_follow_t'), body: i18nT(L, 'push.n_follow_b', { who: fi.name || fi.handle || i18nT(L, 'notif.someone') }), url: `${pushPrefix(slug)}/connect` }); }
const me = actorId(base, slug);
const keys = getOrCreateKeys(slug);
const accept = { '@context': AP_CONTEXT, id: `${me}#accept-${Date.now()}-${rid()}`, type: 'Accept', actor: me, object: act };
deliver(remote.inbox, accept, `${me}#main-key`, keys.private_pem).catch((e) => console.warn('[AP] Accept delivery failed:', e.message));
// Auto-backfill: send our recent posts as Create so the instance has our history
// (Mastodon doesn't fetch history on follow). ONCE PER REMOTE INSTANCE only —
// Mastodon dedupes notes per-instance, so re-filling an instance that already has
// a follower of ours is wasted work (and won't re-populate the new follower's
// timeline anyway). Deliver to the shared inbox (instance-level) when present.
// Sync insert+check (no await between) → no interleave race with concurrent Follows.
const instanceFilled = sharedInbox &&
db.prepare('SELECT 1 FROM ap_followers WHERE slug = ? AND shared_inbox = ? AND actor_uri != ? LIMIT 1')
.get(slug, sharedInbox, who);
if (!instanceFilled) {
backfillNewFollower(base, slug, sharedInbox || remote.inbox).catch(() => { /* best-effort */ });
}
console.log('[AP] Follow', who, '→', slug, verified ? '(sig ok)' : '(sig unverified)');
return 202;
}
// Een luisteraar die weggaat, hoort meteen weg te zijn.
if (type === 'Undo' && act.object && act.object.type === 'Follow') {
const doel = typeof act.object.object === 'string' ? act.object.object : (act.object.object && act.object.object.id);
const libSlug = libraryOwnerSlug(doel);
const wie = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
if (libSlug && wie && luisteraars.verwijder(libSlug, wie)) {
console.log('[AP] library unfollow from', wie, '->', libSlug);
return 202;
}
}
if (type === 'Undo' && act.object) {
const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
const ot = act.object.type;
if (ot === 'Follow') {
const obj = act.object.object;
const slug = slugParam || slugFromActorUrl(typeof obj === 'string' ? obj : (obj && obj.id));
if (who && slug) { fStmts().del.run(slug, who); console.log('[AP] Unfollow', who, '→', slug); }
return 202;
}
if (ot === 'Like' || ot === 'Announce') {
const tgt = act.object.object;
const pid = postIdFromNoteUrl(typeof tgt === 'string' ? tgt : (tgt && tgt.id), base);
if (who && pid) { iStmts().delLA.run(ot.toLowerCase(), pid, who); console.log('[AP] Undo', ot, who, '→', pid); }
return 202;
}
return 202;
}
const actorUri = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
const resolveActor = async (uri) => ((verified && verified.id === uri) ? verified : await fetchActor(uri).catch(() => null));
// Our OWN activity is already stored via ap_outbox: don't store it twice.
// "Our own" means THIS inbox's owner, not "anyone who happens to live on this
// machine". The old reading dropped every activity between two sites on one
// instance, so a note from a co-located guardian to its ward was accepted
// with a 202 and then quietly thrown away: no mention, no away, no help
// request. Neighbours are not us (Robins regel, 29-7: on this machine
// everything behaves as if every Klonkt were somewhere else).
const isLocalActor = !!(actorUri && slugParam && actorUri === actorId(base, slugParam));
// Inbound reply: a Create whose object replies to one of our notes (post OR comment).
if (type === 'Create' && act.object && TIJDLIJN_SOORTEN.has(act.object.type)) {
const o = act.object;
// A poll ballot: a Note carrying a `name` (the chosen option) inReplyTo one of OUR poll
// posts. Record it (deduped per actor) BEFORE the reply logic so a vote is never stored
// as a comment. recordPollBallot returns handled=false only if the target isn't a poll.
if (o.name && o.inReplyTo && actorUri && !isLocalActor) {
const seg = postIdFromNoteUrl(o.inReplyTo, base);
if (seg && localPostExists(seg)) {
const rec = recordPollBallot(seg, actorUri, o.name);
if (rec.handled) { console.log('[AP] poll vote', actorUri, '→', seg); return 202; }
}
}
const tgt = findThreadTarget(o.inReplyTo, base);
if (tgt && actorUri && !isLocalActor) {
const ai = actorInfo(await resolveActor(actorUri), actorUri);
const html = HtmlSanitizerService.sanitize(o.content || '');
if (isRejectedObject(o.id)) { console.log('[AP] reply skipped (tombstoned)', o.id); return 202; }
iStmts().ins.run('reply', tgt.post_id, o.id || '', actorUri, ai.name, ai.handle, ai.url, ai.icon, html, o.published || null, tgt.parent_uri, noteVisibility(o), extractEmojiTags(o.tag), emojiJsonOf(ai.emojis));
console.log('[AP] reply', actorUri, '→', tgt.post_id);
// A reply is a post too: Berichten renders it the way de Krant renders a
// timeline row, so it needs the same media and the same quote/preview card.
{
const where = 'kind = ? AND post_id = ? AND actor_uri = ? AND object_uri = ?';
const key = ['reply', tgt.post_id, actorUri, o.id || ''];
const mj = mediaFromNote(o);
if (mj && mj !== '[]') { try { db.prepare(`UPDATE ap_interactions SET media_json = ? WHERE ${where}`).run(mj, ...key); } catch { /* ignore */ } }
resolveCard(o).then((c) => {
if (!c) return;
const col = c.column === 'quote_json' ? 'quote_json' : 'embed_json'; // never a value from the wire
try { db.prepare(`UPDATE ap_interactions SET ${col} = ? WHERE ${where}`).run(c.json, ...key); } catch { /* ignore */ }
}).catch(() => { /* best-effort */ });
}
{
// Private (followers/direct) replies push as a DM ping WITHOUT content
// (the push service should never carry private text, design decision);
// public replies carry a short snippet.
const ctx = pushPostCtx(tgt.post_id);
const vis = noteVisibility(o);
const priv = vis === 'direct' || vis === 'followers';
if (ctx) {
const L = pushLang(ctx.site);
const who = ai.name || ai.handle || i18nT(L, 'notif.someone');
if (priv) pushEvent(ctx.site, { type: 'dm', title: i18nT(L, 'push.n_dm_t'), body: i18nT(L, 'push.n_dm_b', { who }), url: `${pushPrefix(ctx.site)}/messages` });
else pushEvent(ctx.site, { type: 'reply', title: i18nT(L, 'push.n_reply_t', { title: ctx.title }), body: `${who}: ${HtmlSanitizerService.toPlainText(html).slice(0, 90)}`, url: ctx.url });
}
}
return 202;
}
// Home timeline (client): a top-level post from an account we follow.
if (actorUri && !isLocalActor && belongsInTimeline(o)) {
let subs = []; try { subs = db.prepare('SELECT slug, auto_boost FROM ap_following WHERE actor_uri = ?').all(actorUri); } catch { /* table may not exist yet */ }
if (subs.length) {
const ai = actorInfo(await resolveActor(actorUri), actorUri);
const { html, atts: _atts, url: _url } = timelineFields(o);
const media = JSON.stringify(_atts);
const poll = parsePoll(o); // a Question (fediverse poll) → cache its options/counts
// "Feature" = show in the Cirkel (local only). We do NOT auto-Announce
// incoming posts to the fediverse — that flooded followers. Boosting to the
// fediverse is only ever a deliberate, manual per-post action (the 🔁 on
// the timeline).
for (const s of subs) {
tlStmts().ins.run(o.id, s.slug, actorUri, ai.name, ai.handle, ai.icon, ai.url, html, _url, o.published || null, media, o.sensitive ? 1 : 0, contentWarning(o));
// FEP-633c §2.2: register the ward hint on the stored object (no action yet).
if (Guardianship.objectHasGuardians(o)) { try { db.prepare('UPDATE ap_timeline SET has_guardians = 1 WHERE id = ? AND slug = ?').run(o.id, s.slug); } catch { /* ignore */ } }
// FEP-9098: keep the note's custom-emoji tags so the C2S inbox read can serve them.
{ const ej = extractEmojiTags(o.tag); if (ej) { try { db.prepare('UPDATE ap_timeline SET emoji_json = ? WHERE id = ? AND slug = ?').run(ej, o.id, s.slug); } catch { /* ignore */ } } }
storeAuthorEmoji(o.id, s.slug, ai); // custom-emoji display name for the byline
// FEP-e232 + FEP-044f: keep the note's object-link/quote tags for the same read.
{ const lj = extractLinkJson(o); if (lj) { try { db.prepare('UPDATE ap_timeline SET link_json = ? WHERE id = ? AND slug = ?').run(lj, o.id, s.slug); } catch { /* ignore */ } } }
if (poll) { try { db.prepare('UPDATE ap_timeline SET poll_json = ? WHERE id = ? AND slug = ?').run(JSON.stringify(poll), o.id, s.slug); } catch { /* ignore */ } }
}
// FEP-044f embedded quote card: resolve the quoted post out of band so
// the inbox response is not blocked on a remote fetch. Best-effort.
if (quoteHrefOf(o)) {
const slugs = subs.map((s) => s.slug);
resolveQuote(o).then((qj) => {
if (!qj) return;
for (const sl of slugs) { try { db.prepare('UPDATE ap_timeline SET quote_json = ? WHERE id = ? AND slug = ?').run(qj, o.id, sl); } catch { /* ignore */ } }
}).catch(() => { /* best-effort */ });
} else {
// No fediverse quote: try an EXTERNAL embed (oEmbed / known provider),
// thumbnail-only. Also out of band, and stored for everyone; the gate
// that decides who may SEE it is applied at serve time (§5.3-style
// gated feature, see the inbox read).
const slugs = subs.map((s) => s.slug);
resolveExternalEmbed(o.content).then((ej) => {
if (!ej) return;
for (const sl of slugs) { try { db.prepare('UPDATE ap_timeline SET embed_json = ? WHERE id = ? AND slug = ?').run(ej, o.id, sl); } catch { /* ignore */ } }
}).catch(() => { /* best-effort */ });
}
console.log('[AP] timeline +', actorUri, 'x' + subs.length);
}
}
// Een ANTWOORD van iemand die we volgen: bewaar de URI (shaer-e9g). Zo'n
// bericht komt hier gewoon binnen, ondertekend door de schrijver zelf, maar
// belongsInTimeline houdt het uit de Krant en daarna raakten we het kwijt.
// Kwam er later een doorgestuurd antwoord OP dat bericht, dan kenden we de
// ouder niet en wezen we het af -- terwijl we hem wel degelijk hadden gehad.
// Er verandert niets aan wat we tonen of van vreemden aannemen: de schrijver
// moet iemand zijn die je zelf bent gaan volgen.
if (actorUri && !isLocalActor && o.id && o.inReplyTo && noteVisibility(o) !== 'direct' && isFollowedActor(actorUri)) {
rememberNoteUri(o.id);
}
// Mentioned in a post that is NOT a reply to our content (a reply to us already returned
// above): store a mention notification for each of our actors named in the Mention tags.
// Requires our own base prefix on the tag href — /ap/users/ on a REMOTE host is
// someone else's actor, not ours.
// Een markering op een hulpvraag (shaer-lgo): een mede-guardian laat weten
// dat hij ernaar kijkt, of dat het is afgehandeld. Gewone directe note met
// een shaer:-markering, net als de zwaai -- dus die komt hier langs. VOOR de
// mention-opslag, want dit is staat en geen bericht om te bewaren; de ward
// krijgt hem wel als bericht te lezen, en dat gebeurt hieronder.
if (actorUri && !isLocalActor) {
const mark = Guardianship.help.parseMarker(o);
if (mark) {
const ai = actorInfo(await resolveActor(actorUri).catch(() => null), actorUri);
Guardianship.help.record(mark.noteUri, actorUri, mark.kind, ai && ai.handle);
wakeGuardian(slug); // een mede-guardian pakte iets op: het paneel hoort het meteen
console.log('[AP] help', mark.kind, actorUri, '→', mark.noteUri);
}
}
if (actorUri && !isLocalActor && o.id) {
const slugs = localMentionSlugs(o.tag, base);
if (slugs.length) {
const ai = actorInfo(await resolveActor(actorUri), actorUri);
const html = HtmlSanitizerService.sanitize(o.content || '');
// FEP-633c 5.2.1: a ward's call for help rides a direct mention; the
// flag is stored so the Guardian PWA's message centre can list it.
const help = Guardianship.isHelpRequest(o);
const wave = Guardianship.isWave(o);
const hasG = Guardianship.objectHasGuardians(o); // §2.2 hint, register-only
// FEP-633c 3.6.1: a guardian declares itself away to its ward, on the
// same direct note the mention below stores (so the kid also reads it
// as an ordinary message). Recorded only from an actual guardian of
// the addressed ward, and only with an end: an absence without an end
// is logged and dropped, never guessed.
if (Guardianship.availability.isAway(o)) {
const until = Guardianship.availability.parseEndTime(o.endTime);
for (const slug of slugs) {
const isG = (() => { try { return Guardianship.listGuardians(slug).some((g) => g.other_uri === actorUri); } catch { return false; } })();
if (!isG) continue;
if (!until || until <= Date.now()) { console.warn('[AP] away without a (future) end ignored (3.6.1):', actorUri, '→', slug); continue; }
Guardianship.availability.declareAway(slug, actorUri, until);
console.log('[AP] guardian declared away (3.6.1):', actorUri, '→', slug, 'until', new Date(until).toISOString());
}
}
// Een kind dat zelf om een poort vraagt (shaer-8ru). Zelfde weg als de
// afwezigheidsmelding: een gewone directe note met een shaer:-markering,
// per genoemde ontvanger afgehandeld.
//
// ALLEEN VAN EEN EIGEN WARD. Een verzoek van een vreemde is geen vraag
// maar een onbekende die iets over jouw instellingen wil zeggen -- dat
// hoort in geen enkele lijst te belanden waar een guardian op afgaat.
{
const req = Guardianship.gatereq.parseRequest(o);
if (req) {
for (const slug of slugs) {
const mijn = (() => { try { return Guardianship.listWards(slug).some((w) => w.other_uri === actorUri); } catch { return false; } })();
if (!mijn) { console.warn('[AP] gate request from someone who is not our ward, ignored:', actorUri, '→', slug); continue; }
Guardianship.gatereq.record(slug, actorUri, req.feature, o.id);
wakeGuardian(slug); // het kind vroeg om een poort
console.log('[AP] gate request', req.feature, actorUri, '→', slug);
}
}
}
for (const slug of slugs) {
try {
const r = db.prepare(`INSERT OR IGNORE INTO ap_mentions (slug, object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, actor_url, content, published, help_request, wave, has_guardians, emoji_json, actor_emoji_json, media_json, created_at)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`)
.run(slug, o.id, safeUrl(o.url) || null, actorUri, ai.name, ai.handle, ai.icon, ai.url, html, o.published || null, help ? 1 : 0, wave ? 1 : 0, hasG ? 1 : 0,
extractEmojiTags(o.tag), emojiJsonOf(ai.emojis), mediaFromNote(o));
if (r.changes) {
// The quote / link-preview card resolves out of band (a remote
// fetch), exactly as it does for a timeline post, so the inbox
// answer is never blocked on it.
resolveCard(o).then((c) => {
if (!c) return;
const col = c.column === 'quote_json' ? 'quote_json' : 'embed_json'; // never a value from the wire
try { db.prepare(`UPDATE ap_mentions SET ${col} = ? WHERE slug = ? AND object_uri = ?`).run(c.json, slug, o.id); } catch { /* ignore */ }
}).catch(() => { /* best-effort */ });
console.log('[AP] mention', actorUri, '→', slug, help ? '(help request)' : '');
const vis = noteVisibility(o);
const priv = vis === 'direct' || vis === 'followers';
const L = pushLang(slug);
const who = ai.name || ai.handle || i18nT(L, 'notif.someone');
// Same privacy rule as replies: private mentions push without content.
// A help request pushes as its own alert type, aimed at the
// Guardian PWA's message centre.
if (help) pushEvent(slug, { type: 'help', title: i18nT(L, 'push.n_help_t'), body: i18nT(L, 'push.n_help_b', { who }), url: '/guardian' });
else if (priv) pushEvent(slug, { type: 'dm', title: i18nT(L, 'push.n_dm_t'), body: i18nT(L, 'push.n_dm_b', { who }), url: `${pushPrefix(slug)}/messages` });
else pushEvent(slug, { type: 'reply', title: i18nT(L, 'push.n_mention_t'), body: `${who}: ${HtmlSanitizerService.toPlainText(html).slice(0, 90)}`, url: `${pushPrefix(slug)}/messages` });
}
} catch { /* ignore */ }
}
}
}
return 202;
}
// A remote post we cached was edited upstream → refresh our cached copy. This is the
// push-based edit-sync that keeps the Cirkel/timeline fresh without polling (selfHeal
// does it on a version bump; this does it live). Scope to the SIGNING actor so B can't
// edit A's note (the signature gate guarantees claimedActor == the verified signer).
if (type === 'Update' && act.object && (act.object.type === 'Note' || act.object.type === 'Article' || act.object.type === 'Question')) {
const o = act.object;
if (o.id && claimedActor) {
const html = HtmlSanitizerService.sanitize(o.content || '');
const media = mediaFromNote(o);
try {
// Refresh url too (COALESCE keeps the old one if the Update omits it): a remote slug
// rename keeps the same AP id but changes the human url, so without this the cached
// post would keep linking to the old, now-dead URL.
const r = db.prepare('UPDATE ap_timeline SET content = ?, media_json = ?, nsfw = ?, cw = ?, url = COALESCE(?, url) WHERE id = ? AND author_uri = ?')
.run(html, media, o.sensitive ? 1 : 0, contentWarning(o), o.url || null, o.id, claimedActor);
if (r.changes) console.log('[AP] timeline update', claimedActor, '→', o.id);
// A poll's Update carries the fresh vote counts / closed state. Refresh per-row so each
// site keeps its own `voted` state while the counts/closed update to the new totals.
const poll = parsePoll(o);
if (poll) {
const rows = db.prepare('SELECT rowid AS rid, poll_json FROM ap_timeline WHERE id = ? AND author_uri = ?').all(o.id, claimedActor);
const upd = db.prepare('UPDATE ap_timeline SET poll_json = ? WHERE rowid = ?');
for (const rw of rows) {
let voted = null; try { voted = rw.poll_json ? (JSON.parse(rw.poll_json).voted || null) : null; } catch { /* ignore */ }
upd.run(JSON.stringify({ ...poll, voted }), rw.rid);
}
}
} catch { /* ignore */ }
// If this note is a cached fediverse reply on one of our posts, refresh its text too.
try { db.prepare('UPDATE ap_interactions SET content = ? WHERE object_uri = ? AND actor_uri = ?').run(html, o.id, claimedActor); } catch { /* ignore */ }
}
return 202;
}
if (type === 'Like' || type === 'Announce') {
const tgt = act.object;
const objUrl = typeof tgt === 'string' ? tgt : (tgt && tgt.id);
const pid = postIdFromNoteUrl(objUrl, base);
if (pid && actorUri && !isLocalActor && localPostExists(pid)) {
// A boost/like of a non-public post is dropped, not stored: nobody
// outside the audience should even hold it (shaer-tqc hardening).
const vp = db.prepare('SELECT fan_only, ap_visibility FROM posts WHERE id = ?').get(pid);
if (vp && (vp.fan_only || vp.ap_visibility === 'direct' || vp.ap_visibility === 'friends')) {
console.log('[AP] dropped', type, 'on non-public post', pid);
return;
}
const ai = actorInfo(await resolveActor(actorUri), actorUri);
iStmts().ins.run(type.toLowerCase(), pid, '', actorUri, ai.name, ai.handle, ai.url, ai.icon, null, null, null, noteVisibility(act), null, emojiJsonOf(ai.emojis));
console.log('[AP]', type === 'Like' ? 'like' : 'boost', actorUri, '→', pid);
{
const ctx = pushPostCtx(pid);
if (ctx) {
const L = pushLang(ctx.site);
const who = ai.name || ai.handle || i18nT(L, 'notif.someone');
if (type === 'Like') pushEvent(ctx.site, { type: 'like', title: i18nT(L, 'push.n_like_t'), body: i18nT(L, 'push.n_like_b', { who, title: ctx.title }), url: ctx.url });
else pushEvent(ctx.site, { type: 'boost', title: i18nT(L, 'push.n_boost_t'), body: i18nT(L, 'push.n_boost_b', { who, title: ctx.title }), url: ctx.url });
}
}
} else if (type === 'Announce' && objUrl && actorUri && !isLocalActor) {
// A boost FROM an account we follow, of a REMOTE post → show it in the News feed.
// We only STORE it for display; we NEVER auto-Announce it onward (anti-feedback-loop:
// re-announcing an incoming Announce would cascade boosts across the network).
let subs = []; try { subs = db.prepare('SELECT slug FROM ap_following WHERE actor_uri = ?').all(actorUri); } catch { /* table may not exist */ }
if (subs.length) {
const bn = await fetchNoteAP(objUrl);
if (bn && bn !== 404 && (bn.type === 'Note' || bn.type === 'Article') && bn.id) {
const origUri = actorUriOf(bn.attributedTo);
// Block completeness: even if you follow the booster, drop a boost whose ORIGINAL
// author is blocked — otherwise a block is bypassed via someone else's boost.
if (origUri && isBlockedAny(origUri)) { console.log('[AP] timeline boost dropped (blocked origin)', origUri, 'via', actorUri); return 202; }
const oai = actorInfo(await resolveActor(origUri), origUri);
const html = HtmlSanitizerService.sanitize(bn.content || '');
const media = mediaFromNote(bn);
const booster = actorInfo(await resolveActor(actorUri), actorUri);
for (const s of subs) {
// published = now → the boost shows as fresh activity at the top (Mastodon shows
// reblogs at reblog-time, not the original's date). INSERT OR IGNORE: if we already
// have the note (e.g. we also follow the author), keep it and DON'T relabel it.
let inserted = false;
try { const r = tlStmts().ins.run(bn.id, s.slug, origUri || '', oai.name, oai.handle, oai.icon, oai.url, html, bn.url || null, new Date().toISOString(), media, bn.sensitive ? 1 : 0, contentWarning(bn)); inserted = r.changes > 0; } catch { /* ignore */ }
if (inserted) { try { db.prepare('UPDATE ap_timeline SET reblog_name = ?, reblog_handle = ?, reblog_icon = ?, reblog_emoji_json = ? WHERE slug = ? AND id = ?').run(booster.name, booster.handle, booster.icon, (booster.emojis && Object.keys(booster.emojis).length) ? JSON.stringify(booster.emojis) : null, s.slug, bn.id); } catch { /* ignore */ } }
storeAuthorEmoji(bn.id, s.slug, oai); // custom-emoji display name for the byline
// A boost carries the same renderable tags as a Create: capture the
// note's content emojis (FEP-9098) and object links / quote (FEP-e232/
// 044f) so boosted posts render like any other, not as raw shortcodes.
{ const ej = extractEmojiTags(bn.tag); if (ej) { try { db.prepare('UPDATE ap_timeline SET emoji_json = ? WHERE id = ? AND slug = ?').run(ej, bn.id, s.slug); } catch { /* ignore */ } } }
{ const lj = extractLinkJson(bn); if (lj) { try { db.prepare('UPDATE ap_timeline SET link_json = ? WHERE id = ? AND slug = ?').run(lj, bn.id, s.slug); } catch { /* ignore */ } } }
}
// FEP-044f: resolve the embedded quote card for a boosted post too
// (out of band, best-effort, so it does not block the inbox response).
if (quoteHrefOf(bn)) {
const slugs = subs.map((s) => s.slug);
resolveQuote(bn).then((qj) => {
if (!qj) return;
for (const sl of slugs) { try { db.prepare('UPDATE ap_timeline SET quote_json = ? WHERE id = ? AND slug = ?').run(qj, bn.id, sl); } catch { /* ignore */ } }
}).catch(() => { /* best-effort */ });
}
console.log('[AP] timeline boost +', actorUri, 'x' + subs.length);
}
}
}
return 202;
}
if (type === 'Delete') {
// A remote note was deleted upstream → drop it from replies AND the timeline.
// Scope to the SIGNING actor so actor B can't delete actor A's content (the
// signature gate guarantees claimedActor == the verified signer here).
const oid = typeof act.object === 'string' ? act.object : (act.object && act.object.id);
if (oid && claimedActor) {
try { db.prepare('DELETE FROM ap_interactions WHERE object_uri = ? AND actor_uri = ?').run(oid, claimedActor); } catch { /* ignore */ }
try { db.prepare('DELETE FROM ap_timeline WHERE id = ? AND author_uri = ?').run(oid, claimedActor); } catch { /* ignore */ }
// Also clear a boost/like YOU made of this now-deleted remote post (the interact-page
// ap_my_reactions state), so it can't stay stuck as "boosted" on a post that's gone.
// Guard: only when the deleter owns the note's domain (B mustn't clear your reactions
// to A's posts).
try {
let sameHost = false;
try { sameHost = new URL(oid).host === new URL(claimedActor).host; } catch { sameHost = false; }
if (sameHost) db.prepare('DELETE FROM ap_my_reactions WHERE target_uri = ?').run(oid);
} catch { /* ignore */ }
}
return 202;
}
// Accept/Reject of a Follow WE sent (client side).
if (type === 'Accept' && act.object) {
const fid = typeof act.object === 'string' ? act.object : (act.object && act.object.id);
let raak = 0;
if (fid) { try { raak = fwStmts().acc.run(fid).changes; } catch { /* ignore */ } }
// TERUGVAL, en die is nodig gebleken tegen Funkwhale. Een Accept hoort de
// Follow terug te geven die hij beantwoordt, maar Funkwhale verzint er een
// EIGEN id voor, in ONZE namespace:
//
// wij stuurden .../ap/users/dev#follow-1786161977286-bb2de32f
// Funkwhale zegt .../ap/users/dev#follows/19fd8b00-8f66-...
//
// Matchen op follow_id raakt dan niets, en de volgrelatie bleef eeuwig op
// 'pending' staan terwijl de logregel 'accepted' riep -- een stille no-op
// die pas opviel toen er nooit iets binnenkwam.
//
// Het paar dat we WEL zeker weten is (deze site, deze actor): de Accept is
// handtekening-geverifieerd, en actorUri is de ondertekenaar. Alleen een
// rij die nog op pending staat wordt geraakt, dus dit kan niets anders
// openzetten dan een follow die wij zelf hebben verstuurd.
//
// En de slug mag NIET van slugParam afhangen: Funkwhale bezorgt op de
// GEDEELDE inbox, en dan is die leeg. Wie wij zijn staat in de ingesloten
// Follow -- die hebben wij immers zelf verstuurd, dus `object.actor` is
// onze eigen actor-URI.
let mij = slugParam;
if (!mij && act.object && typeof act.object === 'object') mij = slugFromActorUrl(act.object.actor);
if (!raak && mij && actorUri) {
try { raak = fwStmts().accByActor.run(mij, actorUri).changes; } catch { /* ignore */ }
}
// Eerlijk loggen: zonder treffer is er niets geaccepteerd, en dat hoort te
// zien te zijn in plaats van als succes voorbij te komen.
console.log('[AP] follow', raak ? 'accepted' : 'accept UNMATCHED', actorUri, fid ? '(' + fid + ')' : '');
// The moment a friendship exists is the moment the history comes along
// (Robins besluit, 30-7): delivery cannot reach into the past, so the
// fresh follower pulls the outbox, signed, and the other side now serves
// the friends-only posts too.
if (slugParam && actorUri) backfillFromOutbox(slugParam, actorUri).catch(() => { /* best-effort */ });
return 202;
}
if (type === 'Reject' && act.object) {
const who = actorUri;
if (who && slugParam) { try { fwStmts().del.run(slugParam, who); } catch { /* ignore */ } }
return 202;
}
// Zeg ook WAT er viel. Een kale "Create (ignored)" verbergt het verschil
// tussen een soort die we bewust overslaan en een die we niet kennen -- en
// dat verschil was precies de vraag bij Funkwhale, dat Create(Audio) stuurt
// waar deze inbox alleen Note, Article en Question aanneemt.
const objType = act.object && typeof act.object === 'object' ? act.object.type : (typeof act.object === 'string' ? '' : null);
console.log('[AP] inbox', type || 'unknown', objType ? '(' + objType + ')' : '', '→', slugParam || 'shared',
'from', ip, 'by', claimedActor || '?', '(ignored)');
return 202;
}
// ── Op slot na een verhuizing (FEP-7628) ──────────────────────────
//
// Een verhuisd account serveert `movedTo` en is daarmee dood verklaard. Toch kon
// je er gewoon op posten, volgen, liken en reageren, en dat federeerde vrolijk
// de wereld in. Drie dingen gaan daar mis:
//
// - Nieuwe posts krijgen een object-URI op een adres dat je hebt opgezegd. Die
// URI's overleven het domein niet, en de reacties erop ook niet.
// - Je volgers zijn al verhuisd, dus je post in het niets terwijl het lijkt of
// je post.
// - Een server die je movedTo ziet EN tegelijk verse activiteit van dat adres
// krijgt, krijgt tegenstrijdige signalen over de verhuizing.
//
// Daarom staat de poort op de UITGAANDE kant en niet op de knoppen: een
// C2S-client (Shaer) praat rechtstreeks met deze functies en zou anders zo langs
// een verborgen knop lopen. De UI volgt de poort, niet andersom.
//
// WAT DICHT GAAT: posten, reageren, volgen, liken, boosten, stemmen, en een
// tweede verhuizing.
// WAT OPEN BLIJFT: alles wat de wegwijzer draagt (de actor, webfinger, je
// bestaande posts, de outbox), alles inkomend (reacties op oude posts blijven
// binnenkomen en leesbaar), je eigen beheer (archief exporteren, volglijst
// downloaden), en ontvolgen -- opruimen mag altijd.
// Rapporteren blijft OOK open: dat is een veiligheidsklep, geen inhoud maken.
//
// OMKEERBAAR: `moved_to` leegmaken heft het slot op. Een verhuizing kan mislukken
// en dan moet je terug kunnen.
export function movedLock(site) {
const to = site && site.moved_to && /^https?:\/\//i.test(String(site.moved_to))
? String(site.moved_to) : null;
return to ? { locked: true, movedTo: to } : { locked: false, movedTo: null };
}
/** Weigering in de vorm die de aanroepers al kennen: een object met `error`. */
function movedRefusal(site, wat) {
const l = movedLock(site);
if (!l.locked) return null;
console.warn('[AP] geweigerd, dit account is verhuisd:', wat, '→', l.movedTo);
return { error: 'moved', movedTo: l.movedTo };
}
// Deliver a new post as Create(Note) to all followers' inboxes (fire-and-forget).
// Needs PUBLIC_BASE_URL (absolute URLs); no-op without followers or base.
export async function deliverCreate(site, post) {
if (movedLock(site).locked) { console.warn('[AP] Create niet bezorgd, account verhuisd:', site && site.slug); return; }
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug) return;
// Resolve inline @user@host mentions → link them in the note + collect their inboxes, so a
// mentioned person is notified even if they don't follow us (Mastodon-standard mention).
const mres = await resolveMentionsInText(base, post.content || '');
let post2 = mres.inboxes.length ? { ...post, content: mres.html } : post;
// FEP-044f: does this post quote a fediverse object? Resolve it once, here,
// and remember it on the post, so buildNote (sync, also used by the outbox)
// never has to fetch. The quoted author's inbox joins the delivery set: that
// IS the notification.
const quoteInboxes = [];
// EERST BAKKEN, dan pas linken zoeken (shaer-k3f, gevonden op het toestel):
// firstExternalUrl leest -ankers, en de web-editor bakt die er bij
// het opslaan al in -- maar een post uit de APP is platte tekst waarin de
// URL nog geen anker is. Zonder deze bak zag het C2S-pad dus nooit een link
// en kreeg een app-post nooit een kaart, terwijl de preview hem net wel
// beloofd had.
const gebakken = bakePostContent(post2.content || '');
if (post2.quote_uri === undefined || post2.quote_uri === null) {
const q = await resolveOwnQuote(gebakken);
if (q) {
try { db.prepare('UPDATE posts SET quote_uri = ?, quote_actor = ? WHERE id = ?').run(q.uri, q.actor || null, post.id); } catch { /* ignore */ }
post2 = { ...post2, quote_uri: q.uri, quote_actor: q.actor || null };
}
}
// De kaart op de eigen post (shaer-k3f), langs dezelfde pijplijn als een
// binnenkomende: een fediverse-quote wordt een quote-snapshot, anders
// probeert de link een externe kaart. VOOR de vroege return hieronder, want
// ook een post zonder volgers hoort zijn kaart te krijgen -- de app leest
// hem uit de outbox, niet uit een bezorging. Best-effort en eenmalig: wat
// hier niet lukt blijft een kale link, precies wat het was.
if (!post2.quote_json && !post2.embed_json) {
try {
if (post2.quote_uri) {
const qj = await resolveQuoteByUri(post2.quote_uri);
if (qj) { db.prepare('UPDATE posts SET quote_json = ? WHERE id = ?').run(qj, post.id); post2 = { ...post2, quote_json: qj }; }
} else {
const ej = await resolveExternalEmbed(gebakken);
if (ej) { db.prepare('UPDATE posts SET embed_json = ? WHERE id = ?').run(ej, post.id); post2 = { ...post2, embed_json: ej }; }
}
} catch { /* een kaart is nooit een blokkade voor de post zelf */ }
}
if (post2.quote_actor) {
const a = await fetchActor(post2.quote_actor).catch(() => null);
const inbox = a && ((a.endpoints && a.endpoints.sharedInbox) || a.inbox);
if (inbox) quoteInboxes.push(inbox);
}
const followers = fStmts().list.all(site.slug);
const inboxes = [...new Set([...followers.map((f) => f.shared_inbox || f.inbox), ...mres.inboxes, ...quoteInboxes].filter(Boolean))];
if (!inboxes.length) return; // no followers, no one mentioned, no one quoted
const keys = getOrCreateKeys(site.slug);
const keyId = `${actorId(base, site.slug)}#main-key`;
const create = buildCreate(base, site, post2);
for (const inbox of inboxes) deliverWithRetry(site.slug, inbox, create, keyId, keys.private_pem);
}
// On a new Follow, send that follower our most recent posts as Create so their
// timeline shows our history (Mastodon does not backfill on follow). Oldest-first
// so they sort into the follower's timeline at their original dates.
async function backfillNewFollower(base, slug, inbox) {
if (!base || !slug || !inbox) return;
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
if (!site) return;
// Deze lijst filterde op fan_only maar NIET op paid, en haalde `paid` ook niet
// op -- dus stond post.paid op undefined, sloeg buildNote zijn redactie over,
// en duwden we bij ELKE nieuwe volger twintig posts de deur uit met de
// volledige tekst van de betaalde erbij. Een push, dus onherroepelijk: het
// staat daarna in hun inbox. Zelfde reden voor ap_visibility, dat hier
// helemaal ontbrak: een friends- of direct-post hoort niet in een backfill.
// (Barts melding, 15 augustus 2026.)
const recent = db.prepare(
`SELECT id, slug, title, excerpt, content, cover_image_url, cover_video_url, nsfw, content_warning,
c2s_attachments, published_at, created_at, fan_only, ap_visibility, paid, paid_min_cents
FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
AND IFNULL(ap_visibility, 'public') = 'public'
ORDER BY COALESCE(published_at, created_at) DESC LIMIT 20`
).all(site.id).reverse();
if (!recent.length) return;
const keys = getOrCreateKeys(slug);
const keyId = `${actorId(base, slug)}#main-key`;
for (const p of recent) {
try { await deliver(inbox, buildCreate(base, site, p), keyId, keys.private_pem); } catch { /* best-effort */ }
await new Promise((r) => setTimeout(r, 150));
}
console.log('[AP] backfilled', recent.length, 'posts to new follower of', slug);
}
// Tell followers a post is gone (Delete + Tombstone) so it's removed from their feeds.
/**
* Delete(Tombstone) voor een van onze EIGEN objecten, naar alle volgers.
*
* De romp staat apart omdat een post niet het enige is dat wij de draad op
* sturen. Een track is een eersterangs Audio-object met een eigen id
* (shaer-0nh), en die werd bij verwijderen nergens aangekondigd: de rij ging
* weg, het object ging 404 en elke server die hem had geindexeerd hield hem
* voor altijd. Op de hub kwam dat op 21-8 aan het licht als een track die naar
* een dode URL wees.
*
* Het object-id komt van de aanroeper. Dat moet ook wel: bij verwijderen is de
* rij vaak al weg, dus er valt niets meer op te zoeken.
*/
export async function deliverObjectDelete(site, objectId) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug || !objectId) return;
const followers = fStmts().list.all(site.slug);
if (!followers.length) return;
const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
const keys = getOrCreateKeys(site.slug);
const me = actorId(base, site.slug);
const del = {
'@context': AP_CONTEXT,
id: `${objectId}#delete-${Date.now()}-${rid()}`,
type: 'Delete',
actor: me,
to: [PUBLIC],
object: { id: objectId, type: 'Tombstone' },
};
for (const inbox of inboxes) deliverWithRetry(site.slug, inbox, del, `${me}#main-key`, keys.private_pem);
}
export async function deliverDelete(site, post) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !post || !post.id) return;
return deliverObjectDelete(site, noteId(base, post.id));
}
/**
* Zelfde voor een track. Roep dit aan VOOR het verwijderen van de rij, net als
* bij een post: daarna is `id` er nog wel maar de context niet meer.
*/
export async function deliverTrackDelete(site, trackId) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug || !trackId) return;
return deliverObjectDelete(site, trackUri(base, site, trackId));
}
// Tell followers an already-published post changed (Update + edited Note) so
// Mastodon refreshes the cached copy (e.g. after fixing content).
export async function deliverUpdate(site, post) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug || !post || !post.id) return;
const mres = await resolveMentionsInText(base, post.content || ''); // link mentions + collect inboxes
const post2 = mres.inboxes.length ? { ...post, content: mres.html } : post;
const followers = fStmts().list.all(site.slug);
const inboxes = [...new Set([...followers.map((f) => f.shared_inbox || f.inbox), ...mres.inboxes].filter(Boolean))];
if (!inboxes.length) return;
const keys = getOrCreateKeys(site.slug);
const me = actorId(base, site.slug);
const note = buildNote(base, site, post2);
note.updated = new Date().toISOString();
const update = {
'@context': AP_CONTEXT,
id: `${noteId(base, post.id)}#update-${Date.now()}-${rid()}`,
type: 'Update', actor: me, to: [PUBLIC], cc: note.cc,
object: note,
};
for (const inbox of inboxes) deliverWithRetry(site.slug, inbox, update, `${me}#main-key`, keys.private_pem);
}
// Tell followers the ACTOR changed (Update + Person) so Mastodon re-processes the
// account AND re-fetches the featured (pinned) collection — there is no standard
// "featured changed" activity, so this is how a pin/unpin propagates promptly.
export async function deliverActorUpdate(site) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug) return;
const followers = fStmts().list.all(site.slug);
if (!followers.length) return;
const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
const keys = getOrCreateKeys(site.slug);
const me = actorId(base, site.slug);
const update = {
'@context': AP_CONTEXT,
id: `${me}#update-${Date.now()}-${rid()}`,
type: 'Update', actor: me, to: [PUBLIC], cc: [`${me}/followers`],
object: buildActor(base, site),
};
for (const inbox of inboxes) deliverWithRetry(site.slug, inbox, update, `${me}#main-key`, keys.private_pem);
}
// Reliably set the pinned order on followers' instances via Add/Remove activities
// (how Mastodon itself federates pins) — pushed to the inbox + processed immediately,
// unlike the featured COLLECTION which Mastodon caches with sticky StatusPins.
// Mastodon's Add skips an already-pinned status, so we REMOVE every pin first, wait,
// then ADD in rank-DESCENDING order (rank 1 added LAST → newest StatusPin → shown first,
// because Mastodon displays pins newest-first). `alsoRemove` = ids to unpin too.
// Serialize pin-resyncs per site: two concurrent /save calls would otherwise interleave
// their Remove -> wait -> Add sequences and scramble the StatusPin order on Mastodon. A
// resync already in flight for a site coalesces later requests into ONE rerun after it
// finishes (accumulating their extra unpins), so rapid saves don't pile up N full resyncs.
const _pinResync = new Map(); // slug -> { promise, pending, pendingRemove:Set, site }
export function resyncFeaturedPins(site, alsoRemove = []) {
if (!site || !site.slug) return Promise.resolve();
const slug = site.slug;
const running = _pinResync.get(slug);
if (running) {
running.pending = true;
running.site = site; // use the latest site object on the rerun
for (const id of alsoRemove) running.pendingRemove.add(id);
return running.promise;
}
const state = { promise: null, pending: false, pendingRemove: new Set(), site };
state.promise = (async () => {
let extra = alsoRemove;
for (;;) {
try { await doResyncFeaturedPins(state.site, extra); }
catch (e) { console.warn('[AP] pin resync failed:', e.message); }
if (!state.pending) break;
state.pending = false;
extra = [...state.pendingRemove];
state.pendingRemove = new Set();
}
_pinResync.delete(slug);
})();
_pinResync.set(slug, state);
return state.promise;
}
// The actual resync work — do NOT call directly; go through resyncFeaturedPins() above so
// it stays serialized per site.
async function doResyncFeaturedPins(site, alsoRemove = []) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug) return;
const followers = fStmts().list.all(site.slug);
if (!followers.length) return;
const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
const keys = getOrCreateKeys(site.slug);
const me = actorId(base, site.slug);
const keyId = `${me}#main-key`;
const featured = `${me}/featured`;
const note = (id) => noteId(base, id);
const pinned = db.prepare(
`SELECT id FROM posts WHERE site_id = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)
AND pinned IS NOT NULL AND pinned > 0
ORDER BY pinned DESC, COALESCE(published_at, created_at) ASC LIMIT 20`
).all(site.id);
const removeIds = [...new Set([...pinned.map((p) => p.id), ...alsoRemove])];
// 1. Remove every current pin so Mastodon can recreate them in order.
for (const id of removeIds) {
const rm = { '@context': AP_CONTEXT, id: `${me}#rm-${id}-${Date.now()}-${rid()}`, type: 'Remove', actor: me, object: note(id), target: featured, to: [PUBLIC] };
for (const inbox of inboxes) deliver(inbox, rm, keyId, keys.private_pem).catch(() => { /* best-effort */ });
}
if (!pinned.length) { console.log('[AP] unpinned all featured for', site.slug); return; }
await new Promise((r) => setTimeout(r, 5000)); // let the Removes land first
// 2. Add in rank-DESC order, gaps so each StatusPin gets an increasing created_at.
for (const p of pinned) {
const add = { '@context': AP_CONTEXT, id: `${me}#add-${p.id}-${Date.now()}-${rid()}`, type: 'Add', actor: me, object: note(p.id), target: featured, to: [PUBLIC], cc: [`${me}/followers`] };
for (const inbox of inboxes) deliver(inbox, add, keyId, keys.private_pem).catch(() => { /* best-effort */ });
await new Promise((r) => setTimeout(r, 2000));
}
console.log('[AP] resynced', pinned.length, 'featured pins for', site.slug);
}
// ── outbound replies (Klonkt → fediverse) ─────────────────────────
const escHtml = (s) => String(s || '').replace(/[<>&]/g, (c) => ({ '<': '<', '>': '>', '&': '&' }[c]));
const toISO = (v) => { if (!v) return new Date().toISOString(); const s = String(v); const d = new Date(/[TZ]/.test(s) ? s : s.replace(' ', 'T') + 'Z'); return isNaN(d) ? new Date().toISOString() : d.toISOString(); };
// Build one of OUR outbound reply Notes from an ap_outbox row.
// Turn #hashtags in reply text into Mastodon-style hashtag links (clickable + federated).
function linkHashtags(base, html) {
// Prefix: start / whitespace / '>' / opening bracket — "(#tag" is a tag too. NO quote
// chars in this class: a quote precedes attribute values (alt="#…"), which must not match.
return String(html || '').replace(/(^|[\s>([{])#([\p{L}\p{M}\p{N}_]+)/gu, (m, pre, tag) =>
`${pre}#${tag}`);
}
// Auto-link bare http(s) URLs in already-safe HTML (federated copies). Splits on existing
// … so a linked URL is never wrapped twice; requires start/whitespace/'>' before the
// URL so attribute values (src="https://…") never match. Trailing sentence punctuation stays
// outside the link (Mastodon-style).
function linkUrls(html) {
const parts = String(html || '').split(/(]*>[\s\S]*?<\/a>)/gi);
for (let i = 0; i < parts.length; i++) {
if (/^([{])(https?:\/\/[^\s<]+?)([.,;:!?)\]»]*)(?=$|[\s<])/g,
(m, pre, url, trail) => `${pre}${url}${trail}`);
}
return parts.join('');
}
// Linkify inline #hashtags and bare URLs in BODY html for on-site DISPLAY, using the
// EXACT same rules as the federated copy (linkHashtags/linkUrls), so the website and the
// Mastodon copy agree instead of the website showing raw text. Idempotent: existing
// … (editor links, embeds, shortcode buttons) are split out and left untouched, so
// nothing is double-wrapped. Pass base='' → root-relative /tag/ links.
export function linkifyBody(base, html) {
const withTags = String(html || '')
.split(/(]*>[\s\S]*?<\/a>)/gi)
.map((seg) => (/^@([^<]+)<\/a>/gi;
let m;
while ((m = re.exec(content || ''))) {
const href = m[1];
if (seen.has(href)) continue; seen.add(href);
tags.push({ type: 'Mention', href, name: '@' + m[2] });
}
return tags;
}
// Resolve inline @user@domain mentions in reply/post text → link them (href = actor URI)
// and collect the mentioned actors' inboxes so they get notified. Best-effort per mention.
async function resolveMentionsInText(base, html) {
const inboxes = [];
const handles = new Set();
// Prefix also allows opening brackets — "(@user@host + me)" is a mention too (real-world
// miss: a bracketed mention federated as plain text and its target was never notified).
const re = /(^|[\s>([{])@([\p{L}\p{M}\p{N}_.-]+@[\p{L}\p{M}\p{N}.-]+)/gu;
let m;
while ((m = re.exec(html || ''))) handles.add(m[2]);
let out = String(html || '');
for (const h of handles) {
let actorUri = null;
try { actorUri = await webfingerResolve('@' + h); } catch { actorUri = null; }
if (!actorUri) continue;
const actor = await fetchActor(actorUri).catch(() => null);
const inbox = actor && ((actor.endpoints && actor.endpoints.sharedInbox) || actor.inbox);
if (inbox) inboxes.push(inbox);
const profileUrl = actorInfo(actor, actorUri).url || actorUri; // human profile page → the link href
const esc = h.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
out = out.replace(new RegExp('(^|[\\s>([{])@' + esc + '(?![\\p{L}\\p{M}\\p{N}_.-])', 'gu'),
(full, pre) => `${pre}@${h}`);
}
return { html: out, inboxes };
}
export function buildReplyNote(base, site, row) {
// Thin delegate: replies are built by buildNote (the single Note entry point) in reply mode.
return buildNote(base, site, row, { isReply: true });
}
// The account's own outbound notes (replies and direct messages) as AS2
// Notes, newest first. The C2S inbox read serves these alongside the
// timeline: without them your own reply existed everywhere EXCEPT in your
// own app (Robins melding, 30-7: "replyen werkt nog niet"; het antwoord
// stond op de server maar de app kreeg het nooit terug, dus je probeerde
// het opnieuw en liep in de duplicate-guard).
export function getSentNotes(base, site, limit = 60) {
return db.prepare('SELECT * FROM ap_outbox WHERE site_slug = ? ORDER BY created_at DESC LIMIT ?')
.all(site.slug, limit)
.map((row) => buildReplyNote(base, site, row));
}
// Resolve one of our outbound reply Notes by id (for /ap/notes/:id fallback).
export function getOutboxNote(base, id) {
const row = iStmts().getO.get(id);
if (!row) return null;
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(row.site_slug);
if (!site) return null;
return buildReplyNote(base, site, row);
}
// The direct-note leg (ward call-for-help) lives in the guardianship module
// (src/services/guardianship/delivery.js); wired with our AP helpers at the
// bottom of this file. Re-exported so every existing caller keeps working.
export const c2sVisibility = Guardianship.c2sVisibility;
export const deliverDirectNote = Guardianship.deliverDirectNote;
// Send a reply FROM this site to a remote actor (in reply to their inbound reply).
// `parent` = an ap_interactions row (actor_uri, actor_url, actor_handle, object_uri).
/**
* Een gate-voorstel de deur uit (FEP-633c 5.6, shaer-8ru).
*
* STOND IN routes/guardian.js en kon daar alleen door de PWA aangeroepen worden.
* De apps moeten hetzelfde kunnen, en een tweede implementatie ernaast zou een
* tweede weg naar hetzelfde besluit zijn -- precies de fout die we vandaag bij
* de antwoordpoort hebben rechtgezet, toen de innamepoort alleen in C2S bleek te
* zitten en het webpad eromheen liep. Een pad dus.
*
* EEN WEG, waar de ward ook woont (Robins regel, 29-7): voorstellen over de
* lijn en de server van de ward laat tellen. Co-locatie verandert alleen het
* transport -- deliverToActor lust een lokale ontvanger terug door dezelfde
* inbox. De oude kortsluiting boekte de stem hier meteen, en zo bleef het
* remote-pad een maand stuk zonder dat iemand het merkte.
*/
export function proposeGate(site, wardUri, feature, allow) {
const uri = String(wardUri || '').trim();
if (!uri) return { status: 400, error: 'empty_uri' };
if (!Guardianship.gated.featureColumn(feature)) return { status: 400, error: 'unknown_feature' };
// Alleen een guardian van dit kind. Zonder deze regel zou iedereen met een
// token een instelling van een vreemd kind kunnen aanvragen.
if (!Guardianship.listWards(site.slug).some((w) => w.other_uri === uri)) {
return { status: 403, error: 'not_your_ward' };
}
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const me = actorId(base, site.slug);
const offerId = `${me}/gated/${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
const offer = Guardianship.gated.buildGatedOffer(offerId, me, uri, feature, allow);
// Ons eigen spoor van wat we stuurden: de server van de ward antwoordt op deze
// Offer zodra het besluit valt, en dat antwoord heeft een rij nodig om in te
// landen. Het is ook het enige waardoor het scherm van de voorsteller meer kan
// zeggen dan een knoptekst.
Guardianship.gated.recordSent(offerId, site.slug, uri, feature, allow);
deliverToActor(site, uri, offer).catch(() => { /* queued, best-effort */ });
const localSlug = (base && uri.startsWith(`${base}/`)) ? uri.replace(/\/+$/, '').split('/').pop() : null;
const progress = localSlug ? Guardianship.gated.gatedProgress(localSlug, feature) : null;
return { status: 200, ok: true, allow, state: 'open', offerId, ...(progress || { federated: true }) };
}
export async function deliverReply(site, { postId, postSlug, parent, text, html, language, attachments, mentions, visibility }) {
const _mv = movedRefusal(site, 'reply'); if (_mv) return _mv;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
// Rich replies: `html` is the reply editor's HTML (sanitized here); `text` is
// the plain-text fallback (no-JS path, C2S `source`). Either may carry the reply.
const richClean = html ? HtmlSanitizerService.sanitize(String(html)) : '';
const rich = richClean && HtmlSanitizerService.toPlainText(richClean).trim() ? richClean : '';
// Attachments: only OUR OWN uploads (/media/... paths, no remote URLs — the
// upload route is the sole producer), image/audio/video only, max 4.
const media = (Array.isArray(attachments) ? attachments : [])
.filter((a) => a && typeof a.url === 'string' && /^\/media\/[\w./-]+$/.test(a.url)
&& /^(image|audio|video)\//.test(String(a.mediaType || '')))
.slice(0, 4)
.map((a) => ({ url: a.url, mediaType: String(a.mediaType), name: String(a.name || '').slice(0, 120) }));
// A media-only reply (no text) is a valid reply.
if (!base || !site || !site.slug || !parent || (!String(text || '').trim() && !rich && !media.length)) return null;
// DE POORT STAAT HIER en niet alleen in de outbox (shaer-r4c). routes/posts.js
// roept deliverReply op drie plekken rechtstreeks aan -- de eigen webinterface
// van Klonkt gaat dus nooit langs ingestOutboxActivity. Een poort die alleen in
// C2S staat is een poort met een deur ernaast.
//
// Dit is het knooppunt dat beide paden delen. De reddingsboei komt hier niet
// langs: een hulpvraag is altijd direct en loopt via deliverDirectNote, dus de
// boei blijft open zonder dat daar een uitzondering voor nodig is.
{
const isWard = (() => { try { return Guardianship.listGuardians(site.slug).length > 0; } catch { return false; } })();
if (!Guardianship.wardGateAllowed(site.gate_replies, isWard)) return null;
}
const me = actorId(base, site.slug);
// u02, the mentions bar: `mentions` undefined = legacy behavior (mention the
// parent author). An ARRAY (possibly empty) = the kept conversation partners
// exactly as the bar shows them; the mention prefix, the Mention tags (via
// mentionTags over the content) and the delivery targets all follow it.
const kept = Array.isArray(mentions)
? mentions
.filter((m) => m && typeof m.uri === 'string' && /^https?:\/\//i.test(m.uri))
.slice(0, 8)
.map((m) => ({
uri: m.uri,
url: (typeof m.url === 'string' && /^https?:\/\//i.test(m.url)) ? m.url : m.uri,
handle: String(m.handle || deriveHandle(m.uri)).slice(0, 120),
}))
: null;
const mentionAnchor = (uri, url, h) => {
const disp = h && h[0] === '@' ? h : '@' + (h || '');
return `${escHtml(disp)} `;
};
const handle = parent.actor_handle || deriveHandle(parent.actor_uri);
const mention = kept
? kept.map((k) => mentionAnchor(k.uri, k.url, k.handle)).join('')
: (parent.actor_uri ? mentionAnchor(parent.actor_uri, parent.actor_url, handle) : '');
// Who the stored reply is "to": the parent when kept, else the first kept chip.
const parentKept = !kept || kept.some((k) => k.uri === parent.actor_uri);
const toActorUri = parentKept ? (parent.actor_uri || null) : (kept[0] ? kept[0].uri : null);
const toHandle = parentKept ? handle : (kept[0] ? kept[0].handle : null);
let content;
let mres;
if (rich) {
// Same enrichment pipeline as the plain path (mentions/hashtags/URLs), on
// sanitized editor HTML. The parent mention goes inline into the first
// paragraph (Mastodon convention), or becomes its own leading one.
mres = await resolveMentionsInText(base, rich);
const processed = linkUrls(linkHashtags(base, mres.html));
if (processed.startsWith('')) {
content = processed.replace('
', `
${mention}`); // inline in the first paragraph
} else if (/^<(blockquote|ul|ol|pre|h[1-6]|div|hr)\b/i.test(processed)) {
content = `
${mention}
${processed}`; // block content: own leading paragraph
} else {
content = `${mention}${processed}
`; // bare inline text: one paragraph together
}
} else {
const body = escHtml(String(text).trim()).replace(/\r?\n/g, '
');
mres = await resolveMentionsInText(base, body); // link inline @mentions + collect their inboxes
content = `${mention}${linkUrls(linkHashtags(base, mres.html))}
`;
}
const replyLang = /^[a-z]{2,3}(-[A-Za-z0-9-]+)?$/.test(String(language || '')) ? language : null;
// Dedup: skip if the exact same reply was already sent (double-submit guard).
// Attachments count toward "the same": two media-only replies share content.
const mediaJson = media.length ? JSON.stringify(media) : null;
// A duplicate is idempotent success, not an error: it answers with the
// EXISTING id. Returning without one made the C2S ingest say 502
// reply_failed on a double-submit (Robins schermafdruk, 30-7), so a retry
// of a reply the app never showed looked like the reply itself failing.
const dup = db.prepare('SELECT id FROM ap_outbox WHERE site_slug = ? AND IFNULL(in_reply_to, \'\') = ? AND content = ? AND IFNULL(attachments, \'\') = IFNULL(?, \'\') LIMIT 1')
.get(site.slug, parent.object_uri || '', content, mediaJson);
if (dup) { console.log('[AP] outreply skipped (duplicate)'); return { duplicate: true, id: dup.id, delivered: 0 }; }
const id = crypto.randomUUID();
iStmts().insO.run(id, site.slug, postId, postSlug || null, parent.object_uri || null, toActorUri, toHandle, content, replyLang, mediaJson);
// Followers-only reply (shaer detail-view): mark the row so buildNote drops
// Public from cc. Default (undefined/'public'/'quiet') stays quiet-public.
if (visibility === 'friends') { try { db.prepare('UPDATE ap_outbox SET visibility = ? WHERE id = ?').run('friends', id); } catch { /* ignore */ } }
const row = iStmts().getO.get(id);
const note = buildReplyNote(base, site, row);
const create = {
'@context': AP_CONTEXT,
id: note.id + '#create', type: 'Create', actor: me,
published: note.published, to: note.to, cc: note.cc, object: note,
};
const keys = getOrCreateKeys(site.slug);
const keyId = `${me}#main-key`;
const inboxes = new Set();
// Everyone the mentions bar kept gets pinged; legacy path = the parent only.
const mentionTargets = kept ? kept.map((k) => k.uri) : (parent.actor_uri ? [parent.actor_uri] : []);
for (const uri of mentionTargets) {
const a = await fetchActor(uri).catch(() => null);
if (a) inboxes.add((a.endpoints && a.endpoints.sharedInbox) || a.inbox);
}
if (parent.threadInbox) inboxes.add(parent.threadInbox); // back-compat (single)
(parent.threadInboxes || []).forEach((i) => inboxes.add(i)); // whole ancestor chain
for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
mres.inboxes.forEach((i) => inboxes.add(i)); // people @mentioned inline in the reply
inboxes.delete(`${me}/inbox`); // never deliver to ourselves (already in ap_outbox)
inboxes.delete(`${base}/ap/inbox`); // (our own shared inbox) → avoids a self-duplicate
let delivered = 0;
for (const inbox of [...inboxes].filter(Boolean)) {
let ok = false;
try { const st = await deliver(inbox, create, keyId, keys.private_pem); ok = st >= 200 && st < 300; } catch { ok = false; }
if (ok) delivered++;
else enqueueDelivery(site.slug, inbox, create); // durable: retry a briefly-offline recipient (was silently dropped)
}
console.log('[AP] outreply', site.slug, '→', parent.actor_uri, 'delivered', delivered);
return { id, content, delivered };
}
// attributedTo may be a string, an object {id}, or an ARRAY — e.g. a PeerTube Video is
// attributed to [Person (account), Group (channel)]. Pick a usable actor URI (prefer Person).
function actorUriOf(att) {
if (!att) return null;
if (typeof att === 'string') return att;
if (Array.isArray(att)) {
const person = att.find((a) => a && typeof a === 'object' && a.type === 'Person' && a.id);
if (person) return person.id;
for (const a of att) { if (typeof a === 'string') return a; if (a && a.id) return a.id; }
return null;
}
return att.id || null;
}
// Resolve a remote post URL (any fediverse/Klonkt post) into a reply target.
// Returns a parent-shaped object usable by deliverReply(), or null.
// The server's own note, built straight from the DB. resolveRemoteNote used
// to fetch EVERYTHING over HTTPS, including notes living right here: a
// hairpin fetch fails on home setups (a Klonkt on a Mac behind a tunnel), the
// /ap/notes route rightly hides friends-only posts, and a punycode-spelled
// own URL read as remote on a byte comparison. For the authenticated C2S
// caller none of those walls apply; the DB is one prepare() away.
// `forSlug` is that caller: only the post's own site gets its non-public
// notes on this shortcut (public ones anyone, same as the route serves).
function localNoteObject(url, forSlug) {
if (!isOwnUrl(url)) return null;
const m = String(url).match(/\/ap\/notes\/([^/?#]+)/);
if (!m) return null;
const id = decodeURIComponent(m[1]);
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const post = db.prepare("SELECT * FROM posts WHERE id = ? AND status = 'published'").get(id);
if (post) {
const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(post.site_id);
if (!site) return null;
const nonPublic = post.fan_only || post.ap_visibility === 'friends' || post.ap_visibility === 'direct';
if (nonPublic && (!forSlug || forSlug !== site.slug)) return null;
return buildNote(base, site, post);
}
return getOutboxNote(base, id); // our own outbound replies
}
// The own actor document, same shortcut, same reason.
function localActorObject(uri) {
if (!isOwnUrl(uri)) return null;
const m = String(uri).match(/\/ap\/users\/([^/?#]+)/);
const site = m ? db.prepare('SELECT * FROM sites WHERE slug = ?').get(decodeURIComponent(m[1])) : null;
return site ? buildActor((process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''), site) : null;
}
// ── De thread onder een post (shaer-tqz) ───────────────────────────
//
// Klonkt is hier een TOLK, geen archief (Barts besluit, 7-8): de antwoorden
// worden opgehaald op het moment dat iemand kijkt en daarna weer vergeten.
// Geen tabel, geen migratie -- wie replies bewaart van elke post die iemand
// tegenkomt, laat de omvang van zijn database bepalen door surfgedrag. Dat is
// de AFWIJKING, niet de norm: Mastodon serveert /context uit zijn eigen
// database, en dat verdient zich daar terug omdat honderden mensen de cache
// delen. Een Klonkt-instance is de server van één persoon.
//
// Waarom dit niet in de app kan: de replies-collectie van een vreemde server
// eist in secure mode een ONDERTEKEND verzoek, en de sleutel staat hier en kan
// hier niet weg. Voor de opgaande inReplyTo-keten komt de app weg met een
// ongetekende GET (mist er een, jammer); voor een thread van dertig is "de
// helft doet het niet" geen resultaat.
//
// Je krijgt hier NOOIT de hele thread: een replies-collectie bevat alleen wat
// die ene server gezien heeft. De UI hoort "wat de bron weet" te tonen en geen
// volledigheid te suggereren.
// NIET hetzelfde als maybeCrawlThread verderop: die kruipt de thread onder je
// EIGEN posts af en bewaart de antwoorden in ap_interactions (dat zijn de
// jouwe, die horen te blijven). Dit hier is voor een post van een ANDER die je
// tegenkomt, en bewaart niets.
const THREAD_VIEW_LIMIT = 30;
const THREAD_VIEW_TTL_MS = 120_000;
const THREAD_VIEW_CACHE_MAX = 200;
const threadViewCache = new Map(); // `${slug}|${uri}` -> { at, out } -- geheugen, weg bij herstart
/** Eén pagina items uit een AS2-collectie, welke spelling hij ook koos. */
function collectionItems(coll) {
if (!coll || typeof coll !== 'object') return [];
const arr = coll.orderedItems || coll.items;
return Array.isArray(arr) ? arr : [];
}
/**
* De directe antwoorden op één note, genormaliseerd voor de C2S-lezer.
*
* ALLEEN ophalen en normaliseren; de poorten zitten in de route. De
* kringfilter (de dichte stand van shaer:externalThreads) woont in
* filterThreadToCircle en de beeld/muziek/emoji-poorten in
* gateAttachments/stripEmojiTags -- per verzoek, buiten deze cache om, want de
* stand van een poort mag hier niet twee minuten bevriezen. Geblokkeerde
* actors zijn een andere categorie en verdwijnen WEL hier, zonder telling:
* een blokkade is onzichtbaar, ook als getal.
*/
export async function getThread(slug, objectUri) {
const key = `${slug}|${objectUri}`;
const hit = threadViewCache.get(key);
if (hit && Date.now() - hit.at < THREAD_VIEW_TTL_MS) return hit.out;
// De status waarmee de BRON antwoordde op de note zelf. 401/403/404/410 is
// een besluit van die server (niet gedeeld, of weg); alles daarbuiten -- ook
// een stuk netwerk dat wegviel -- is een storing. De route moet dat verschil
// kunnen zeggen, anders wijst de melding naar de verkeerde partij.
let sourceStatus = 0;
const get = (u) => localNoteObject(u, slug) || signedGetJson(slug, u, (st) => { sourceStatus = st; });
const note = await get(objectUri);
const repliesRef = note && note.replies;
let coll = null;
if (typeof repliesRef === 'string') coll = await signedGetJson(slug, repliesRef);
else if (repliesRef && typeof repliesRef === 'object') {
coll = collectionItems(repliesRef).length || repliesRef.first ? repliesRef
: (repliesRef.id ? await signedGetJson(slug, repliesRef.id) : repliesRef);
}
// De pagina-wandeling van collectReplyItems, maar met behoud van INLINE
// objecten (die niet opnieuw opgehaald hoeven). Niet "de eerste pagina":
// Mastodon serveert `first` als inline-pagina met LEGE items en een `next`
// waar de antwoorden echt staan -- wie alleen de eerste pagina leest, ziet
// op elke Mastodon-post een leeg gesprek. Dat was precies Barts melding
// (8-8, reacties op een vreemde post). Eigen posts maskeerden het: die
// gaan door de lokale kortsluiting en hebben orderedItems meteen vol.
let items = [];
let node = coll;
if (node && node.first && !collectionItems(node).length) {
node = typeof node.first === 'string' ? await signedGetJson(slug, node.first) : node.first;
}
let pages = 0;
while (node && pages++ < 3 && items.length < THREAD_VIEW_LIMIT) {
items.push(...collectionItems(node));
if (!node.next) break;
node = typeof node.next === 'string' ? await signedGetJson(slug, node.next) : node.next;
}
items = items.slice(0, THREAD_VIEW_LIMIT);
// Alles tegelijk in plaats van om de beurt: dertig vreemde servers na elkaar
// afwachten is een halve minuut kijken naar een spinner.
const objs = await Promise.all(items.map(async (it) => {
const o = typeof it === 'string' ? await get(it) : (it && it.object && typeof it.object === 'object' ? it.object : it);
return (o && o.id && o.attributedTo) ? o : null;
}));
const kept = [];
for (const o of objs) {
if (!o) continue;
const actorUri = actorUriOf(o.attributedTo);
if (!actorUri || isBlockedAny(actorUri)) continue; // een blokkade telt niet mee
kept.push({ o, actorUri });
}
// Bylines: één fetch per unieke auteur, niet één per antwoord.
const authors = new Map();
await Promise.all([...new Set(kept.map((k) => k.actorUri))].map(async (uri) => {
authors.set(uri, localActorObject(uri) || await signedGetJson(slug, uri).catch(() => null));
}));
const notes = kept.map(({ o, actorUri }) => ({
id: o.id,
type: 'Note',
// De ingesloten actor (shaer-nmw): de byline hoort in attributedTo, waar
// elke AP-lezer hem zoekt, en niet in een eigen property ernaast.
attributedTo: actorObject(actorUri, actorInfo(authors.get(actorUri), actorUri)),
inReplyTo: (typeof o.inReplyTo === 'string' ? o.inReplyTo : (o.inReplyTo && o.inReplyTo.id)) || objectUri,
content: HtmlSanitizerService.sanitize(String(o.content || '').slice(0, 50_000)),
url: safeUrl(typeof o.url === 'string' ? o.url : (o.url && o.url.href)) || undefined,
published: typeof o.published === 'string' ? o.published : undefined,
sensitive: !!o.sensitive,
summary: (contentWarning(o) || '').slice(0, 500) || undefined,
attachment: (() => {
const arr = Array.isArray(o.attachment) ? o.attachment : (o.attachment ? [o.attachment] : []);
const out = arr.map((a) => ({ type: 'Document', mediaType: (a && a.mediaType) || undefined, url: safeUrl(a && a.url), name: (a && typeof a.name === 'string') ? a.name.slice(0, 1500) : undefined }))
.filter((a) => a.url);
return out.length ? out.slice(0, 8) : undefined;
})(),
// FEP-9098: de custom emoji van het antwoord (":shortcode:" -> plaatje).
// Zonder deze tags rendert een reply van een Mastodon-account zijn emoji
// als kale tekst (Barts punt, 8-8). Alleen naam + geschoond icoon-adres
// gaan door; de rest van de vreemde tag-array blijft achter.
tag: (() => {
const j = extractEmojiTags(o.tag);
if (!j) return undefined;
const out = JSON.parse(j)
.map((t) => ({ type: 'Emoji', name: t.name, icon: { type: 'Image', url: safeUrl(t.icon && (t.icon.url || (Array.isArray(t.icon) && t.icon[0] && t.icon[0].url))) } }))
.filter((t) => t.icon.url)
.slice(0, 30);
return out.length ? out : undefined;
})(),
})).sort((a, b) => String(a.published || '').localeCompare(String(b.published || '')));
const out = { notes, found: !!note, sourceStatus };
threadViewCache.set(key, { at: Date.now(), out });
if (threadViewCache.size > THREAD_VIEW_CACHE_MAX) {
const oldest = [...threadViewCache.entries()].sort((a, b) => a[1].at - b[1].at)[0];
if (oldest) threadViewCache.delete(oldest[0]);
}
return out;
}
/**
* De thread gefilterd op de kring die de guardians al kennen (gevolgd of
* volgend) -- de dichte stand van shaer:externalThreads. PER VERZOEK, buiten de
* threadcache om: een poort die de guardians net dichtzetten mag niet nog twee
* minuten open nawerken uit een cache. Wat er buiten valt wordt GETELD, nooit
* stil weggelaten.
*/
export function filterThreadToCircle(slug, notes) {
const circle = new Set();
try { for (const r of db.prepare("SELECT actor_uri FROM ap_following WHERE slug = ? AND status = 'accepted'").all(slug)) circle.add(r.actor_uri); } catch { /* geen tabel */ }
try { for (const r of db.prepare('SELECT actor_uri FROM ap_followers WHERE slug = ?').all(slug)) circle.add(r.actor_uri); } catch { /* geen tabel */ }
const kept = [], out = { hidden: 0 };
for (const n of notes) {
// actorUriOf, niet n.attributedTo: sinds de byline ingesloten meegaat is
// dat een OBJECT en zou een kale vergelijking hier stil alles wegfilteren
// -- een ward met een lege thread en nergens een foutmelding.
if (circle.has(actorUriOf(n.attributedTo))) kept.push(n);
else out.hidden += 1;
}
out.notes = kept;
return out;
}
export async function resolveRemoteNote(url, opts = {}) {
if (!/^https?:\/\//i.test(String(url || ''))) return null;
// With `asSlug` the fetches are SIGNED as that local actor. An anonymous
// GET can only read public notes; a friends-only note (Shaer's default!)
// rightly refuses it, which made every reply to a friend's post fail while
// a reply to your own public post worked (Robins melding, 30-7). Signed,
// the other server sees WHO asks and serves what the friendship earns.
const get = (u) => (opts.asSlug ? signedGetJson(opts.asSlug, u) : fetchActor(u).catch(() => null));
const note = localNoteObject(url, opts.asSlug) || await get(url); // own DB first, then AP GET
if (!note || !note.id) return null;
const att = note.attributedTo;
const actorUri = actorUriOf(att);
if (!actorUri) return null;
const actor = localActorObject(actorUri) || await get(actorUri);
const ai = actorInfo(actor, actorUri);
// Is what we're replying to a post (or a comment) on one of OUR posts? If so,
// link our reply to that local post so it shows nested in the post thread.
const localTgt = findThreadTarget(note.id, (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, ''));
// Walk the WHOLE reply chain upward (comment → parent comment → … → root post)
// and collect every ancestor author's inbox, so each participant's server —
// including the original post's author — receives + threads our reply.
const threadInboxes = [];
const seenInbox = new Set();
let cursor = note.inReplyTo, guard = 0;
while (cursor && guard++ < 6) {
const url = typeof cursor === 'string' ? cursor : (cursor && cursor.id);
if (!url) break;
const pn = localNoteObject(url, opts.asSlug) || await get(url);
if (!pn) break;
const pa = actorUriOf(pn.attributedTo);
if (pa && pa !== actorUri) {
const paDoc = await get(pa);
const inbox = paDoc && ((paDoc.endpoints && paDoc.endpoints.sharedInbox) || paDoc.inbox);
if (inbox && !seenInbox.has(inbox)) { seenInbox.add(inbox); threadInboxes.push(inbox); }
}
cursor = pn.inReplyTo; // climb to the next ancestor
}
// For non-Note objects (PeerTube Video, Article, …) the meaningful label is `name` (the
// title); prepend it so the reply page shows what you're replying to (sanitize cleans it).
let rawHtml = String(note.content || '').replace(/\[\[(track|album|playlist):[^\]]+\]\]/gi, '');
if (note.name && note.type && note.type !== 'Note') rawHtml = `${note.name}
` + rawHtml;
const images = (Array.isArray(note.attachment) ? note.attachment : [])
.filter((a) => a && a.url && (!a.mediaType || /^image\//i.test(a.mediaType)))
.map((a) => safeUrl(a.url)).filter(Boolean);
// A Klonkt hosted-audio post strips its cover from `attachment` (so Mastodon
// shows the player card, not a loose image) and puts it in `image` instead.
// Same fallback as mediaFromNote() so a boosted music post keeps its cover.
if (!images.length && note.image) {
const im = Array.isArray(note.image) ? note.image[0] : note.image;
const iu = safeUrl(typeof im === 'string' ? im : (im && im.url));
if (iu) images.push(iu);
}
return {
object_uri: safeUrl(note.id) || note.id,
actor_uri: actorUri,
actor_url: ai.url,
actor_handle: ai.handle,
actor_name: ai.name,
actor_icon: ai.icon,
url: note.url || url,
content: HtmlSanitizerService.sanitize(rawHtml), // full, sanitized
sensitive: !!note.sensitive, // remote CW → blur in the Cirkel
cw: contentWarning(note) || '',
images,
// Full typed media (incl. video/mp4) for the timeline cache. `images` above is
// image-only for the interact page preview; a boosted video-only post (Loops)
// lost its media entirely because upsertBoostedNote only saw `images`.
media: mediaFromNote(note),
threadInboxes, // every ancestor author's inbox
localPostId: localTgt ? localTgt.post_id : '', // our post this belongs to (if any)
poll: parsePoll(note), // a Question → its options/counts (else null)
preview: HtmlSanitizerService.toPlainText(note.content || '').slice(0, 240),
};
}
// List a site's own outbound fediverse replies (for the manage/delete view).
// The plain editable text of a stored reply (unwrap links → their text,
→ newline)
// so the manage view can prefill an edit box; the mention is re-added on save.
function outboxEditableText(content) {
return String(content || '')
.replace(/
/gi, '\n')
.replace(/]*>([\s\S]*?)<\/a>/gi, '$1')
.replace(/<[^>]+>/g, '')
.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&')
.trim();
}
export function listOutbox(siteSlug) {
// post_slug reist mee sinds Berichten gesprekken toont: het is de sleutel
// waarop een verzonden antwoord bij de ontvangen antwoorden op dezelfde post
// gaat staan (zie threadKey). Zonder die kolom viel een uitwisseling uit
// elkaar in "Verzonden" en "Gesprekken".
return db.prepare('SELECT id, content, to_handle, to_actor, to_actors, post_slug, in_reply_to, attachments, language, created_at FROM ap_outbox WHERE site_slug = ? ORDER BY created_at DESC')
.all(siteSlug).map((r) => { const c = stripLeadingMentions(r.content); return { ...r, content: c, editable: outboxEditableText(c) }; });
}
// Delete one of our outbound replies: send Delete(Tombstone) to recipients + remove it.
export async function deliverOutboxDelete(site, outboxId) {
const row = iStmts().getO.get(outboxId);
if (!row || row.site_slug !== site.slug) return false;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (base) {
const me = actorId(base, site.slug);
const nid = noteId(base, row.id);
const del = { '@context': AP_CONTEXT, id: `${nid}#delete-${Date.now()}-${rid()}`, type: 'Delete', actor: me, to: [PUBLIC], object: { id: nid, type: 'Tombstone' } };
const keys = getOrCreateKeys(site.slug);
const inboxes = new Set();
if (row.to_actor) { const a = await fetchActor(row.to_actor).catch(() => null); if (a) inboxes.add((a.endpoints && a.endpoints.sharedInbox) || a.inbox); }
for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
for (const inbox of [...inboxes].filter(Boolean)) {
try { const st = await deliver(inbox, del, `${me}#main-key`, keys.private_pem); if (st >= 200 && st < 300) continue; } catch { /* queue below */ }
enqueueDelivery(site.slug, inbox, del); // durable: a failed comment-delete now retries (was silently dropped)
}
}
db.prepare('DELETE FROM ap_outbox WHERE id = ?').run(outboxId);
return true;
}
// Edit one of our outbound replies: rewrite the stored content (mention re-added + #tags
// re-linked) and send an Update(Note) so recipients refresh their cached copy.
export async function deliverOutboxUpdate(site, outboxId, newText, opts = {}) {
const row = iStmts().getO.get(outboxId);
if (!row || row.site_slug !== site.slug) return false;
const text = String(newText || '').trim();
// Rich edit: same sanitize + enrichment pipeline as deliverReply.
const richClean = opts.html ? HtmlSanitizerService.sanitize(String(opts.html)) : '';
const rich = richClean && HtmlSanitizerService.toPlainText(richClean).trim() ? richClean : '';
if (!text && !rich) return false;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base) return false;
const me = actorId(base, site.slug);
const toActor = row.to_actor ? await fetchActor(row.to_actor).catch(() => null) : null;
const toProfile = row.to_actor ? (actorInfo(toActor, row.to_actor).url || row.to_actor) : '';
const _h = row.to_handle || deriveHandle(row.to_actor);
const toHandle = _h && _h[0] === '@' ? _h : '@' + (_h || '');
// An edit must not drop co-mentions (u02): reuse the OLD content's leading
// mention anchors (the bar's kept list at send time) when present; only fall
// back to rebuilding the single to_actor mention for legacy rows.
const oldPrefix = (String(row.content || '')
.match(/^\s*(?:]*>)?\s*((?:]*class="u-url mention"[^>]*>\s*@[^<]+<\/a>[\s ]*)+)/i) || [])[1] || '';
const mention = oldPrefix || (row.to_actor
? `${escHtml(toHandle)} ` : '');
let content;
let mres;
if (rich) {
mres = await resolveMentionsInText(base, rich);
const processed = linkUrls(linkHashtags(base, mres.html));
if (processed.startsWith('
')) content = processed.replace('
', `
${mention}`);
else if (/^<(blockquote|ul|ol|pre|h[1-6]|div|hr)\b/i.test(processed)) content = `
${mention}
${processed}`;
else content = `${mention}${processed}
`;
} else {
mres = await resolveMentionsInText(base, escHtml(text).replace(/\r?\n/g, '
'));
content = `${mention}${linkUrls(linkHashtags(base, mres.html))}
`;
}
// Language may be updated with the edit; attachments always survive untouched.
const newLang = /^[a-z]{2,3}(-[A-Za-z0-9-]+)?$/.test(String(opts.language || '')) ? opts.language : null;
db.prepare('UPDATE ap_outbox SET content = ?, language = COALESCE(?, language) WHERE id = ?').run(content, newLang, outboxId);
const note = buildReplyNote(base, site, iStmts().getO.get(outboxId));
note.updated = new Date().toISOString();
const update = {
'@context': AP_CONTEXT,
id: `${note.id}#update-${Date.now()}-${rid()}`, type: 'Update', actor: me,
published: note.published, updated: note.updated, to: note.to, cc: note.cc, object: note,
};
const keys = getOrCreateKeys(site.slug);
const inboxes = new Set();
if (toActor) inboxes.add((toActor.endpoints && toActor.endpoints.sharedInbox) || toActor.inbox);
for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
mres.inboxes.forEach((i) => inboxes.add(i)); // people @mentioned inline in the edit
inboxes.delete(`${me}/inbox`); inboxes.delete(`${base}/ap/inbox`);
let delivered = 0;
for (const inbox of [...inboxes].filter(Boolean)) {
let ok = false;
try { const st = await deliver(inbox, update, `${me}#main-key`, keys.private_pem); ok = st >= 200 && st < 300; } catch { ok = false; }
if (ok) delivered++;
else enqueueDelivery(site.slug, inbox, update); // durable: retry the edit later (was silently dropped)
}
console.log('[AP] outreply edit', site.slug, 'delivered', delivered);
return { ok: true, content, delivered };
}
// Store the author's display-name emoji map (from actorInfo().emojis) on a
// timeline row, so the byline can render a ":shortcode:" name. No-op when the
// name has no custom emoji (the common case).
function storeAuthorEmoji(id, slug, ai) {
if (!ai || !ai.emojis || !Object.keys(ai.emojis).length) return;
try { db.prepare('UPDATE ap_timeline SET author_emoji_json = ? WHERE id = ? AND slug = ?').run(JSON.stringify(ai.emojis), id, slug); } catch { /* ignore */ }
}
// A display-name emoji map (actorInfo().emojis) → JSON to store, or null.
function emojiJsonOf(map) { return (map && Object.keys(map).length) ? JSON.stringify(map) : null; }
// ── Cirkel = posts from the accounts you auto-boost ("feature an artist") ──
let _abCount, _cirkelPosts, _cirkelMembers;
export function autoBoostCount(slug) {
try { if (!_abCount) _abCount = db.prepare('SELECT COUNT(*) AS n FROM ap_following WHERE slug = ? AND auto_boost = 1'); return _abCount.get(slug).n; } catch { return 0; }
}
export function getCirkelPosts(slug, limit, offset) {
try {
// Cirkel = posts from featured (auto_boost) accounts + posts you boosted
// (t.boosted), mixed by date. One row per note in ap_timeline → no duplicates.
if (!_cirkelPosts) _cirkelPosts = db.prepare(`
SELECT t.id, t.author_uri, t.author_name, t.author_handle, t.author_icon, t.author_url,
t.content, t.url, t.published, t.media_json, t.nsfw, t.cw,
(rb.target_uri IS NOT NULL) AS boosted
FROM ap_timeline t
LEFT JOIN ap_following f ON f.slug = t.slug AND f.actor_uri = t.author_uri
-- Uit de tussentabel, niet uit t.boosted: die kolom is een afgeleide. De
-- UNIQUE(site_slug, target_uri, kind) garandeert hoogstens één match, dus
-- deze join kan geen rijen verdubbelen.
LEFT JOIN ap_my_reactions rb ON rb.site_slug = t.slug AND rb.target_uri = t.id AND rb.kind = 'boost'
WHERE t.slug = ? AND (f.auto_boost = 1 OR rb.target_uri IS NOT NULL)
ORDER BY COALESCE(t.published, t.created_at) DESC, t.rowid DESC
LIMIT ? OFFSET ?`);
return _cirkelPosts.all(slug, limit || 60, offset || 0);
} catch { return []; }
}
export function getCirkelMembers(slug) {
try { if (!_cirkelMembers) _cirkelMembers = db.prepare('SELECT name, url, icon FROM ap_following WHERE slug = ? AND auto_boost = 1 ORDER BY name'); return _cirkelMembers.all(slug); } catch { return []; }
}
// ── Self-heal: re-sync the fediverse cache (ap_timeline) after a DRASTIC update ──
// Runs ONCE per SELFHEAL_VERSION bump — NOT on every boot. Re-fetches each cached
// note and refreshes content + media (recovers covers/edits that were delivered
// during a flux window, e.g. a fleet-wide update), and drops notes that are gone
// (404/410). Bump SELFHEAL_VERSION only on a release that warrants a re-sync.
const SELFHEAL_VERSION = 22; // v22: summary is pas een waarschuwing MET sensitive, en een artikel houdt zijn titel
async function fetchNoteAP(url) {
try {
const r = await fetch(url, { headers: { Accept: 'application/activity+json' } });
if (r.status === 404 || r.status === 410) return 404;
if (r.ok) return await r.json();
} catch { /* unreachable */ }
return null;
}
function mediaFromNote(note) {
const atts = (Array.isArray(note.attachment) ? note.attachment : []).map((a) => {
const m = { url: safeUrl(a && a.url), type: (a && a.mediaType) || '' };
// A federated video may carry its poster as an AS2 icon (shaer-zowq).
const iconUrl = a && a.icon && safeUrl(typeof a.icon === 'string' ? a.icon : a.icon.url);
if (iconUrl && /^video\//i.test(m.type)) m.poster = iconUrl;
return m;
}).filter((m) => m.url);
if (!atts.some((m) => !m.type || /image/i.test(m.type)) && note.image) {
const im = Array.isArray(note.image) ? note.image[0] : note.image;
const iu = safeUrl(typeof im === 'string' ? im : (im && im.url));
if (iu) atts.push({ url: iu, type: (im && im.mediaType) || 'image/jpeg' });
}
return JSON.stringify(atts);
}
// FEP-044f, emit side. The mirror of extractQuoteUrl (ingest): when one of our
// own posts quotes a fediverse object, say so in the shapes the network really
// reads. `quote` is the FEP property; quoteUrl / _misskey_quote are the de-facto
// ones Mastodon and Misskey look at, and the FEP-e232 `Link` in `tag` is the
// third form. All three point at the same object, which is what every reader
// expects. The quoted author goes in `cc`, because being quoted without being
// told is exactly the rudeness this FEP is trying to design away.
export function applyQuoteProps(note, quoteUri, quoteActor) {
if (!note || typeof quoteUri !== 'string' || !/^https?:\/\//i.test(quoteUri)) return note;
note.quote = quoteUri;
note.quoteUrl = quoteUri;
note['_misskey_quote'] = quoteUri;
note.tag = [...(note.tag || []), {
type: 'Link',
mediaType: 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
href: quoteUri,
rel: ['https://misskey-hub.net/ns#_misskey_quote'],
name: quoteUri,
}];
if (typeof quoteActor === 'string' && /^https?:\/\//i.test(quoteActor)) {
note.cc = [...new Set([...(note.cc || []), quoteActor])];
}
return note;
}
// The first external (non-fediverse) link in a note, resolved to the same card
// shape as a quote: THUMBNAIL ONLY, never the provider's iframe. An arbitrary
// third-party frame inside a kid-safe app is a hole you cannot close again, so
// the embed carries an image and a title and nothing executable.
// Returns the JSON to store, or null when there is nothing worth showing.
export async function resolveExternalEmbed(html) {
const first = firstExternalUrl(html);
if (!first) return null;
const io = EmbedResolver.liveIO({
safeFetch,
detectProvider: (u) => AudioEmbedService.detectProvider(u),
fetchActor,
actorInfo,
});
const card = await EmbedResolver.resolveEmbed(first, io).catch(() => null);
// 'ap' is handled by the quote path; a bare 'link' is not worth a card.
if (!card || card.kind === 'ap' || card.kind === 'link') return null;
const thumb = (card.media || []).find((m) => m && m.url);
if (!thumb && !card.title) return null;
// Title, provider and author name come from a third party. Store them as
// PLAIN TEXT (tags stripped, length-capped), so no renderer downstream has to
// be the one that remembers to escape. A card is a card, not an essay.
const plain = (v) => (v ? HtmlSanitizerService.toPlainText(String(v)).trim().slice(0, 200) : null);
return JSON.stringify({
url: card.url,
kind: card.kind, // 'provider' | 'oembed'
provider: plain(card.provider),
title: plain(card.title),
author: card.author ? { ...card.author, name: plain(card.author.name), handle: plain(card.author.handle) } : null,
media: thumb ? [thumb] : [], // thumbnail only, no html/iframe
});
}
/**
* Does our own post link to a fediverse object? Returns { uri, actor } when the
* first external link resolves to a quotable AP object, else null. Runs once at
* publish time; the answer is stored on the post.
*/
export async function resolveOwnQuote(html) {
const first = firstExternalUrl(html);
if (!first) return null;
const io = EmbedResolver.liveIO({ safeFetch, detectProvider: () => null, fetchActor, actorInfo });
const card = await EmbedResolver.resolveEmbed(first, io).catch(() => null);
if (!card || card.kind !== 'ap' || !card.id) return null;
return { uri: card.id, actor: card.attributedTo || null };
}
/**
* De composer-preview (shaer-k3f): één URL langs exact dezelfde pijplijn als
* publiceren, zodat wat de preview toont ook is wat de post krijgt. Twee
* uitkomsten, hoogstens een gevuld: een AP-object wordt een quote-snapshot,
* een externe link probeert een kaart. Beide als JSON-string, dezelfde vorm
* als de kolommen -- de route serveert ze door timelineQuote/timelineEmbed en
* de gate, net als de tijdlijn.
*/
export async function previewCard(url) {
if (!/^https?:\/\//i.test(String(url || ''))) return {};
const html = `x`;
const q = await resolveOwnQuote(html);
if (q && q.uri) {
const quoteJson = await resolveQuoteByUri(q.uri).catch(() => null);
if (quoteJson) return { quoteJson };
} else {
const embedJson = await resolveExternalEmbed(html).catch(() => null);
if (embedJson) return { embedJson };
}
return {};
}
/** The first http(s) link in sanitized note HTML that is not a mention/hashtag. */
export function firstExternalUrl(html) {
if (!html || typeof html !== 'string') return null;
for (const m of html.matchAll(/]*href=["']([^"']+)["'][^>]*>/gi)) {
const tag = m[0];
if (/\b(mention|hashtag|u-url)\b/i.test(tag) && /mention|hashtag/i.test(tag)) continue;
const href = m[1];
if (/^https?:\/\//i.test(href)) return href;
}
return null;
}
/** The stored external-embed card, for the C2S read. */
// ── Standaardvormen in plaats van eigen dialect (shaer-nmw) ───────
//
// Robins waarschuwing: geen Klonkt/Shaer-dialect schrijven waar AS2 of een FEP
// het al regelt. Vier eigen properties hadden een standaard naast zich staan,
// en deze helpers zijn die standaard -- een definitie per vorm, zodat de tien
// plekken die ze emitten niet elk hun eigen variant krijgen.
//
// De oude shaer:-velden blijven er voorlopig NAAST staan. Een app in het veld
// leest ze nog, en een leeg scherm is een duurdere fout dan een dubbel veld;
// ze gaan eruit als de clients om zijn (tweede helft van shaer-nmw).
/** FEP-9098 Emoji-tags uit een {shortcode: url}-kaart. */
function emojiTagsFromMap(emojis) {
const uit = Object.entries(emojis || {})
.filter(([naam, url]) => naam && url)
.map(([naam, url]) => ({ type: 'Emoji', name: naam, icon: { type: 'Image', url } }));
return uit.length ? uit : undefined;
}
/**
* Een actor als INGESLOTEN OBJECT voor `attributedTo` / `actor`.
*
* AS2 staat toe dat attributedTo een object is in plaats van een URI, en dan
* heeft ELKE client er wat aan -- niet alleen de onze, die er shaer:author
* naast kreeg. `preferredUsername` is de lokale naam; een lezer leidt de handle
* af uit die naam plus de host van de id, precies zoals wij serverkant ook
* doen. Weten we niets van de persoon, dan blijft het de kale URI: een leeg
* object zou beweren dat we hem kennen.
*/
export function actorObject(uri, info) {
if (!uri) return undefined;
const iets = info && (info.name || info.handle || info.icon || info.url);
if (!iets) return uri;
const o = { id: uri, type: 'Person' };
if (info.name) o.name = info.name;
const lokaal = String(info.handle || '').replace(/^@/, '').split('@')[0];
if (lokaal) o.preferredUsername = lokaal;
if (info.icon) o.icon = { type: 'Image', url: info.icon };
if (info.url) o.url = info.url;
const tags = emojiTagsFromMap(info.emojis);
if (tags) o.tag = tags;
return o;
}
/**
* De linkkaart als AS2 `preview` (core: "identifies an entity that provides a
* preview of this object"). Een Page met url, name en image IS een kaart; daar
* hoefde shaer:embed nooit voor te bestaan.
*
* Wat WEL van ons blijft is de spelerpagina: dat die alleen meegaat als de
* guardians de poort openden is FEP-633c-gedrag en heeft geen AS2-tegenhanger.
*/
export function previewObject(embedJson, { playback = false } = {}) {
const e = timelineEmbed(embedJson, { playback });
if (!e) return undefined;
const thumb = (e.media || []).find((m) => m && m.url);
const p = { type: 'Page', url: e.url };
if (e.title) p.name = e.title;
if (thumb) p.image = { type: 'Image', url: thumb.url };
if (e.author && (e.author.name || e.author.handle)) {
p.attributedTo = { type: 'Person', name: e.author.name || e.author.handle };
}
if (e['shaer:playerUrl']) p['shaer:playerUrl'] = e['shaer:playerUrl'];
if (e['shaer:playable']) p['shaer:playable'] = e['shaer:playable'];
return p;
}
/**
* De geciteerde post als OBJECT in `quote` (FEP-044f staat toe dat quote het
* object zelf is, niet alleen een URI). De opgeslagen momentopname wordt hier
* een echte Note, met de auteur als ingesloten actor -- dus geen tweede eigen
* property voor iets dat de FEP al kan.
*/
export function quoteObject(quoteJson) {
const q = timelineQuote(quoteJson);
if (!q) return undefined;
const note = { type: 'Note', id: q.url, url: q.url };
if (q.content) note.content = q.content;
if (q.published) note.published = q.published;
if (q.author) {
note.attributedTo = actorObject(q.author.url || q.url, {
name: q.author.name, handle: q.author.handle, icon: q.author.icon,
});
}
const media = (q.media || []).filter((m) => m && m.url)
.map((m) => ({ type: 'Document', mediaType: m.type || undefined, url: m.url }));
if (media.length) note.attachment = media;
const tags = emojiTagsFromMap(q.emojis);
if (tags) note.tag = tags;
return note;
}
export function timelineEmbed(embedJson, { playback = false } = {}) {
try {
const e = embedJson ? JSON.parse(embedJson) : null;
if (!e || typeof e !== 'object' || !e.url) return undefined;
// The player URL is served ONLY when the playback gate is open (FEP-633c
// 5.6). Deciding it here keeps the provider knowledge in one place: the
// client never needs a list of hosts, it just plays what it is handed.
// Privacy-enhanced variants only: nocookie for YouTube, the instance's own
// player for PeerTube. Without one the card stays a thumbnail.
const player = playback ? playerUrlFor(e.url) : null;
if (player) return { ...e, 'shaer:playerUrl': player };
// The gate is shut and there IS something behind it. Saying so costs
// nothing (the card already shows a video thumbnail) and saves the child
// from tapping a card that will never answer: the app can explain instead
// of doing nothing. It stays a statement of fact, never a way in.
return playerUrlFor(e.url) ? { ...e, 'shaer:playable': true } : e;
} catch { return undefined; }
}
/** The embeddable player for a URL, or null when we will not frame it. */
export function playerUrlFor(url) {
if (typeof url !== 'string') return null;
let p = null;
try { p = AudioEmbedService.detectProvider(url); } catch { p = null; }
if (p && p.provider === 'youtube' && p.id) return `https://www.youtube-nocookie.com/embed/${p.id}?rel=0&modestbranding=1&playsinline=1`;
if (p && p.provider === 'vimeo' && p.id) return `https://player.vimeo.com/video/${p.id}`;
// PeerTube is decentralised, so it is matched by its watch-URL shape rather
// than a provider list. Host chars are validated before it is inlined.
const pt = url.match(/^https?:\/\/([\w.-]+(?::\d+)?)\/(?:w|videos\/watch)\/([\w-]{6,})/i);
if (pt) return `https://${pt[1]}/videos/embed/${pt[2]}`;
return null;
}
// FEP-044f embedded quote card: resolve the quoted post to a compact, sanitised
// snapshot { url, author{name,handle,icon}, content, published, media } so the
// client can render it as a nested card instead of a bare link. Best-effort and
// SSRF-safe (apGetJson): returns null on any failure, and the client falls back
// to the object-link chip. The content goes through the same sanitiser as every
// other note, so the kid-safe guarantees hold.
async function resolveQuote(note) {
const url = quoteHrefOf(note);
if (!url) return null;
return resolveQuoteByUri(url);
}
/** Hetzelfde snapshot, maar vanaf een kale URI: eigen posts en de
* composer-preview (shaer-k3f) kennen alleen de link, niet de tag-vorm. */
async function resolveQuoteByUri(url) {
const q = await apGetJson(url);
if (!q || typeof q !== 'object') return null;
const authorUri = typeof q.attributedTo === 'string' ? q.attributedTo
: (q.attributedTo && typeof q.attributedTo.id === 'string' ? q.attributedTo.id : null);
const ai = authorUri ? actorInfo(await fetchActor(authorUri), authorUri) : null;
// The quoted post's own FEP-9098 emojis, so :shortcode: renders in the card.
const emojis = {};
try {
for (const e of JSON.parse(extractEmojiTags(q.tag) || '[]')) {
const u = e.icon && (e.icon.url || (Array.isArray(e.icon) && e.icon[0] && e.icon[0].url));
if (typeof e.name === 'string' && u) emojis[e.name] = u;
}
} catch { /* ignore */ }
let media = []; try { media = JSON.parse(mediaFromNote(q)); } catch { /* ignore */ }
const snapshot = {
url: safeUrl(q.url || q.id || url) || url,
author: ai ? { name: ai.name, handle: ai.handle, icon: ai.icon } : null,
content: HtmlSanitizerService.sanitize(q.content || ''),
published: q.published || null,
media,
emojis: Object.keys(emojis).length ? emojis : undefined,
};
return JSON.stringify(snapshot);
}
/**
* The card under a post: a fediverse quote (FEP-044f) when the note has one,
* otherwise an external link preview. Both render as the SAME card, so only one
* of the two is ever stored. Returns {column, json} or null.
*
* Both halves reach out over the network, which is why every caller runs this
* out of band: an inbox answer must never wait on a third party.
*/
async function resolveCard(o) {
if (quoteHrefOf(o)) {
const qj = await resolveQuote(o);
return qj ? { column: 'quote_json', json: qj } : null;
}
const ej = await resolveExternalEmbed(o && o.content);
return ej ? { column: 'embed_json', json: ej } : null;
}
// AP-native catch-up: pull an actor's standard `outbox` collection and merge their recent
// top-level posts into the timeline for `slug`. Push (Create delivery) cannot backfill
// history-from-before-you-followed or a delivery that was missed while you were down;
// reading the outbox is the spec-conform way to catch up. PULL ONLY — sends nothing.
export async function backfillFromOutbox(slug, actorUri, limit = 20) {
try {
if (!slug || !actorUri) return 0;
const actor = await fetchActor(actorUri);
if (!actor || !actor.outbox) return 0;
// Signed as the follower (30-7): the serving side recognises an accepted
// friend and hands the friends-only history along; an anonymous GET only
// ever sees the public set. A server that ignores the signature behaves
// exactly as before.
let page = await signedGetJson(slug, typeof actor.outbox === 'string' ? actor.outbox : actor.outbox.id);
let items = (page && (page.orderedItems || page.items)) || [];
if (!items.length && page && page.first) {
page = await signedGetJson(slug, typeof page.first === 'string' ? page.first : page.first.id);
items = (page && (page.orderedItems || page.items)) || [];
}
if (!Array.isArray(items) || !items.length) return 0;
const ai = actorInfo(actor, actorUri);
let added = 0;
for (const it of items.slice(0, limit)) {
// Each item is usually a Create wrapping a Note, or sometimes the Note itself.
const o = (it && typeof it.object === 'object' && it.object) ? it.object : it;
if (!o || !o.id) continue;
if (o.type && o.type !== 'Note' && o.type !== 'Article' && o.type !== 'Question') continue; // skip boosts/other
if (o.inReplyTo) continue; // top-level only
const auth = actorUriOf(o.attributedTo);
if (auth && auth !== actorUri) continue; // their OWN posts only
const html = HtmlSanitizerService.sanitize(o.content || '');
const poll = parsePoll(o); // a Question (poll) → carry its options/counts on backfill too
try {
const r = tlStmts().ins.run(o.id, slug, actorUri, ai.name, ai.handle, ai.icon, ai.url, html, o.url || null, o.published || null, mediaFromNote(o), o.sensitive ? 1 : 0, contentWarning(o));
if (r && r.changes > 0) added++;
// FEP-9098: keep custom-emoji tags from backfilled posts too.
{ const ej = extractEmojiTags(o.tag); if (ej) { try { db.prepare('UPDATE ap_timeline SET emoji_json = ? WHERE id = ? AND slug = ?').run(ej, o.id, slug); } catch { /* ignore */ } } }
storeAuthorEmoji(o.id, slug, ai); // custom-emoji display name for the byline
// FEP-e232 + FEP-044f: keep object-link/quote tags from backfilled posts too.
{ const lj = extractLinkJson(o); if (lj) { try { db.prepare('UPDATE ap_timeline SET link_json = ? WHERE id = ? AND slug = ?').run(lj, o.id, slug); } catch { /* ignore */ } } }
// FEP-044f: resolve the embedded quote card for backfilled posts too.
if (quoteHrefOf(o)) { const qj = await resolveQuote(o); if (qj) { try { db.prepare('UPDATE ap_timeline SET quote_json = ? WHERE id = ? AND slug = ?').run(qj, o.id, slug); } catch { /* ignore */ } } }
// Set poll_json if this is a poll and we don't already have it (COALESCE preserves a vote).
if (poll) { try { db.prepare('UPDATE ap_timeline SET poll_json = COALESCE(poll_json, ?) WHERE id = ? AND slug = ?').run(JSON.stringify(poll), o.id, slug); } catch { /* ignore */ } }
} catch { /* ignore */ }
}
if (added) console.log('[AP] outbox backfill', actorUri, '→', slug, '+' + added);
return added;
} catch { return 0; }
}
// ── Remote thread crawl (fill the gaps in a local post's conversation) ────────────
// Most replies reach us by delivery, but replies-to-replies that live on other servers and
// aren't addressed to us are missed. This pulls the AS2 `replies` collections of the replies
// we DO have, caching any newly-found ones in ap_interactions.
//
// Matches Mastodon's behaviour: ONE level per crawl (like its FetchRepliesService), not a deep
// recursive walk. Deeper levels fill in incrementally across crawls — once a fetched reply is
// cached it becomes a seed itself, so its own replies are pulled on a later view (Mastodon's
// per-status cascade). Bounded + polite (serial), PULL only, and stale-while-revalidate: it
// never runs in a page request — the view renders from cache; a stale post kicks off a
// background refresh for the NEXT view.
const THREAD_TTL_MS = 15 * 60 * 1000; // don't re-crawl a post more than ~4×/hour
const THREAD_MAX_DEPTH = 1; // one hop per crawl (like Mastodon); deeper fills in over crawls
const THREAD_MAX_FETCHES = 30; // hard cap on remote GETs per crawl (be a good peer)
const _crawlingThreads = new Set(); // per-post in-flight lock (no stampede across views)
function threadCrawlTs(postId) {
try { const r = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('thread_crawl:' + postId); return r ? (Number(r.value) || 0) : 0; }
catch { return 0; }
}
function setThreadCrawlTs(postId, ts) {
try { db.prepare('INSERT INTO app_settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run('thread_crawl:' + postId, String(ts)); }
catch { /* ignore */ }
}
// Read a note's `replies` (string ref / Collection with `first` / paged CollectionPages) →
// child note URIs. Every remote GET goes through `budget` so the whole crawl stays capped.
async function collectReplyItems(repliesRef, maxPages, budget) {
const uris = [];
let node = typeof repliesRef === 'string' ? await budget.get(repliesRef) : repliesRef;
if (node && node.first) node = typeof node.first === 'string' ? await budget.get(node.first) : node.first;
let pages = 0;
while (node && pages++ < maxPages) {
for (const it of (node.items || node.orderedItems || [])) {
const u = typeof it === 'string' ? it : (it && it.id);
if (u && /^https?:\/\//i.test(u)) uris.push(u);
}
if (!node.next) break;
node = typeof node.next === 'string' ? await budget.get(node.next) : node.next;
}
return uris;
}
async function crawlThread(postId) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base) return;
// Seed frontier = the remote reply note URIs we already have; also the dedup set.
let known;
try { known = new Set(db.prepare("SELECT object_uri FROM ap_interactions WHERE post_id = ? AND kind = 'reply' AND object_uri != ''").all(postId).map((r) => r.object_uri)); }
catch { return; }
const seeds = [...known].filter((u) => /^https?:\/\//i.test(u));
if (!seeds.length) return; // nothing remote to expand
// Owner-removed replies (tombstones) join the dedup set AFTER seeding, so the
// crawler never re-adds them via thread-filling (they're gone from the seeds
// already because rejectInteraction deleted their ap_interactions row).
try { for (const r of db.prepare('SELECT object_uri FROM ap_rejected_objects WHERE post_id = ?').all(postId)) known.add(r.object_uri); }
catch { /* table always exists after boot migration */ }
let fetches = 0;
const budget = { get: async (u) => { if (fetches >= THREAD_MAX_FETCHES) return null; fetches++; return apGetJson(u); } };
const visited = new Set(); // notes whose replies collection we've already expanded
let frontier = seeds.slice();
let added = 0;
for (let depth = 0; depth < THREAD_MAX_DEPTH && frontier.length && fetches < THREAD_MAX_FETCHES; depth++) {
const nextFrontier = [];
for (const noteUri of frontier) {
if (visited.has(noteUri) || fetches >= THREAD_MAX_FETCHES) continue;
visited.add(noteUri);
const note = await budget.get(noteUri);
if (!note || !note.replies) continue;
const childUris = await collectReplyItems(note.replies, 2, budget);
for (const cu of childUris) {
if (known.has(cu) || fetches >= THREAD_MAX_FETCHES) continue;
known.add(cu);
const child = await budget.get(cu);
if (!child || !child.id || (child.type !== 'Note' && child.type !== 'Article')) continue;
if (isRejectedObject(child.id)) continue; // note id can differ from the collection URI (redirects)
const actorUri = actorUriOf(child.attributedTo);
if (!actorUri || isBlockedAny(actorUri)) continue; // skip blocked authors
const actor = await budget.get(actorUri); // may be null if budget spent → fallback handle
const ai = actorInfo(actor, actorUri);
const html = HtmlSanitizerService.sanitize(child.content || '');
// The child replies to `note` by construction (it's in note's replies collection).
try { iStmts().ins.run('reply', postId, child.id, actorUri, ai.name, ai.handle, ai.url, ai.icon, html, child.published || null, note.id || noteUri, noteVisibility(child), extractEmojiTags(child.tag), emojiJsonOf(ai.emojis)); added++; } catch { /* ignore */ }
nextFrontier.push(child.id); // expand this reply's own replies next depth
}
}
frontier = nextFrontier;
}
if (added) console.log('[AP] thread crawl', postId, '+' + added, 'remote replies (' + fetches + ' fetches)');
}
// Stale-while-revalidate entry point: call from the post view. Renders nothing, blocks nothing —
// fires a background crawl only if this post hasn't been crawled within the TTL.
export function maybeCrawlThread(postId) {
if (!postId || _crawlingThreads.has(postId)) return;
if (Date.now() - threadCrawlTs(postId) < THREAD_TTL_MS) return;
_crawlingThreads.add(postId);
setThreadCrawlTs(postId, Date.now()); // optimistic mark so concurrent/next views don't re-fire
crawlThread(postId).catch((e) => console.warn('[AP] thread crawl failed:', e && e.message)).finally(() => _crawlingThreads.delete(postId));
}
let _selfHealing = false;
export async function selfHealTimeline() {
if (_selfHealing) return; _selfHealing = true;
try {
let cur = 0;
try { const r = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('selfheal_version'); cur = r ? (parseInt(r.value, 10) || 0) : 0; } catch { return; }
if (cur >= SELFHEAL_VERSION) return; // already healed for this version — skip on normal boots
// v21: direct notes used to land in the timeline as if they were posts, so a
// ward's 🛟 help request showed up in the guardian's Krant. The insert now
// refuses them; drop the ones already cached. Scoped to the two kinds we can
// still recognise afterwards (help request, wave) — a plain public mention
// from someone you follow IS a timeline post and must stay.
try {
const r = db.prepare(`DELETE FROM ap_timeline WHERE EXISTS (
SELECT 1 FROM ap_mentions m
WHERE m.object_uri = ap_timeline.id AND m.slug = ap_timeline.slug
AND (m.help_request = 1 OR m.wave = 1))`).run();
if (r.changes) console.log(`[AP] self-heal v21: ${r.changes} direct note(s) removed from the timeline`);
} catch { /* table may predate the columns */ }
let rows = [];
try { rows = db.prepare('SELECT id, slug, content, media_json, nsfw, cw, url, emoji_json, link_json, quote_json, author_uri, author_name, author_emoji_json, reblog_name, reblog_handle, reblog_emoji_json, embed_json FROM ap_timeline ORDER BY rowid DESC LIMIT 200').all(); } catch { /* no table */ }
let healed = 0, failed = 0;
for (const r of rows) {
// Link previews first, and deliberately BEFORE the note re-fetch. A
// preview is resolved from the content we already hold, so hanging it
// behind a remote fetch meant one unreachable origin skipped the whole
// row (`continue` below) and the card never appeared. It needs nothing
// from the origin, so it must not depend on it.
if (!r.quote_json && !r.embed_json) {
try {
const ej = await resolveExternalEmbed(r.content);
if (ej) db.prepare('UPDATE ap_timeline SET embed_json = ? WHERE id = ?').run(ej, r.id);
} catch { /* best-effort, never blocks the heal */ }
}
try {
const note = await fetchNoteAP(r.id);
if (note === 404) { db.prepare('DELETE FROM ap_timeline WHERE id = ?').run(r.id); healed++; continue; }
if (!note || typeof note !== 'object') { failed++; continue; } // origin unreachable right now
// Door DEZELFDE bouwer als de innamekant (v22). Hij bouwde de inhoud
// hier zelf op, en daardoor miste een gerepareerde rij precies wat de
// inname wel doet -- de titel van een artikel bijvoorbeeld. Een
// zelfherstel dat een andere vorm oplevert dan de inname repareert naar
// een derde toestand.
const velden = timelineFields(note);
const html = velden.html;
const media = velden.atts.length ? JSON.stringify(velden.atts) : mediaFromNote(note);
const nsfw = note.sensitive ? 1 : 0; // re-sync NSFW/sensitive + CW onto already-cached posts
const cw = contentWarning(note);
const url = note.url || null; // re-sync the human url (catches a remote slug rename)
const emoji = extractEmojiTags(note.tag); // FEP-9098: re-capture custom-emoji tags (v8)
const link = extractLinkJson(note); // FEP-e232 + FEP-044f: re-capture object-link/quote tags (v9)
// FEP-044f: resolve the embedded quote card (v11). COALESCE-style: keep a
// cached snapshot if the quoted post is momentarily unreachable now.
const quote = quoteHrefOf(note) ? (await resolveQuote(note)) || r.quote_json || null : null;
if ((html && html !== r.content) || media !== (r.media_json || '[]') || nsfw !== (r.nsfw || 0) || (cw || '') !== (r.cw || '') || (url && url !== r.url) || (emoji || '') !== (r.emoji_json || '') || (link || '') !== (r.link_json || '') || (quote || '') !== (r.quote_json || '')) {
db.prepare('UPDATE ap_timeline SET content = ?, media_json = ?, nsfw = ?, cw = ?, url = COALESCE(?, url), emoji_json = ?, link_json = ?, quote_json = ? WHERE id = ?').run(html || r.content, media, nsfw, cw, url, emoji, link, quote, r.id);
healed++;
}
// v13: a custom-emoji display name needs the author's emoji map. Fetch
// the actor once, only for rows whose name has a shortcode and no map yet.
if (/:[A-Za-z0-9_+-]+:/.test(r.author_name || '') && !r.author_emoji_json && r.author_uri) {
const ai = actorInfo(await fetchActor(r.author_uri), r.author_uri);
if (ai.emojis) { try { db.prepare('UPDATE ap_timeline SET author_emoji_json = ? WHERE id = ?').run(JSON.stringify(ai.emojis), r.id); } catch { /* ignore */ } }
}
// v14: same for the booster's display name ("X boosted"). The row stores
// no booster URI, so resolve it from the handle via webfinger. Scoped to
// this exact row (slug) since a note can be boosted by different people.
if (/:[A-Za-z0-9_+-]+:/.test(r.reblog_name || '') && !r.reblog_emoji_json && r.reblog_handle) {
const bUri = await webfingerResolve(r.reblog_handle);
const em = bUri ? actorNameEmojis(await fetchActor(bUri)) : undefined;
if (em) { try { db.prepare('UPDATE ap_timeline SET reblog_emoji_json = ? WHERE id = ? AND slug = ?').run(JSON.stringify(em), r.id, r.slug); } catch { /* ignore */ } }
}
} catch { failed++; /* per-note best-effort */ }
}
// Only mark this version DONE after a clean pass. Some origins are briefly
// offline exactly when we heal (phone-hosted instances!): skipping them and
// consuming the version would leave those rows stale forever. Instead retry
// on the next boots, giving up after a few attempts (permanently-dead
// origins answer 404/410 and are deleted above, so they don't loop).
const setSetting = (k, v) => { try { db.prepare('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)').run(k, String(v)); } catch { /* ignore */ } };
let attempts = 0;
try { const a = db.prepare('SELECT value FROM app_settings WHERE key = ?').get('selfheal_attempts'); attempts = a ? (parseInt(a.value, 10) || 0) : 0; } catch { /* ignore */ }
if (failed === 0 || attempts >= 4) {
setSetting('selfheal_version', SELFHEAL_VERSION);
setSetting('selfheal_attempts', 0);
} else {
setSetting('selfheal_attempts', attempts + 1);
}
if (rows.length) console.log(`[AP] self-heal v${SELFHEAL_VERSION}: ${healed}/${rows.length} timeline notes${failed ? ` (${failed} unreachable — will retry next boot)` : ''}`);
} catch { /* never block boot */ } finally { _selfHealing = false; }
}
// Follow a fediverse account by @handle (WebFinger → actor → signed Follow).
/**
* FEP-7628 (DRAFT status — the shape is Mastodon's since 2019, but the FEP can
* still change): an account our sites follow says it moved to a new home.
*
* Validity has two independent legs, and both must hold:
* 1. The SIGNER is a party to the move: the old actor announcing its own move
* (push mode) or the new actor doing it (pull mode). A third party
* narrating someone else's move is refused — without this, any signed
* stranger could re-point our follows.
* 2. The NEW actor claims the old identity in its `alsoKnownAs`. That is the
* cross-side proof: the mover controls both ends. Without it, whoever
* holds ONE end could hijack the other end's followers.
*
* Effect: every local site following the old actor unfollows it and follows
* the new one, keeping its auto-boost choice. Deliberately NOT retargeted:
* guardianship relations (FEP-633c) — a guardian is a security anchor, not a
* feed subscription, and moving one is shaer-tge's gated decision, not a
* side effect of an inbox event. We only log when a move touches one.
*
* Deps are injectable for tests (no network in node:test).
*/
export async function handleMoveInbox(act, { verifiedActor = null, fetchActorFn = null, followFn = null, unfollowFn = null } = {}) {
const oldUri = typeof act.object === 'string' ? act.object : (act.object && act.object.id);
const newUri = typeof act.target === 'string' ? act.target : (act.target && act.target.id);
if (!oldUri || !newUri || oldUri === newUri) return 400;
if (!verifiedActor || (verifiedActor !== oldUri && verifiedActor !== newUri)) {
console.warn('[AP] Move refused: signer is not a party to the move', verifiedActor || '(unsigned)', oldUri, '→', newUri);
return 401;
}
// Nobody here follows the old actor → nothing to move. This also makes
// redelivery idempotent: after the first swap the rows are gone.
let rows = [];
try { rows = db.prepare('SELECT * FROM ap_following WHERE actor_uri = ?').all(oldUri); } catch { /* fresh init */ }
if (!rows.length) return 202;
// A blocked destination is declined outright: the old follow stays (it goes
// stale on its own), and we will not open a door to a blocked house.
if (isBlockedAny(newUri)) { console.log('[AP] Move dropped: target is blocked', newUri); return 202; }
const target = await (fetchActorFn || fetchActor)(newUri);
const aka = [].concat((target && target.alsoKnownAs) || [])
.map((a) => (typeof a === 'string' ? a : (a && a.id))).filter(Boolean);
if (!target || !target.id || !aka.includes(oldUri)) {
console.warn('[AP] Move refused: target does not claim the old actor in alsoKnownAs', oldUri, '→', newUri);
return 202; // decline to act; no 4xx, the sender may be a well-meaning retrying server
}
// EERST de guardianship, DAARNA pas de follows. Die volgorde is geen netheid
// maar de hele werking, en hij is met bloed geschreven: bij Robins verhuizing
// op 13-8 stond het andersom en het log liet precies zien wat er dan gebeurt.
//
// [AP] outgoing Follow beta → .../robo (gated, awaiting guardians)
//
// Beta is zelf een ward. Zijn UITGAANDE follow naar de verhuisde guardian werd
// gepoort (§5.3), want op dat moment stond het nieuwe adres nog niet in zijn
// guardian-lijst: de code hieronder had de relatie nog niet bijgewerkt. En de
// INKOMENDE kant heeft hetzelfde probleem, want de ward gate't een Follow van
// een onbekende. Dus beide richtingen bleven hangen op goedkeuring die niemand
// hoefde te geven, omdat het om een guardian ging die er al was.
//
// Met de relatie eerst is de verhuisde actor al een erkende guardian als de
// follows langskomen, en gaat de auto-acceptatie gewoon door.
//
// Een Move is een Move: de guardian is dezelfde guardian, het kind is hetzelfde
// kind, alleen het adres is nieuw. Zelfde bescherming als de re-follow: alleen
// na een geverifieerde Move, en niet naar een geblokkeerde bestemming (daar
// zijn we hierboven al uitgestapt). De twee harde randen van shaer-tge staan
// hier LOS van: weigeren te verhuizen naar een instance die shaer:guardians
// niet kan dragen is een controle aan de UITGAANDE kant, en het
// terugkeren-zonder-set is een alsoKnownAs-kwestie.
try {
const g = db.prepare('SELECT slug, role FROM ap_guardianships WHERE other_uri = ? AND status = ?').all(oldUri, 'accepted');
if (g.length) {
const r = db.prepare('UPDATE ap_guardianships SET other_uri = ? WHERE other_uri = ? AND status = ?').run(newUri, oldUri, 'accepted');
console.log('[AP] guardianship moved:', oldUri, '→', newUri, `(${r.changes}x)`, g.map((x) => `${x.role}:${x.slug}`).join(', '));
}
} catch (e) { console.warn('[AP] guardianship move failed:', e && e.message); }
for (const row of rows) {
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(row.slug);
if (!site) continue;
try {
await (unfollowFn || unfollowActor)(site, oldUri);
const already = fwStmts().one.get(row.slug, newUri);
if (!already) await (followFn || followActor)(site, newUri, !!row.auto_boost);
console.log('[AP] follow moved', row.slug, ':', oldUri, '→', newUri);
} catch (e) {
console.warn('[AP] move re-follow failed for', row.slug, e && e.message);
}
}
return 202;
}
/**
* Slice 2 van shaer-0j2 (FEP-7628, DRAFT): de UITGAANDE helft — deze Klonkt
* is het oude huis en kondigt het vertrek aan. Twee eisen voordat er iets
* de deur uit gaat:
* 1. Geen guardians: een warded account verhuizen zonder de guardianship
* te hertargeten zou het vangnet van het kind stil breken; dat is
* shaer-tge's gated beslissing, dus tot die er is weigert een bewaakt
* account de verhuizing.
* 2. De NIEUWE actor claimt ons in alsoKnownAs — dezelfde back-reference
* die elke ontvangende server (onze eigen slice 1 incluis) eist. Zonder
* die claim is de Move overal dood bij aankomst.
* De Move gaat duurzaam naar elke volger-inbox; hun servers doen de
* re-follow. `moved_to` wordt hier vastgelegd; het SERVEREN ervan op de
* actor (en het beleid van de oude site) is slice 3.
* Deps injecteerbaar voor tests (geen netwerk in node:test).
*/
export async function moveAccount(site, targetRaw, { fetchActorFn = null, deliverFn = null } = {}) {
// Al verhuisd? Dan eerst het slot eraf (moved_to leegmaken). Anders stapel je
// wegwijzers op elkaar en weet niemand meer waar de keten eindigt.
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug) return { error: 'config' };
if (movedLock(site).locked) return { error: 'already_moved', movedTo: movedLock(site).movedTo };
try {
// Was een harde weigering voor elk bewaakt account (shaer-tge); sinds 8-8
// een GATE met dezelfde standaard: de automatiek weigert voor een ward,
// maar de guardians kunnen shaer:accountMove expliciet openzetten -- en
// expliciet dichtzetten geldt dan ook voor een account dat net geen ward
// meer is, net als bij de embeds.
const isWard = Guardianship.listGuardians(site.slug).length > 0;
if (!Guardianship.wardGateAllowed(site.gate_account_move, isWard)) {
console.warn('[AP] move refused: gated (shaer-tge):', site.slug, '→', String(targetRaw || ''));
return { error: 'guarded_account' };
}
} catch { /* geen guardianship-tabellen = geen guardians */ }
const s = String(targetRaw || '').trim();
let targetUri = null;
if (/^https?:\/\//i.test(s)) targetUri = safeUrl(s);
else if (s.includes('@')) targetUri = await webfingerResolve(s);
if (!targetUri) return { error: 'not_found' };
const me = actorId(base, site.slug);
if (targetUri === me) return { error: 'self' };
const target = await (fetchActorFn ? fetchActorFn(targetUri) : signedGetJson(site.slug, targetUri));
if (!target || !target.id || !target.inbox) return { error: 'unreachable' };
const aka = [].concat(target.alsoKnownAs || [])
.map((a) => (typeof a === 'string' ? a : (a && a.id))).filter(Boolean);
if (!aka.includes(me)) return { error: 'no_backreference' };
db.prepare('UPDATE sites SET moved_to = ? WHERE slug = ?').run(target.id, site.slug);
const keys = getOrCreateKeys(site.slug);
const move = {
'@context': AP_CONTEXT,
id: `${me}#move-${Date.now()}-${rid()}`,
type: 'Move',
actor: me,
object: me,
target: target.id,
to: [`${me}/followers`],
};
// FEP-7628: after setting movedTo, notify the followers with an Update of
// the actor, so their servers hold the signpost even if the Move itself is
// lost. Built from the FRESH row: `site` still carries the pre-move values.
const movedSite = db.prepare('SELECT * FROM sites WHERE slug = ?').get(site.slug) || { ...site, moved_to: target.id };
const update = {
'@context': AP_CONTEXT,
id: `${me}#update-${Date.now()}-${rid()}`,
type: 'Update', actor: me, to: [PUBLIC], cc: [`${me}/followers`],
object: buildActor(base, movedSite),
published: new Date().toISOString(),
};
const inboxes = [...new Set(fStmts().list.all(site.slug).map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
const send = deliverFn || deliverWithRetry;
for (const inbox of inboxes) {
await send(site.slug, inbox, update, `${me}#main-key`, keys.private_pem);
await send(site.slug, inbox, move, `${me}#main-key`, keys.private_pem);
}
console.log('[AP] MOVE announced:', site.slug, '→', target.id, 'to', inboxes.length, 'inbox(es)');
return { ok: true, target: target.id, inboxes: inboxes.length };
}
// FEP-633c §5.3 note (authorized fetch): true when `actorUri` is a committed
/**
* Who is reading this outbox, and what may they see (30-7)?
* - 'blocked': a verified caller this instance blocks. They get an EMPTY
* collection, not even the public set (Robins eis): a block is a closed
* door, and a signed fetch is the caller knocking with their name on it.
* - 'friend': the owner (bearer) or a verified accepted follower or
* guardian: the fan-only history rides along.
* - 'public': everyone else: the public set.
*/
export function outboxAudience(slug, { bearerSlug = null, verifiedActor = null } = {}) {
if (bearerSlug && bearerSlug === slug) return 'friend';
if (!verifiedActor) return 'public';
if (isBlockedAny(verifiedActor)) return 'blocked';
// FEP-1580, Source Instance: wie ondertekend vraagt namens de actor waar wij
// NAARTOE verhuisd zijn, moet behandeld worden alsof wij het zelf vragen.
// Anders kan de nieuwe instantie alleen het publieke deel ophalen en verhuist
// je fan-only geschiedenis niet mee.
if (isMoveTarget(slug, verifiedActor)) return 'friend';
try {
if (db.prepare('SELECT 1 FROM ap_followers WHERE slug = ? AND actor_uri = ?').get(slug, verifiedActor)) return 'friend';
} catch { /* table absent on fresh init */ }
if (isWardGuardian(slug, verifiedActor)) return 'friend';
return 'public';
}
/**
* FEP-1580, de hele autorisatie van de bronkant in één predicaat.
*
* De spec zegt: behandel een verzoek dat namens de DOEL-actor getekend is alsof
* de BRON-actor het deed, voor zichtbaarheid en toegang. Wij hangen dat aan
* `moved_to`, en dat mag omdat moveAccount() `no_backreference` weigert: het
* veld komt er alleen te staan als de doel-actor ons al in `alsoKnownAs` had.
* Dus staat er iets, dan heeft iemand met beheer op BEIDE kanten dat gewild.
* Een typefout kan hier niet binnenkomen, want die haalt de move zelf niet.
*
* Dat dit veilig is leunt op de keyId-binding in verifyRequest (shaer-xd8i):
* zonder die controle kon een actor tekenen met de sleutel van een buurman op
* dezelfde host, en dan is "wie tekende dit" te zacht om je hele geschiedenis
* aan af te geven.
*/
export function isMoveTarget(slug, actorUri) {
if (!slug || !actorUri) return false;
try {
const row = db.prepare('SELECT moved_to FROM sites WHERE slug = ?').get(slug);
return !!(row && row.moved_to && row.moved_to === actorUri);
} catch { return false; }
}
// guardian of the local ward `wardSlug` — so a signed GET from it may read the
// ward's non-public history without the guardian appearing as a follower.
export function isWardGuardian(wardSlug, actorUri) {
try { return !!Guardianship.getRelation(wardSlug, 'ward', actorUri); } catch { return false; }
}
// FEP-633c §5.3: the guardians approved a gated follow of their ward. Send the
// Accept to the follower and record them, so delivery (incl. followers-only)
// begins. `pending` is a row from ap_pending_follows.
/**
* FEP-633c §5.3, the direction that was never gated (bead shaer-p729).
*
* A ward's OWN follow waited for nobody: it went straight out and the guardians
* got a note afterwards (1a2f206). That is informing, not gating — the door is
* already open when the message lands. Now it waits, with two exceptions that
* are not favours but the same decision already taken:
*
* - the target is one of the ward's own guardians. Following the adult who
* watches over you is not a question anyone needs to answer.
* - the target already follows the ward THROUGH THE GATE. A guardian
* approved that person by name; asking again about the same person only
* teaches everyone to stop reading the question.
*
* Returns the held request, or null when the follow may go out now.
* Deliberately not a boolean: a held follow must be distinguishable from a sent
* one all the way up to the app, which is the lesson the error path already
* learned (Robins melding, 31-7).
*/
export async function gateOutgoingFollow(site, targetUri) {
const slug = site && site.slug;
if (!slug || !targetUri) return null;
const guardians = Guardianship.listGuardians(slug).map((g) => g.other_uri);
if (!guardians.length) return null; // not a ward: nothing to gate
// shaer:following (shaer-p729) — its own gate, apart from shaer:follows,
// which governs the OTHER direction. §5.3 fixes the inbound one on: a Follow
// aimed at a ward MUST pass the guardians. About this direction the FEP says
// nothing, so it is ours to set and ours to let go of, and the guardians can
// relax it for a child who has grown into it. Undecided means gated for a
// ward, the same automatiek as the rest of the family.
const gateRow = db.prepare('SELECT gate_following FROM sites WHERE slug = ?').get(slug);
if (Guardianship.wardGateAllowed(gateRow && gateRow.gate_following, true)) return null;
if (guardians.includes(targetUri)) return null; // your own guardian
if (Guardianship.outgoing.isMutual(slug, targetUri)) return null; // already vetted by name
const seen = Guardianship.outgoing.findFor(slug, targetUri);
if (seen && seen.status === 'approved') return null; // the guardians said yes already
if (seen && (seen.status === 'pending' || seen.status === 'denied')) return seen;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const wardActor = actorId(base, slug);
const target = await fetchActor(targetUri).catch(() => null);
const ti = actorInfo(target, targetUri);
const id = `${wardActor}#outfollow-${Date.now()}-${rid()}`;
const held = Guardianship.outgoing.recordPending(slug, {
id, target: targetUri,
inbox: target && ((target.endpoints && target.endpoints.sharedInbox) || target.inbox),
name: ti.name, handle: ti.handle, icon: ti.icon,
});
// Same routing as the inbound gate: a guardian on this instance gets a push
// and reads /guardian; one elsewhere gets an Offer delivered so its own
// server holds a copy to answer from.
const wardKeys = getOrCreateKeys(slug);
const followObj = { id, type: 'Follow', actor: wardActor, object: targetUri };
for (const g of guardians) {
try { Guardianship.availability.recordRequest(slug, g, id, Date.now()); } catch { /* never load-bearing */ }
}
for (const g of guardians) {
const gslug = g.startsWith(`${base}/`) ? slugFromActorUrl(g) : null;
const isLocal = gslug && db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(gslug);
if (isLocal) {
const L = pushLang(gslug);
// De andere richting, en dus andere woorden: hier vraagt het kind of het
// iemand mag volgen. Met dezelfde tekst als hierboven kon een guardian
// op zijn telefoon niet zien wie er nu eigenlijk om wie vroeg.
pushEvent(gslug, { type: 'guardian', title: i18nT(L, 'push.n_guard_folout_t'), body: i18nT(L, 'push.n_guard_folout_b', { who: ti.name || ti.handle || i18nT(L, 'notif.someone'), ward: slug }), url: `${pushPrefix(gslug)}/guardian` });
} else {
fetchActor(g).then((ga) => {
const inbox = ga && ((ga.endpoints && ga.endpoints.sharedInbox) || ga.inbox);
if (!inbox) return;
// Zou DIT antwoord het besluit afmaken (shaer-8vt)? Bij twee guardians is de
// drempel 1, dus de EERSTE ja beslist -- en dat is precies wat de
// beantwoorder niet kon weten.
const beslissend = Guardianship.gated.isDecisive(0, Guardianship.follows.followThreshold(guardians.length));
const offer = { '@context': AP_CONTEXT, id: `${wardActor}#outfollowoffer-${Date.now()}-${rid()}`, type: 'Offer', actor: wardActor, to: [g], object: followObj, 'shaer:followApproval': true, 'shaer:direction': 'outgoing', 'shaer:decisive': beslissend };
deliverWithRetry(slug, inbox, offer, `${wardActor}#main-key`, wardKeys.private_pem).catch(() => {});
}).catch(() => {});
}
}
console.log('[AP] outgoing Follow', slug, '→', targetUri, '(gated, awaiting guardians)');
return held || { id, ward_slug: slug, target_uri: targetUri, status: 'pending' };
}
/**
* The guardians said yes: send the ward's Follow for real (§5.3, shaer-p729).
*
* The row stays behind as `approved` rather than being deleted. It is the
* record that these guardians vetted this target, so an unfollow-and-refollow
* later does not put the same question in front of them again.
*/
export async function performApprovedFollow(pending) {
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(pending.ward_slug);
if (!site) return { error: 'no_such_ward' };
const r = await followActor(site, pending.target_uri, false, { approved: true });
if (r && r.error) return { error: r.error };
console.log('[AP] outgoing Follow approved', pending.ward_slug, '→', pending.target_uri);
return { ok: true };
}
export async function acceptGatedFollow(pending) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const slug = pending.ward_slug;
const me = actorId(base, slug);
const keys = getOrCreateKeys(slug);
fStmts().ins.run(slug, pending.follower_uri, pending.follower_inbox, pending.follower_shared_inbox, pending.follower_name, pending.follower_handle, pending.follower_icon);
// This follower came through the §5.3 gate: a guardian said yes to this
// person by name. That is precisely what lets the ward follow them back later
// without asking the same guardians the same question twice (shaer-p729).
db.prepare('UPDATE ap_followers SET gate_approved = 1 WHERE slug = ? AND actor_uri = ?').run(slug, pending.follower_uri);
const original = pending.activity_json ? JSON.parse(pending.activity_json) : { type: 'Follow', actor: pending.follower_uri, object: me };
const accept = { '@context': AP_CONTEXT, id: `${me}#accept-${Date.now()}-${rid()}`, type: 'Accept', actor: me, object: original };
await deliverWithRetry(slug, pending.follower_inbox, accept, `${me}#main-key`, keys.private_pem);
const filled = pending.follower_shared_inbox &&
db.prepare('SELECT 1 FROM ap_followers WHERE slug = ? AND shared_inbox = ? AND actor_uri != ? LIMIT 1').get(slug, pending.follower_shared_inbox, pending.follower_uri);
if (!filled) backfillNewFollower(base, slug, pending.follower_shared_inbox || pending.follower_inbox).catch(() => {});
console.log('[AP] gated Follow accepted', pending.follower_uri, '→ ward', slug);
return { ok: true };
}
// The guardians denied the follow: send a Reject so the follower's server clears
// its pending state, then the caller drops the record.
export async function rejectGatedFollow(pending) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const slug = pending.ward_slug;
const me = actorId(base, slug);
const keys = getOrCreateKeys(slug);
const original = pending.activity_json ? JSON.parse(pending.activity_json) : { type: 'Follow', actor: pending.follower_uri, object: me };
const reject = { '@context': AP_CONTEXT, id: `${me}#reject-${Date.now()}-${rid()}`, type: 'Reject', actor: me, object: original };
if (pending.follower_inbox) await deliverWithRetry(slug, pending.follower_inbox, reject, `${me}#main-key`, keys.private_pem).catch(() => {});
console.log('[AP] gated Follow rejected', pending.follower_uri, '→ ward', slug);
return { ok: true };
}
// ── Cross-instance follow-approval (FEP-633c §5.3, modelled on the guardian
// offer). Inbound: an Offer(Follow) forwarded by a ward to a guardian (leg
// 2), or a guardian's Accept/Reject coming back to the ward (leg 4). ──────
async function handleFollowApprovalInbox(act, slugParam) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const type = Array.isArray(act.type) ? act.type[0] : act.type;
const actorUri = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
// Leg 2: I am a guardian; the object is the Follow to approve. The Offer is
// signed by the ward, so act.actor is the ward.
if (type === 'Offer') {
const fo = (act.object && typeof act.object === 'object') ? act.object : null;
const foType = fo && (Array.isArray(fo.type) ? fo.type[0] : fo.type);
if (!fo || foType !== 'Follow') return false;
const followId = fo.id;
const follower = typeof fo.actor === 'string' ? fo.actor : (fo.actor && fo.actor.id);
const wardUri = actorUri;
if (!followId || !follower || !wardUri) return false;
const recips = (Array.isArray(act.to) ? act.to : (act.to ? [act.to] : [])).filter((x) => typeof x === 'string');
if (slugParam) recips.push(actorId(base, slugParam));
let stored = false;
for (const r of new Set(recips)) {
const gslug = slugFromActorUrl(r);
if (!gslug) continue;
if (!Guardianship.getRelation(gslug, 'guardian', wardUri)) continue; // must actually guard this ward
const wardDoc = await fetchActor(wardUri).catch(() => null);
const fai = actorInfo(await fetchActor(follower).catch(() => null), follower);
// De RICHTING bewaren (shaer-jdb). shaer:direction wordt sinds de uitgaande
// gate meegestuurd maar werd nergens gelezen, dus een uitgaande belandde
// hier als "deze ward wil deze ward volgen" met het doel weggegooid.
// Terugval voor oudere afzenders: is de volger de ward zelf, dan is het
// uitgaand -- dat volgt uit de vorm en hoeft niet geloofd te worden.
const uitgaand = act['shaer:direction'] === 'outgoing' || follower === wardUri;
const doel = uitgaand ? (typeof fo.object === 'string' ? fo.object : (fo.object && fo.object.id)) : null;
const dai = uitgaand ? actorInfo(await fetchActor(doel).catch(() => null), doel) : null;
Guardianship.follows.recordReview(gslug, {
id: followId, wardUri, wardInbox: wardDoc && wardDoc.inbox,
follower, followerHandle: fai.handle, followerIcon: fai.icon, followJson: JSON.stringify(fo),
direction: uitgaand ? 'outgoing' : 'incoming',
target: doel || null, targetHandle: dai ? dai.handle : null,
});
const L = pushLang(gslug);
// `uitgaand` staat hier al, drie regels hoger, en werd voor de melding
// weer weggegooid: elke richting kreeg dezelfde tekst, geleend van
// offer_for_ward. Op de telefoon las een volgverzoek dus als een
// adoptie-aanvraag, en beide richtingen als elkaar.
const wardNaam = (wardDoc && (wardDoc.preferredUsername || wardDoc.name)) || slugFromActorUrl(wardUri) || wardUri;
const anderNaam = uitgaand
? ((dai && (dai.name || dai.handle)) || i18nT(L, 'notif.someone'))
: (fai.name || fai.handle || i18nT(L, 'notif.someone'));
pushEvent(gslug, {
type: 'guardian',
title: i18nT(L, uitgaand ? 'push.n_guard_folout_t' : 'push.n_guard_folin_t'),
body: i18nT(L, uitgaand ? 'push.n_guard_folout_b' : 'push.n_guard_folin_b', { who: anderNaam, ward: wardNaam }),
url: `${pushPrefix(gslug)}/guardian`,
});
stored = true;
}
return stored;
}
// Leg 4: I am the ward; a guardian decided. object is the Follow (id).
const fo = act.object;
const followId = typeof fo === 'string' ? fo : (fo && fo.id);
if (!followId) return false;
const pending = Guardianship.follows.getPending(followId);
if (!pending) return false;
const allGuardians = Guardianship.listGuardians(pending.ward_slug).map((g) => g.other_uri);
if (!allGuardians.includes(actorUri)) return false; // only a real guardian of this ward decides
const decision = type === 'Reject' ? 'reject' : 'approve';
// §3.5: the quorum runs over the AVAILABLE set. The voter itself was
// restored by the one-answer rule when its activity arrived, so answering
// is exactly what counts a guardian back in.
const guardians = Guardianship.availability.availableSet(pending.ward_slug, allGuardians, Date.now());
const r = Guardianship.follows.decide(followId, actorUri, decision, guardians);
try {
if (r.outcome === 'approved') { await acceptGatedFollow(r.follow); Guardianship.follows.remove(followId); }
else if (r.outcome === 'rejected') { await rejectGatedFollow(r.follow); Guardianship.follows.remove(followId); }
} catch { /* delivery is retried */ }
return true;
}
// Leg 3: a guardian in /guardian decides on a forwarded follow; send the
// Accept/Reject back to the ward's inbox (signed by the guardian).
export async function sendFollowDecision(guardianSite, review, decision) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const me = actorId(base, guardianSite.slug);
const keys = getOrCreateKeys(guardianSite.slug);
const fo = review.follow_json ? JSON.parse(review.follow_json) : { id: review.id, type: 'Follow', actor: review.follower_uri, object: review.ward_uri };
const activity = { '@context': AP_CONTEXT, id: `${me}#followdec-${Date.now()}-${rid()}`, type: decision === 'reject' ? 'Reject' : 'Accept', actor: me, to: [review.ward_uri], object: fo, 'shaer:followApproval': true };
if (review.ward_inbox) await deliverWithRetry(guardianSite.slug, review.ward_inbox, activity, `${me}#main-key`, keys.private_pem);
return { ok: true };
}
// Send a Like or Announce (boost) on a remote note FROM this site.
export async function sendInteraction(site, kind, targetNoteId, authorUri) {
const _mv = movedRefusal(site, `interaction:${kind}`); if (_mv) return _mv;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug || !targetNoteId) return { error: 'config' };
const me = actorId(base, site.slug);
const keys = getOrCreateKeys(site.slug);
// 'unboost' = Undo(Announce): retracts a boost so followers' servers remove the
// reblog (matched on actor+object — no record of the original Announce needed).
const fanout = (kind === 'boost' || kind === 'unboost'); // also goes to our followers
const followersCol = `${me}/followers`;
// Address the original author in cc so their server (Mastodon, WordPress/ActivityPub, …)
// attributes the boost to their post and notifies them — without this, a shared-inbox
// receiver has nothing to route the Announce to. Non-fragment activity ids + a `published`
// stamp keep us aligned with what Mastodon emits.
const audience = authorUri ? [followersCol, authorUri] : [followersCol];
let act;
if (kind === 'unboost' || kind === 'unlike') {
// Undo(Announce) retracts a boost; Undo(Like) un-favourites (matched on actor+object,
// no record of the original activity needed — Mastodon honours both).
const inner = kind === 'unboost' ? 'Announce' : 'Like';
act = {
'@context': AP_CONTEXT,
id: `${me}/undo/${Date.now()}-${rid()}`, type: 'Undo', actor: me,
object: { id: `${me}/${inner.toLowerCase()}/${Date.now()}-${rid()}`, type: inner, actor: me, object: targetNoteId },
};
if (kind === 'unboost') { act.to = [PUBLIC]; act.cc = audience; }
} else {
const type = kind === 'boost' ? 'Announce' : 'Like';
act = {
'@context': AP_CONTEXT,
id: `${me}/${type.toLowerCase()}/${Date.now()}-${rid()}`,
type, actor: me, object: targetNoteId,
};
if (type === 'Announce') { act.published = new Date().toISOString(); act.to = [PUBLIC]; act.cc = audience; }
}
const inboxes = new Set();
// Author first, via their PERSONAL inbox (not the shared one) so a multi-user receiver
// routes the Announce/Like to the right post unambiguously.
if (authorUri) { const a = await fetchActor(authorUri).catch(() => null); if (a) inboxes.add(a.inbox || (a.endpoints && a.endpoints.sharedInbox)); }
if (fanout) { for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox); }
// Queue each delivery (immediate attempt + backoff retries on failure via ap_delivery)
// instead of a single fire-and-forget POST, so a transient hiccup at the receiver doesn't
// silently lose the boost — same durability a new post (deliverCreate) already gets.
let queued = 0;
for (const inbox of [...inboxes].filter(Boolean)) { deliverWithRetry(site.slug, inbox, act, `${me}#main-key`, keys.private_pem); queued++; }
console.log('[AP]', kind, site.slug, '→', targetNoteId, 'queued', queued, 'inbox(es)');
return { ok: true, delivered: queued };
}
// Notifications inbox: new followers + replies/likes/boosts on this site's posts.
export function getNotifications(slug, limit) {
// Per-source cap scales with the requested limit so Messages can page deep
// (Load more). Bounded so a huge offset can't ask for unbounded rows.
const L = Math.min(1000, Math.max(80, limit || 60));
const out = [];
try {
for (const f of db.prepare('SELECT actor_uri, created_at FROM ap_followers WHERE slug = ? ORDER BY created_at DESC LIMIT ?').all(slug, L)) {
out.push({ type: 'follow', handle: deriveHandle(f.actor_uri), url: f.actor_uri, created_at: f.created_at });
}
} catch { /* ignore */ }
try {
const rows = db.prepare(`
SELECT i.id AS interaction_id, i.kind, i.actor_uri, i.actor_name, i.actor_handle, i.actor_url, i.actor_icon, i.content, i.created_at, i.published, i.visibility,
i.emoji_json, i.actor_emoji_json, i.media_json, i.quote_json, i.embed_json,
p.slug AS post_slug, p.title AS post_title
FROM ap_interactions i LEFT JOIN posts p ON p.id = i.post_id
WHERE p.site_id = (SELECT id FROM sites WHERE slug = ?)
ORDER BY i.created_at DESC LIMIT ?
`).all(slug, L);
for (const r of rows) out.push({
type: r.kind, name: r.actor_name, handle: r.actor_handle, url: r.actor_url, icon: r.actor_icon,
// Waar een antwoord uit de draad heen moet: het id is de parent voor
// deliverReply, de uri het adres voor een direct bericht.
interactionId: r.interaction_id, actorUri: r.actor_uri,
content: stripLeadingMentions(r.content), post_slug: r.post_slug, post_title: r.post_title, created_at: r.created_at,
// When the post was written, for display. created_at (when it reached us)
// stays the sort key and the unread watermark: a note that federated late
// is still new to you.
published: r.published,
emoji_json: r.emoji_json, actor_emoji_json: r.actor_emoji_json, // FEP-9098 (messages render)
media_json: r.media_json, quote_json: r.quote_json, embed_json: r.embed_json, // rendered like a Krant post
// followers/direct = a private message to the owner (not on the public thread) → 🔒 in Messages
visibility: r.visibility || 'public',
});
} catch { /* ignore */ }
try {
for (const r of db.prepare('SELECT actor_uri, actor_name, actor_handle, actor_icon, content, objects, created_at FROM ap_reports WHERE slug = ? ORDER BY created_at DESC LIMIT ?').all(slug, L)) {
// The reported objects: our own notes resolve to post links so the owner
// sees WHICH post the report is about; other URIs (e.g. the actor itself)
// are skipped — the report row already names the account.
const about = [];
try {
for (const u of JSON.parse(r.objects || '[]')) {
const m = String(u).match(/\/ap\/notes\/([^/?#]+)/);
if (!m) continue;
const p = db.prepare('SELECT slug, title FROM posts WHERE id = ?').get(decodeURIComponent(m[1]));
if (p) about.push({ slug: p.slug, title: p.title || p.slug });
}
} catch { /* malformed objects json → no links */ }
out.push({ type: 'report', name: r.actor_name, handle: r.actor_handle, url: r.actor_uri, icon: r.actor_icon, content: r.content, objects: about, created_at: r.created_at });
}
} catch { /* ignore */ }
try {
for (const r of db.prepare(`SELECT object_uri, note_url, actor_uri, actor_name, actor_handle, actor_icon, actor_url, content, wave, help_request, created_at, published,
emoji_json, actor_emoji_json, media_json, quote_json, embed_json
FROM ap_mentions WHERE slug = ? ORDER BY created_at DESC LIMIT ?`).all(slug, L)) {
out.push({ type: 'mention', name: r.actor_name, handle: r.actor_handle, url: r.actor_url || r.actor_uri, icon: r.actor_icon, content: stripLeadingMentions(r.content), note_url: r.note_url || r.object_uri, wave: r.wave ? 1 : 0, help_request: r.help_request ? 1 : 0, actorUri: r.actor_uri, created_at: r.created_at, published: r.published,
// Same trimmings a Krant row has, so Berichten renders the post identically.
emoji_json: r.emoji_json, actor_emoji_json: r.actor_emoji_json, media_json: r.media_json, quote_json: r.quote_json, embed_json: r.embed_json });
}
} catch { /* ignore */ }
// Your own polls that have closed → a "results are in" item, derived read-time
// from poll_json (Scheduler marks closed=1) with the tally via ownPollView.
try {
const site = db.prepare('SELECT id FROM sites WHERE slug = ?').get(slug);
if (site) {
const polls = db.prepare(`
SELECT id, slug, title, poll_json FROM posts
WHERE site_id = ? AND poll_json IS NOT NULL
AND json_extract(poll_json, '$.closed') = 1
AND json_extract(poll_json, '$.endTime') IS NOT NULL
ORDER BY json_extract(poll_json, '$.endTime') DESC LIMIT 20`).all(site.id);
for (const p of polls) {
const view = ownPollView(p);
if (!view) continue;
let endTime = null; try { endTime = JSON.parse(p.poll_json).endTime; } catch { /* keep null */ }
out.push({ type: 'poll_done', post_slug: p.slug, post_title: p.title, poll: view, created_at: endTime || null });
}
}
} catch { /* ignore */ }
// NaN-safe sort: one row with a missing/garbled created_at would otherwise make the
// comparator return NaN and scramble the WHOLE ordering (seen live: follow rows landing
// between likes, which also broke Messages' like-grouping).
out.sort((a, b) => _msgTs(b) - _msgTs(a));
return out.slice(0, limit || 60);
}
function _msgTs(x) { const t = Date.parse((x && x.created_at) || ''); return Number.isFinite(t) ? t : 0; }
// ── Blocking / defederation ───────────────────────────────────────
// Extracted to BlocklistService (shared: Klonkt's Block tab + Shaer's "in
// Orbit"). Thin delegations keep every existing caller working.
export function listBlocks(slug) { return Blocklist.listBlocks(slug); }
// True if an actor (or its whole domain) is blocked anywhere on this instance.
// Report a remote post or account to its home instance (moderation). Sends the Mastodon-standard
// AS2 `Flag`: object = [reported account, reported status?], content = the reason, delivered to the
// reported account's inbox so their instance's moderators receive it. objectUri = a post URL (its
// author is resolved + included) OR pass actorUri to report an account directly.
export async function sendReport(site, { objectUri, actorUri, reason }) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!base || !site || !site.slug) return { error: 'config' };
let targetActor = actorUri || null;
let noteUri = null;
if (objectUri && /^https?:\/\//i.test(objectUri)) {
const note = await apGetJson(objectUri).catch(() => null);
if (note && note.id) { noteUri = note.id; if (!targetActor) targetActor = actorUriOf(note.attributedTo); }
else if (!targetActor) return { error: 'not_found' };
}
if (!targetActor || !/^https?:\/\//i.test(targetActor)) return { error: 'not_found' };
const actor = await fetchActor(targetActor).catch(() => null);
const inbox = actor && (actor.inbox || (actor.endpoints && actor.endpoints.sharedInbox)); // personal inbox → their moderators
if (!inbox) return { error: 'unreachable' };
const me = actorId(base, site.slug);
const keys = getOrCreateKeys(site.slug);
const object = [targetActor];
if (noteUri && noteUri !== targetActor) object.push(noteUri);
const flag = {
'@context': AP_CONTEXT,
id: `${me}#report-${Date.now()}-${rid()}`,
type: 'Flag',
actor: me,
content: String(reason == null ? '' : reason).slice(0, 3000),
object, // [account, status?] — Mastodon's Flag shape
to: [targetActor],
};
deliverWithRetry(site.slug, inbox, flag, `${me}#main-key`, keys.private_pem);
return { ok: true };
}
export function isBlockedAny(actorUri) { return Blocklist.isBlockedAny(actorUri); }
// Block an actor (@handle or actor URL) or a whole domain; purges their content.
// The handle resolver is ours; the storage/purge lives in BlocklistService.
//
// De BEZORGING hoort ook hier: BlocklistService kent de database, niet het
// afleveren. Een Block gaat naar de inbox van wie je blokkeert, een
// Undo(Block) bij het opheffen -- zonder retry-wachtrij, want een blokkade
// wacht niet op een server die even plat ligt (en bij opheffen komt de ander
// vanzelf weer langs).
async function bezorgBlokkade(site, target, undo) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const me = actorId(base, site.slug);
const blok = { id: `${me}#block-${Date.now()}-${rid()}`, type: 'Block', actor: me, object: target, to: [target] };
const activiteit = undo
? { '@context': AP_CONTEXT, id: `${me}#unblock-${Date.now()}-${rid()}`, type: 'Undo', actor: me, object: blok, to: [target] }
: { '@context': AP_CONTEXT, ...blok };
const r = await deliverToActor(site, target, activiteit);
console.log('[AP]', undo ? 'Undo(Block)' : 'Block', site.slug, '→', target, r && r.delivered ? 'bezorgd' : 'niet bezorgd');
}
export async function blockTarget(site, input) { return Blocklist.blockTarget(site, input, webfingerResolve, bezorgBlokkade); }
export function unblock(site, target) { return Blocklist.unblock(site, target, bezorgBlokkade); }
// ── Guardianship module wiring (src/services/guardianship/) ────────
// The module owns FEP-633c (context, relations, handshake, queues, the
// direct-note leg); we hand it our AP helpers ONCE and delegate. It never
// imports us back.
function selfActorId(slug) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
return actorId(base, slug);
}
// Deliver one activity to one actor's inbox, signed; queued + retried on any
// hiccup so a slow or briefly-down ward server never loses the offer. Returns
// { delivered, inbox }: delivered=false means the account could not be
// resolved at all (a bad handle) — the offer stays recorded regardless.
export async function deliverToActor(site, actorUri, activity) {
const me = selfActorId(site.slug);
const keys = getOrCreateKeys(site.slug);
const payload = { '@context': AP_CONTEXT, ...activity };
// Co-location is a TRANSPORT detail, never a decision path (Robins regel,
// 29-7). An inbox on this machine is not reachable over HTTP from this
// machine, and should not be, so a local recipient is handed the activity
// straight into the same inbox handler the wire would reach. Everything
// above this line therefore behaves as if every Klonkt were remote: one code
// path, exercised by every deployment, including the checks. Two bugs in one
// day came from having a second, local-only path that hid a broken remote
// one.
const localSlug = localSlugOf(actorUri);
if (localSlug && db.prepare('SELECT 1 FROM sites WHERE slug = ?').get(localSlug)) {
const host = (() => { try { return new URL(selfActorId(site.slug)).host; } catch { return ''; } })();
const req = { body: payload, ip: 'loopback', protocol: 'https', get: () => host, headers: {} };
// The signer is us, and we say so: the actor-versus-signer check runs
// exactly as it does over the wire, so a mismatch fails here too.
const status = await handleInbox(req, localSlug, { id: me }).catch(() => 500);
const ok = status >= 200 && status < 300;
console.log('[AP]', activity.type, ok ? 'delivered (loopback) →' : `got ${status} (loopback) from`, actorUri);
return { delivered: ok, inbox: `${actorUri}/inbox`, loopback: true, status };
}
const a = await fetchActor(actorUri).catch(() => null);
const inbox = a && (a.inbox || (a.endpoints && a.endpoints.sharedInbox));
if (!inbox) {
console.warn('[AP] guardianship: could not resolve an inbox for', actorUri, '(offer recorded, not sent)');
return { delivered: false, inbox: null };
}
try {
const st = await deliver(inbox, payload, `${me}#main-key`, keys.private_pem);
if (st >= 200 && st < 300) { console.log('[AP] guardianship', activity.type, 'delivered →', inbox, st); return { delivered: true, inbox }; }
console.warn('[AP] guardianship', activity.type, 'got', st, 'from', inbox, '→ queued for retry');
} catch (e) { console.warn('[AP] guardianship', activity.type, 'to', inbox, 'failed:', e.message, '→ queued for retry'); }
enqueueDelivery(site.slug, inbox, payload);
return { delivered: true, inbox }; // queued: the retry worker gets it there
}
Guardianship.wireDelivery({
actorId, fetchActor, localActor, deliverTo: deliverToActor, deriveHandle, escHtml, linkUrls, linkHashtags,
getOutboxRow: (id) => iStmts().getO.get(id),
buildReplyNote, AP_CONTEXT, getOrCreateKeys, deliver, enqueueDelivery,
// Rijke directe berichten: dezelfde sanitizer als deliverReply gebruikt, zodat
// een antwoord uit Berichten door precies één poort gaat.
sanitizeHtml: (h) => HtmlSanitizerService.sanitize(h),
htmlToPlainText: (h) => HtmlSanitizerService.toPlainText(h),
});
/**
* The actor document of a site WE host, read straight from the database.
* Same shape fetchActor returns for anyone else, plus `local: true` so the
* caller can take the loopback instead of a POST to our own hostname.
* Null for an actor we do not host: that one really is fetched.
*/
function localActor(actorUri) {
const slug = localSlugOf(actorUri);
if (!slug) return null;
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
if (!site) return null;
// primary_slug is what buildActor uses to pick '/' over '/user/'; the
// actor route sets it the same way before building.
const p = db.prepare('SELECT slug FROM sites WHERE is_primary = 1').get();
try { return { ...buildActor(base, { ...site, primary_slug: p && p.slug }), local: true }; } catch { return null; }
}
// Which local site (if any) hosts this actor URI — used by the handshake to
// apply the local side of a commit and to derive a ward's existing guardians.
export function localSlugOf(actorUri) {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
if (!actorUri || !actorUri.startsWith(`${base}/ap/users/`)) return null;
const slug = slugFromActorUrl(actorUri);
if (!slug) return null;
try { return db.prepare('SELECT slug FROM sites WHERE slug = ?').get(slug) ? slug : null; }
catch { return null; }
}
Guardianship.wireHandshake({
selfId: selfActorId,
localSlug: localSlugOf,
deliverTo: deliverToActor,
deriveHandle,
fetchActor,
// Guardian PWA / Berichten push. The kid answers an incoming offer in its
// own Berichten; an existing guardian and a commit land in the PWA.
//
// De labels hangen aan dezelfde sleutels als het Guardian-paneel, zodat een
// melding en het scherm waar hij heen wijst hetzelfde woord gebruiken.
onEvent: (slug, ev) => onGuardianshipEvent(slug, ev),
});
/**
* Wat er gebeurt als de guardianship-module iets uitzendt.
*
* TWEE VERSCHILLENDE VRAGEN, en ze horen niet dezelfde te zijn: wie maak je
* WAKKER (push kiest bewust een handvol soorten), en wat moet een scherm dat
* openstaat WETEN (alles). Het paneel werd daarom voorheen niet gewekt door de
* tien soorten zonder pushtekst -- die zag je pas bij de volgende tik.
*
* Apart en met een naam, zodat een toets erbij kan. Verstopt in de deps-literal
* was hij onbereikbaar, en een mutatie die het wekken weghaalde bleef groen.
*/
/**
* Hoeveel er van bewaard blijft. Een logboek dat oneindig groeit is een
* logboek dat niemand meer opent, en dit is geschiedenis, geen archief: wat
* ertoe doet staat vooraan.
*/
export const GUARDIAN_EVENT_KEEP = 200;
/**
* Leg de gebeurtenis vast VOOR de melding.
*
* De meldingstabel beslist wie er wakker van wordt, en dat is terecht een korte
* lijst -- maar hij besliste daarmee ook wat er onthouden werd, en dat was niet
* de bedoeling. Elf van de achttien soorten verdwenen spoorloos, met hun inhoud:
* een geweigerd aanbod droeg de REDEN mee tot hier en niet verder, terwijl §4.2
* eist dat de ward en zijn guardians die te horen krijgen.
*
* Vastleggen en melden zijn nu twee dingen. Alles komt in het logboek; alleen
* wat een mens moet wekken gaat ook als push de deur uit.
*/
export function recordGuardianEvent(slug, ev) {
if (!slug || !ev || !ev.kind) return;
try {
db.prepare('INSERT INTO ap_guardian_events (slug, kind, payload, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)')
.run(slug, String(ev.kind), JSON.stringify(ev));
db.prepare(`DELETE FROM ap_guardian_events WHERE slug = ? AND id NOT IN
(SELECT id FROM ap_guardian_events WHERE slug = ? ORDER BY id DESC LIMIT ?)`)
.run(slug, slug, GUARDIAN_EVENT_KEEP);
} catch { /* een logboek mag nooit de gebeurtenis zelf breken */ }
}
/** De laatste gebeurtenissen voor dit account, nieuwste eerst. */
export function listGuardianEvents(slug, limit = 50) {
try {
return db.prepare('SELECT id, kind, payload, created_at FROM ap_guardian_events WHERE slug = ? ORDER BY id DESC LIMIT ?')
.all(slug, Math.max(1, Math.min(Number(limit) || 50, GUARDIAN_EVENT_KEEP)))
.map((r) => ({ id: r.id, kind: r.kind, created: r.created_at, ...safeJson(r.payload) }));
} catch { return []; }
}
function safeJson(s) { try { return JSON.parse(s) || {}; } catch { return {}; } }
export function onGuardianshipEvent(slug, ev) {
recordGuardianEvent(slug, ev);
wakeGuardian(slug);
const p = guardianEventPush(slug, ev);
if (p) pushEvent(slug, p);
return p;
}
/**
* Welke melding hoort bij een guardianship-gebeurtenis, of geen.
*
* Apart en puur, omdat dit een BESLISSING is en geen bezorging: de
* guardianship-module zendt veertien soorten uit en deze tabel bepaalt welke
* daarvan een mens wakker maken. Dat hoort toetsbaar te zijn zonder web-push
* erbij te halen.
*/
export function guardianEventPush(slug, ev) {
const L = pushLang(slug);
const texts = {
offer_received: ['push.n_guard_offer_t', 'push.n_guard_offer_b'], // I am the ward
offer_for_ward: ['push.n_guard_cog_t', 'push.n_guard_cog_b'], // I co-guard this ward
committed: ['push.n_guard_ward_t', 'push.n_guard_ward_b'],
// §3.2: a guardian ended the relation. The ward hears that someone who
// was looking after them has gone; a co-guardian hears they are one fewer.
guardian_left: ['push.n_guard_left_t', 'push.n_guard_left_b'],
coguardian_left: ['push.n_guard_cogleft_t', 'push.n_guard_cogleft_b'],
// 5.6 gated settings. Zonder deze twee is de hele tally stil: een guardian
// hoort niet dat er een antwoord van hem gewenst is, en dus loopt het
// venster leeg en verloopt het voorstel. Een drempel die niemand ziet is
// geen drempel.
gated_review: ['push.n_gate_ask_t', 'push.n_gate_ask_b'], // jij moet antwoorden
gated_outcome: ['push.n_gate_done_t', 'push.n_gate_done_b'], // er is besloten
}[ev.kind];
if (!texts) return null;
const who = deriveHandle(ev.candidate || ev.guardian || ev.ward || '') || '?';
// Een gate-melding zonder te zeggen WELKE instelling is nutteloos: er zijn er
// meer dan een, en ze betekenen heel verschillende dingen voor een kind.
const wat = i18nT(L, GATE_LABEL[ev.feature] || 'guardian.prop_embeds');
const stand = i18nT(L, ev.value ? 'guardian.prop_on' : 'guardian.prop_off');
const uitkomst = i18nT(L, GATE_OUTCOME[ev.outcome] || 'guardian.prop_st_open');
const url = (ev.kind === 'offer_received' || ev.kind === 'guardian_left') ? `${pushPrefix(slug)}/messages` : '/guardian';
return { type: 'guardian', title: i18nT(L, texts[0]), body: i18nT(L, texts[1], { who, wat, stand, uitkomst }), url };
}
// Van een gated feature naar het woord dat het Guardian-paneel er al voor
// gebruikt. Een onbekende feature valt terug op het algemene woord in plaats van
// de melding te laten vervallen: liever een iets vager bericht dan geen bericht.
const GATE_LABEL = {
'shaer:externalEmbeds': 'guardian.prop_embeds',
'shaer:externalPlayback': 'guardian.prop_play',
};
const GATE_OUTCOME = {
accepted: 'guardian.prop_st_accepted',
rejected: 'guardian.prop_st_rejected',
expired: 'guardian.prop_st_expired',
};
// The notification duty of FEP-633c 3.6.2, wired once for every place a
// dormancy promotion can happen (queue reads, fan-outs, tallies): marking a
// guardian dormant MUST notify it, in protocol AND over the §6 handle. The
// one-answer rule is worthless to someone who does not know an answer is
// wanted. The handle of a committed guardian is its inbox (§6 minimum), which
// is the same door this delivery knocks on; both attempts are logged.
Guardianship.wireAvailability({
onDormant: (wardSlug, guardianUri) => {
const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(wardSlug);
if (!base || !site) return;
const me = selfActorId(wardSlug);
const note = {
id: `${me}/dormant/${Date.now().toString(36)}${rid()}`,
type: 'Note', attributedTo: me, to: [guardianUri],
'shaer:dormant': true,
content: 'You have been observed dormant as a guardian. Nothing is wrong and nothing is held against you: one answer restores everything (FEP-633c 3.6.2).
',
};
deliverToActor(site, guardianUri, { id: `${note.id}#create`, type: 'Create', actor: me, to: [guardianUri], object: note })
.catch(() => { /* retried by the queue */ });
console.log('[AP] guardian observed dormant (3.6.2):', guardianUri, 'ward', wardSlug, '(notified in protocol; the §6 handle is the same inbox)');
},
});
// De C2S-inname zijn werktuigen geven (stap 4, shaer-drc). Onderaan, zodat
// elke const hierboven al bestaat; een verzoek kan pas na deze evaluatie
// binnenkomen, dus de koppeling is altijd eerder dan de eerste aanroep.
wireC2S({
proposeGate, deriveHandle, resolveRemoteNote, deliverReply, markRead,
postIdFromNoteUrl, sendInteraction, setReaction, gateOutgoingFollow,
followActor, unfollowActor, blockTarget, unblock, deliverDelete,
deliverOutboxDelete, bakePostContent, bakePostContentWithMentions,
deliverCreate,
});
// En de tijdlijn-leeskant zijn ene werktuig (stap 5): liked/boosted komen
// sinds stap 6 uit ap-reactions, maar de koppeling blijft HIER lopen -- twee
// zustermodules die elkaar importeren zou een kring zijn.
wireTimeline({ getReactionsFor });
// Het reactiecluster zijn ene werktuig (stap 6): de verhuisgrendel (FEP-7628).
wireReactions({ movedLock });
// De volgwinkel zijn zes werktuigen (stap 7): de verhuisweigering, de
// §5.3-poortwachter, de actorlezer, de id-staart en de twee bezorgers.
wireFollowing({ movedRefusal, gateOutgoingFollow, actorInfo, rid, backfillFromOutbox, deliverToActor });
// De peilingen hun vier werktuigen (stap 8): de Update-bezorging voor de
// telling, de id-staart, de verhuisweigering en de attributedTo-lezer.
wirePolls({ deliverUpdate, rid, movedRefusal, actorUriOf });
export default {
movedLock,
// FEP-1580 bronkant. Vergeet je hem hier, dan werpt elke route die hem
// aanroept een 500 en lijkt het alsof de poort dicht staat terwijl hij
// ontbreekt (precies hoe movedLock zich een dag eerder verstopte).
isMoveTarget, signedGetJson, signedGetHeaders,
AP_CONTEXT, getOrCreateKeys, apWants, sendAP, actorId, noteId, stripLeadingMentions, pagedCollection,
deriveHandle, localSlugOf, outboxSlice, PAGINA_GROOTTE,
buildActor, buildNote, buildCreate, buildOutbox, buildFollowers, buildFollowing, buildFeatured,
channelUrls, channelCategory, timelineFields, guessMediaType,
siteOpenTracks, openTrack, buildTrackAudio, buildTrackCollection, buildTrackCreate, trackHostPosts,
buildPlaylistCollection, playlistOpenTracks, listPlaylistsAP, playlistLinkTags,
buildPostTrackCollection, uitgavePost,
buildLibrary, libraryId,
followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate, deliverDelete, deliverObjectDelete, deliverTrackDelete, deliverUpdate, deliverActorUpdate, resyncFeaturedPins,
feedCursor, feedChangesSince, waitForFeedChange,
getInteractions, getInteractionById, setInteractionBoosted, setInteractionLiked, buildReplyNote, getOutboxNote, getSentNotes, deliverReply, resolveRemoteNote, noteAudience, mayReadNote,
listOutbox, deliverOutboxDelete, deliverOutboxUpdate, deliverDirectNote,
webfingerResolve, followActor, resolveRemoteActor, unfollowActor, handleMoveInbox, moveAccount, listFollowing, setAutoBoost, backfillFromOutbox, getTimeline, timelineRowsByIds, contentWarning, getDirectMessages, readMarkers, markRead, unreadPerConversation, messageRowsByUri, replyRowsByUri, conversationHeads, conversationHistory, isoStamp, timelineAttachments, timelineEmojis, timelineObjectLinks, timelineQuote, timelineEmbed, applyQuoteProps, deliverToActor, sendInteraction, voteOnPoll, voteOnRemotePoll,
acceptGatedFollow, rejectGatedFollow, isWardGuardian, outboxAudience, sendFollowDecision,
gateOutgoingFollow, performApprovedFollow, recordGuardianEvent, listGuardianEvents, GUARDIAN_EVENT_KEEP,
parseOwnPoll, pollTally, ownPollView, deliverPollUpdate, maybeCrawlThread, sendReport, localMentionSlugs, previewCard,
autoBoostCount, boostedCount, setReaction, getReaction, getReactionsFor, canonicalReactionUri, migrateReactions, upsertBoostedNote, getCirkelPosts, getCirkelMembers, selfHealTimeline,
getNotifications, listBlocks, isBlockedAny, blockTarget, unblock,
deliverWithRetry, enqueueDelivery, processDeliveryQueue, startDeliveryWorker,
sendMaybe304, etagFor, onGuardian, wakeGuardian, onGuardianshipEvent, proposeGate, getReplyUris, getThread, filterThreadToCircle, gateAttachments, stripEmojiTags, actorObject, previewObject, quoteObject, markNotificationsSeen, countUnseenNotifications, hasPlayableAudio,
linkifyBody, bakePostContent, bakePostContentWithMentions, listFollowers, removeFollower, listConnections,
noteVisibility, belongsInTimeline, playerUrlFor, isRejectedObject, rejectInteraction, interactionReportTarget,
getMessages, notificationsSeenAt, ingestOutboxActivity, c2sVisibility, actorDisplay, buildActorRef, prefersEnriched, selfAuthor, getReplyMessages, onNews, wakeNews,
};