source: Klonkt/src/services/guardianship/delivery.js@ 8b83cba

main
Last change on this file since 8b83cba was 8b83cba, checked in by Bart <bart@…>, 4 weeks ago

Een direct bericht haalt de ontvanger ondertekend op

@catsalad@… aanschrijven gaf "502 direct_failed". Niet de client:
infosec.exchange draait Mastodons secure mode en antwoordt 401 op een anonieme
GET van het actor-document. fetchActor KAN ondertekenen, maar alleen als je
zegt namens wie -- en wireDelivery gaf hem kaal door, dus deze weg probeerde het
nooit. Geen document, geen inbox, ontvanger valt weg, en met de laatste
ontvanger geeft deliverDirectNote null: 502.

Precies de les van 31-7 bij het volgen vanaf een boost: die weg kreeg toen
signedGetJson, deze bleef achter. Het bewijs staat in de data -- boiert volgt
catsalad met status accepted, dus een ondertekende ophaal naar diezelfde server
werkt allang; alleen deze aanroep deed het niet.

Onbetekend blijft eerst. Dat is een veiligheidskeuze (zie de kop van
fetchActor): pas als dat mislukt tekent hij, en alleen voor die ene URL.

Co-Authored-By: Claude Opus 5 <claude@…>

  • Property mode set to 100644
