source: Klonkt/src/services/ActivityPubService.js@ 52ea6df

main
Last change on this file since 52ea6df was 55bc7f9, checked in by Robin Genis <roboburr@…>, 3 months ago

feat(activitypub): reply back to the fediverse (Phase 4 outbound)

Site owner can reply to an inbound fediverse interaction from the post page. The
reply is sent as a signed Create(Note) with inReplyTo + @Mention to the remote
actor's inbox + our followers, stored in ap_outbox, shown in the thread, and
resolvable at /ap/notes/<id>.

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

  • Property mode set to 100644
File size: 22.9 KB
Line 
1/**
2 * ActivityPubService — Klonkt as a real ActivityPub actor (fediverse bridge).
3 *
4 * Phase 1 (this file): the PUBLISH/discoverable side.
5 * - per-site RSA keypair (Mastodon-compatible HTTP Signatures; separate from
6 * the Ed25519 keys used by the lighter Cirkels v1)
7 * - builders for the Actor document, Note objects and the Outbox collection
8 * - apWants(): HTTP content-negotiation helper (activity+json vs HTML)
9 *
10 * The interactive side (inbox: Follow/Accept, signature verify, delivery to
11 * followers) lands in the next step and is tested live against Mastodon.
12 *
13 * AP actor URLs live under /ap/* so they never clash with the human pages:
14 * actor = <base>/ap/users/<slug>
15 * inbox = <actor>/inbox outbox = <actor>/outbox
16 * note = <base>/ap/notes/<postId>
17 */
18import crypto from 'crypto';
19import db from '../config/database.js';
20import HtmlSanitizerService from './HtmlSanitizerService.js';
21
22const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
23const MAX_OUTBOX = 20;
24
25// ── RSA keys per actor (lazy, cached in DB) ───────────────────────
26// Prepared lazily (NOT at module load) — the ap_keys table is created in
27// initializeDatabase(), which runs after this module is imported.
28let _sel, _ins;
29function keyStmts() {
30 if (!_sel) {
31 _sel = db.prepare('SELECT public_pem, private_pem FROM ap_keys WHERE slug = ?');
32 _ins = db.prepare('INSERT OR IGNORE INTO ap_keys (slug, public_pem, private_pem, created_at) VALUES (?,?,?,CURRENT_TIMESTAMP)');
33 }
34 return { sel: _sel, ins: _ins };
35}
36
37export function getOrCreateKeys(slug) {
38 const { sel, ins } = keyStmts();
39 const row = sel.get(slug);
40 if (row) return row;
41 const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
42 modulusLength: 2048,
43 publicKeyEncoding: { type: 'spki', format: 'pem' },
44 privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
45 });
46 ins.run(slug, publicKey, privateKey);
47 return sel.get(slug) || { public_pem: publicKey, private_pem: privateKey };
48}
49
50// ── content negotiation ───────────────────────────────────────────
51// True when the caller wants ActivityPub JSON rather than the HTML page.
52export function apWants(req) {
53 const a = String(req.headers.accept || '').toLowerCase();
54 return a.includes('application/activity+json') ||
55 (a.includes('application/ld+json') && a.includes('activitystreams'));
56}
57
58const AP_CONTENT_TYPE = 'application/activity+json; charset=utf-8';
59export function sendAP(res, obj) {
60 res.type(AP_CONTENT_TYPE);
61 res.set('Cache-Control', 'public, max-age=120');
62 res.send(JSON.stringify(obj));
63}
64
65// ── document builders ─────────────────────────────────────────────
66export function actorId(base, slug) { return `${base}/ap/users/${encodeURIComponent(slug)}`; }
67export function noteId(base, postId) { return `${base}/ap/notes/${encodeURIComponent(postId)}`; }
68
69export function buildActor(base, site) {
70 const id = actorId(base, site.slug);
71 const keys = getOrCreateKeys(site.slug);
72 const actor = {
73 '@context': ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1'],
74 id,
75 type: 'Person',
76 preferredUsername: site.slug,
77 name: site.title || site.slug,
78 summary: site.tagline || site.description || '',
79 url: `${base}/${site.slug === site.primary_slug ? '' : 'user/' + encodeURIComponent(site.slug)}`,
80 manuallyApprovesFollowers: false,
81 discoverable: true,
82 inbox: `${id}/inbox`,
83 outbox: `${id}/outbox`,
84 followers: `${id}/followers`,
85 endpoints: { sharedInbox: `${base}/ap/inbox` },
86 publicKey: {
87 id: `${id}#main-key`,
88 owner: id,
89 publicKeyPem: keys.public_pem,
90 },
91 };
92 if (site.profile_photo) {
93 const u = /^https?:/.test(site.profile_photo) ? site.profile_photo : `${base}${site.profile_photo.startsWith('/') ? '' : '/'}${site.profile_photo}`;
94 actor.icon = { type: 'Image', url: u };
95 }
96 return actor;
97}
98
99// A single post as an AS2 Note (the object), and as a Create activity (for outbox/delivery).
100export function buildNote(base, site, post) {
101 const id = noteId(base, post.id);
102 const aId = actorId(base, site.slug);
103 const human = `${base}/${encodeURIComponent(post.slug)}`;
104 // Mastodon ignores a Note's `name`, so put the title INTO the content (bold
105 // first line) — the standard blog→fediverse convention. post.content is
106 // already sanitized HTML; the title is plain text, so escape it.
107 const escTitle = String(post.title || '').replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]));
108 const titleHtml = post.title ? `<p><strong>${escTitle}</strong></p>` : '';
109
110 // Images travel as AP `attachment` (Mastodon strips <img> from content). Collect
111 // the cover + any inline <img>, make absolute, then strip <img> from the content
112 // to avoid duplicate rendering on clients that DO keep them.
113 const abs = (u) => !u ? null : (/^https?:/i.test(u) ? u : `${base}${u.startsWith('/') ? '' : '/'}${u}`);
114 const mediaType = (u) => {
115 const e = ((u || '').split('?')[0].match(/\.(\w+)$/) || [])[1];
116 return ({ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp', avif: 'image/avif' })[(e || '').toLowerCase()] || 'image/jpeg';
117 };
118 const urls = [];
119 if (post.cover_image_url) urls.push(abs(post.cover_image_url));
120 let body = post.content || '';
121 for (const m of body.matchAll(/<img\b[^>]*\bsrc="([^"]+)"[^>]*>/gi)) urls.push(abs(m[1]));
122 body = body.replace(/<img\b[^>]*>/gi, '');
123 const seen = new Set();
124 const attachment = urls.filter(Boolean)
125 .filter((u) => { if (seen.has(u)) return false; seen.add(u); return true; })
126 .map((u) => ({ type: 'Document', mediaType: mediaType(u), url: u }));
127
128 const note = {
129 id,
130 type: 'Note',
131 attributedTo: aId,
132 content: titleHtml + body,
133 url: human,
134 published: new Date(post.published_at || post.created_at || Date.now()).toISOString(),
135 to: [PUBLIC],
136 cc: [`${aId}/followers`],
137 tag: Array.isArray(post.tags) ? post.tags.map((t) => ({ type: 'Hashtag', name: '#' + String(t).replace(/\s+/g, '') })) : [],
138 };
139 if (attachment.length) note.attachment = attachment;
140 return note;
141}
142
143export function buildCreate(base, site, post) {
144 const note = buildNote(base, site, post);
145 return {
146 '@context': 'https://www.w3.org/ns/activitystreams',
147 id: note.id + '#create',
148 type: 'Create',
149 actor: actorId(base, site.slug),
150 published: note.published,
151 to: note.to,
152 cc: note.cc,
153 object: note,
154 };
155}
156
157export function buildOutbox(base, site, posts) {
158 const id = `${actorId(base, site.slug)}/outbox`;
159 const items = (posts || []).slice(0, MAX_OUTBOX).map((p) => buildCreate(base, site, p));
160 return {
161 '@context': 'https://www.w3.org/ns/activitystreams',
162 id,
163 type: 'OrderedCollection',
164 totalItems: items.length,
165 orderedItems: items,
166 };
167}
168
169export function buildFollowers(base, site, count) {
170 const id = `${actorId(base, site.slug)}/followers`;
171 return {
172 '@context': 'https://www.w3.org/ns/activitystreams',
173 id,
174 type: 'OrderedCollection',
175 totalItems: count || 0,
176 orderedItems: [], // hidden for privacy; count only
177 };
178}
179
180// ── followers store (lazy stmts) ──────────────────────────────────
181let _insF, _delF, _listF, _cntF;
182function fStmts() {
183 if (!_insF) {
184 _insF = db.prepare('INSERT OR IGNORE INTO ap_followers (slug, actor_uri, inbox, shared_inbox, created_at) VALUES (?,?,?,?,CURRENT_TIMESTAMP)');
185 _delF = db.prepare('DELETE FROM ap_followers WHERE slug = ? AND actor_uri = ?');
186 _listF = db.prepare('SELECT inbox, shared_inbox FROM ap_followers WHERE slug = ?');
187 _cntF = db.prepare('SELECT COUNT(*) n FROM ap_followers WHERE slug = ?');
188 }
189 return { ins: _insF, del: _delF, list: _listF, cnt: _cntF };
190}
191export function followerCount(slug) { return fStmts().cnt.get(slug).n; }
192
193// ── inbound interactions store (replies / likes / boosts) + our outbound replies ──
194let _insI, _delLA, _delReply, _listI, _getI, _insO, _listO, _getO;
195function iStmts() {
196 if (!_insI) {
197 _insI = db.prepare('INSERT OR IGNORE INTO ap_interactions (kind, post_id, object_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)');
198 _delLA = db.prepare('DELETE FROM ap_interactions WHERE kind = ? AND post_id = ? AND actor_uri = ?');
199 _delReply = db.prepare("DELETE FROM ap_interactions WHERE kind = 'reply' AND object_uri = ?");
200 _listI = db.prepare('SELECT id, kind, object_uri, actor_uri, actor_name, actor_handle, actor_url, actor_icon, content, published, created_at FROM ap_interactions WHERE post_id = ? ORDER BY created_at ASC');
201 _getI = db.prepare('SELECT * FROM ap_interactions WHERE id = ?');
202 _insO = db.prepare('INSERT INTO ap_outbox (id, site_slug, post_id, post_slug, in_reply_to, to_actor, to_handle, content, created_at) VALUES (?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)');
203 _listO = db.prepare('SELECT * FROM ap_outbox WHERE post_id = ? ORDER BY created_at ASC');
204 _getO = db.prepare('SELECT * FROM ap_outbox WHERE id = ?');
205 }
206 return { ins: _insI, delLA: _delLA, delReply: _delReply, list: _listI, getI: _getI, insO: _insO, listO: _listO, getO: _getO };
207}
208
209export function getInteractionById(id) { return iStmts().getI.get(id); }
210
211const localPostExists = (id) => { try { return !!db.prepare('SELECT 1 FROM posts WHERE id = ?').get(id); } catch { return false; } };
212// Extract our local post id from a note URL, but only if it's ours (base match).
213function postIdFromNoteUrl(url, base) {
214 const s = String(url || '');
215 if (base && !s.startsWith(base)) return null;
216 const m = s.match(/\/ap\/notes\/([^/?#]+)/);
217 return m ? decodeURIComponent(m[1]) : null;
218}
219function deriveHandle(actorUri) {
220 try { const u = new URL(actorUri); const seg = u.pathname.split('/').filter(Boolean).pop() || ''; return `@${seg}@${u.host}`; } catch { return String(actorUri || ''); }
221}
222function actorInfo(doc, actorUri) {
223 let host = ''; try { host = new URL(actorUri).host; } catch { /* keep empty */ }
224 const handle = doc && doc.preferredUsername ? `@${doc.preferredUsername}@${host}` : deriveHandle(actorUri);
225 const icon = doc && doc.icon ? (doc.icon.url || (Array.isArray(doc.icon) && doc.icon[0] && doc.icon[0].url)) : null;
226 return {
227 name: (doc && (doc.name || doc.preferredUsername)) || handle,
228 handle,
229 url: (doc && (doc.url || doc.id)) || actorUri,
230 icon: icon || null,
231 };
232}
233
234// Stored, view-ready summary of a post's inbound fediverse activity + our replies.
235export function getInteractions(postId) {
236 const s = iStmts();
237 const rows = s.list.all(postId);
238 const outReplies = s.listO.all(postId).map((o) => ({
239 id: o.id, content: o.content, in_reply_to: o.in_reply_to, to_handle: o.to_handle,
240 created_at: o.created_at, mine: true,
241 }));
242 return {
243 replies: rows.filter((r) => r.kind === 'reply'),
244 outReplies,
245 likeCount: rows.filter((r) => r.kind === 'like').length,
246 announceCount: rows.filter((r) => r.kind === 'announce').length,
247 total: rows.length + outReplies.length,
248 };
249}
250
251// ── HTTP Signatures + delivery ────────────────────────────────────
252const slugFromActorUrl = (url) => { const m = String(url || '').match(/\/ap\/users\/([^/?#]+)/); return m ? decodeURIComponent(m[1]) : null; };
253
254// Sign + POST an activity to a remote inbox (draft-cavage HTTP Signatures, RSA-SHA256).
255export async function deliver(inboxUrl, bodyObj, keyId, privatePem) {
256 const body = JSON.stringify(bodyObj);
257 const u = new URL(inboxUrl);
258 const date = new Date().toUTCString();
259 const digest = 'SHA-256=' + crypto.createHash('sha256').update(body).digest('base64');
260 const signingString = `(request-target): post ${u.pathname}\nhost: ${u.host}\ndate: ${date}\ndigest: ${digest}`;
261 const signature = crypto.sign('sha256', Buffer.from(signingString), privatePem).toString('base64');
262 const sig = `keyId="${keyId}",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="${signature}"`;
263 const r = await fetch(inboxUrl, {
264 method: 'POST',
265 headers: { 'Content-Type': 'application/activity+json', Accept: 'application/activity+json', Date: date, Digest: digest, Signature: sig },
266 body,
267 signal: AbortSignal.timeout(8000),
268 });
269 return r.status;
270}
271
272export async function fetchActor(url) {
273 try {
274 const r = await fetch(url, { headers: { Accept: 'application/activity+json' }, redirect: 'follow', signal: AbortSignal.timeout(8000) });
275 if (!r.ok) return null;
276 return await r.json();
277 } catch { return null; }
278}
279
280// Best-effort verification of an incoming signed request. Returns the sender's
281// actor doc if the signature checks out, else null. (Not gating yet — MVP.)
282export async function verifyRequest(req) {
283 const sigH = req.headers['signature'];
284 if (!sigH) return null;
285 const p = Object.fromEntries([...sigH.matchAll(/([a-zA-Z]+)="([^"]*)"/g)].map((m) => [m[1], m[2]]));
286 if (!p.keyId || !p.signature) return null;
287 const actor = await fetchActor(p.keyId.split('#')[0]);
288 const pem = actor && actor.publicKey && actor.publicKey.publicKeyPem;
289 if (!pem) return null;
290 const hs = (p.headers || '(request-target) host date').split(/\s+/);
291 const line = hs.map((h) => h === '(request-target)'
292 ? `(request-target): ${req.method.toLowerCase()} ${req.originalUrl}`
293 : `${h}: ${req.headers[h] || ''}`).join('\n');
294 let ok = false;
295 try { ok = crypto.verify('sha256', Buffer.from(line), pem, Buffer.from(p.signature, 'base64')); } catch { ok = false; }
296 if (ok && hs.includes('digest') && req.rawBody) {
297 const exp = 'SHA-256=' + crypto.createHash('sha256').update(req.rawBody).digest('base64');
298 if (req.headers['digest'] !== exp) ok = false;
299 }
300 return ok ? actor : null;
301}
302
303// Handle an incoming inbox POST. slugParam = null for the shared /ap/inbox.
304export async function handleInbox(req, slugParam) {
305 const act = req.body || {};
306 const type = act.type;
307 const base = (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host')}`).replace(/\/+$/, '');
308 const verified = await verifyRequest(req).catch(() => null); // best-effort; not gating (MVP)
309
310 if (type === 'Follow') {
311 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
312 const slug = slugParam || slugFromActorUrl(typeof act.object === 'string' ? act.object : (act.object && act.object.id));
313 if (!who || !slug) return 400;
314 const remote = await fetchActor(who);
315 if (!remote || !remote.inbox) return 202; // can't reach them → drop quietly
316 fStmts().ins.run(slug, who, remote.inbox, (remote.endpoints && remote.endpoints.sharedInbox) || null);
317 const me = actorId(base, slug);
318 const keys = getOrCreateKeys(slug);
319 const accept = { '@context': 'https://www.w3.org/ns/activitystreams', id: `${me}#accept-${Date.now()}`, type: 'Accept', actor: me, object: act };
320 deliver(remote.inbox, accept, `${me}#main-key`, keys.private_pem).catch((e) => console.warn('[AP] Accept delivery failed:', e.message));
321 console.log('[AP] Follow', who, '→', slug, verified ? '(sig ok)' : '(sig unverified)');
322 return 202;
323 }
324 if (type === 'Undo' && act.object) {
325 const who = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
326 const ot = act.object.type;
327 if (ot === 'Follow') {
328 const obj = act.object.object;
329 const slug = slugParam || slugFromActorUrl(typeof obj === 'string' ? obj : (obj && obj.id));
330 if (who && slug) { fStmts().del.run(slug, who); console.log('[AP] Unfollow', who, '→', slug); }
331 return 202;
332 }
333 if (ot === 'Like' || ot === 'Announce') {
334 const tgt = act.object.object;
335 const pid = postIdFromNoteUrl(typeof tgt === 'string' ? tgt : (tgt && tgt.id), base);
336 if (who && pid) { iStmts().delLA.run(ot.toLowerCase(), pid, who); console.log('[AP] Undo', ot, who, '→', pid); }
337 return 202;
338 }
339 return 202;
340 }
341
342 const actorUri = typeof act.actor === 'string' ? act.actor : (act.actor && act.actor.id);
343 const resolveActor = async (uri) => ((verified && verified.id === uri) ? verified : await fetchActor(uri).catch(() => null));
344
345 // Inbound reply: a Create whose object replies to one of our notes.
346 if (type === 'Create' && act.object && (act.object.type === 'Note' || act.object.type === 'Article')) {
347 const o = act.object;
348 const pid = postIdFromNoteUrl(o.inReplyTo, base);
349 if (pid && actorUri && localPostExists(pid)) {
350 const ai = actorInfo(await resolveActor(actorUri), actorUri);
351 const html = HtmlSanitizerService.sanitize(o.content || '');
352 iStmts().ins.run('reply', pid, o.id || '', actorUri, ai.name, ai.handle, ai.url, ai.icon, html, o.published || null);
353 console.log('[AP] reply', actorUri, '→', pid);
354 }
355 return 202;
356 }
357 if (type === 'Like' || type === 'Announce') {
358 const tgt = act.object;
359 const pid = postIdFromNoteUrl(typeof tgt === 'string' ? tgt : (tgt && tgt.id), base);
360 if (pid && actorUri && localPostExists(pid)) {
361 const ai = actorInfo(await resolveActor(actorUri), actorUri);
362 iStmts().ins.run(type.toLowerCase(), pid, '', actorUri, ai.name, ai.handle, ai.url, ai.icon, null, null);
363 console.log('[AP]', type === 'Like' ? 'like' : 'boost', actorUri, '→', pid);
364 }
365 return 202;
366 }
367 if (type === 'Delete') {
368 // A remote reply was deleted upstream → drop it if we stored it.
369 const oid = typeof act.object === 'string' ? act.object : (act.object && act.object.id);
370 if (oid) iStmts().delReply.run(oid);
371 return 202;
372 }
373
374 console.log('[AP] inbox', type || 'unknown', '→', slugParam || 'shared', '(ignored)');
375 return 202;
376}
377
378// Deliver a new post as Create(Note) to all followers' inboxes (fire-and-forget).
379// Needs PUBLIC_BASE_URL (absolute URLs); no-op without followers or base.
380export async function deliverCreate(site, post) {
381 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
382 if (!base || !site || !site.slug) return;
383 const followers = fStmts().list.all(site.slug);
384 if (!followers.length) return;
385 const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
386 const keys = getOrCreateKeys(site.slug);
387 const keyId = `${actorId(base, site.slug)}#main-key`;
388 const create = buildCreate(base, site, post);
389 for (const inbox of inboxes) deliver(inbox, create, keyId, keys.private_pem).catch(() => { /* best-effort */ });
390}
391
392// Tell followers a post is gone (Delete + Tombstone) so it's removed from their feeds.
393export async function deliverDelete(site, post) {
394 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
395 if (!base || !site || !site.slug || !post || !post.id) return;
396 const followers = fStmts().list.all(site.slug);
397 if (!followers.length) return;
398 const inboxes = [...new Set(followers.map((f) => f.shared_inbox || f.inbox).filter(Boolean))];
399 const keys = getOrCreateKeys(site.slug);
400 const me = actorId(base, site.slug);
401 const nid = noteId(base, post.id);
402 const del = {
403 '@context': 'https://www.w3.org/ns/activitystreams',
404 id: `${nid}#delete-${Date.now()}`,
405 type: 'Delete',
406 actor: me,
407 to: [PUBLIC],
408 object: { id: nid, type: 'Tombstone' },
409 };
410 for (const inbox of inboxes) deliver(inbox, del, `${me}#main-key`, keys.private_pem).catch(() => { /* best-effort */ });
411}
412
413// ── outbound replies (Klonkt → fediverse) ─────────────────────────
414const escHtml = (s) => String(s || '').replace(/[<>&]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;' }[c]));
415const 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(); };
416
417// Build one of OUR outbound reply Notes from an ap_outbox row.
418export function buildReplyNote(base, site, row) {
419 const me = actorId(base, site.slug);
420 return {
421 id: noteId(base, row.id),
422 type: 'Note',
423 attributedTo: me,
424 inReplyTo: row.in_reply_to || undefined,
425 content: row.content,
426 url: row.post_slug ? `${base}/${encodeURIComponent(row.post_slug)}` : undefined,
427 published: toISO(row.created_at),
428 to: row.to_actor ? [row.to_actor] : [PUBLIC],
429 cc: [PUBLIC, `${me}/followers`],
430 tag: row.to_actor ? [{ type: 'Mention', href: row.to_actor, name: row.to_handle }] : [],
431 };
432}
433
434// Resolve one of our outbound reply Notes by id (for /ap/notes/:id fallback).
435export function getOutboxNote(base, id) {
436 const row = iStmts().getO.get(id);
437 if (!row) return null;
438 const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(row.site_slug);
439 if (!site) return null;
440 return buildReplyNote(base, site, row);
441}
442
443// Send a reply FROM this site to a remote actor (in reply to their inbound reply).
444// `parent` = an ap_interactions row (actor_uri, actor_url, actor_handle, object_uri).
445export async function deliverReply(site, { postId, postSlug, parent, text }) {
446 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
447 if (!base || !site || !site.slug || !parent || !String(text || '').trim()) return null;
448 const me = actorId(base, site.slug);
449 const handle = parent.actor_handle || deriveHandle(parent.actor_uri);
450 const body = escHtml(String(text).trim()).replace(/\r?\n/g, '<br>');
451 const mention = parent.actor_uri
452 ? `<a href="${escHtml(parent.actor_url || parent.actor_uri)}" class="u-url mention">${escHtml(handle)}</a> ` : '';
453 const content = `<p>${mention}${body}</p>`;
454 const id = crypto.randomUUID();
455 iStmts().insO.run(id, site.slug, postId, postSlug || null, parent.object_uri || null, parent.actor_uri || null, handle, content);
456 const row = iStmts().getO.get(id);
457 const note = buildReplyNote(base, site, row);
458 const create = {
459 '@context': 'https://www.w3.org/ns/activitystreams',
460 id: note.id + '#create', type: 'Create', actor: me,
461 published: note.published, to: note.to, cc: note.cc, object: note,
462 };
463 const keys = getOrCreateKeys(site.slug);
464 const keyId = `${me}#main-key`;
465 const inboxes = new Set();
466 if (parent.actor_uri) {
467 const a = await fetchActor(parent.actor_uri).catch(() => null);
468 if (a) inboxes.add((a.endpoints && a.endpoints.sharedInbox) || a.inbox);
469 }
470 for (const f of fStmts().list.all(site.slug)) inboxes.add(f.shared_inbox || f.inbox);
471 let delivered = 0;
472 for (const inbox of [...inboxes].filter(Boolean)) {
473 try { const st = await deliver(inbox, create, keyId, keys.private_pem); if (st >= 200 && st < 300) delivered++; } catch { /* best-effort */ }
474 }
475 console.log('[AP] outreply', site.slug, '→', parent.actor_uri, 'delivered', delivered);
476 return { id, content, delivered };
477}
478
479export default {
480 getOrCreateKeys, apWants, sendAP, actorId, noteId,
481 buildActor, buildNote, buildCreate, buildOutbox, buildFollowers,
482 followerCount, deliver, fetchActor, verifyRequest, handleInbox, deliverCreate, deliverDelete,
483 getInteractions, getInteractionById, buildReplyNote, getOutboxNote, deliverReply,
484};
Note: See TracBrowser for help on using the repository browser.