| 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 | */
|
|---|
| 18 | import { isGuardianRelationship, GUARDIAN_RELATIONSHIP_COMPACT } from './context.js';
|
|---|
| 19 | import * as offers from './offers.js';
|
|---|
| 20 | import * as relations from './relations.js';
|
|---|
| 21 |
|
|---|
| 22 | let deps = null;
|
|---|
| 23 | export function wireHandshake(d) { deps = d; }
|
|---|
| 24 |
|
|---|
| 25 | const idOf = (v) => (typeof v === 'string' ? v : (v && typeof v === 'object' && typeof v.id === 'string' ? v.id : null));
|
|---|
| 26 | const arr = (v) => (Array.isArray(v) ? v : (v ? [v] : [])).filter((x) => typeof x === 'string');
|
|---|
| 27 |
|
|---|
| 28 | /** Parse a Relationship object into {ward, candidate} or null. */
|
|---|
| 29 | export 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. */
|
|---|
| 40 | async 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 |
|
|---|
| 48 | function 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). */
|
|---|
| 56 | async 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 | function applyCommitLocally(offer, handle) {
|
|---|
| 68 | const wardSlug = deps.localSlug(offer.ward_uri);
|
|---|
| 69 | const candSlug = deps.localSlug(offer.candidate_uri);
|
|---|
| 70 | if (wardSlug) relations.commitGuardianForWard(wardSlug, offer.candidate_uri, { handle, offerId: offer.offer_id });
|
|---|
| 71 | if (candSlug) relations.commitWardForGuardian(candSlug, offer.ward_uri, { handle, offerId: offer.offer_id });
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | /** Commit this local copy of the offer when the tally is complete (ward +
|
|---|
| 75 | * candidate + ≥1 existing guardian, §3.1.2). The handle is the candidate's
|
|---|
| 76 | * inbox (§6 minimum); the commit is order-independent, so whichever accept
|
|---|
| 77 | * lands last triggers it on every copy. */
|
|---|
| 78 | function maybeCommit(slug, offerId) {
|
|---|
| 79 | const offer = offers.getOffer(slug, offerId);
|
|---|
| 80 | if (!offer || !offers.readyToCommit(offer)) return null;
|
|---|
| 81 | const done = offers.commit(slug, offerId, `${offer.candidate_uri}/inbox`);
|
|---|
| 82 | if (done) { applyCommitLocally(done, done.handle); notify(slug, { kind: 'committed', ward: done.ward_uri, guardian: done.candidate_uri }); }
|
|---|
| 83 | return done;
|
|---|
| 84 | }
|
|---|
| 85 |
|
|---|
| 86 | // ── C2S: a LOCAL party acts (PWA, Berichten, or the Shaer app outbox) ──────
|
|---|
| 87 |
|
|---|
| 88 | /**
|
|---|
| 89 | * Handle a guardianship activity POSTed to the local outbox. Returns null when
|
|---|
| 90 | * it is not ours, else {status, ...} for the route.
|
|---|
| 91 | */
|
|---|
| 92 | export async function handleOutbox(site, activity) {
|
|---|
| 93 | const type = Array.isArray(activity.type) ? activity.type[0] : activity.type;
|
|---|
| 94 | if (!['Offer', 'Accept', 'Reject'].includes(type)) return null;
|
|---|
| 95 | const me = deps.selfId(site.slug);
|
|---|
| 96 |
|
|---|
| 97 | // ── Offer: the local site is the guardian-candidate. ───────────────────
|
|---|
| 98 | if (type === 'Offer') {
|
|---|
| 99 | const rel = parseRelationship(activity.object);
|
|---|
| 100 | if (!rel) return null;
|
|---|
| 101 | if (rel.candidate !== me) return { status: 403, error: 'only_the_candidate_offers' }; // fixed initiator (§3.1)
|
|---|
| 102 | if (relations.listGuardians(site.slug).length) return { status: 403, error: 'a_ward_cannot_guard' }; // §1
|
|---|
| 103 | const existing = await existingGuardiansOf(rel.ward);
|
|---|
| 104 | const offerId = `${me}/offers/${Date.now().toString(36)}${Math.floor(Math.random() * 1e4).toString(36)}`;
|
|---|
| 105 | offers.start(site.slug, {
|
|---|
| 106 | offerId, ward: rel.ward, candidate: me, existingGuardians: existing,
|
|---|
| 107 | wardHandle: deps.deriveHandle(rel.ward), candidateHandle: deps.deriveHandle(me),
|
|---|
| 108 | });
|
|---|
| 109 | // The Offer IS the candidate's agreement to serve: record it as the
|
|---|
| 110 | // candidate's accept. So a FREE ward commits on its own single accept (no
|
|---|
| 111 | // second guardian to co-approve yet); once it IS a ward, adding another
|
|---|
| 112 | // guardian still needs an existing guardian to co-accept.
|
|---|
| 113 | offers.recordAccept(site.slug, offerId, me);
|
|---|
| 114 | // Addressed to the ward AND every existing guardian (§3.1.1).
|
|---|
| 115 | const recipients = [rel.ward, ...existing];
|
|---|
| 116 | const delivered = await fanout(site, recipients, offerActivity(offerId, rel.ward, me, recipients));
|
|---|
| 117 | notify(site.slug, { kind: 'offer_sent', ward: rel.ward });
|
|---|
| 118 | return { status: 202, id: offerId, url: offerId, delivered };
|
|---|
| 119 | }
|
|---|
| 120 |
|
|---|
| 121 | // ── Accept / Reject: the local site is a party answering an offer. ─────
|
|---|
| 122 | const offerId = idOf(activity.object);
|
|---|
| 123 | if (!offerId) return { status: 400, error: 'missing_offer' };
|
|---|
| 124 | let offer = offers.getOffer(site.slug, offerId);
|
|---|
| 125 | if (!offer) return { status: 404, error: 'no_such_offer' };
|
|---|
| 126 | const others = offers.parties(offer).filter((p) => p !== me);
|
|---|
| 127 |
|
|---|
| 128 | if (type === 'Reject') {
|
|---|
| 129 | offers.recordReject(site.slug, offerId, me);
|
|---|
| 130 | await fanout(site, others, { id: `${me}/answers/${Date.now().toString(36)}`, type: 'Reject', actor: me, to: others, object: offerId });
|
|---|
| 131 | notify(site.slug, { kind: 'offer_rejected', offer: offerId });
|
|---|
| 132 | return { status: 202, id: offerId, url: offerId };
|
|---|
| 133 | }
|
|---|
| 134 |
|
|---|
| 135 | // Accept: record my accept, broadcast it to the other parties, and commit
|
|---|
| 136 | // this copy if the tally is now complete (order-independent, §3.1.3).
|
|---|
| 137 | offers.recordAccept(site.slug, offerId, me);
|
|---|
| 138 | await fanout(site, others, { id: `${me}/answers/${Date.now().toString(36)}`, type: 'Accept', actor: me, to: others, object: offerId });
|
|---|
| 139 | const done = maybeCommit(site.slug, offerId);
|
|---|
| 140 | return { status: 202, id: offerId, url: offerId, committed: !!done, readyToCommit: offers.readyToCommit(offers.getOffer(site.slug, offerId)) };
|
|---|
| 141 | }
|
|---|
| 142 |
|
|---|
| 143 | // ── S2S: a REMOTE party's activity arrives in a local inbox ────────────────
|
|---|
| 144 |
|
|---|
| 145 | /**
|
|---|
| 146 | * Handle an inbound guardianship activity for the local site `site` (the inbox
|
|---|
| 147 | * owner). Returns true when consumed.
|
|---|
| 148 | */
|
|---|
| 149 | export async function handleInbox(site, activity) {
|
|---|
| 150 | const type = Array.isArray(activity.type) ? activity.type[0] : activity.type;
|
|---|
| 151 | if (!['Offer', 'Accept', 'Reject'].includes(type)) return false;
|
|---|
| 152 | const me = deps.selfId(site.slug);
|
|---|
| 153 | const actor = idOf(activity.actor);
|
|---|
| 154 |
|
|---|
| 155 | if (type === 'Offer') {
|
|---|
| 156 | const rel = parseRelationship(activity.object);
|
|---|
| 157 | if (!rel) return false;
|
|---|
| 158 | // I must be a party: the ward, or one of the existing guardians in `to`.
|
|---|
| 159 | const recipients = arr(activity.to);
|
|---|
| 160 | const existing = recipients.filter((u) => u !== rel.ward);
|
|---|
| 161 | if (rel.ward !== me && !existing.includes(me)) return false;
|
|---|
| 162 | offers.start(site.slug, {
|
|---|
| 163 | offerId: idOf(activity), ward: rel.ward, candidate: rel.candidate, existingGuardians: existing,
|
|---|
| 164 | wardHandle: deps.deriveHandle(rel.ward), candidateHandle: deps.deriveHandle(rel.candidate),
|
|---|
| 165 | });
|
|---|
| 166 | // The Offer carries the candidate's agreement (see the C2S side): record it
|
|---|
| 167 | // so this copy's tally matches — a free ward then commits on its own accept.
|
|---|
| 168 | offers.recordAccept(site.slug, idOf(activity), rel.candidate);
|
|---|
| 169 | notify(site.slug, { kind: rel.ward === me ? 'offer_received' : 'offer_for_ward', ward: rel.ward, candidate: rel.candidate });
|
|---|
| 170 | return true;
|
|---|
| 171 | }
|
|---|
| 172 |
|
|---|
| 173 | // Accept / Reject of an offer we (also) track.
|
|---|
| 174 | const offerId = idOf(activity.object);
|
|---|
| 175 | let offer = offers.getOffer(site.slug, offerId);
|
|---|
| 176 | if (!offer) return false;
|
|---|
| 177 | if (!offers.isParty(offer, actor)) return false;
|
|---|
| 178 |
|
|---|
| 179 | if (type === 'Reject') {
|
|---|
| 180 | offers.recordReject(site.slug, offerId, actor);
|
|---|
| 181 | notify(site.slug, { kind: 'offer_rejected', offer: offerId });
|
|---|
| 182 | return true;
|
|---|
| 183 | }
|
|---|
| 184 |
|
|---|
| 185 | offers.recordAccept(site.slug, offerId, actor);
|
|---|
| 186 | maybeCommit(site.slug, offerId); // commits this copy once the tally is complete
|
|---|
| 187 | return true;
|
|---|
| 188 | }
|
|---|
| 189 |
|
|---|
| 190 | function notify(slug, ev) {
|
|---|
| 191 | try { if (deps && typeof deps.onEvent === 'function') deps.onEvent(slug, ev); } catch { /* best-effort */ }
|
|---|
| 192 | }
|
|---|
| 193 |
|
|---|
| 194 | export default { wireHandshake, handleOutbox, handleInbox, parseRelationship };
|
|---|