source: Klonkt/src/services/guardianship/handshake.js@ 8f8b40f

main
Last change on this file since 8f8b40f was fcd6964, checked in by Robin <roboburr@…>, 7 weeks ago

Guardianship: ward ziet z'n guardians, PWA-assets no-cache, handle-fix

De handshake commit werkte al aan beide kanten (geverifieerd live: sound-fabrics
ziet beta als ward, beta weet dat sound-fabrics guardian is), maar het TONEN
ontbrak op drie plekken. Dit lost de Klonkt-kant op.

  1. Ward-kant: in Berichten ziet een ward nu wie z'n guardians zijn (committed relaties, FEP-633c §2). Die view bestond nog niet.
  2. other_handle bewaarde per ongeluk de FEP-escalatiehandle (candidate/inbox) i.p.v. de @handle, dus overal waar we het toonden kwam een inbox-URL uit. Nu de echte @handle uit de offer; display self-healt oude rijen door @user@host uit de actor-URI af te leiden als de opgeslagen handle geen @ is.
  3. Guardian PWA-assets via /guardian/app.js|css met Cache-Control: no-cache, dus een update wordt nooit meer gemaskeerd door de 1-jaar /assets-cache of een vastgelopen install (dat was de "niks werkt na deploy"-bug). Client zit nu in try/catch met een zichtbare foutbanner i.p.v. stil te hangen.

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

  • applyCommitLocally schrijft de @handle (offer.ward/candidate_handle) naar other_handle

src/routes/posts.js

  • messages-route levert myGuardians (committed guardians met afgeleide @handle)

src/views/pages/messages.ejs

  • "Jouw guardians"-sectie voor de ward

src/services/i18n.js

  • msg.guardians_label (nl/en/de)

src/routes/guardian.js

  • /guardian/app.js|css no-cache; ASSET_V-mtime-machinerie weg

src/assets/js/guardian.js

  • hele client in try/catch met zichtbare foutbanner; handleOf vertrouwt alleen echte @handles

src/views/pages/guardian.ejs

  • assets via no-cache routes i.p.v. /assets?v=

test/guardianship.test.js

  • assert dat other_handle de @handle is na commit

remarks: getest met npm test (6/6). sound-fabrics (stable-lane, handmatig) bewust
niet aangeraakt; wacht op akkoord.

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

  • Property mode set to 100644
