source: Klonkt/src/services/guardianship/delivery.js@ 6bc2e31b

main
Last change on this file since 6bc2e31b was e62f65d, checked in by Robin <roboburr@…>, 7 weeks ago

Guardian 2: de zwaai (shaer:wave), warmte zonder publiceren

Een guardian kan met één tik naar een ward zwaaien: "denkt aan je". Het is een
prive direct-note met een shaer:wave-marker, spiegelbeeld van de reddingsboei
(shaer:helpRequest): nooit een feed-post, geen boosts, geen timeline. Niet-shaer
clients zien gewoon een DM; een shaer-client kan het als zacht seintje tonen. De
guardian publiceert dus niks.

Rijdt op het bestaande direct-note-pad (delivery.js), dus cross-instance en met
retry. De ward ontvangt 'm als prive-mention (marker opgeslagen in ap_mentions.wave
voor latere weergave).

Changed files:
src/services/guardianship/notes.js

  • waveProps/isWave naast de helpRequest-marker

src/services/guardianship/index.js

  • waveProps/isWave geexporteerd

src/services/guardianship/delivery.js

  • deliverDirectNote neemt een wave-vlag, stempelt ap_outbox.wave

src/services/ActivityPubService.js

  • buildReplyNote stempelt shaer:wave; inbound mention slaat wave op

src/config/database.js

  • ap_outbox.wave + ap_mentions.wave

src/routes/guardian2.js

  • POST /api/wave (alleen naar je eigen ward); wave/waved strings

src/views/pages/guardian2.ejs, src/assets/js/guardian2.js

  • Zwaai-knop op elke ward-kaart

src/services/i18n.js

  • guardian2 wave/waved (nl/en/de)

remarks: npm test 167/167; wave-api auth-gated. Ward-kant toont 'm nu als prive-
mention (de emoji draagt 'm); een wave-badge in Berichten + het DM-antwoord-draadje
zijn de volgende, kleine stap.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 5.2 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';
15
16const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
17
18let deps = null;
19/** Called once by ActivityPubService with the shared AP helpers. */
20export function wireDelivery(d) { deps = d; }
21
22// Addressing → visibility. Arrays or bare strings; unknown shapes read as the
23// safest bucket they match.
24export function c2sVisibility(object) {
25 const arr = (v) => (Array.isArray(v) ? v : (v ? [v] : [])).filter((x) => typeof x === 'string');
26 const to = arr(object.to), cc = arr(object.cc);
27 const isPublic = (x) => x === PUBLIC || x === 'as:Public' || x === 'Public';
28 const isFollowers = (x) => /\/followers\/?$/.test(x);
29 if (to.some(isPublic)) return 'public';
30 if (cc.some(isPublic)) return 'quiet';
31 if (to.some(isFollowers) || cc.some(isFollowers)) return 'friends';
32 if (!to.length && !cc.length) return 'public'; // no addressing at all: legacy client, keep old behavior
33 return 'direct';
34}
35
36// A direct note: a NEW conversation (or a direct reply) addressed to specific
37// actors only. Stored in ap_outbox with visibility 'direct' + the recipient
38// list, delivered to exactly those inboxes: no followers fan-out, no Public,
39// so no boosts and no timelines. The same S2S leg a Mastodon DM takes, so a
40// guardian on any instance receives it as a private mention (the ward
41// call-for-help path).
42export async function deliverDirectNote(site, { recipients, text, language, inReplyTo, attachments, helpRequest, wave }) {
43 const { actorId, fetchActor, deriveHandle, escHtml, linkUrls, linkHashtags,
44 getOutboxRow, buildReplyNote, AP_CONTEXT, getOrCreateKeys, deliver, enqueueDelivery } = deps;
45 const base = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
46 const list = [...new Set((recipients || []).filter((u) => /^https?:\/\//i.test(String(u || ''))))].slice(0, 8);
47 if (!base || !site || !site.slug || !list.length || !String(text || '').trim()) return null;
48 const me = actorId(base, site.slug);
49 // Resolve every recipient for a mention anchor + a delivery inbox.
50 const resolved = [];
51 for (const uri of list) {
52 const a = await fetchActor(uri).catch(() => null);
53 if (!a || !(a.inbox || (a.endpoints && a.endpoints.sharedInbox))) continue;
54 resolved.push({ uri, inbox: (a.endpoints && a.endpoints.sharedInbox) || a.inbox, handle: deriveHandle(uri), url: a.url || uri });
55 }
56 if (!resolved.length) return null;
57 const mention = resolved.map((r) => {
58 const disp = r.handle && r.handle[0] === '@' ? r.handle : '@' + (r.handle || '');
59 return `<a href="${escHtml(r.url)}" class="u-url mention" data-actor="${escHtml(r.uri)}">${escHtml(disp)}</a> `;
60 }).join('');
61 const body = escHtml(String(text).trim()).replace(/\r?\n/g, '<br>');
62 const content = `<p>${mention}${linkUrls(linkHashtags(base, body))}</p>`;
63 const lang = /^[a-z]{2,3}(-[A-Za-z0-9-]+)?$/.test(String(language || '')) ? language : null;
64 // Attachments: same rules as deliverReply (own /media/ uploads only,
65 // image/audio/video, max 4) — the help-buoy capture rides this.
66 const media = (Array.isArray(attachments) ? attachments : [])
67 .filter((a) => a && typeof a.url === 'string' && /^\/media\/[\w./-]+$/.test(a.url)
68 && /^(image|audio|video)\//.test(String(a.mediaType || '')))
69 .slice(0, 4)
70 .map((a) => ({ url: a.url, mediaType: String(a.mediaType), name: String(a.name || '').slice(0, 120) }));
71 const id = crypto.randomUUID();
72 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, created_at)
73 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP)`)
74 .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);
75 const row = getOutboxRow(id);
76 const note = buildReplyNote(base, site, row);
77 const create = {
78 '@context': AP_CONTEXT,
79 id: note.id + '#create', type: 'Create', actor: me,
80 published: note.published, to: note.to, cc: note.cc, object: note,
81 };
82 const keys = getOrCreateKeys(site.slug);
83 const keyId = `${me}#main-key`;
84 let delivered = 0;
85 for (const inbox of [...new Set(resolved.map((r) => r.inbox))]) {
86 let ok = false;
87 try { const st = await deliver(inbox, create, keyId, keys.private_pem); ok = st >= 200 && st < 300; } catch { ok = false; }
88 if (ok) delivered++;
89 else enqueueDelivery(site.slug, inbox, create);
90 }
91 console.log('[AP] direct note', site.slug, '→', resolved.length, 'recipient(s), delivered', delivered);
92 return { id, content, delivered };
93}
94
95export default { wireDelivery, c2sVisibility, deliverDirectNote };
Note: See TracBrowser for help on using the repository browser.