File size: 9.6 KB
Line 
1/**
2 * Guardianship (FEP-633c) — the direct-note delivery leg.
3 *
4 * A direct note (private mention, shaer-tqc) is the ward's call-for-help
5 * carrier: addressed to specific actors only, no Public, no followers
6 * fan-out. Moved here from ActivityPubService (guardianship refactor);
7 * behavior is unchanged.
8 *
9 * This module has NO import back into ActivityPubService: the AP helpers it
10 * needs (actor fetch, key material, delivery, note building) are provided
11 * once via wireDelivery(deps) at ActivityPubService load time.
12 */
13import crypto from 'crypto';
14import db from '../../config/database.js';
15import { carriesGuardians } from './context.js';
16
17const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
18
19let deps = null;
20/** Called once by ActivityPubService with the shared AP helpers. */
21export function wireDelivery(d) { deps = d; }
22
23// Addressing → visibility. Arrays or bare strings; unknown shapes read as the
24// safest bucket they match.
25export function c2sVisibility(object) {
26 const arr = (v) => (Array.isArray(v) ? v : (v ? [v] : [])).filter((x) => typeof x === 'string');
27 const to = arr(object.to), cc = arr(object.cc);
28 const isPublic = (x) => x === PUBLIC || x === 'as:Public' || x === 'Public';
29 const isFollowers = (x) => /\/followers\/?$/.test(x);
30 if (to.some(isPublic)) return 'public';
31 if (cc.some(isPublic)) return 'quiet';
32 if (to.some(isFollowers) || cc.some(isFollowers)) return 'friends';
33 if (!to.length && !cc.length) return 'public'; // no addressing at all: legacy client, keep old behavior
34 return 'direct';
35}
36
37// A direct note: a NEW conversation (or a direct reply) addressed to specific
38// actors only. Stored in ap_outbox with visibility 'direct' + the recipient
39// list, delivered to exactly those inboxes: no followers fan-out, no Public,
40// so no boosts and no timelines. The same S2S leg a Mastodon DM takes, so a
41// guardian on any instance receives it as a private mention (the ward
42// call-for-help path).
43export async function deliverDirectNote(site, { recipients, text, html, language, inReplyTo, attachments, helpRequest, wave, awayUntil, helpMark, gateRequest }) {
44 const { actorId, fetchActor, localActor, deliverTo, deriveHandle, escHtml, linkUrls, linkHashtags,
45 getOutboxRow, buildReplyNote, AP_CONTEXT, getOrCreateKeys, deliver, enqueueDelivery } = deps;
46 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
47 const list = [...new Set((recipients || []).filter((u) => /^https?:\/\//i.test(String(u || ''))))].slice(0, 8);
48 if (!base || !site || !site.slug || !list.length || !String(text || '').trim()) return null;
49 const me = actorId(base, site.slug);
50 // Resolve every recipient for a mention anchor + a delivery inbox.
51 const resolved = [];
52 const teapots = [];
53 for (const uri of list) {
54 // An actor we host is read from our own database, not fetched from our own
55 // hostname: that request has to leave the machine and come back, and when
56 // it does not, the recipient is silently dropped from the note. Everything
57 // that decides anything still runs below, for local and remote alike.
58 // ONDERTEKEND ophalen als het onbetekend niet lukt (asSlug). Een instance
59 // met Mastodons secure mode -- infosec.exchange bijvoorbeeld -- antwoordt
60 // 401 op een anonieme GET van het actor-document. Zonder document geen
61 // inbox, dus viel de ontvanger hier stil weg, en met de laatste ontvanger
62 // gaf deliverDirectNote null terug: "502 direct_failed", zonder te zeggen
63 // wie er niet bereikbaar was.
64 //
65 // Dezelfde les als bij het volgen vanaf een boost (Robins melding, 31-7):
66 // die weg kreeg toen signedGetJson, deze niet. fetchActor probeert nog
67 // steeds ONBETEKEND eerst -- dat blijft de veiligheidskeuze -- en tekent
68 // alleen deze ene URL als dat mislukt.
69 const a = (localActor && localActor(uri))
70 || await fetchActor(uri, { asSlug: site.slug }).catch(() => null);
71 if (!a || !(a.inbox || (a.endpoints && a.endpoints.sharedInbox))) continue;
72 // FEP-633c §4.1: an escalation addressed to a "guardian" that carries
73 // guardians of its own goes nowhere. There is no grand-guardian, so we
74 // MUST NOT recurse to that actor's guardians — and we fail SOFTLY: drop
75 // this one target and keep delivering to the rest, because a malformed
76 // guardian must never cost a child the guardians who are fine.
77 //
78 // Only for a call for help. An ordinary direct note is not an escalation,
79 // and a ward is perfectly entitled to message another ward.
80 if (helpRequest && carriesGuardians(a)) { teapots.push(uri); continue; }
81 resolved.push({ uri, inbox: (a.endpoints && a.endpoints.sharedInbox) || a.inbox, local: !!a.local, handle: deriveHandle(uri), url: a.url || uri });
82 }
83 if (teapots.length) console.warn('[AP] not a teapot: escalation dropped for malformed guardian(s)', teapots.join(', '));
84 if (!resolved.length) {
85 // Every guardian was malformed. §4 does not say what to do here because
86 // §4.1 assumes there are others to continue to — but a ward whose whole
87 // safety net is broken has just called for help into nothing, which is the
88 // one outcome this FEP exists to prevent. Say so loudly; the caller can
89 // tell "nobody was reachable" from "nobody was valid".
90 if (teapots.length) console.error('[AP] EVERY guardian of', site.slug, 'is malformed: the call for help reached no one');
91 return null;
92 }
93 const mention = resolved.map((r) => {
94 const disp = r.handle && r.handle[0] === '@' ? r.handle : '@' + (r.handle || '');
95 return `<a href="${escHtml(r.url)}" class="u-url mention" data-actor="${escHtml(r.uri)}">${escHtml(disp)}</a> `;
96 }).join('');
97 // Rijk antwoord: `html` is de HTML uit de reply-editor, hier gesaneerd; `text`
98 // blijft de platte versie (het `source`-veld en de no-JS-fallback). Levert de
99 // sanitizer niets bruikbaars op, dan valt hij terug op de escaped tekst --
100 // een leeggepoetste editor mag geen leeg bericht versturen.
101 const richClean = html ? deps.sanitizeHtml(String(html)) : '';
102 const rich = richClean && deps.htmlToPlainText(richClean).trim() ? richClean : '';
103 const body = escHtml(String(text).trim()).replace(/\r?\n/g, '<br>');
104 // De mention-anker blijft een eigen alinea vooraan: de ontvanger moet in het
105 // bericht genoemd staan, ook als de rijke inhoud met een kop of lijst begint.
106 const content = rich
107 ? `<p>${mention}</p>${linkUrls(linkHashtags(base, rich))}`
108 : `<p>${mention}${linkUrls(linkHashtags(base, body))}</p>`;
109 const lang = /^[a-z]{2,3}(-[A-Za-z0-9-]+)?$/.test(String(language || '')) ? language : null;
110 // Attachments: same rules as deliverReply (own /media/ uploads only,
111 // image/audio/video, max 4) — the help-buoy capture rides this.
112 const media = (Array.isArray(attachments) ? attachments : [])
113 .filter((a) => a && typeof a.url === 'string' && /^\/media\/[\w./-]+$/.test(a.url)
114 && /^(image|audio|video)\//.test(String(a.mediaType || '')))
115 .slice(0, 4)
116 .map((a) => ({ url: a.url, mediaType: String(a.mediaType), name: String(a.name || '').slice(0, 120) }));
117 const id = crypto.randomUUID();
118 db.prepare(`INSERT INTO ap_outbox (id, site_slug, post_id, post_slug, in_reply_to, to_actor, to_handle, content, language, attachments, visibility, to_actors, help_request, wave, away_until, created_at)
119 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`)
120 .run(id, site.slug, '', null, inReplyTo || null, resolved[0].uri, resolved[0].handle, content, lang, media.length ? JSON.stringify(media) : null, 'direct', JSON.stringify(resolved.map((r) => r.uri)), helpRequest ? 1 : 0, wave ? 1 : 0, awayUntil || null);
121 const row = getOutboxRow(id);
122 const note = buildReplyNote(base, site, row);
123 // Markering op een hulpvraag (shaer-lgo): een gewone directe note die er een
124 // shaer:-eigenschap bij draagt, net als de zwaai. Zo reist het over dezelfde
125 // bezorging, ziet de ward het als bericht ("er komt iemand"), en houden de
126 // mede-guardians er staat aan over.
127 if (helpMark && helpMark.noteUri) {
128 note[helpMark.kind === 'handled' ? 'shaer:helpHandled' : 'shaer:helpPickup'] = helpMark.noteUri;
129 }
130 // Een kind dat zelf om een poort vraagt (shaer-8ru). Alleen de naam van de
131 // feature reist mee -- geen vrije tekst, zie gatereq.js.
132 if (gateRequest) note['shaer:gateRequest'] = String(gateRequest);
133 const create = {
134 '@context': AP_CONTEXT,
135 id: note.id + '#create', type: 'Create', actor: me,
136 published: note.published, to: note.to, cc: note.cc, object: note,
137 };
138 const keys = getOrCreateKeys(site.slug);
139 const keyId = `${me}#main-key`;
140 let delivered = 0;
141 // A recipient on this machine takes the loopback (deliverToActor), which
142 // hands the Create to the same inbox handler an HTTP POST would reach: the
143 // note is stored, the mention is stored, and a shaer:away on it is applied,
144 // all by the code that does it for everyone else. A hairpin POST to our own
145 // hostname is not that code path, it is a second one that only appears to be.
146 for (const r of resolved.filter((x) => x.local)) {
147 const res = await deliverTo(site, r.uri, create).catch(() => null);
148 if (res && res.delivered) delivered++;
149 }
150 // Remote: one POST per inbox, so two guardians on the same server share it.
151 for (const inbox of [...new Set(resolved.filter((x) => !x.local).map((r) => r.inbox))]) {
152 let ok = false;
153 try { const st = await deliver(inbox, create, keyId, keys.private_pem); ok = st >= 200 && st < 300; } catch { ok = false; }
154 if (ok) delivered++;
155 else enqueueDelivery(site.slug, inbox, create);
156 }
157 console.log('[AP] direct note', site.slug, '→', resolved.length, 'recipient(s), delivered', delivered);
158 return { id, content, delivered, teapots };
159}
160
161export default { wireDelivery, c2sVisibility, deliverDirectNote };
Note: See TracBrowser for help on using the repository browser.