File size: 9.6 KB
Line 
1/**
2 * Guardianship (FEP-633c §3) — the adoption handshake, multi-party and
3 * distributed across instances.
4 *
5 * The candidate Offers a Relationship{subject: ward, object: candidate},
6 * addressed to the ward AND every existing guardian of the ward. Each party
7 * (ward, existing guardians, and finally the candidate) Accepts, addressed to
8 * all the others, so every instance's copy of the tally converges. The
9 * candidate's Accept is the LAST one and carries the escalation handle in
10 * `result`: that return is the atomic commit (§3.1.3). Only then does the
11 * ward gain the guardian in shaer:guardians and the guardian gain the ward.
12 * A single Reject from any party voids the offer (§3.2).
13 *
14 * The state machine lives in offers.js (a faithful port of the Shaer test
15 * daemon); this module wires it onto Klonkt's C2S/S2S plumbing. AP helpers
16 * arrive once via wireHandshake(deps); nothing here imports ActivityPubService.
17 */
18import { isGuardianRelationship, GUARDIAN_RELATIONSHIP_COMPACT } from './context.js';
19import * as offers from './offers.js';
20import * as relations from './relations.js';
21
22let deps = null;
23export function wireHandshake(d) { deps = d; }
24
25const idOf = (v) => (typeof v === 'string' ? v : (v && typeof v === 'object' && typeof v.id === 'string' ? v.id : null));
26const arr = (v) => (Array.isArray(v) ? v : (v ? [v] : [])).filter((x) => typeof x === 'string');
27
28/** Parse a Relationship object into {ward, candidate} or null. */
29export function parseRelationship(rel) {
30 if (!rel || typeof rel !== 'object') return null;
31 const type = Array.isArray(rel.type) ? rel.type[0] : rel.type;
32 if (type !== 'Relationship') return null;
33 if (!isGuardianRelationship(String(rel.relationship || ''))) return null;
34 const ward = idOf(rel.subject);
35 const candidate = idOf(rel.object);
36 return ward && candidate ? { ward, candidate } : null;
37}
38
39/** The existing guardians of a ward: local list, or the remote actor's shaer:guardians. */
40async function existingGuardiansOf(wardUri) {
41 const local = deps.localSlug(wardUri);
42 if (local) return relations.listGuardians(local).map((r) => r.other_uri);
43 const doc = await deps.fetchActor(wardUri).catch(() => null);
44 const g = doc && doc['shaer:guardians'];
45 return Array.isArray(g) ? g.filter((x) => typeof x === 'string') : [];
46}
47
48function offerActivity(offerId, ward, candidate, recipients) {
49 return {
50 id: offerId, type: 'Offer', actor: candidate, to: recipients,
51 object: { type: 'Relationship', subject: ward, relationship: GUARDIAN_RELATIONSHIP_COMPACT, object: candidate },
52 };
53}
54
55/** Deliver `activity` to every uri in `recipients` (skipping the local self). */
56async function fanout(site, recipients, activity) {
57 let anyDelivered = false;
58 for (const uri of [...new Set(recipients)]) {
59 const r = await deps.deliverTo(site, uri, activity).catch(() => ({ delivered: false }));
60 if (r && r.delivered !== false) anyDelivered = true;
61 }
62 return anyDelivered;
63}
64
65/** Apply the local side of a commit: the ward writes its guardian, the
66 * candidate writes its ward. Each instance writes only what it hosts.
67 * other_handle is the human @handle for display (from the offer); the FEP
68 * escalation handle (candidate inbox) lives on the offer row, not here. */
69function applyCommitLocally(offer) {
70 const wardSlug = deps.localSlug(offer.ward_uri);
71 const candSlug = deps.localSlug(offer.candidate_uri);
72 if (wardSlug) relations.commitGuardianForWard(wardSlug, offer.candidate_uri, { handle: offer.candidate_handle, offerId: offer.offer_id });
73 if (candSlug) relations.commitWardForGuardian(candSlug, offer.ward_uri, { handle: offer.ward_handle, offerId: offer.offer_id });
74}
75
76/** Commit this local copy of the offer when the tally is complete (ward +
77 * candidate + ≥1 existing guardian, §3.1.2). The handle is the candidate's
78 * inbox (§6 minimum); the commit is order-independent, so whichever accept
79 * lands last triggers it on every copy. */
80function maybeCommit(slug, offerId) {
81 const offer = offers.getOffer(slug, offerId);
82 if (!offer || !offers.readyToCommit(offer)) return null;
83 const done = offers.commit(slug, offerId, `${offer.candidate_uri}/inbox`);
84 if (done) { applyCommitLocally(done); notify(slug, { kind: 'committed', ward: done.ward_uri, guardian: done.candidate_uri }); }
85 return done;
86}
87
88// ── C2S: a LOCAL party acts (PWA, Berichten, or the Shaer app outbox) ──────
89
90/**
91 * Handle a guardianship activity POSTed to the local outbox. Returns null when
92 * it is not ours, else {status, ...} for the route.
93 */
94export async function handleOutbox(site, activity) {
95 const type = Array.isArray(activity.type) ? activity.type[0] : activity.type;
96 if (!['Offer', 'Accept', 'Reject'].includes(type)) return null;
97 const me = deps.selfId(site.slug);
98
99 // ── Offer: the local site is the guardian-candidate. ───────────────────
100 if (type === 'Offer') {
101 const rel = parseRelationship(activity.object);
102 if (!rel) return null;
103 if (rel.candidate !== me) return { status: 403, error: 'only_the_candidate_offers' }; // fixed initiator (§3.1)
104 if (relations.listGuardians(site.slug).length) return { status: 403, error: 'a_ward_cannot_guard' }; // §1
105 const existing = await existingGuardiansOf(rel.ward);
106 const offerId = `${me}/offers/${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
107 offers.start(site.slug, {
108 offerId, ward: rel.ward, candidate: me, existingGuardians: existing,
109 wardHandle: deps.deriveHandle(rel.ward), candidateHandle: deps.deriveHandle(me),
110 });
111 // The Offer IS the candidate's agreement to serve: record it as the
112 // candidate's accept. So a FREE ward commits on its own single accept (no
113 // second guardian to co-approve yet); once it IS a ward, adding another
114 // guardian still needs an existing guardian to co-accept.
115 offers.recordAccept(site.slug, offerId, me);
116 // Addressed to the ward AND every existing guardian (§3.1.1).
117 const recipients = [rel.ward, ...existing];
118 const delivered = await fanout(site, recipients, offerActivity(offerId, rel.ward, me, recipients));
119 notify(site.slug, { kind: 'offer_sent', ward: rel.ward });
120 return { status: 202, id: offerId, url: offerId, delivered };
121 }
122
123 // ── Accept / Reject: the local site is a party answering an offer. ─────
124 const offerId = idOf(activity.object);
125 if (!offerId) return { status: 400, error: 'missing_offer' };
126 let offer = offers.getOffer(site.slug, offerId);
127 if (!offer) return { status: 404, error: 'no_such_offer' };
128 const others = offers.parties(offer).filter((p) => p !== me);
129
130 if (type === 'Reject') {
131 offers.recordReject(site.slug, offerId, me);
132 await fanout(site, others, { id: `${me}/answers/${Date.now().toString(36)}`, type: 'Reject', actor: me, to: others, object: offerId });
133 notify(site.slug, { kind: 'offer_rejected', offer: offerId });
134 return { status: 202, id: offerId, url: offerId };
135 }
136
137 // Accept: record my accept, broadcast it to the other parties, and commit
138 // this copy if the tally is now complete (order-independent, §3.1.3).
139 offers.recordAccept(site.slug, offerId, me);
140 await fanout(site, others, { id: `${me}/answers/${Date.now().toString(36)}`, type: 'Accept', actor: me, to: others, object: offerId });
141 const done = maybeCommit(site.slug, offerId);
142 return { status: 202, id: offerId, url: offerId, committed: !!done, readyToCommit: offers.readyToCommit(offers.getOffer(site.slug, offerId)) };
143}
144
145// ── S2S: a REMOTE party's activity arrives in a local inbox ────────────────
146
147/**
148 * Handle an inbound guardianship activity for the local site `site` (the inbox
149 * owner). Returns true when consumed.
150 */
151export async function handleInbox(site, activity) {
152 const type = Array.isArray(activity.type) ? activity.type[0] : activity.type;
153 if (!['Offer', 'Accept', 'Reject'].includes(type)) return false;
154 const me = deps.selfId(site.slug);
155 const actor = idOf(activity.actor);
156
157 if (type === 'Offer') {
158 const rel = parseRelationship(activity.object);
159 if (!rel) return false;
160 // I must be a party: the ward, or one of the existing guardians in `to`.
161 const recipients = arr(activity.to);
162 const existing = recipients.filter((u) => u !== rel.ward);
163 if (rel.ward !== me && !existing.includes(me)) return false;
164 offers.start(site.slug, {
165 offerId: idOf(activity), ward: rel.ward, candidate: rel.candidate, existingGuardians: existing,
166 wardHandle: deps.deriveHandle(rel.ward), candidateHandle: deps.deriveHandle(rel.candidate),
167 });
168 // The Offer carries the candidate's agreement (see the C2S side): record it
169 // so this copy's tally matches — a free ward then commits on its own accept.
170 offers.recordAccept(site.slug, idOf(activity), rel.candidate);
171 notify(site.slug, { kind: rel.ward === me ? 'offer_received' : 'offer_for_ward', ward: rel.ward, candidate: rel.candidate });
172 return true;
173 }
174
175 // Accept / Reject of an offer we (also) track.
176 const offerId = idOf(activity.object);
177 let offer = offers.getOffer(site.slug, offerId);
178 if (!offer) return false;
179 if (!offers.isParty(offer, actor)) return false;
180
181 if (type === 'Reject') {
182 offers.recordReject(site.slug, offerId, actor);
183 notify(site.slug, { kind: 'offer_rejected', offer: offerId });
184 return true;
185 }
186
187 offers.recordAccept(site.slug, offerId, actor);
188 maybeCommit(site.slug, offerId); // commits this copy once the tally is complete
189 return true;
190}
191
192function notify(slug, ev) {
193 try { if (deps && typeof deps.onEvent === 'function') deps.onEvent(slug, ev); } catch { /* best-effort */ }
194}
195
196export default { wireHandshake, handleOutbox, handleInbox, parseRelationship };
Note: See TracBrowser for help on using the repository browser.