From 908f7ea97389c3dc0a18b20024bb9fd7c640863b Mon Sep 17 00:00:00 2001 From: Sylvain Duchesne Date: Fri, 30 Oct 2026 17:06:38 +0100 Subject: [PATCH] Keep sign-ups unlinkable on ActivityPods, and land the pending coherence-pass work Participation privacy (decision_2026-10-29_participation-privacy-mechanism): a sign-up is a private Join naming the meeting point, addressed to nobody, handled by the backend on emission. Attendee lists hold member URNs hashed from (WebID, event, a secret kept in the participant's profile), so counts stay public and only contacts recognise anyone; the creator has no read right and is notified anonymously. Each person's participations collection, created by the backend at the first sign-up, is readable by their /contacts WAC group only, never world-readable. The member URN is sticky per (meeting point, participant) and every collection write is verified by reading back, so a refused write leaves the act unrecorded and retryable. The EventRef mechanism and its browser-side provisioning are gone. The backend now runs with WebACL on, as the reference apps do, on its own secure datasets festipod / settings-festipod instead of the pod provider's settings dataset; pod-notifications needs it. The compose header and the deployment leaf say how to reset a stack whose datasets predate this. The rights matrix covers the new mechanism live (148 hard lines), including a forged contact Accept between throwaway accounts: the stranger enters the contacts list (platform defect, reported upstream) but is refused the profile and the participations. Tests may attack as long as they never break the dev environment (rule_tests-never-break-the-dev-environment). Also lands the coherence-pass work that was still uncommitted: contacts as the Pod's social graph and invite links, image upload to the Pod, the meeting-point form, profile completion gate, and the doctrine for them. Superseded briefs and decisions are deleted rather than annotated. --- .env.example | 4 +- .../knowledge_profile-completion-gate.md | 15 + .../knowledge_screen-pattern.md | 1 + ...e_tests-never-break-the-dev-environment.md | 12 + .../activitypods-providers/usage_festipod.md | 8 +- .../brief_2026-07-20_attendance-set-model.md | 97 - ...6-10-03_structure-for-two-rights-models.md | 100 - ...f_2026-10-09_activitypods-first-backend.md | 13 +- .../caveat_t06-unverified-on-a-real-pod.md | 16 + .../cookbook_local-activitypods-platform.md | 14 +- ...10-21_contacts-are-the-pod-social-graph.md | 26 + ...26-10-21_images-are-uploaded-to-the-pod.md | 18 + .../data-layer/knowledge_context-internals.md | 7 +- .../concepts/data-layer/knowledge_entities.md | 8 +- .../concepts/functional-domain/_overview.md | 6 +- ..._participation-listing-is-contacts-only.md | 32 + ...0-21_meeting-point-form-title-and-place.md | 12 + ...ection-sharing-is-the-invite-capability.md | 20 + ...6-10-29_participation-privacy-mechanism.md | 59 + .../knowledge_data-scopes-and-discovery.md | 8 +- .../tech-stack/knowledge_deployment.md | 3 +- .../handoff/refine-provider-abstraction.md | 17 +- .project/rules/INDEX.md | 7 + .../festipod-only-reference-app-patterns.md | 15 + .project/to-discuss.md | 2 + AGENTS.md | 4 + backend/.env.example | 4 +- backend/moleculer.config.js | 8 +- backend/services/app.service.js | 60 +- backend/services/attendance-ledger.js | 86 +- backend/services/attendees.service.js | 19 +- backend/services/catalog-store.js | 2 +- backend/services/catalog.service.js | 20 +- backend/services/catalog.service.test.js | 50 + backend/services/collection-attach.js | 4 +- backend/services/collection-handlers.test.js | 42 +- backend/services/collection-items.js | 55 + backend/services/collection-items.test.js | 64 + backend/services/core/core.service.js | 18 +- backend/services/emitted-activity.js | 13 +- backend/services/emitted-activity.test.js | 34 + backend/services/keyed-serializer.js | 6 +- backend/services/member-urn.js | 53 + backend/services/member-urn.test.js | 50 + backend/services/participation-world.js | 294 +++ backend/services/participations.service.js | 191 ++ .../services/participations.service.test.js | 155 ++ backend/services/public-read-acl.js | 89 +- backend/services/public-read.service.js | 46 +- backend/services/public-surface.js | 20 +- backend/services/registration.service.js | 373 ++- backend/services/registration.service.test.js | 967 ++++++-- docker-compose.coolify.yml | 13 +- docs/cucumber-integration.md | 2 +- reports/cucumber-report.html | 2 +- reports/cucumber-report.json | 1996 ++++++++--------- scripts/diag-invite.ts | 160 ++ scripts/e2e-login-flow.ts | 10 + scripts/e2e-revocation.ts | 7 + scripts/e2e-rights-matrix-support.ts | 10 +- scripts/e2e-rights-matrix.ts | 1184 ++++++++-- src/app/App.tsx | 48 +- src/index.css | 26 +- src/index.ts | 5 +- src/modules/auth/screens/WelcomeScreen.tsx | 4 - .../event/features/e2e-activitypods.feature | 10 +- .../event/screens/CreateEventScreen.tsx | 73 +- .../event/screens/EventDetailScreen.tsx | 20 +- src/modules/event/screens/EventsScreen.tsx | 43 +- src/modules/event/screens/InviteScreen.tsx | 40 +- .../event/screens/MeetingPointsScreen.tsx | 77 +- .../event/screens/ParticipantsListScreen.tsx | 37 +- .../event/screens/UpdateEventScreen.tsx | 12 +- .../event/steps/e2e/activitypods.steps.ts | 62 +- src/modules/event/useDiscoverEvents.ts | 21 +- src/modules/home/screens/HomeScreen.tsx | 79 +- .../features/us-16-point-rencontre.feature | 4 +- .../features/us-10-profil-participant.feature | 6 +- .../user/features/us-22-parrainer.feature | 18 +- .../us-23-connexion-utilisateurs.feature | 8 +- .../features/us-9-visualiser-photo.feature | 3 +- src/modules/user/screens/ConnectScreen.tsx | 205 +- .../user/screens/FriendsListScreen.tsx | 27 +- src/modules/user/screens/ProfileScreen.tsx | 40 +- .../user/screens/ShareProfileScreen.tsx | 135 +- .../user/screens/UpdateProfileScreen.tsx | 43 +- .../user/screens/UserProfileScreen.tsx | 156 +- src/modules/user/steps/ui/user.steps.ts | 38 +- src/shared/components/sketchy/Avatar.tsx | 55 +- src/shared/components/sketchy/Badge.tsx | 21 - src/shared/components/sketchy/EventCover.tsx | 23 +- .../components/sketchy/EventMeetingPoints.tsx | 27 +- src/shared/components/sketchy/ImagePicker.tsx | 51 + src/shared/components/sketchy/Placeholder.tsx | 26 - src/shared/components/sketchy/index.ts | 8 +- src/shared/context/FestipodDataContext.tsx | 10 +- src/shared/context/festipodDataBase.ts | 39 +- src/shared/context/ngData.tsx | 21 +- src/shared/context/refineData.test.tsx | 685 ++++-- src/shared/context/refineData.tsx | 877 ++++++-- src/shared/context/refineDerive.test.ts | 90 +- src/shared/context/refineDerive.ts | 129 +- src/shared/data/actor.test.ts | 15 +- src/shared/data/actor.ts | 4 + src/shared/data/attendees.ts | 8 +- src/shared/data/catalog.test.ts | 27 + src/shared/data/catalog.ts | 32 +- src/shared/data/contacts.test.ts | 101 + src/shared/data/contacts.ts | 157 ++ src/shared/data/features.ts | 81 +- src/shared/data/index.ts | 379 ---- src/shared/data/outbox.test.ts | 61 +- src/shared/data/outbox.ts | 45 +- src/shared/data/participationPrivacy.test.ts | 89 + src/shared/data/participationPrivacy.ts | 98 + src/shared/data/shapeAdapters.ts | 3 + src/shared/data/stepDefinitions.ts | 100 +- src/shared/data/types.ts | 9 +- src/shared/hooks/useInviteLink.ts | 59 + src/shared/hooks/useUploadImage.ts | 54 + .../refine/providers/activitypods.test.ts | 49 +- src/shared/refine/providers/activitypods.ts | 43 +- .../shapes/orm/festipodShapes.schema.ts | 33 + .../shapes/orm/festipodShapes.typings.ts | 18 + src/shared/shapes/shex/festipodShapes.shex | 6 + src/shared/steps/ui/navigation.steps.ts | 1 + src/shared/support/activitypodsStack.ts | 110 +- src/shared/support/world.ts | 7 +- .../test-harness/screenSanitizers.test.tsx | 10 +- src/shared/utils/cssUrl.test.ts | 18 + src/shared/utils/cssUrl.ts | 10 + src/shared/utils/grantPublicRead.ts | 48 + src/shared/utils/inviteLink.test.ts | 102 + src/shared/utils/inviteLink.ts | 130 ++ src/shared/utils/nodeinfo.test.ts | 74 + src/shared/utils/nodeinfo.ts | 95 + src/shared/utils/search.test.ts | 10 + src/shared/utils/search.ts | 7 + 138 files changed, 8347 insertions(+), 3679 deletions(-) create mode 100644 .project/concepts/app-architecture/knowledge_profile-completion-gate.md create mode 100644 .project/concepts/bdd-testing/rule_tests-never-break-the-dev-environment.md delete mode 100644 .project/concepts/data-layer/brief_2026-07-20_attendance-set-model.md delete mode 100644 .project/concepts/data-layer/brief_2026-10-03_structure-for-two-rights-models.md create mode 100644 .project/concepts/data-layer/caveat_t06-unverified-on-a-real-pod.md create mode 100644 .project/concepts/data-layer/decision_2026-10-21_contacts-are-the-pod-social-graph.md create mode 100644 .project/concepts/data-layer/decision_2026-10-21_images-are-uploaded-to-the-pod.md create mode 100644 .project/concepts/functional-domain/behavior_participation-listing-is-contacts-only.md create mode 100644 .project/concepts/functional-domain/decision_2026-10-21_meeting-point-form-title-and-place.md create mode 100644 .project/concepts/functional-domain/decision_2026-10-22_connection-sharing-is-the-invite-capability.md create mode 100644 .project/concepts/functional-domain/decision_2026-10-29_participation-privacy-mechanism.md create mode 100644 .project/rules/INDEX.md create mode 100644 .project/rules/activitypods/festipod-only-reference-app-patterns.md create mode 100644 backend/services/collection-items.js create mode 100644 backend/services/collection-items.test.js create mode 100644 backend/services/member-urn.js create mode 100644 backend/services/member-urn.test.js create mode 100644 backend/services/participation-world.js create mode 100644 backend/services/participations.service.js create mode 100644 backend/services/participations.service.test.js create mode 100644 scripts/diag-invite.ts create mode 100644 src/shared/components/sketchy/ImagePicker.tsx delete mode 100644 src/shared/components/sketchy/Placeholder.tsx create mode 100644 src/shared/data/contacts.test.ts create mode 100644 src/shared/data/contacts.ts delete mode 100644 src/shared/data/index.ts create mode 100644 src/shared/data/participationPrivacy.test.ts create mode 100644 src/shared/data/participationPrivacy.ts create mode 100644 src/shared/hooks/useInviteLink.ts create mode 100644 src/shared/hooks/useUploadImage.ts create mode 100644 src/shared/utils/cssUrl.test.ts create mode 100644 src/shared/utils/cssUrl.ts create mode 100644 src/shared/utils/grantPublicRead.ts create mode 100644 src/shared/utils/inviteLink.test.ts create mode 100644 src/shared/utils/inviteLink.ts create mode 100644 src/shared/utils/nodeinfo.test.ts create mode 100644 src/shared/utils/nodeinfo.ts create mode 100644 src/shared/utils/search.test.ts create mode 100644 src/shared/utils/search.ts diff --git a/.env.example b/.env.example index 5594d79..03c77fc 100644 --- a/.env.example +++ b/.env.example @@ -54,7 +54,7 @@ SEMAPPS_FRONT_URL=http://localhost:4000 SEMAPPS_SPARQL_ENDPOINT=http://localhost:3030/ # Dataset Jena/Fuseki principal utilisé par le backend. -SEMAPPS_MAIN_DATASET=settings +SEMAPPS_MAIN_DATASET=festipod # Identifiants Jena/Fuseki. SEMAPPS_JENA_USER=admin @@ -65,7 +65,7 @@ SEMAPPS_REDIS_CACHE_URL=redis://localhost:6390/3 SEMAPPS_QUEUE_SERVICE_URL=redis://localhost:6390/4 # Dataset utilisé par le service auth.account. -SEMAPPS_AUTH_ACCOUNTS_DATASET_NAME=settings +SEMAPPS_AUTH_ACCOUNTS_DATASET_NAME=settings-festipod # Dépôt de shapes/shapetrees utilisé pour déclarer les besoins d'accès. SEMAPPS_SHAPE_REPOSITORY_URL=https://shapes.activitypods.org/ diff --git a/.project/concepts/app-architecture/knowledge_profile-completion-gate.md b/.project/concepts/app-architecture/knowledge_profile-completion-gate.md new file mode 100644 index 0000000..3e9d85d --- /dev/null +++ b/.project/concepts/app-architecture/knowledge_profile-completion-gate.md @@ -0,0 +1,15 @@ +--- +type: knowledge +summary: Signed in on a Pod, the app is held behind ProfileCompletionGate — a profile with an empty name shows the profile form in onboarding mode, a Pod with no readable profile shows an explanatory message; the only completion flag is the presence of a name +--- + +# Profile completion gate + +`FestipodDataContextValue.profileStatus` (`'loading' | 'ready' | 'missing'`, absent on providers where it does not apply) is computed by the refine provider from the actor document and the profile read. `ProfileCompletionGate` (in the app shell, inside the data provider) uses it: + +- `loading` → nothing is rendered yet; +- `missing` → a blocking, honest message: the Pod links no readable profile and Festipod cannot create or link one (outside the pinned contract); +- `ready` with an empty `currentUser.name` → `UpdateProfileScreen` in `onboarding` mode (explanation, no way out until saved, no pre-filled fiction); +- otherwise the routed screen. + +The flag is the name itself — nothing is stored locally, so the form disappears for good once a name is saved and the profile re-read. diff --git a/.project/concepts/app-architecture/knowledge_screen-pattern.md b/.project/concepts/app-architecture/knowledge_screen-pattern.md index da28985..e8e5d24 100644 --- a/.project/concepts/app-architecture/knowledge_screen-pattern.md +++ b/.project/concepts/app-architecture/knowledge_screen-pattern.md @@ -39,6 +39,7 @@ export function MyScreen() { // named function, NEVER any props - **Zero props, no exception left**: every registered screen receives nothing; everything comes from context/hooks (`useFestipodData`, `useNavigate`, `useParams`). `WelcomeScreen` does not use `useFestipodData` (intro) — but still takes no props. (`LoginScreen`/`ConnexionScreen`/`AccessGateScreen` no longer exist — Festipod renders no access screen of its own; see [[knowledge_screens]] and [[knowledge_app-shell]].) - **Identity: the current user may not be there yet.** `currentUserId` is the NURI of the profile document this session **owns**, so it is **empty until that document resolves** — see [[caveat_identity-ids-in-screens]] before keying anything on it. - **The confirmation FOLLOWS the write.** Mutations reject rather than returning quietly, so a screen must `await` (or `.then`) before announcing anything: success toast and navigation on resolve, an error toast on reject, and the user kept on their edits. A toast fired beside the call announces a write that may never have happened — the pattern that had to be corrected on the event and profile edit screens. +- **Reading what the session has not read yet is asked for from an effect.** A screen about one event calls `openEvent(eventId)`, a screen about someone else's events calls `openUserEvents(userId)` (`UserProfileScreen`); both are state changes, so they run in a `useEffect` keyed on the id, never during render, and the getters (`getEvent`, `getUserEvents`) answer with what has landed. They are idempotent and are no-ops on providers whose read set is already complete (local fixtures); `openUserEvents` is also a no-op for oneself and for anyone who is not a contact. Verified in `festipodDataBase.ts` (the context contract), `refineData.tsx` (the ActivityPods implementation). - **A write affordance is decided by ownership, in three states.** Both the control that *offers* the write and the screen that *performs* it consult the same answer (`data-layer` → [[knowledge_write-rights-are-ownership]]). `unknown` is never folded into either side: showing the form lets a non-owner edit on a guess, and bouncing them out tells a genuine owner their thing is not theirs. Render it as its own pending state. - **Layout**: full-height flex column; `Header` at the top, content at `flex:1; overflow:auto`, `BottomNav` at the bottom **only for hub screens** (Home, Events, Profile, Friends). Flow screens (creation, editing, detail) have no `BottomNav`. - **Feedback**: `showToast(message, 'success'|'info'|'error')` (`ToastContainer` mechanism exported by `sketchy/`). diff --git a/.project/concepts/bdd-testing/rule_tests-never-break-the-dev-environment.md b/.project/concepts/bdd-testing/rule_tests-never-break-the-dev-environment.md new file mode 100644 index 0000000..d3b6691 --- /dev/null +++ b/.project/concepts/bdd-testing/rule_tests-never-break-the-dev-environment.md @@ -0,0 +1,12 @@ +--- +type: rule +summary: Tests are free in what they exercise — attacks, forged or spoofed activities included — with one restriction: nothing a test does may break the dev environment (pod provider and its datasets, the backend's datasets, Redis, persistent test accounts) +--- + +# Tests never break the dev environment + +**Rule:** (user directive 2026-10-30) A test may exercise anything, attacks included — a forged `Accept`, a spoofed or malformed activity, a crafted write — as long as it cannot break the dev environment. Concretely: an attack runs only between the throwaway accounts the run creates, and the run still deletes them; a test never writes another user's data, never alters a persistent account (the smoke's `alice`) beyond what the app itself does, never deletes, recreates or flushes a Fuseki dataset or Redis, and leaves the stack as it found it. + +**Why:** the local stack is the shared state every suite and every manual session rely on; a broken pod provider, dataset or cache costs a reset (slow sign-ups, lost app registrations). An earlier reading — "no forged activity is ever sent to the stack" — was stricter than intended and left real attack paths unproven: the forged-contact line of the rights matrix is the only live proof that the participations audience resists a forged contact ([[decision_2026-10-29_participation-privacy-mechanism]]). + +**How to apply:** before adding an attack line, check its blast radius: it touches only accounts created in this run, and its cleanup still runs when it fails. A MANUAL-CHECK line that is manual only because it would forge an activity may be promoted to a live line under the same condition. Read through the user's rules-allow-judgment: what is protected is the environment's integrity, not a list of forbidden activity types. diff --git a/.project/concepts/data-layer/activitypods-providers/usage_festipod.md b/.project/concepts/data-layer/activitypods-providers/usage_festipod.md index 172c497..44db65f 100644 --- a/.project/concepts/data-layer/activitypods-providers/usage_festipod.md +++ b/.project/concepts/data-layer/activitypods-providers/usage_festipod.md @@ -8,7 +8,7 @@ against: 66616484b96fb2227cd8cdf02321aacfb4811365 Festipod is a mobile-first web application: users create **meeting points** grafted onto public events, and sign up to them. Its entire persistence goes through Refine, behind a **backend seam** that exists so the app can support several Refine backends and let the user switch between them at runtime. This package is one of the two backends targeted; the other is a Refine provider over NextGraph plus its polyfill. The seam's own contract — what a backend must answer before it can be added — lives in code, in `src/shared/refine/providers/types.ts`. -The seam is wired since 2026-10-09 (T04.e): this backend is the registered default, and Festipod reads and writes through it — `useList` over the shared `as:Event` container (split into events and meeting points by the bindings' `isInstance`), creates and updates through the data provider, and the embedded `apods:attendees` collection through the participation binding's `membersOf`. Joins/leaves are the one write beside Refine (the package implements no `custom`): an `as:Join`/`as:Leave` posted to the user's own outbox by `src/shared/data/outbox.ts`, per the platform flow recorded in the 2026-10-09 brief. What the list below declares is therefore measured where a runtime check exists and declared elsewhere; `against:` names the observation's commit, and the package publishes no engagement, so there is nothing to pull and nothing that can drift — what is recorded here is read against our own reconstruction, and re-read when it is re-stamped. +The seam is wired since 2026-10-09 (T04.e): this backend is the registered default, and Festipod reads and writes through it — `useList` over the shared `as:Event` container (split into events and meeting points by the bindings' `isInstance`), creates and updates through the data provider, and the embedded `apods:attendees` collection through the participation binding's `membersOf`. Joins/leaves are the one write beside Refine (the package implements no `custom`): an `as:Join`/`as:Leave` posted to the user's own outbox by `src/shared/data/outbox.ts`, naming the meeting point with no addressee, so that only its author and the app can read it. What the list below declares is therefore measured where a runtime check exists and declared elsewhere; `against:` names the observation's commit, and the package publishes no engagement, so there is nothing to pull and nothing that can drift — what is recorded here is read against our own reconstruction, and re-read when it is re-stamped. ## Consumed surface @@ -32,6 +32,8 @@ Four resources, one per persisted entity: **events**, **meeting points**, **part Through Refine's hooks only, never the provider directly: `useList` → `getList`, `useCreate` → `create`, `useUpdate` → `update`, `useDelete` → `deleteOne`. `getOne` is reached by Refine's cache plumbing rather than an explicit call. The app mounts Refine with `liveMode: 'auto'` and `mutationMode: 'optimistic'`. +`update` of the own profile is also how the participation secret is stored: before the first Join the app re-reads its profile explicitly (`getOne`, refetched, never trusting a cached copy), and when no secret is there writes `http://festipod.org/participationSecret` through `update` with the **full IRI** as the key, then reads the stored value back from the answer. The pod stores and returns such a predicate under the full IRI (verified live 2026-10-29 with the app's token), whatever the `fp` prefix registration. + `create` of an event or a meeting point carries `to: as:Public` among its variables: Festipod's declaration that the record is public, on which the Festipod backend's public read and discovery listing depend. See constraint 10. ### Record handling @@ -51,7 +53,7 @@ What must keep holding for this backend to serve the app. 1. **Festipod's own vocabulary, not ActivityStreams.** The four entities are Festipod domain types defined by SHEX shapes this repo holds; none is an ActivityStreams type. A caller-supplied `jsonContext` and caller-supplied `types` are what make that possible, and both must stay caller-supplied. 2. **The identifier a record is addressed by must stay the identifier other records reference.** The seam carries the two separately because they differ on the other targeted backend; here they coincide, and the app relies on that. Splitting them later would break every cross-entity reference silently. 3. **A partial update must stay partial.** The app sends only changed fields. A move to replacing the resource would drop every field omitted, with no error. -4. **Every participation must be readable by every user.** The participant count is the number of participations of an event, counted with no filtering. What is confidential is the **link between a participation and a person** — only a connection can read the profile a participation points at and recognise who it is — never the participation record itself. The provider alone cannot satisfy it (need 1). +4. **Every participation must be readable by every user.** The participant count is the number of participations of an event, counted with no filtering. What is confidential is the **link between a participation and a person**: an attendee list holds opaque member URNs, and only a connection, who reads the secret on the person's profile, can recognise who a URN is — never the list itself. The provider alone cannot satisfy it (need 1). 5. **The count is never a stored, incremented field.** Reading a counter, adding one and writing it back derives each write from a read of the previous one and races itself through any data provider. This is measured, not theoretical, and it is why the app derives the count from the participation list at read time. 6. **Changes must be pushed, not polled.** Neither the app nor its BDD suites has a polling loop, and adding one is ruled out by project doctrine. `liveMode: 'auto'` is mounted on that basis. 7. **No process-global state that outlives a remount.** Two backends coexist in one page and the user switches between them at runtime; switching remounts Refine to discard the cache of the backend being left. Building this backend's providers must have no side effect that accumulates across switches — see friction 1, which is where this currently bites. @@ -65,7 +67,7 @@ What must keep holding for this backend to serve the app. 2. **`getList` fetches the whole container on every call.** Filtering, sorting and pagination run in memory afterwards, so the cost of listing an event's participations grows with the user's total number of participations rather than with the event. No workaround; it is why a filter on a `getList` buys nothing beyond convenience. 3. **A list subscription reports membership only.** A container channel delivers `Add`/`Remove`, not a member's own fields changing, so a list of events does not refresh when an event's title, place or time is edited. Watching each record instead would open one channel per row. The event list is exactly the screen where this is visible. 4. **`types` takes precedence over `shapeTreeUri`, the opposite of what the configuration type documents.** The declared behaviour is that `types` is "only used as a fallback when `shapeTreeUri` is not set"; a resource setting both is in fact resolved from `types`. Establishing which one actually wins cost a read of the resolution path. Configuring exactly one avoids it, but the documentation should say which wins. -5. **The member shape of an `apods:attendees` collection is not pinned anywhere Festipod may read at work time.** The reconstruction documents the container discovery, not what a membership record is: a bare actor URI, or an object carrying event/participant/status. The project reconnaissance records only that a join "adds the actor to the collection" and that members come back "as full objects for a reader who is allowed, and as URIs otherwise". The ActivityPods backend's participation binding is designed against that: a member maps to `{ id, userId, isConfirmed: true }` (membership IS the attendance), with `eventId` supplied by the reader — the event the collection was read from — because a member carries no event link. The first runtime read against the local platform (T04.g) must confirm or correct this mapping. +5. **The member shape of an `apods:attendees` collection is not pinned anywhere Festipod may read at work time.** The reconstruction documents the container discovery, not what a membership record is. Read against a local platform (verified 2026-10-12), the collection is its own resource, linked from the meeting point by URI and never embedded; its items are, in Festipod, opaque member URNs recorded by the Festipod backend, and the participation binding maps each to `{ id, userId, isConfirmed: true }` (membership IS the attendance), `eventId` being supplied by the reader — the meeting point the collection was read from. The `userId` of such a record is a member URN, not a person: a person is recognised only by hashing (see constraint 4). 6. **The live provider's `subscribe` rejects with an uncaught `Forbidden` when the Pod refuses its push channel.** On this platform the channel creation (`POST /.notifications/WebSocketChannel2023`) answers 403 for the app's session, and each refusal surfaces as one unhandled rejection in the page — raised inside the provider, where the app cannot catch it; Festipod's end-to-end checks recognise it by its throw site. Reporting the refusal through the subscription's error path would let the app handle it. diff --git a/.project/concepts/data-layer/brief_2026-07-20_attendance-set-model.md b/.project/concepts/data-layer/brief_2026-07-20_attendance-set-model.md deleted file mode 100644 index ac47478..0000000 --- a/.project/concepts/data-layer/brief_2026-07-20_attendance-set-model.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -type: brief -summary: Target model for sign-ups — a Participation READABLE by everyone (event ref + `active` boolean + a key-less reference to the participant's profile), deposited into the event's inbox; the creator processes the inbox, dedups WITHOUT knowing who, files the reference into a Set on the event and PURGES the cancelled ones; count = Set.size with no filtering (accepted upper bound); only connections can read the profile and recognize the person. Supersedes the mutated counter + plaintext userId. ---- - -# Brief (2026-07-20, revised 2026-07-27) — Set-based sign-ups - -## The model - -Laid down and refined by the PO on 2026-07-27. Everything is **keys and URLs** — no roles, no membership, no allow-list. - -1. The participant creates a **Participation** object, **readable by everyone**, holding: the **reference to the event**, an **`active` boolean**, and a **reference to their *protected* profile that carries no key**. **Nothing else** — no description for now. -2. They deposit the **Participation's reference** into the **event's inbox**. -3. The **creator** processes their inbox **automatically**, as soon as they are online. -4. They **dedup** (see below) — **without knowing who the participant is**: they hold a name for the profile, not the key to read it. -5. They file a **reference** to the Participation into a **Set** carried by the event's document. -6. Anyone reads **`Set.size`** → the number of participants. -7. Someone **connected** to the participant holds their profile's cap, reads it, and **recognizes** the person. - -**Withdrawal**: the participant sets `active` to false **on their own object**. The creator sees it when reading, and **purges** — removing the reference from the Set. - -Three properties follow: **anonymous attendance by default** (even the creator cannot see who); **nobody modifies anyone else's sign-up** (only the participant holds the write key to their own object); **no plaintext `userId`** ever travels. - -### The principle that holds it all together: the truth is in the object, messages are only hints - -The object **controlled by the participant** is what counts. Any message — an inbox deposit, a purge notification — is only a **hint** that triggers a check, never an authority. - -Consequence: **forgery becomes structurally harmless**. A fake « purge X » leads the creator to read X, find it still active, and do nothing. That is why inbox deposits **need not be signed** — which is just as well, since the contract promises no authenticated sender. - -### Why a flag rather than a deletion - -Without the read key, a **deletion** cannot be told apart from "nothing was ever there". A **readable** object carrying a **flag** transforms the problem: the cancellation no longer has to be *detected*, it is simply *read*. The blocker disappears instead of being worked around with a forgeable message. - -### Why the identity pointer targets the existing profile - -No need for a second document per participation: the participant's **protected profile** already plays that role, and their connections **already** hold the key to read it — that is the very definition of being connected. A third party sees an opaque reference. - -The advantage over an encrypted field inside the Participation: **adding a connection rewrites nothing**. The profile is shared with a new connection once, durably (and irreversibly — the contract publishes no revocation). An encrypted field would require re-encrypting to N recipients and rewriting the Participation on every new connection. - -## What this rests on - -Two guarantees the contract publishes, and one thing it does not. - -| What the model needs | Where it stands | -|---|---| -| A reference can **name without granting read access** | Published: *"A returned reference carries no key… A reference found inside a document yields a name, not a key."* | -| Sharing is **per document, durable and one-way** | Published: `inbox.share(doc, toUser)` — one act, no revocation, nothing per reader on a public document | -| **Anyone may deposit, only the owner reads** the inbox | Published: `inbox.postToDocument` / `inbox.read` | -| A **dedup key** letting the creator count distinct people without reading them | **NOT published.** See below — this is the open dependency. | - -## The dedup: the requirement, and the gap - -**The requirement, validated by the PO (2026-07-27)**: the creator must be able to tell two references from the *same* person apart from two references from *different* people, **without ever knowing who** — otherwise the count is not a count of people, and a participant could inflate it by creating several Participations. - -**The contract publishes nothing that does this.** A reference "yields a name, not a key", and no call answers "do these two references belong to one person?". So the mechanism is **not Festipod's to specify**: it is a **gap to raise with the provider**, stated as a need — *a stable, per-person discriminator that can be compared without reading the referenced document*. - -Design consequence, whatever the mechanism turns out to be: the Set is **keyed by that discriminator** — at most one reference per person. `Set.size` = the number of distinct people. - -### The reservation that must outlive this brief - -Any such discriminator is by construction a **pseudonym**: it does not say *who*, but it is comparable across contexts, so whoever collects references can link them. **Never present a Festipod action as "anonymous"** when it circulates one — the contract guarantees no anonymity, and making the Participation public widens the surface on which it is collected. Whether the pseudonym can be rotated, or scoped, is part of the gap above. - -## Trade-offs deliberately accepted (PO, 2026-07-27) - -- **No filtering on read.** The count is `Set.size`, **without** checking the `active` flags. We accept the **staleness risk**: a cancelled participation still counts until the creator has purged. `Set.size` is therefore an **upper bound**, exact once purged. *Rationale: keep reads simple and O(1).* -- **Purging is the creator's job.** No curator service, no catch-up by readers. -- **No description** in the Participation for now. *(To be reopened when the need arises: whatever we put there would become public.)* -- **Creator offline**: the Set does not move until they have processed their inbox. Accepted. - -## What changes vs the current implementation - -What exists today ([[knowledge_context-internals]] §participantCount) derives a `participantCount` **written by the owner** from inbox markers carrying the **plaintext `userId`**. - -- **Drop the `userId`** from inbox deposits → only the **Participation's reference** remains. -- **Count distinct people** through the discriminator above, no longer `userId`s. -- **`event.participantCount` goes away**, replaced by `Set.size`. -- **Identity resolution** now goes through **reading the profile** (hence through being connected), no longer through the marker. -- **Withdrawal stops being a deletion** → `active` set to false + a purge by the creator. See [[caveat_participation-deletion]], whose requirement (« authoritative, must not come back ») still holds but changes mechanism. - -Still valid as-is: **reactive reads**, **re-arming on reconnection**, and the **id-space fix** already shipped. - -## Open points - -- **Participation scope** — it becomes **public**, whereas current product doctrine places it in *protected* ([[knowledge_data-scopes-and-discovery]], concept `functional-domain`). That leaf describes **what is implemented**: do not change it until this brief has graduated, but **do update it at that point**. -- **Recognition by connections** (step 7) — and what happens to a broken connection: the contract publishes **no revocation**, so sharing a profile is permanent. Explicitly deferred to a second stage. -- **Public reads are not recursive** — this is the principle the whole model rests on, and it deserves to be stated on its own: *an item in the **public** store is public — whoever has the URL reads the content.* But **not recursively**: public content may **reference** private content, and **that is exactly our case**. So the creator reads the Participation (public) and **cannot** follow the reference to the profile (protected). That is what yields both readability by the creator and anonymity towards them — with no additional mechanism. - -## Dependencies - -- **Blocking — a contract gap**: no published way to **dedup without reading** (see above). Until the contract answers it, coding this model would produce a count that **claims** to be a count of people without being one. Raise it with the provider; do not emulate it here. -- **Parked**: **identity terminology** (wallet / user / profile) — see `.project/to-discuss.md`. - -## Status: model settled, implementation gated - -The model is **settled** (PO, 2026-07-27). What remains gated is the **implementation**, waiting on the dependency above. **Do not remove the current owner-derived counter** in the meantime ([[knowledge_context-internals]]). - -Links: [[caveat_participation-deletion]], [[rule_document-per-entity]], [[rule_app-uses-sdk-surface-only]], app-security ([[brief_2026-05-18_authorization-matrix]], [[knowledge_trust-model]]). diff --git a/.project/concepts/data-layer/brief_2026-10-03_structure-for-two-rights-models.md b/.project/concepts/data-layer/brief_2026-10-03_structure-for-two-rights-models.md deleted file mode 100644 index 9eb4ac6..0000000 --- a/.project/concepts/data-layer/brief_2026-10-03_structure-for-two-rights-models.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -type: brief -summary: One persisted shape holding on BOTH backends — NextGraph (per-document encryption) and ActivityPods (WAC) — references rather than embedded content, no stored counter, with the acl:Append behaviour and the deduplication gap left open ---- - -# Brief (2026-10-03) — One data shape for two rights models - -Festipod puts all its persistence behind interchangeable Refine backends (the seam's own contract is in code, `src/shared/refine/providers/types.ts`). Two are targeted: NextGraph plus its polyfill, and `@activitypods/refine-providers`, whose reconstructed observation is pinned beside this leaf ([[contract_activitypods-providers]]). The question this brief answers: what structure survives both rights models unchanged. - -## The primitives, side by side - -| What is needed | ActivityPods | NextGraph | -|---|---|---| -| Unit of rights | LDP resource + WAC | **document** | -| List attached to a resource | `as:Collection` attached by a predicate, `semapps:dereferenceItems` | a Set inside the document | -| Let a third party contribute | `acl:Append`, or `apods:PostOutbox` to the recipient's inbox | `inbox.postToDocument` | -| Grant "my connections" | `acl:agentGroup` + a WAC group | per-document sharing, once per connection | -| Name without granting access | reference + WAC refuses the GET | reference carrying no key | -| Revoke | `pod-permissions.remove` exists | not published | -| Write offline | no (client-server) | yes (local-first) | - -## The design rule that follows - -**The common denominator is NextGraph**, whose model is the strict subset: no groups, no revocation, sharing wholesale per document. So structure for NextGraph and ActivityPods will serve that structure — more cheaply even, with groups. The converse does not hold: any structure that needs a server-side projection or a revocation is untenable on NextGraph. - -## The structure - -``` -Event own document, public, written by its creator - └─ participations an attached list of REFERENCES (never embedded content) -Participation own document, owned by THE PARTICIPANT - ├─ event → ref - ├─ active → boolean - └─ participant → ref to the Profile -Profile own document, protected -``` - -## Why references and not embedded content — three facts - -1. **Ownership.** The participation must be writable by its participant and by nobody else (withdrawal must be authoritative — [[caveat_participation-deletion]]). On NextGraph write access is granted per document, so the participation **must be** a document; embedded in the event it would be writable only by the event's creator. -2. **Per-reader variation is impossible inside a single document on NextGraph**, because encryption and sharing are per document. It is obtained by **indirection**: the reference is always present, and what varies is the ability to **follow** it. -3. [[rule_document-per-entity]] already says this, and says it for exactly this reason. - -## The non-visibility mechanism differs — PO precision, 2026-10-03 - -On NextGraph the target is **undecipherable** for want of a key: nothing is absent, the reference itself is readable. On ActivityPods it is either inaccessible (WAC refuses the GET) or the reference is omitted by server-side projection. Both land on the same application state: **a reference one may or may not resolve.** - -## Consequence on the domain types - -The type models the NextGraph shape, where everything is present: - -```ts -interface FpParticipationData { - id: string; - event: string; - active: boolean; // NOT optional — the participation is readable by everyone - participant: string; // NOT optional — a reference, which names without granting access -} -``` - -Resolution alone may fail: `resolveParticipant(ref)` yields `FpUserData | undefined`, where `undefined` means "not a connection". ActivityPods' omission is a **degradation the binding absorbs**: it reports "a participation whose participant does not resolve" — the same state as "I do not hold the key". - -An error made in session and corrected here: `active?` and `participant?` were proposed first, which lifted the ActivityPods adaptation into the common model. - -## The count - -**No stored counter, ever.** The number of participants is `participations.length`. `knownParticipants` is the participations whose participant resolves — a presence test, not an access check. Withdrawal is `active: false` on one's own document. - -## The three invariants that make the app platform-indifferent - -1. One document per entity; never embedded content. -2. A reference may be unresolvable, and that is a **normal state** — neither an error nor an absence (the app shows "someone"). -3. The list is an **upper bound that converges**; never assume it is complete at the instant (already documented by [[caveat_participant-count-one-connection-lag]]). - -## Open points - -### NOT VERIFIED — does `acl:Append` on a collection let a third party insert an item without being able to remove one? - -WAC mode enforcement lives in `@semapps/webacl`, absent from the ActivityPods checkout consulted and not installed. The mode is real and genuinely used (`tests/apps/example.app.js` declares `accessMode: ['acl:Read', 'acl:Append']`), but its behaviour on a SparqlPatch `INSERT DATA` / `DELETE DATA` was not observed. - -**The structure does not depend on the answer.** If Append works that way, the participant appends directly and the count is immediate. Otherwise the route is `apods:PostOutbox` to the creator's inbox, whose app adds the reference — which is exactly the NextGraph shape. Only the latency changes. - -### OPEN — deduplication: neither platform counts people, and the implementation here does not either - -[[brief_2026-07-20_attendance-set-model]] requires that the creator tell two references from the *same* person apart from two references from different people, **without knowing who** — otherwise the count is not a count of people and a participant can inflate it. **The code here does not do that** (verified 2026-10-05). A different problem is solved, and solved well: `materializeAttendance` (`src/shared/data/registration.ts`) keys its active set by a **per-deposit** `uid` minted from time plus randomness, so a broker re-sync replaying the same deposits converges instead of double-counting — that is **replay idempotence**, not person identity. The count is therefore a count of **deposits**: the same person joining twice counts twice. Three further findings about the current implementation: - -- **The plaintext `userId` travels in the deposit**, and the cancellation fallback depends on it — a leave without a known `regUid` cancels the earliest still-active join carrying that `userId`, so N leaves cancel N joins. The attendance-set brief's own change *"drop the `userId` from inbox deposits"* was never made, so the creator **does** know who and the anonymity property does not hold today. The privacy-preserving discriminator was never needed because the privacy was never implemented. -- **Participations live in the protected scope**, not public, and withdrawal is still a deletion ([[caveat_participation-deletion]]) — so the target model is not in place either. The attendance-set brief's own status line, *model settled / implementation gated*, still holds. -- **The gap was never raised through the declared channel.** The five frictions in this app's polyfill declaration (`polyfill-surface/usage_festipod.md`) cover inbox idempotence, the absence of a push on one's own deposit, the reactive read not seeing one's own write, the impossibility of resetting the test wallet, and a wrong published signature. None asks for a per-person discriminator. - -So the divergence is not "NextGraph has an upstream gap while ActivityPods does not": **both count deposits rather than people.** ActivityPods could arbitrate server-side because the server sees everything; NextGraph awaits a primitive. And the gap sits in **neither Refine provider** — it is in the polyfill on one side and the server on the other, which is what matters when deciding what to contribute where. The upper bound remains the common fallback position, already accepted by the PO. - -## Two ActivityPods constraints not to rediscover later - -- **The Refine providers cover CRUD only.** Creating the collection, setting WAC, creating a group, posting to the outbox are not in the data provider, which does not implement Refine's `custom` either — so there is no escape hatch through Refine and those calls happen beside it. -- **A custom ontology prefix must be registered at prefix.cc**, the Pod provider requiring every ontology to have a known prefix; this concerns our `fp:`. Shape trees must also sit at a public URL, one per entity, since they cannot reference other shapes — no sharing cascade. - -## Reservation to keep alive - -The reference to the profile is readable by everyone and therefore collectable: it is a **correlatable pseudonym, not anonymity**, and must never be presented as such. The reservation comes from the attendance-set-model brief, and the 2026-10-03 precision reactivates it. diff --git a/.project/concepts/data-layer/brief_2026-10-09_activitypods-first-backend.md b/.project/concepts/data-layer/brief_2026-10-09_activitypods-first-backend.md index 9695a23..a84e4eb 100644 --- a/.project/concepts/data-layer/brief_2026-10-09_activitypods-first-backend.md +++ b/.project/concepts/data-layer/brief_2026-10-09_activitypods-first-backend.md @@ -18,26 +18,23 @@ Directives recorded at the resumption of the hand-off (`.project/handoff/refine- Reading these at this stage is adoption-time reading, explicitly directed — the standing constraint against reading provider sources at work time is unaffected (`@activitypods/refine-providers` remains specified by its pinned reconstruction, `activitypods-providers/contract_activitypods-providers.md`). -- **Example apps** — `/home/sylvain/projects/reconnexion/welcometomyplace` and `/home/sylvain/projects/reconnexion/mutual-aid.app`: working integrations to mine for provider configuration, resources, and the on-behalf backend pattern. +- **Example apps** — the reference apps under `~/projects/activitypods/` (`welcometomyplace`, `mutual-aid.app`, `portejunes`), the only allowed source of pod-interaction patterns (project rule `festipod-only-reference-app-patterns`). - **ActivityPods platform source** — `/home/sylvain/projects/activitypods/activitypods`; Semapps lives in a sibling folder. - **Shapes** — `/home/sylvain/projects/activitypods/shapes`: readily usable, and **evolvable by us** if Festipod's entities require it (that repo is ours to adapt). -## Constraints already on record (see the 2026-10-03 brief and the reconstruction) +## Constraints on record -- `fp:` must be registered at prefix.cc; shape trees must sit at public URLs, one per entity, no sharing cascade. +- A Festipod CLASS with its own shape tree needs `fp:` registered at prefix.cc: the pod registers the ontology of every class it creates a data registration for, and refuses one whose prefix it cannot find (`registerOntologyFromClass` in the pod provider). Shape trees must sit at public URLs, one per entity, no sharing cascade. A Festipod PREDICATE on an existing resource does not need it: the pod stored and returned a `http://festipod.org/` predicate on a profile, `fp` unregistered (verified live 2026-10-29: written with the app's token, returned under the full IRI). - The Refine providers cover CRUD only; `custom` is not implemented — no escape hatch through Refine. - `getMany` silently drops failed fetches — it erases the "unreadable reference" state the model needs (a candidate contribution). -- `acl:Append` third-party insert-without-remove behaviour is NOT VERIFIED; the structure does not depend on the answer. ## Reconnaissance answers (2026-10-09) - **On-behalf mechanism — ANSWERED.** An app backend is an ActivityPub actor (`@activitypods/app` `AppService`, Moleculer); it signs pod requests as the app actor and the pod impersonates the user after checking registration + grants. Frontend calls use the Solid-OIDC dual-identity token instead. No unattended per-user backend token exists. -- **Registration/Participation — production precedent found.** welcometomyplace persists NO registration resource: a join is an `as:Join` activity posted to the user's outbox, the backend service handles it and adds the actor to the event's `apods:attendees` collection (attached via `attachPredicate`, `PodCollectionsHandlerMixin`); a leave is `as:Leave`, same path in reverse. Membership is read via `pod-collections.getItems`. mutual-aid uses none of this (comments, likes, announces only). +- **Registration/Participation — production precedent found.** welcometomyplace persists NO registration resource: a join is an `as:Join` activity posted to the user's outbox, the backend service handles it and adds the actor to the event's `apods:attendees` collection (attached via `attachPredicate`, `PodCollectionsHandlerMixin`); a leave is `as:Leave`, same path in reverse. Membership is read via `pod-collections.getItems`. mutual-aid uses none of this (comments, likes, announces only). Festipod's adaptation, where participants must stay unidentifiable to non-contacts: [[decision_2026-10-29_participation-privacy-mechanism]]. - **Event-in-event — feasible without touching any shape.** The `as/Event` and `as/Profile` SHACL shapes are open (no `sh:closed`), and the generic ActivityStreams vocabulary already defines `as:context`, `as:partOf`, `as:inReplyTo`. A meeting point is a plain `as/Event` carrying an `as:context` link to its parent event — the presence of the link is what distinguishes it, nothing else. Shapes are consumed for access needs and container setup, not server-side resource validation, so nothing breaks. ## Open questions -- Participation topology — the one real divergence from the 2026-10-03 structure: welcometomyplace keeps the canonical list creator-side (an `apods:attendees` collection on the event, writes backend-mediated), where the two-rights-models structure makes each participation a participant-owned document. Both land on the same application state (a reference that may or may not resolve); the choice is who owns the write path. **Arbitration route decided 2026-10-09: the implementation plan evaluates both against the concrete screens (count, withdrawal, discovery, reference non-resolution) and submits an argued recommendation before anything is frozen.** -- `as:Join` has a shape but no shape tree: if participations must be addressable as resources in access needs, adding `shapetrees/as/Join.ttl` for an already-existing AS type is the minimal move — or the collection pattern makes it unnecessary. - The backend's deployment shape (service alongside the app? a platform app?). -- Whether the four pointed-to provider contributions (from the hand-off) are still the right set once the backend exists — some may move from "contribution to the providers" to "our backend's job". +- Whether the three pointed-to provider contributions (from the hand-off) are still the right set once the backend exists — some may move from "contribution to the providers" to "our backend's job". diff --git a/.project/concepts/data-layer/caveat_t06-unverified-on-a-real-pod.md b/.project/concepts/data-layer/caveat_t06-unverified-on-a-real-pod.md new file mode 100644 index 0000000..dc87c87 --- /dev/null +++ b/.project/concepts/data-layer/caveat_t06-unverified-on-a-real-pod.md @@ -0,0 +1,16 @@ +--- +type: caveat +summary: Several coherence-pass features were built and unit-tested but never played against a real pod — invitations, image upload, bio/city/photo round trip, profile completion — plus a few known limits of the read side +last_checked: 2026-10-21 +--- + +# Caveat: built but not verified on a real pod + +Unit and UI-layer tests are green; none of the following has run against a live ActivityPods stack. Treat as unverified, and re-check at the first run on a pod: + +- **Invitations**: that the `Announce` is delivered to the chosen contacts' Pods. +- **Image upload** ([[decision_2026-10-21_images-are-uploaded-to-the-pod]]): container resolution, the `Location` header, the public-read grant, and the re-consent for the File access need. +- **Profile round trip**: bio, city and photo (`image`) written and read back through the provider. +- **Profile completion**: the onboarding gate on a pod whose profile has an empty name; a pod linking no profile at all only gets a message, since creating and linking an `as:Profile` is outside the pinned contract. + +Known limits of the read side, by design or by backend: catalogue entries carry no participant count (so cards of events never opened show none, and gain one once opened); an empty catalogue is indistinguishable from an unreachable one; another person's events are not listable (`getUserEvents` answers for the signed-in user only). diff --git a/.project/concepts/data-layer/cookbook_local-activitypods-platform.md b/.project/concepts/data-layer/cookbook_local-activitypods-platform.md index 4b32d42..0d31e5f 100644 --- a/.project/concepts/data-layer/cookbook_local-activitypods-platform.md +++ b/.project/concepts/data-layer/cookbook_local-activitypods-platform.md @@ -31,8 +31,20 @@ pod provider 3000 (OpenID + `/auth` signup/login), pod provider frontend 5000, F On a fresh pod, an `as:Event` POST lands at the pod root (`/alice/data/`): typed containers such as `/alice/data/as/event` exist only after a user installs an app whose access needs declare that shape tree. Do not expect typed containers before app registration. +## Data location (hard-won, 2026-10-26) + +- **Fuseki's data dir must stay on the SSD** (`/home`, NVMe). Measured: a signup is ~10 s on the SSD, 150–200 s on the spinning HDD (`/hdd-home`) — TDB2 fsyncs per write and the seek time dominates. The HDD mount also hosts the bulk of the host's files; keep fuseki off it. +- **Never replace `data/fuseki` with a symlink after the container exists.** Docker resolves the bind source when the container is CREATED; moving the data away and leaving a link behind leaves the running container with a broken/empty mount (symptom: signup 500 « Error when creating secure dataset … FileNotFoundException: /fuseki/system_files/… »). `docker restart fuseki` re-resolves and heals — until the next behind-its-back move. +- The e2e suites delete the accounts they create at the end of every run (user decision 2026-10-26): `DELETE http://localhost:3000/.account/:username` with the user's token (a user may delete only their own account). The platform tombstones the account, sends the Delete activity, and drops the fuseki dataset on a delay — so test data no longer accumulates and the periodic full wipe is no longer needed. `diag-invite.ts` is the only suite left without cleanup (manual diagnostic). + +## Backend fresh-boot note + +The Festipod backend has its OWN datasets, `festipod` (main, created SECURE at first boot — WebACL is on) and `settings-festipod` (accounts), named like the sibling apps' (`welcometomyplace`/`settings-wtmp`…). Never point it at the pod provider's `settings` dataset, and never delete or recreate `settings`: it holds the pod provider's accounts. A backend dataset reset follows the compose file's header (delete the datasets and the secure dataset's files on disk, empty the backend's Redis cache database). After a reset, pod accounts that had installed the app must install it again: the new backend knows none of their registrations. + +On a FRESH backend dataset (after a wipe), the app's actor and its access-need group are created in parallel by the mixin's boot and can race: the actor can end up without `interop:hasAccessNeedGroup` (symptom: `GET /app` links a group that 404s; consents register zero grants). `backend/services/app.service.js` heals this at boot by polling for the group (up to 60 s) and attaching it. If the backend is restarted while its dataset is wiped, wait for the heal before running consented flows — or simply re-check `GET /app` links a group that resolves 200. + ## Teardown -`pkill -f moleculer-runner; pkill -f react-scripts`, then `docker compose down` in `pod-provider/`. Data persists in `pod-provider/data/` (gitignored); delete that directory to fully reset. +`pkill -f moleculer-runner; pkill -f react-scripts`, then `docker compose down` in `pod-provider/`. Data persists in `pod-provider/data/` (gitignored); delete that directory to fully reset. With the suites cleaning up after themselves (above), a full reset should now be a rare event, not a maintenance ritual. Current stack test account: `alice` / `Test1test` on localhost:3000. diff --git a/.project/concepts/data-layer/decision_2026-10-21_contacts-are-the-pod-social-graph.md b/.project/concepts/data-layer/decision_2026-10-21_contacts-are-the-pod-social-graph.md new file mode 100644 index 0000000..0260bcf --- /dev/null +++ b/.project/concepts/data-layer/decision_2026-10-21_contacts-are-the-pod-social-graph.md @@ -0,0 +1,26 @@ +--- +type: decision +summary: Festipod keeps no friend model; contacts are the Pod's own apods:contacts collection, a contact request is an Offer{Add{my profile}} posted from the browser to my own outbox, invitations are Announce{event} activities, and nothing is built for acceptance or push +--- + +# Decision (2026-10-21): contacts are the Pod's social graph + +## Decision + +- **No home-made friend model.** A user's network is the `apods:contacts` collection linked from their actor document (the app falls back to the profile record), managed by the Pod — mutual when both went through the request/accept flow, though not guaranteed (see the platform defects below). In the app, `friendships` is only a mirror of that collection and `getFriends` reads it. Contacts are resolved to profiles through the same path as event participants. +- **Contact request** (`addFriend`): an `Offer{ object: Add{ object: { id, type: 'Profile' } }, to, target }` addressed to the other person's actor, posted to the requester's **own outbox with their own token**, from the browser (`src/shared/data/contacts.ts`). The `type: 'Profile'` is embedded in the activity: the platform's `CONTACT_REQUEST` matcher requires it, and it must not dereference the profile — a protected profile 403s anonymously and a bare-URI object was silently ignored (fixed 2026-10-22). The recipient lands it in `apods:contactRequests` and accepts on their Pod provider's own network page. **Festipod builds no acceptance screen.** +- **Sharing my connection** (the primary flow — see [[decision_2026-10-22_connection-sharing-is-the-invite-capability]]): an **invite capability** (VerifiableCredential) issued by the Pod (`POST {webId}/vc/v0.3/credentials/issue`), shared as `{frontendUrl}/invite/{capability}`; the recipient's contact request carries a VerifiablePresentation of it and is **auto-accepted** by the inviter's Pod. Strictly better than the bare request: no manual acceptance, and the invitee sees the inviter's profile (name, photo) through the grant. +- **Invitation to an event** (`inviteToEvent`): an `Announce{ object: , to: [chosen contacts] }` posted the same way. The invitable set is the real contacts only. +- **No backend service added.** A user-initiated request needs nothing the browser cannot do; a backend handler (notifications for people without the app) would be speculative without a pod to test it on. Push notifications stay the Pod provider's job. +- Providers with no Pod (the disconnected demo, the suspended NextGraph path) **reject** `addFriend` and `inviteToEvent` instead of simulating state. + +## Channels + +Participations are **public objects** (anyone sees that there are participants), but the **identity link** is protected — the profile is readable by contacts only, and the carved rule [[behavior_participation-listing-is-contacts-only]] reserves listing a person's events to their contacts, for every client. How contacts recognise participants and list a contact's events is [[decision_2026-10-29_participation-privacy-mechanism]]; the app reads no one else's outbox. + +## Consequences + +- "Demande envoyée" is session-local: the target's request collection is not readable by the sender, so after a reload the button offers the request again. +- There is no `removeFriend`. +- The `apods:contacts` list is a display, not a grant: the pod adds the sender of a received `Accept` of a contact request without checking a request was sent (a sender whose profile it cannot read is turned away; one who first sent a request of their own is added — verified live 2026-10-29), and keeps a removed contact in the `/contacts` WAC group (both platform defects reported upstream 2026-10-29). Festipod never derives a read right from the list — rights follow the group, see [[decision_2026-10-29_participation-privacy-mechanism]]. +- The request/accept round trip is verified live by the rights matrix (2026-10-29): the request posted from the requester's outbox, its acceptance naming the stored `Offer`, both lists then naming each other. diff --git a/.project/concepts/data-layer/decision_2026-10-21_images-are-uploaded-to-the-pod.md b/.project/concepts/data-layer/decision_2026-10-21_images-are-uploaded-to-the-pod.md new file mode 100644 index 0000000..20d571f --- /dev/null +++ b/.project/concepts/data-layer/decision_2026-10-21_images-are-uploaded-to-the-pod.md @@ -0,0 +1,18 @@ +--- +type: decision +summary: Images (event cover, profile photo) are uploaded as binary LDP resources to the Pod's file container from the browser, then made publicly readable; the URL is stored in coverImage / photo; existing users must re-consent for the new File access need +--- + +# Decision (2026-10-21): images live in the user's Pod + +## Decision + +- `useUploadImage` (`src/shared/hooks/`) resolves the Pod's `file` container, POSTs the file binary with the user's token and reads the new URL from the `Location` header, then calls `grantPublicRead` (`src/shared/utils/`): a best-effort WAC ACL PATCH granting `foaf:Agent` read. Without the grant, an image nobody else can read is a dead feature. Without a session (the demo) the upload rejects. +- The URL is stored as `coverImage` on an event and `photo` on a profile. On ActivityPods the cover maps to the AS2 term `image` and the profile photo to `vcard:photo` — the term both reference apps read (mutual-aid, welcometomyplace), after verifying the `vcard:` prefix is present in the platform context. Interop cross-apps : une photo stockée sur un autre vocabulaire serait invisible partout. +- The app declares the `shapetrees/File` access need (read + write) in `backend/services/app.service.js`. **Users who registered the app before this change must re-consent** for uploads to be allowed. +- `resolveContainerUri` and `fetchJson` come from `@activitypods/refine-providers/utils`, which the pinned contract does not list: this use is outside the contract and must be declared in the usage declaration / raised to the provider. +- The event cover falls back to a neutral gradient; the old stock-photo map is gone. + +## Consequences + +Covers and avatars are visible to anyone who can read the event or profile record, as the `grantPublicRead` makes the file itself public. Never verified end to end on a real pod — see [[caveat_t06-unverified-on-a-real-pod]]. diff --git a/.project/concepts/data-layer/knowledge_context-internals.md b/.project/concepts/data-layer/knowledge_context-internals.md index 2dd59d4..2c6cc39 100644 --- a/.project/concepts/data-layer/knowledge_context-internals.md +++ b/.project/concepts/data-layer/knowledge_context-internals.md @@ -55,9 +55,6 @@ Mutations on the create/participate path **reject** rather than returning quietl A `Participation` written **today** carries the profile document's NURI in `fp:user`, so the direct join `u.id === userId` matches. Participations written under the **earlier** scheme carry `urn:festipod:user:`, which matches nothing directly. **`resolveParticipantUser`** is the single join point and tries, in order: (1) the direct id match — today's writes, and the demo seed's bare `user-1` space; (2) failing that, strip `USER_PRINCIPAL_PREFIX` and compare the remainder to `normalizeIdentifier(profile.username)`. Never join by direct comparison at a call site: getting it wrong renders every participant as « participant inconnu », which shipped once. `USER_PRINCIPAL_PREFIX` is **read-side only** — nothing mints it any more; it is not a shape to write against. The inbox deposit `uid` (`mint…`) is a third space that takes **no** part: it identifies a deposit for the counter, never a user. - -> **Horizon.** The target model drops the plaintext `userId` and resolves identity by reading the profile — [[brief_2026-07-20_attendance-set-model]], gated. The id-space fix is noted there as still valid: do not undo it in anticipation. - ## Reads = `watchShape`, writes = an optimistic overlay Reads go through `useShapeQuery(shape, scope)` — three scoped reads (events/public, profiles/protected, participations/protected) mapped by `shapeAdapters.ts`; `ready` combines their `isSuccess` flags. The app resolves, lists and re-queries nothing ([[rule_document-per-entity]] §Reads). @@ -90,6 +87,10 @@ Two measurement points are laid down **as a pair**: the owner's materializer log The app settles its identity once, before anything renders, and offers no way to change it (`app-security` → [[decision_2026-08-10_the-barrier-names-no-identity]]). One page hosts exactly one identity for its whole life, so there is no identity-change reset: no `useEffect([identifier])`, no cap reset, no registry-cache reset. Do not reintroduce a reset for a transition that cannot happen. Cross-identity **isolation** is still a real requirement, but proving it needs two genuinely separate browser contexts (`bdd-testing` → [[rule_tests-validate-festipod-not-the-sdk]]). +## On ActivityPods the context is `refineData.tsx`, and read-your-writes is confirmed by a collection + +The ActivityPods implementation of the same context (`src/shared/context/refineData.tsx`) holds a join or leave as a pending act on top of the reads and releases it only when a read issued after the act confirms it — the person's own participations collection for membership, the meeting point's attendee list for the count — or when a bounded re-read schedule runs out (verified in code). A read that merely shows the asserted state is not a confirmation: it may predate the act. Details: [[decision_2026-10-29_participation-privacy-mechanism]]. + ## Mutations are no-ops in local mode In local/demo mode (`useLocalData`), `createEvent`/`joinEvent`/`leaveEvent`/`updateEvent` are **no-ops** (a log, no state change) — yet the screens still show a success toast. Misleading UX, unchanged. See [[knowledge_data-modes]]. diff --git a/.project/concepts/data-layer/knowledge_entities.md b/.project/concepts/data-layer/knowledge_entities.md index 76abecb..30c7a39 100644 --- a/.project/concepts/data-layer/knowledge_entities.md +++ b/.project/concepts/data-layer/knowledge_entities.md @@ -1,6 +1,6 @@ --- type: knowledge -summary: The Fp* app types and their SHEX shapes — Event (no host), UserProfile, Participation, MeetingPoint and Notification are persisted, Friendship stays local-only; the generated ORM names carry NO Fp prefix and are aliased at the import sites +summary: The Fp* app types and their SHEX shapes — Event (no host), UserProfile, Participation, MeetingPoint and Notification are persisted, Friendship has no shape of its own; the generated ORM names carry NO Fp prefix and are aliased at the import sites last_checked: 2026-08-17 --- @@ -11,11 +11,13 @@ last_checked: 2026-08-17 | Type | Persistence | Key fields | |---|---|---| | `FpEventData` | SDK (Event shape) | title, date, startDate, endDate, startTime, endTime, location, distance, participantCount, coverImage | -| `FpUserData` | SDK (UserProfile shape) | name, initials, username, role, isPublic | +| `FpUserData` | SDK (UserProfile shape) | name, initials, username, role, isPublic, bio, city, photo (all optional; on ActivityPods `photo` is the AS2 `image`) | | `FpParticipationData` | SDK (Participation shape) | event + user + isConfirmed | | `FpMeetingPointData` | SDK (MeetingPoint shape) | event, host, title, place, time | | `FpNotificationData` | SDK (Notification shape) | recipient, type, ref, payload, timestamp, isRead | -| `FpFriendshipData` | **local-only** | userId + friendId | +| `FpFriendshipData` | **derived** on ActivityPods (mirror of the Pod's `apods:contacts`, see [[decision_2026-10-21_contacts-are-the-pod-social-graph]]); absent elsewhere | userId + friendId | + +**On ActivityPods the participation is not a document of its own.** A sign-up is a member URN in the meeting point's `apods:attendees` collection plus the meeting point's URI in the person's participations collection (linked from the profile as `http://festipod.org/participations`); the person's `http://festipod.org/participationSecret` on the profile is what lets their contacts recognise the URN. No shape describes any of these — see [[decision_2026-10-29_participation-privacy-mechanism]] and `src/shared/data/participationPrivacy.ts` (verified in code). **An event has no host.** `hostName`/`hostInitials` are gone from the type and the shape alike — the event is only the anchor, and the host lives one level down on the meeting point (`FpMeetingPointData.hostId`, SHEX `fp:MeetingPoint.host`). See concept `functional-domain`, [[knowledge_actors-and-concepts]]. diff --git a/.project/concepts/functional-domain/_overview.md b/.project/concepts/functional-domain/_overview.md index efe904a..96e9b16 100644 --- a/.project/concepts/functional-domain/_overview.md +++ b/.project/concepts/functional-domain/_overview.md @@ -2,7 +2,7 @@ type: _overview summary: Festipod's product model — the meeting point grafted onto a public event as the unit of value, its actors, its business concepts, and the confidentiality scopes (public/protected/private) per entity triggers: - keywords: [point de rencontre, rencontre, greffe, greffer, événement, déclarant, hôte, inscrit, inscription, communauté, connexion, festival, déduplication, découverte, périmètre, scope, public, protected, privé] + keywords: [point de rencontre, rencontre, greffe, greffer, événement, déclarant, hôte, inscrit, inscription, participation, participer, communauté, connexion, festival, déduplication, découverte, périmètre, scope, public, protected, privé] paths: ["src/modules/*/features/**"] --- @@ -18,12 +18,14 @@ Festipod lets users create **meeting points** that *graft* themselves onto exist ## Scope & confidentiality -The product model of **who sees what** — personal data reserved to one's network, public events/meeting points, identified-or-anonymous sign-up notification — is a business fact: see [[knowledge_data-scopes-and-discovery]]. The detailed authorization matrix (actor × verb) and its incubation live in the `app-security` concept ([[brief_2026-05-18_authorization-matrix]]). +The product model of **who sees what** — personal data reserved to one's network, public events/meeting points, an anonymous sign-up notification to the host — is a business fact: see [[knowledge_data-scopes-and-discovery]]. The detailed authorization matrix (actor × verb) and its incubation live in the `app-security` concept ([[brief_2026-05-18_authorization-matrix]]). ## Links - [[knowledge_business-model]] — the event / meeting point inversion - [[knowledge_actors-and-concepts]] — reference for actors and business concepts - [[knowledge_data-scopes-and-discovery]] — public/protected/private scopes per entity + discovery +- [[behavior_participation-listing-is-contacts-only]] — the carved-in-stone rule: listing someone's events is contacts-only +- [[decision_2026-10-29_participation-privacy-mechanism]] — the mechanism enforcing it on ActivityPods (private Join, hashed member URNs, contacts-readable participations collection) - [[knowledge_roadmap]] — current features vs upcoming evolutions - [[brief_2026-06-15_event-deduplication]] — open challenge of deduplicating events in P2P diff --git a/.project/concepts/functional-domain/behavior_participation-listing-is-contacts-only.md b/.project/concepts/functional-domain/behavior_participation-listing-is-contacts-only.md new file mode 100644 index 0000000..3ce1a8f --- /dev/null +++ b/.project/concepts/functional-domain/behavior_participation-listing-is-contacts-only.md @@ -0,0 +1,32 @@ +--- +type: behavior +summary: The link between a person and the events they participate in is personal data — listing someone's events is reserved to their contacts; the person themself always can, anyone else never +--- + +# Participation listing is contacts-only + +> **La règle (canonical statement, French):** *« On ne doit pouvoir lister les événements auxquels participe une personne que si on est en contact avec elle. »* + +A **product invariant**, carved in stone (user decision 2026-10-23). It governs any feature, screen, query or data-layer mechanism that surfaces *which events a given person participates in* — whoever asks, whichever channel. + +## What it protects + +The set of events someone attends reveals where they go, when, and with whom — it is **personal data**, in the same class as the profile itself. The event and the meeting point are public; the *link person ↔ participation* is not. An ordinary user must learn nothing from it; only a **connection** (bilateral contact) may. + +## The three outcomes + +| Who asks | Answer | +|---|---| +| The person themself | always listable — their own acts are theirs | +| A contact (bilateral connection) | listable — being a contact IS the grant | +| Anyone else | **never** — no listing, no count of *their* events, no cross-event correlation | + +## Deliberately mechanism-free + +The rule states the **what**, never the **how** — and that is intended. Which resource carries the link, how contacts read it, what the data layer exposes: all free, and all **constrained**. Any implementation choice — an attendees collection, an outbox read, an index, a grant — is acceptable **only while** the rule holds for every client, not just the Festipod app. A mechanism that lets a foreign client enumerate one person's events (correlatable IDs, scannable public collections) violates the rule even if the app's own UI behaves. + +## Related + +- [[knowledge_data-scopes-and-discovery]] — the scopes model this rule tightens (participation: public as an object, the identity link is protected) +- [[decision_2026-10-29_participation-privacy-mechanism]] — the mechanism enforcing this rule on ActivityPods (private Join, hashed member URNs, contacts-readable participations collection) +- [[decision_2026-10-21_contacts-are-the-pod-social-graph]] — what "contact" means (the Pod's bilateral `apods:contacts`) diff --git a/.project/concepts/functional-domain/decision_2026-10-21_meeting-point-form-title-and-place.md b/.project/concepts/functional-domain/decision_2026-10-21_meeting-point-form-title-and-place.md new file mode 100644 index 0000000..e803151 --- /dev/null +++ b/.project/concepts/functional-domain/decision_2026-10-21_meeting-point-form-title-and-place.md @@ -0,0 +1,12 @@ +--- +type: decision +summary: The meeting-point creation form carries a title (optional) and a place (required) only; free-text "when", duration and invitees were removed because the Pod vocabulary has no slot for them, and creation is announced only once it happened +--- + +# Decision (2026-10-21): the meeting-point form asks only what can be stored + +- Fields: **title** (optional, the intent) and **place** (required, stored as `location`). Nothing is merged into another field any more. +- **When**, **duration** and **invitees** were removed from the form: ActivityStreams has no term for a free-text moment or a free-text duration (`startTime` and `duration` are structured values), and the app has no invitee model. A field that vanishes after submit is worse than no field. `time` stays unmapped on ActivityPods; screens show it only when a record carries one, and the invented "~60 min" is gone. +- Reopening this needs a slot offered by the provider (or a structured time/duration input), not a new free-text field. +- `addMeetingPoint` returns a promise: the refine provider propagates the write, the disconnected demo rejects. The screen toasts success only after resolution and an error otherwise. +- Titles may be absent: cards show the place alone, and the title line only when there is one. diff --git a/.project/concepts/functional-domain/decision_2026-10-22_connection-sharing-is-the-invite-capability.md b/.project/concepts/functional-domain/decision_2026-10-22_connection-sharing-is-the-invite-capability.md new file mode 100644 index 0000000..583b0f5 --- /dev/null +++ b/.project/concepts/functional-domain/decision_2026-10-22_connection-sharing-is-the-invite-capability.md @@ -0,0 +1,20 @@ +--- +type: decision +summary: Sharing my connection means creating an invite capability (VerifiableCredential issued by the Pod) and sharing the pod provider's /invite/ page — the recipient's contact request carries a VerifiablePresentation of the capability and is auto-accepted; no QR, no profile-url page +--- + +# Decision (2026-10-22): connection sharing is the invite capability + +## Decision + +- **No QR code.** Neither the reference apps nor the platform need one (kept from the 2026-10-21 arbitration). +- **The shared link is the platform's invite page, not a profile page.** Festipod creates an **invite capability** — a `VerifiableCredential` issued by the user's own Pod at `POST {webId}/vc/v0.3/credentials/issue` (name "Invite Link"; `apods:hasActivityGrant` = the contact-request shape; `apods:hasAuthorization` = Read on the profile document) — and shares `{frontendUrl}/invite/{encodeURIComponent(capabilityUri)}`. Implementation: `src/shared/utils/inviteLink.ts`, `src/shared/hooks/useInviteLink.ts`. +- **Why this and not the `/network/@user@host` page**: a bare profile link fails exactly for the person it is shared with — the not-yet-contact, who gets an empty public view and a manual-accept round trip on the Pod provider. The invite page instead reads the inviter's profile **through the capability** (rich name/photo) and its Connect button posts the contact request **with a VerifiablePresentation of the capability**, which the inviter's Pod verifies and **auto-accepts** (`inviteLinkContactRequest` in the pod provider backend). The capability IS the proof of invitation. +- The `frontendUrl` (host of the invite page) is discovered via nodeinfo of the viewer's pod host, as before. +- The earlier `decision_2026-10-21_profile-link-not-qr` is **superseded by this one** (link target changed from the network page to the invite page). + +## Consequences + +- The ActivityPods pod-provider frontend fix of 2026-10-22 (public view of `/network` no longer fetching the private profile) is no longer on Festipod's contact path; it remains a standalone correctness fix there, uncommitted. +- Invite capabilities are created on demand; several valid ones may coexist (each grants the same profile read). Revocation is the Pod provider's job. +- Not yet verified end to end on a real pod pair — same caveat as the contacts decision. diff --git a/.project/concepts/functional-domain/decision_2026-10-29_participation-privacy-mechanism.md b/.project/concepts/functional-domain/decision_2026-10-29_participation-privacy-mechanism.md new file mode 100644 index 0000000..5c92ae6 --- /dev/null +++ b/.project/concepts/functional-domain/decision_2026-10-29_participation-privacy-mechanism.md @@ -0,0 +1,59 @@ +--- +type: decision +summary: How sign-ups stay unlinkable on ActivityPods — a private Join handled by the backend on emission; attendee lists of member URNs hashed with a secret kept in the profile, so only contacts recognise anyone; a participations collection per person readable by their contacts group; the creator notified anonymously +--- + +# Decision (2026-10-29): the participation privacy mechanism + +User-validated 2026-10-29. Enforces [[behavior_participation-listing-is-contacts-only]] on the ActivityPods backend, using only patterns of the reference apps (project rule `festipod-only-reference-app-patterns`). ActivityPods itself is never modified. + +## What it protects: two links + +- **Event → participants.** From an event (always public) anyone can count the participations, but nobody learns *who* participates — no name, no WebID — unless a contact. +- **Person → events.** Nobody can list the events a person participates in, unless a contact. Nothing published on a person's behalf identifies an event. + +The **creator of a meeting point has no particular read right**: for these two links they are "anyone else" unless a contact of the participant. The **Festipod backend** is not a person: it acts (records, notifies) and shows nothing to anyone. + +"Contact" is the audience the platform itself shares the profile with: the person's `/contacts` WAC group. The pod puts someone in it only through the person's own acts — the target of a contact request they send, the requester of a request they accept, whoever presents an invite link they issued (accepted automatically, so a forwarded link admits its holder) — never through an activity a stranger sends. + +| Who | From an event | From a person | +|---|---|---| +| The person themself | sees themself | lists their events | +| A contact (current or future) | recognises which of their contacts participate | lists the person's events, past ones included | +| Anyone else, the creator included | a count of participations, opaque member URNs | nothing | + +## The mechanism + +1. **Sign-up.** The participant posts an `as:Join` (withdrawal: `as:Leave`) to their own outbox, naming the **meeting point directly**, **not public and not addressed to anyone**. The outbox is filtered by read rights: a non-public activity is readable only by its recipients and its author (verified 2026-10-29 on the local pod — absent from the anonymous listing, direct GET refused 403), so the target stays hidden from strangers with no intermediate object. +2. **The backend acts on emission** — `onEmit` of the participant's outbox, the welcometomyplace registration pattern (`PodActivitiesHandlerMixin`); the app reads the outbox through `apods:ReadOutbox`. The creator's inbox receives no activity of the participant. +3. **The member URN.** `urn:festipod:userref: ")>`, where the event URI is the meeting point's anchor (`as:context`). The backend computes it from the participant's secret and records it in the meeting point's `apods:attendees` collection (in the creator's pod). Properties: the same for one person across all meeting points of one event (the per-event count is the number of **distinct** URNs, publicly computable); unrelated from one event to another; computable only by whoever can read the secret — the person, their contacts, the app. A client never supplies a URN, and the backend's ledger assigns one URN per (meeting point, participant), persisted before any write: every later act on that pair — after a failure or a rewrite of the secret — uses it, so one person never holds two entries in one list. Every collection write is verified by reading the collection back: a refused write or a failed read leaves the act unrecorded and unnotified, so the next act retries it. +4. **The secret** lives in the participant's `as:Profile`, under the Festipod predicate `http://festipod.org/participationSecret` (32 random bytes, hex), so it has exactly the profile's audience: the app and the person's contacts. The participant's browser generates it at the first sign-up when absent and writes it through the ordinary profile update, before posting the Join. A Join whose author's profile carries no usable secret is refused by the backend (nothing recorded). Verified live 2026-10-29: the pod stores this predicate written with the app's token and returns it under its full IRI, although `fp` is not registered at prefix.cc. +5. **The participations collection** — the person-side record of where they participate, for themself and for their contacts. An `as:Collection` in the participant's pod, attached to their profile under `http://festipod.org/participations`, created by the backend the way welcometomyplace attaches `apods:attendees` to an event (`PodCollectionsHandlerMixin`), and readable by the participant's `/contacts` WAC group (`pod-permissions.add` with `acl:agentGroup`, the group found through `pod-wac-groups.getUriFromCollectionUri` on `apods:contacts`). The group is evaluated at read time: a future contact sees past participations. The pod creates such a collection **world-readable** (observed 2026-10-12 on the attendee lists): the backend takes that public read away, with the same revocation it applies to the list of a meeting point switched private — a participations collection readable by strangers would list the person's events to anyone. Its items are meeting point URIs, added on a Join and removed on a Leave by the backend. The backend creates the collection at the person's first sign-up when the profile links none (one creation at a time per person); a profile with no collection has no participation to list. +6. **Recognition on an event.** The viewer reads each contact's profile once per session (it is read for names anyway) and keeps the secrets in memory; for an event, it puts the URNs of all its meeting points' lists in a set, hashes each contact once and tests membership — O(contacts + participations) per event, no network beyond the lists. Measured 2026-10-29 (Bun, Web Crypto): 500 contacts / 2 000 participations in 3.4 ms, 5 000 / 20 000 in 28 ms. +7. **Notification of the creator** on every sign-up and withdrawal, sent by the backend with `pod-notifications.send` (the welcometomyplace call), **always anonymous** ("a participant…"); the backend never passes the participant's profile. Naming a participant to a creator who is their contact would need a trustworthy contacts signal the app can read: the `/contacts` group is not readable by the app (403, verified live 2026-10-29), and the `apods:contacts` list can be forged (below). `pod-notifications.send` posts from the app's own outbox, which requires the backend to run with WebACL on a secure main dataset, as the three reference apps do. + +## Rejected alternatives + +- **Addressing the Join to the creator** (welcometomyplace's choice, where events are private): the creator's inbox, and the participant's outbox as a recipient, show them the participant's WebID. +- **Addressing the Join to the contacts**: an activity's read rights are granted once, at emission, to each recipient individually (semapps `setRightsHandler`; `getRecipients` expands only the sender's followers) — future contacts would never see past participations. +- **One read grant per item of the `apods:contacts` list**, kept in sync with contact changes: the list is forgeable — on a received `Accept` of a contact request the pod adds its sender without checking that a request was ever sent (pod provider `contacts/request.ts`, `acceptContactRequest.onReceive`); it first caches the sender's profile, so a sender whose profile the recipient cannot read is not added, but a sender who first sends the person a contact request (which lets the person read the sender's profile) is added (both verified live 2026-10-29) — a stranger would then gain the person's participations, where the group grants them nothing (verified live the same day: the forged contact is refused the profile and the participations collection, and is notified anonymously). +- **Granting the contacts group read on each Join**: the app holds read only on activities (`apods:ReadOutbox` maps to a default read on the activities container), no control; the browser's token carries the app's rights. +- **A private object named by the Join** (an "event reference"): useless once the Join is non-public, and creating its container and ACL from the browser is not a reference-app path. +- **A secret readable by its owner only**: contacts could not recognise anyone from the event side, and resolving identities would mean reading every contact's participations on every event view. +- **The backend resolving identities for viewers**: it would turn the backend into the gate of identity on the main screen. +- **Participations stored in the profile itself**: the profile is read for every contact at session start and would grow with each person's history. + +## Accepted residuals + +- The target of a contact request is in the requester's `/contacts` group as soon as it is sent, before accepting: they see the requester's profile and participations (user-accepted 2026-10-29). Showing such pending requests in the contacts screen is to be discussed. +- **Platform defect, reported upstream (2026-10-29):** `removeContact` removes from the `apods:contacts` list only, never from the `/contacts` group nor from the profile's read authorisation (pod provider `contacts/manager.ts`) — a removed contact keeps seeing the profile and the participations until the platform fixes it. +- **Platform defect, reported upstream (2026-10-29):** the `apods:contacts` list accepts a forged `Accept` (above) — the reason notifications stay anonymous; the contacts screen, which displays that list, shows such a stranger as a contact. +- A person who rewrites their secret between two meeting points of one event is counted twice in that event — no worse than a second account. +- The outbox root, read anonymously, carries in its pagination link the URI (never the content) of the newest activity: it reveals that an activity exists. +- An act writes twice (the list in the creator's pod, the collection in the participant's pod), not atomically: a failed write leaves the two apart until the person's next act on that meeting point. +- Removing the app leaves the collection and its grant in place. +- If the pod keeps refusing to link a new collection to the profile, each retried Join leaves one more empty, unlinked collection in the person's pod (the act itself stays unrecorded and retryable). + +## Not built: public users + +A future per-person setting will make some users **public**: their Joins become public, their list entries hold their WebID instead of a URN, their participations collection becomes readable by everyone. Switching a person between the two modes converts their existing entries. Nothing in the mechanism above precludes it. diff --git a/.project/concepts/functional-domain/knowledge_data-scopes-and-discovery.md b/.project/concepts/functional-domain/knowledge_data-scopes-and-discovery.md index 050f2bd..86bbdd4 100644 --- a/.project/concepts/functional-domain/knowledge_data-scopes-and-discovery.md +++ b/.project/concepts/functional-domain/knowledge_data-scopes-and-discovery.md @@ -16,14 +16,14 @@ Every entity is stored in the **scope** matching who must be able to read it: | Event (the anchor) | **public** | everyone | | Meeting point | **public** | everyone | | Network profile (name, avatar, bio, city, interests) | **protected** | the holder + their connections | -| Participation / sign-up to a meeting point | **protected** | the participant + their connections | +| Participation / sign-up to a meeting point | **public object, private link** | everyone sees *that* (and how many) participate; *who* participates is contacts-only — [[behavior_participation-listing-is-contacts-only]] | | Connection index | **protected** | the holder + their connections | | Private profile (settings, email, preferences) | **private** | the holder alone | | Connection A↔B (bilateral link, + future messaging) | **dialog** | both users | -**Deviation on the ActivityPods backend (user decision 2026-10-12, open):** a public meeting point's attendee list — its `apods:attendees` collection, whose members are WebIDs, which embed usernames — is **world-readable**, the pod's default, instead of protected. Moving it to the protected scope is a later task; until then the end-to-end rights matrix tracks it as a KNOWN-DEVIATION line, never as a positive assertion. When the meeting point is switched private, its attendee list stops being readable anonymously with it. +The attendee list of a public meeting point — its `apods:attendees` collection — is world-readable, and that is the **model, not a deviation**: participations are public objects. What is protected is the **identity link**: the list holds opaque member URNs that only a contact of the participant can recognise, and a person's events are listable by their contacts only; the meeting point's creator has no particular read right. The mechanism is [[decision_2026-10-29_participation-privacy-mechanism]]. When the meeting point is switched private, its attendee list stops being readable anonymously with it. -Guiding principle: **the "public" side (meeting point, event) and the "personal" side (profile, participations, connections) coexist within a single user.** Personal information is reserved to the **network** (bilateral connections), never visible to an ordinary user. +Guiding principle: **the "public" side (meeting point, event, the participation as an object) and the "personal" side (profile, the identity link of a participation, connections) coexist within a single user.** Personal information is reserved to the **network** (bilateral connections), never visible to an ordinary user. - **Meeting points / events are universally public.** Any user can read them and subscribe; creating a meeting point makes you its host, declaring an event makes you its declarer (no prerequisite). - **The host is the sole holder of write rights** on their meeting point; the declarer has no particular right over the meeting points grafted onto their event. @@ -40,7 +40,7 @@ The intent is the same on both backends — every public event is findable by ev - **ActivityPods (the default backend): the Festipod backend's catalog.** An event or meeting point is public when Festipod creates it addressed to the ActivityStreams Public collection (`to: as:Public`). Such a record is readable by anyone at its URI, and the Festipod backend lists it in its catalog at once — no curation. The listing follows the record: the owner's edits update it; a deletion, or a switch to private, removes it and makes the record and its attendee list unreadable anonymously again. Only a record's owner can change its listing. Découvrir shows the user's own events plus the catalog's; opening another user's event reads that event, its meeting points and their attendee counts anonymously, by URI. Costs, accepted: a record created while the backend was not receiving the pod's notifications is never listed (no backfill), and the catalog lists meeting points too, so its own total is not an event count. Verified end to end by `bun run test:e2e-rights` (groups catalog, discovery, visibility). - **NextGraph (backend suspended): a curated shared-index document** — [[decision_2026-08-17_discovery-through-a-shared-index]] (concept `data-layer`), no code consumes it yet. An ordinary public document the app reaches by a reference it hardcodes; anyone may deposit a reference to their event, only the index's owner curates deposits into visible entries, ordered by start date. Its accepted costs: an event is findable only once **someone curates** the index (an operator role, no fixed schedule); an event declared before its document could carry the indexed field never becomes findable; a withdrawn or corrected event **stays listed**, so a reader must tolerate a reference that no longer resolves or resolves to something changed; an entry's position is **frozen at curation**. -> **Sign-up notification (product intent).** Signing up to a meeting point notifies its host: identified if the participant is one of the host's connections, **unnamed otherwise**. This "identified if known, unnamed otherwise" falls out of scope placement — the host can read the sign-up, but not the *protected* profile it points at unless they are connected. The app states the intent; it implements no filter of its own. +> **Sign-up notification.** Signing up to a meeting point, and withdrawing, notifies its host. The intent is "identified if the participant is one of the host's connections, unnamed otherwise"; on ActivityPods it is **always unnamed** for now — the host has no read right over who signed up, and the app has no trustworthy contacts signal to decide otherwise ([[decision_2026-10-29_participation-privacy-mechanism]]). ## Settled: the event write model is OWNER-ONLY diff --git a/.project/concepts/tech-stack/knowledge_deployment.md b/.project/concepts/tech-stack/knowledge_deployment.md index 6120c3d..62a7d69 100644 --- a/.project/concepts/tech-stack/knowledge_deployment.md +++ b/.project/concepts/tech-stack/knowledge_deployment.md @@ -15,7 +15,8 @@ last_checked: 2026-10-19 **The backend is base-path aware** (`backend/services/base-path.js`), because SemApps is: it mounts every route it adds under the base URL's path (LDP resources, the app actor and its inbox, public keys, access needs, webhooks, `/nodeinfo/2.1`) but keeps the `/.well-known` ones (`context.jsonld`, `nodeinfo`, `solid`, `void`) at the origin root. Festipod's own routes (`/app`, `/as/actor/app`, `/catalog`) are mounted under the base path the same way, the public-surface allow-list matches paths relative to it (the two `/.well-known` endpoints against the full path), and the Solid-OIDC `client_id` is the requested URI rebuilt from the base URL as written — so it equals, byte for byte, the actor URI the backend mints and the `${backendUrl}/as/actor/app` the front end derives. At the root (`http://localhost:3003`, local dev) every decision is identical to the pre-base-path code. To verify: `bun test backend/services` (with and without `SEMAPPS_HOME_URL=https:///api/`). **First-boot traps.** -- The backend registers its app actor in its dataset with the domain it has on the FIRST boot: set the domains in Coolify before the first deployment; changing them later means deleting the two datasets and redeploying. +- The backend registers its app actor in its dataset with the domain it has on the FIRST boot: set the domains in Coolify before the first deployment. +- The backend runs with WebACL on, as the reference apps do, so its main dataset must be SECURE: the backend creates it so when it does not exist, and refuses to start ("the main dataset is not secure") on an existing one created otherwise. Starting again from nothing (domains changed, or a dataset created before WebACL was on): delete the two datasets in Fuseki AND the secure dataset's files Fuseki's delete leaves on disk (`databases/
`, `
Acl`, `
Mirror`, `configuration/
.ttl`), empty the stack's Redis (its cache keeps serving the old app actor, keys and access needs), redeploy — then every user installs the app again. The exact steps are in the compose file's header. - On a cold first boot, `GET app` answers from an in-memory copy of the actor taken before the access-need group got linked, so it lacks `interop:hasAccessNeedGroup` until the backend restarts (the actor itself, `as/actor/app`, is right). A real sign-in is unaffected — the pod reads the actor — but the rights matrix's programmatic install reads `/app`: restart the backend once after a first deployment. **Verified 2026-10-19, locally, not yet on Coolify**: both images built from a clean export of the tree, run against the local pod provider behind a same-origin proxy that routes `/api` and `/.well-known` to the backend unstripped with the Host header kept (as Traefik does) — the login flow, the rights matrix (98/98 hard lines) and the revocation probe all pass; the same images at the origin root pass them too. diff --git a/.project/handoff/refine-provider-abstraction.md b/.project/handoff/refine-provider-abstraction.md index 98190cb..fc02806 100644 --- a/.project/handoff/refine-provider-abstraction.md +++ b/.project/handoff/refine-provider-abstraction.md @@ -87,20 +87,15 @@ The reconstruction is the specification. Its source was read **once, deliberatel - `types` takes precedence over `shapeTreeUri` when both are set — the **opposite** of what the configuration type documents. - `custom` is not implemented, so there is **no escape hatch through Refine** for non-CRUD operations. - Collections are POSTable LDP resources (`/as/collection`) with `semapps:dereferenceItems` — *"all items will be dereferenced (if permissions allow)"*. That is how `event.participations` can come back as full objects for a reader who is allowed, and as URIs otherwise, in one read. Items are added/removed by SparqlPatch on `as:items`. -- `acl:Append` exists among the WAC modes and is really used in app access needs. **Whether it lets a third party insert an item without being able to remove one is NOT VERIFIED** — enforcement lives in `@semapps/webacl`, absent from the checkout. The structure does not depend on the answer: if it works that way the participant appends directly; otherwise the route is `apods:PostOutbox` to the owner's inbox, which is exactly the NextGraph shape, and only latency changes. - An app declares `accessNeeds` (`shapeTreeUri` + `accessMode`) plus special needs: `apods:CreateCollection`, `apods:CreateWacGroup`, `apods:PostOutbox`, `apods:QuerySparqlEndpoint`, `apods:UpdateWebId`, inbox/outbox reads. - **Backend-less apps are supported**: `onlineBackend` is false only when the app description document at the `clientId` URI is not fetchable. A static file suffices. -- A custom ontology prefix **must be registered at prefix.cc** (the Pod provider requires every ontology to have a known prefix) — this concerns Festipod's `fp:`. Shape trees must sit at a public URL, one per entity, and **cannot reference other shapes** (no sharing cascade). +- A Festipod **class** with its own shape tree needs `fp:` registered at prefix.cc (the pod registers the ontology of every class it creates a data registration for, and refuses an unknown prefix); shape trees must sit at a public URL, one per entity, and **cannot reference other shapes** (no sharing cascade). A Festipod **predicate** on an existing resource does not: verified 2026-10-29 on a profile with the owner's token (app-token path to confirm live). -**Four contributions this points to** (we may contribute to these providers): `getMany` must signal the unreadable instead of swallowing it; an append path into a collection one does not own; collection support as a resource with `dereferenceItems`; and a teardown for the auth provider's timer. +**Three contributions this points to** (we may contribute to these providers): `getMany` must signal the unreadable instead of swallowing it; collection support as a resource with `dereferenceItems`; and a teardown for the auth provider's timer. -## The deduplication question — answered, and still open +## Participation privacy and deduplication — settled -The attendance model (`brief_2026-07-20_attendance-set-model`, PO 2026-07-27) requires the creator to tell two references from the *same* person apart from two from different people **without knowing who**, or the count is not a count of people and a participant can inflate it. - -**Checked on this base: not solved.** A different problem is, and well. `materializeAttendance` (`src/shared/data/registration.ts`) keys its active set by a **per-deposit** `uid` minted from time plus randomness, so a broker re-sync replaying the same deposits converges — that is **replay idempotence**, not person identity. The count counts **deposits**: the same person joining twice counts twice. Further: the **plaintext `userId` travels in the deposit** and the cancellation fallback depends on it (a leave without a known `regUid` cancels the earliest still-active join for that `userId`), so the creator *does* know who and the anonymity the model rests on does not hold. Participations are in the **protected** scope rather than public, and withdrawal is still a deletion. And the gap was **never raised** through the channel meant for it. - -So both platforms count deposits rather than people, and the gap sits in **neither Refine provider** — polyfill on one side, server on the other. ActivityPods could arbitrate server-side because the server sees everything. +Settled 2026-10-29: `.project/concepts/functional-domain/decision_2026-10-29_participation-privacy-mechanism.md` — a private Join handled by the backend on emission, attendee lists of per-(person, event) member URNs (distinct-person counts, no identity), recognition by contacts only, a contacts-readable participations collection per person. ## Problems hit, and how they turned out @@ -148,7 +143,7 @@ What was missing for Festipod's premise — discover other users' public events - **Attendee lists stay world-readable for now** (2026-10-12) — an explicit deviation from the domain doctrine, where participation is in the protected scope (`functional-domain`, `knowledge_data-scopes-and-discovery`): anonymous readers of a public meeting point's attendee collection see its members' WebIDs, which embed usernames. The matrix tracks it as a KNOWN-DEVIATION line (printed, non-fatal, flags loudly the day it changes). Moving participation to the protected scope is a later task. - **A revoked app logs the user out** (2026-10-12): picker with a notice, never sent back to consent. -- **Defensive testing only** (2026-10-13): no automated check sends a forged or spoofed activity; such checks are MANUAL-CHECK lines (below). +- **Tests never break the dev environment** (user rule 2026-10-30, concept `bdd-testing`): attacks, forged or spoofed activities included, are allowed between the throwaway accounts a run creates and deletes. - **Trusted local network** (2026-10-13): no key rotation after the exposure below; it is recorded as a risk. Until `88f23b7` the Festipod backend served, anonymously and on all interfaces (reached from the LAN), an open `/sparql` over its `settings` dataset — the app actor's private key, the pod provider's password hashes and emails (the dataset is shared with the pod provider locally), webhook URLs, catalog snapshots — and the private key again at `/key` through the LDP catch-all. Fuseki still listens on all interfaces with `admin/admin`. **MANUAL checks** — kept out of the automated matrix because they need a crafted request; each is covered by backend unit tests and owes one manual run by a human: (1) a Delete posted to a user's OWN outbox that embeds a Tombstone of ANOTHER user's event must not de-index it (`catalog.service` ownership, `emitted-activity` re-read); (2) a forged pod notification (webhook) must not publish a private event, grant or revoke a read, or list/de-list anything; (3) a crafted delivery to `POST /as/actor/app/inbox` or `/.webhooks/`, and any write outside them, must change nothing (`public-surface`, `emitted-activity`). @@ -176,7 +171,7 @@ What was missing for Festipod's premise — discover other users' public events - Adding `## Needs` to the polyfill declaration is where the per-person discriminator belongs. It is **outward-facing** (the provider reads it on its next pull), so it awaits the user's go. - `acl:Append` behaviour, as above. - The router's prefix stripping, with the second backend. -- The four provider contributions. +- The three provider contributions. - Wiring the seam: DONE 2026-10-09 (T04 tree, tip `f8c2e3b`) — `FestipodDataContext` runs over Refine with the ActivityPods backend as the registered default; the join→collection loop is built but `@suspendu` until the app is installed on a pod (consent screen). Current state: `## Current gate state` above. The app-install blocker is CLEARED end-to-end 2026-10-12 (tips `3aa9131` → this state): the login → Solid-OIDC → consent → registration → app loop completes on the aligned stack, verified by an automated Playwright probe (fresh user: picker → login → consent → `/home` authenticated → event created → meeting point attached). The chain of causes, in the order they surfaced: (1) the pod provider's OIDC adapter resolves an unknown client_id by fetching it and requires a Solid-OIDC Client ID Document — `/app` serves it when the request carries the `JsonLdContext` header, the actor otherwise; (2) the platform stack has to run a coherent version — the app packages are pinned at npm latest (`@activitypods/app` 2.3.2, refine-providers 0.2.0) and the pod provider runs the release tag v2.3.12 (fresh pull + full data reset + the pod frontend needing `VITE_CONFIG_URL` in dev and redis remapped to :6390 per the cookbook); (3) on a cold start the actor's `interop:hasAccessNeedGroup` link races the access-need-group creation and is never attached — an idempotent heal in `backend/services/app.service.js` `started()` patches it when missing; (4) the auth provider's `registerApp` discovers the AppRegistration via a `Link: rel="interop:registeredAgent"` header the pod only returns when the requester's token identity (azp = the configured client_id) equals the registration's `registeredAgent`, which the pod stores under the app ACTOR uri — so the Solid-OIDC client_id IS the actor uri (`${backendUrl}/as/actor/app`), and `/as/actor/app` serves the actor / the Client ID Document by the same header trick through a standalone `client-id-doc` service (routing it to `app.get` deadlocked boot: the app service's own `awaitCreateComplete` polls the actor over HTTP while the service is still starting). The pinned contract carries a dated re-baseline section recording the registerApp/getAppStatus findings (authorized one-time re-read). The verify-compat shim was removed once the aligned stack made it redundant. A revoked app is now detected client-side (`4fc856f`, `d4fcb7e` — see `## T05`). The join→collection scenarios are re-enabled and green (5/5 smoke), and the full authenticated UI flow is banked as a durable gate: `bun run test:e2e-flow` (scripts/e2e-login-flow.ts — picker → login → consent → authenticated → event → meeting point, fresh user, benign-4xx classification, non-zero exit on any fatal ≥400). Platform fragility observed while un-suspending: hand-crafting an `apods:attendees` collection (instead of letting the backend attach it) crashed the festipod backend with an uncaught `Invalid URL` in `@activitypods/app` `pod-collections-handler.getGroupSlugFromCollectionUri(undefined)` — the scenario now reads the attached collection rather than building it; the crash path itself is platform-side. - Both usage declarations are named `usage_festipod.md`, so the bare stem is ambiguous as a wikilink — refer to either by folder path. - Driving `getAppStatus()`: DONE (`4fc856f`, `d4fcb7e`). Festipod relies on its `installed` member, which the reconstruction does not pin — recorded in the activitypods-providers usage declaration (constraint 9, need 3), together with its reliance on `create` sending `to` unchanged (constraint 10). diff --git a/.project/rules/INDEX.md b/.project/rules/INDEX.md new file mode 100644 index 0000000..9ff2614 --- /dev/null +++ b/.project/rules/INDEX.md @@ -0,0 +1,7 @@ +# Rules (local) + +Each rule below shows its one-line summary. **Read the full file** when a rule looks relevant — it carries the *why* and *how to apply* needed to use the rule with judgment. + +## activitypods + +- **festipod-only-reference-app-patterns** — N'écrire sur le pod ActivityPods que par des patterns des apps de référence du dossier ~/projects/activitypods/, sinon exception justifiée. → `.project/rules/activitypods/festipod-only-reference-app-patterns.md` diff --git a/.project/rules/activitypods/festipod-only-reference-app-patterns.md b/.project/rules/activitypods/festipod-only-reference-app-patterns.md new file mode 100644 index 0000000..8e7d0f2 --- /dev/null +++ b/.project/rules/activitypods/festipod-only-reference-app-patterns.md @@ -0,0 +1,15 @@ +--- +name: festipod-only-reference-app-patterns +summary: N'écrire sur le pod ActivityPods que par des patterns des apps de référence du dossier ~/projects/activitypods/, sinon exception justifiée. +group: activitypods +scope: local +created: 2026-10-28 +--- + +# Ne faire sur le pod que ce que font les apps de référence + +**Rule:** Dans Festipod, n'utiliser pour interagir avec la plateforme ActivityPods que des patterns déjà présents dans les applications de référence du dossier `~/projects/activitypods/`, sauf si aucune autre solution n'existe — auquel cas l'exception doit être nommée et justifiée explicitement avant de coder. + +**Why:** La validation live du 2026-10-28 a montré que tout chemin de plateforme non exercé par une app de référence est un terrain miné : le provisioning holder-side navigateur (création de conteneur dans `as/collection` + PATCH `/_acl` avec un token de session Solid-OIDC `azp`) a révélé deux bugs fournisseurs (500 après création effective du conteneur ; hang sans écriture dans `webacl.resource.addRights`), alors que les chemins utilisés par les apps de référence fonctionnent en production. Aucune app de référence ne provisionne d'infrastructure depuis le frontend : toute écriture pod hors données (conteneur, ACL, groupe, collection) se fait **backend-side, signée app-actor** via `signature.proxy.query`. + +**How to apply:** Références canoniques (2026-10-28, les mieux maintenues, ajoutées au dossier) : **`welcometomyplace`, `mutual-aid.app`, `portejunes`** — en priorité welcometomyplace, seule à exercer les patterns sociaux avancés. Secondaires : `mastopod` (access needs simples), `refine-providers/examples/antd-app` (frontend), et les services du app-framework (`activitypods/app-framework/app`). Avant toute écriture pod, vérifier le pattern dans ces sources ; s'il est absent des trois canoniques, ne pas coder : chercher une composition de patterns existants, et à défaut demander la décision utilisateur en nommant l'exception. Patterns welcometomyplace que Festipod réutilise : traiter un Join/Leave sur `onEmit` de l'outbox du participant (`registration.service.js`) ; collection lisible par un groupe = `pod-permissions.add({agentPredicate: 'acl:agentGroup', mode: 'acl:Read'})` sur une collection `pod-collections` (`attendees.service.js`), le groupe `/contacts` d'un utilisateur trouvé par `pod-wac-groups.getUriFromCollectionUri({collectionUri: apods:contacts})` — jamais un droit par élément de la liste `apods:contacts`, falsifiable par un `Accept` forgé ; notifier = `pod-notifications.send`, qui exige un backend en WebACL activé sur un dataset sécurisé, comme les trois apps de référence. Ne JAMAIS reprendre leur `addMember` de l'organisateur dans le groupe `/contacts` du participant : c'est un choix produit de welcometomyplace (événements privés), une fuite d'identité sous la règle de Festipod (`behavior_participation-listing-is-contacts-only`). Couvre l'usage de la plateforme, pas les choix produit propres à Festipod. diff --git a/.project/to-discuss.md b/.project/to-discuss.md index 34ea52f..2e16a39 100644 --- a/.project/to-discuss.md +++ b/.project/to-discuss.md @@ -1,3 +1,5 @@ # To discuss - [ ] clarifier le vocabulaire d'identité employé par Festipod (wallet, utilisateur, profil, username) et réconcilier decision_2026-07-06 (« identifiant = wallet ») et decision_2026-07-20 (« username dans le profil ») avec ce que le contrat publie aujourd'hui : `ensureIdentity()` ne prend aucun identifiant, et `username` ne désigne plus que `UserProfile.username` +- [ ] déclarer (usage_festipod) et faire confirmer par le fournisseur l'usage de `fetchJson` et `resolveContainerUri` (`@activitypods/refine-providers/utils`) pour l'upload d'images : utilisés par `useUploadImage` mais absents du contrat épinglé ; et le moyen de créer/lier un `as:Profile` quand le Pod n'en expose aucun (aujourd'hui : message seulement) +- [ ] afficher « en attente » dans l'écran des contacts les personnes à qui l'utilisateur a envoyé une demande non encore acceptée (elles voient déjà son profil et ses participations : le groupe /contacts les inclut dès l'envoi) — source possible : les `Offer` sans réponse de son outbox, ou une collection des demandes envoyées à demander en amont diff --git a/AGENTS.md b/AGENTS.md index 5ae7926..9c62f44 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,3 +38,7 @@ La connaissance détaillée vit dans `.project/concepts/` (système *concept*) : | `app-security` | Isolation déléguée au SDK (pas de contrôle d'accès dans les écrans), auth wallet, matrice d'autorisations cible | Pour **documenter** un fait projet : `/concept document ` (ne pas écrire en libre dans `.project/`). + +## Rules + +@.project/rules/INDEX.md diff --git a/backend/.env.example b/backend/.env.example index 8011071..f8013a0 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -6,9 +6,9 @@ SEMAPPS_FRONT_URL=http://localhost:4000 SEMAPPS_SHAPE_REPOSITORY_URL=https://shapes.activitypods.org/ SEMAPPS_PORT=3003 SEMAPPS_SPARQL_ENDPOINT=http://localhost:3030/ -SEMAPPS_MAIN_DATASET=settings +SEMAPPS_MAIN_DATASET=festipod SEMAPPS_JENA_USER=admin SEMAPPS_JENA_PASSWORD=admin SEMAPPS_REDIS_CACHE_URL=redis://localhost:6390/3 SEMAPPS_QUEUE_SERVICE_URL=redis://localhost:6390/4 -SEMAPPS_AUTH_ACCOUNTS_DATASET_NAME=settings +SEMAPPS_AUTH_ACCOUNTS_DATASET_NAME=settings-festipod diff --git a/backend/moleculer.config.js b/backend/moleculer.config.js index 0137df3..1835c38 100644 --- a/backend/moleculer.config.js +++ b/backend/moleculer.config.js @@ -1,4 +1,4 @@ -const { CacherMiddleware } = require('@semapps/webacl'); +const { WebAclMiddleware, CacherMiddleware } = require('@semapps/webacl'); const CONFIG = require('./config/config'); Error.stackTraceLimit = Infinity; @@ -42,7 +42,11 @@ module.exports = { middlewares: [ SkipOrphanBlankNodesCleanupMiddleware(), SystemCallWebIdMiddleware(), - CacherMiddleware(cacherConfig) + // As in the reference apps: the cacher before the WebACL middleware, which checks the read + // rights of every `ldp.resource.get` and gives each resource created in the main dataset the + // rights its container prescribes (the app actor and its public key readable by anyone, say). + CacherMiddleware(cacherConfig), + WebAclMiddleware({ baseUrl: CONFIG.HOME_URL }) ], logger: { type: 'Console', diff --git a/backend/services/app.service.js b/backend/services/app.service.js index f5194a2..c0b1ab9 100644 --- a/backend/services/app.service.js +++ b/backend/services/app.service.js @@ -47,6 +47,12 @@ module.exports = { accessMode: ['acl:Read', 'acl:Write'], preferredScope: 'interop:AllFromRegistry' }, + { + // The images users upload (event covers, avatars): the Pod's `file` container. + shapeTreeUri: urlJoin(CONFIG.SHAPE_REPOSITORY_URL, 'shapetrees/File'), + accessMode: ['acl:Read', 'acl:Write'], + preferredScope: 'interop:AllFromRegistry' + }, { shapeTreeUri: urlJoin(CONFIG.SHAPE_REPOSITORY_URL, 'shapetrees/vcard/Group'), accessMode: 'acl:Read', @@ -56,7 +62,6 @@ module.exports = { 'apods:ReadOutbox', 'apods:PostOutbox', 'apods:QuerySparqlEndpoint', - 'apods:CreateWacGroup', 'apods:CreateCollection', 'apods:UpdateWebId' ], @@ -124,29 +129,52 @@ module.exports = { // group then exists while the actor never gets `interop:hasAccessNeedGroup`, and both the // pod frontend (consent screen) and the pod backend (requirements discovery) read the // needs from that link — an empty consent registers the app with zero grants and the - // register flow loops. Idempotent: only patches when the link is missing. + // register flow loops. The heal itself can ALSO lose the race: it may run before the + // mixin has created the group (observed 2026-10-26 on a fresh dataset — the one-shot + // heal found no group and silently did nothing), so it polls for the group instead of + // checking once. Idempotent: only patches when the link is missing. const actorUri = urlJoin(CONFIG.HOME_URL, 'as/actor/app'); - const actor = await this.broker.call('ldp.resource.get', { - resourceUri: actorUri, - accept: 'application/ld+json', - webId: 'system' - }); - const link = actor && actor['interop:hasAccessNeedGroup']; - const hasLink = Array.isArray(link) ? link.length > 0 : Boolean(link); - if (!hasLink) { + const actorHasLink = async () => { + const actor = await this.broker.call('ldp.resource.get', { + resourceUri: actorUri, + accept: 'application/ld+json', + webId: 'system' + }); + const link = actor && actor['interop:hasAccessNeedGroup']; + return Array.isArray(link) ? link.length > 0 : Boolean(link); + }; + const findGroup = async () => { const groups = await this.broker.call('access-needs-groups.list', { filters: { 'http://www.w3.org/ns/solid/interop#accessNecessity': 'http://www.w3.org/ns/solid/interop#AccessRequired' }, accept: 'application/ld+json' }); - const group = groups && groups['ldp:contains'] && groups['ldp:contains'][0]; - if (group) { - await this.broker.call('actors.attachAccessNeedGroup', { - accessNeedGroupUri: group.id || group['@id'] - }); - this.logger.info(`Healed the actor's interop:hasAccessNeedGroup link to ${group.id || group['@id']}`); + return groups && groups['ldp:contains'] && groups['ldp:contains'][0]; + }; + // A started() handler must not block the broker's boot, but the link must + // exist before the first consent/register flow; ~1 min is far past the + // observed gap (seconds) while the dataset is empty. + const deadline = Date.now() + 60000; + for (;;) { + try { + if (await actorHasLink()) break; + const group = await findGroup(); + if (group) { + await this.broker.call('actors.attachAccessNeedGroup', { + accessNeedGroupUri: group.id || group['@id'] + }); + this.logger.info(`Healed the actor's interop:hasAccessNeedGroup link to ${group.id || group['@id']}`); + break; + } + } catch (e) { + this.logger.warn(`Access-need-group heal attempt failed: ${e.message}`); } + if (Date.now() >= deadline) { + this.logger.error('No access-need group appeared within 60s; the actor stays unlinked — consents will register zero grants'); + break; + } + await new Promise(r => setTimeout(r, 2000)); } } }; diff --git a/backend/services/attendance-ledger.js b/backend/services/attendance-ledger.js index 5e57dbc..0d5584e 100644 --- a/backend/services/attendance-ledger.js +++ b/backend/services/attendance-ledger.js @@ -1,5 +1,6 @@ -// The last participation act applied for each (meeting point, participant) — what makes attendance -// independent of the order notifications arrive in. +// The last participation act applied for each (meeting point, participant WebID) — what makes attendance +// independent of the order notifications arrive in, and what remembers which member URN that act put in +// (or took out of) the meeting point's attendee list. // // WHY. A participant's Join and Leave reach the backend as separate notifications, handled // concurrently; the per-meeting-point lock (`keyed-serializer.js`) serializes them, but in the order @@ -16,30 +17,61 @@ // attending, "leave then join" ends attending. All acts of one participant are stamped by her own pod, // so they share one clock. // +// THE MEMBER is STICKY per pair. The URN listed for a participant is computed from the secret on their +// profile, which they may rewrite between acts. So the entry remembers the URN once chosen and reuses it +// for every later act of the pair — `member` is persisted (`persistMember`) BEFORE the first attendee-list +// write, WRITE-ONCE (inserted only when absent, never replaced, not rewritten when an act is recorded), +// and never recomputed afterwards: a later Join keeps it, a Leave removes that one. This is what +// keeps the pair listed under exactly ONE URN even when an act fails half-way (the add lands, a later step +// throws, the act is left unrecorded) and the participant then rewrites their secret and acts again — +// without it, the second act would compute a second URN and the list would carry both. +// +// The member and the act are persisted SEPARATELY: `member` the moment a URN is first chosen for the pair, +// the act (its URI, its stamp, its kind) only once BOTH collections match it. So the entry may hold a +// member with no act yet (a first act that failed before recording) — `lastAttendance` returns it so the +// retry reuses the URN, while the absent act makes the retry the "first" act for ordering (`isNewerAct`). +// +// THE KEY is the participant's WebID, not the member URN. This exposes nothing new at rest: the entry +// already holds the act's URI, which lies in the participant's pod and so already identifies them. +// // WHERE IT LIVES. Like the catalog (`catalog-store.js`): in the backend's main dataset, DEFAULT graph // (persisted by Fuseki), so the rule holds across a backend restart. One entry per pair, under a minted -// `urn:festipod:attendance:` subject, with three Festipod predicates: the act's URI, its stamp, its kind. +// `urn:festipod:attendance:` subject, with four Festipod predicates: the act's URI, its stamp, its kind, +// the member URN applied. const { iriRef, stringLiteral } = require('./catalog-store'); const ACT = 'http://festipod.org/attendanceAct'; const PUBLISHED = 'http://festipod.org/attendancePublished'; const CHANGE = 'http://festipod.org/attendanceChange'; +const MEMBER = 'http://festipod.org/attendanceMember'; /** The subject of the (meeting point, participant) entry: both URIs percent-encoded into one URN. */ -function attendanceSubject(meetingPointUri, memberUri) { - return `urn:festipod:attendance:${encodeURIComponent(meetingPointUri)}:${encodeURIComponent(memberUri)}`; +function attendanceSubject(meetingPointUri, participantUri) { + return `urn:festipod:attendance:${encodeURIComponent(meetingPointUri)}:${encodeURIComponent(participantUri)}`; } -/** The last act applied for the pair: one row (act, published, change) or none. */ -function lastAttendanceQuery(meetingPointUri, memberUri) { - const s = iriRef(attendanceSubject(meetingPointUri, memberUri)); - return `SELECT ?act ?published ?change WHERE { ${s} <${ACT}> ?act ; <${PUBLISHED}> ?published ; <${CHANGE}> ?change } LIMIT 1`; +// The pair's entry, anchored on its sticky `member`: a row iff a URN has been chosen for the pair, the +// act fields bound only once an act was recorded (OPTIONAL — a member may be persisted with no act yet). +function lastAttendanceQuery(meetingPointUri, participantUri) { + const s = iriRef(attendanceSubject(meetingPointUri, participantUri)); + return `SELECT ?act ?published ?change ?member WHERE { ${s} <${MEMBER}> ?member . OPTIONAL { ${s} <${ACT}> ?act ; <${PUBLISHED}> ?published ; <${CHANGE}> ?change } } LIMIT 1`; } -/** Replace the pair's entry with `{ activityUri, published, change }`. One update = one transaction. */ -function recordAttendanceUpdate(meetingPointUri, memberUri, { activityUri, published, change }) { - const s = iriRef(attendanceSubject(meetingPointUri, memberUri)); +// Set the pair's sticky member URN ONLY IF IT HAS NONE: the member is written once and never replaced, +// so a write still in flight from an act that timed out cannot overwrite the URN a later act already +// chose and listed. The caller reads the entry back and applies whatever member it holds. +function persistMemberUpdate(meetingPointUri, participantUri, member) { + const s = iriRef(attendanceSubject(meetingPointUri, participantUri)); + return ` + INSERT { ${s} <${MEMBER}> ${stringLiteral(member)} } + WHERE { FILTER NOT EXISTS { ${s} <${MEMBER}> ?member } } + `; +} + +/** Replace the pair's recorded act `{ activityUri, published, change }`; its member is left as persisted. */ +function recordAttendanceUpdate(meetingPointUri, participantUri, { activityUri, published, change }) { + const s = iriRef(attendanceSubject(meetingPointUri, participantUri)); return ` DELETE { ${s} ?p ?o } INSERT { ${s} <${ACT}> ${iriRef(activityUri)} ; <${PUBLISHED}> ${stringLiteral(published)} ; <${CHANGE}> ${stringLiteral(change)} } @@ -66,23 +98,41 @@ const termValue = term => (term && typeof term === 'object' ? term.value : term) // ── Store operations: `ctx` is a moleculer context (anything with `call`) ── -/** The last act applied for the pair, `{ activityUri, published, change }`, or undefined. */ -async function lastAttendance(ctx, { dataset, meetingPointUri, memberUri }) { - const rows = await ctx.call('triplestore.query', { query: lastAttendanceQuery(meetingPointUri, memberUri), dataset, webId: 'system' }); +/** + * The pair's entry, `{ activityUri, published, change, member }`, or undefined when no URN was ever + * chosen for it. `member` is always set when a row is returned; the act fields are undefined when a + * member was persisted but no act recorded yet (a first act that failed before recording). + */ +async function lastAttendance(ctx, { dataset, meetingPointUri, participantUri }) { + const rows = await ctx.call('triplestore.query', { query: lastAttendanceQuery(meetingPointUri, participantUri), dataset, webId: 'system' }); const row = Array.isArray(rows) ? rows[0] : undefined; if (!row) return undefined; - return { activityUri: termValue(row.act), published: termValue(row.published), change: termValue(row.change) }; + return { activityUri: termValue(row.act), published: termValue(row.published), change: termValue(row.change), member: termValue(row.member) }; } -async function recordAttendance(ctx, { dataset, meetingPointUri, memberUri, act }) { - await ctx.call('triplestore.update', { query: recordAttendanceUpdate(meetingPointUri, memberUri, act), dataset, webId: 'system' }); +/** + * Persist `member` as the pair's sticky URN unless it already has one — before any attendee-list write + * (see the header) — then resolve the member the entry holds NOW: `member` itself, or the one another + * act persisted first. The caller applies that one, never its own candidate. + */ +async function persistMember(ctx, { dataset, meetingPointUri, participantUri, member }) { + await ctx.call('triplestore.update', { query: persistMemberUpdate(meetingPointUri, participantUri, member), dataset, webId: 'system' }); + const entry = await lastAttendance(ctx, { dataset, meetingPointUri, participantUri }); + if (!entry || !entry.member) throw new Error(`the member URN of ${participantUri} on ${meetingPointUri} could not be persisted`); + return entry.member; +} + +async function recordAttendance(ctx, { dataset, meetingPointUri, participantUri, act }) { + await ctx.call('triplestore.update', { query: recordAttendanceUpdate(meetingPointUri, participantUri, act), dataset, webId: 'system' }); } module.exports = { attendanceSubject, lastAttendanceQuery, + persistMemberUpdate, recordAttendanceUpdate, isNewerAct, lastAttendance, + persistMember, recordAttendance }; diff --git a/backend/services/attendees.service.js b/backend/services/attendees.service.js index 6a4d6b8..dde92dc 100644 --- a/backend/services/attendees.service.js +++ b/backend/services/attendees.service.js @@ -4,14 +4,17 @@ const CONFIG = require('../config/config'); const { neverThrowingMatcher, verifiedEmit, uriOf } = require('./emitted-activity'); const { guardedCreateAndAttach } = require('./collection-attach'); -// Attaches an `apods:attendees` collection (and a WAC group of the same members) to every -// `as:Event` created in a user's pod that this backend learns of through the outbox watcher — -// plain events as well as meeting points (observed 2026-10-12). A join adds the actor to it. +// Attaches an `apods:attendees` collection to every `as:Event` created in a user's pod that this +// backend learns of through the outbox watcher — plain events as well as meeting points (observed +// 2026-10-12). A join adds the participant's MEMBER URN to it (never a WebID — see +// registration.service.js, member-urn.js and decision_2026-10-29_participation-privacy-mechanism), +// so the collection's members are opaque URNs only readers of the participant's secret (they, their +// contacts, the app) can recognise, and no WAC group mirrors them. // // Who may read the collection: the pod creates it world-readable (`acl:Read` for `foaf:Agent`) — a -// platform default, observed 2026-10-12, not a choice made here. Whether attendee lists of a PUBLIC -// event SHOULD be world-readable is an open product question (the functional-domain doctrine places -// participation in the protected scope); this service does not settle it. What it does settle: the +// platform default, observed 2026-10-12, not a choice made here. The collection is the PUBLIC +// surface of a participation: a count of opaque members, no identity (the model, per +// knowledge_data-scopes-and-discovery — not an open question). What this service settles: the // collection it creates never stays more readable than its event. Once attached, it records that // collection's public read as Festipod's (`public-read.recordCreated`) and asks `public-read.reconcile` // to align the event AND its collection with the event's current public intent — granted while the @@ -26,7 +29,9 @@ module.exports = { ordered: false, summary: 'Meeting point attendees' }, - createWacGroup: true + // Members are member URNs, not agents — a mirrored WAC group would be meaningless + // (decision_2026-10-29_participation-privacy-mechanism). + createWacGroup: false }, dependencies: ['public-read'], // The mixin's create handler would act on the object embedded in the (unauthenticated) webhook diff --git a/backend/services/catalog-store.js b/backend/services/catalog-store.js index 4889934..0925df0 100644 --- a/backend/services/catalog-store.js +++ b/backend/services/catalog-store.js @@ -2,7 +2,7 @@ * The catalog index, persisted in the backend's own triplestore so it survives a * backend restart (it used to be process memory). * - * WHERE IT LIVES. In the backend's main dataset (`settings`), in the DEFAULT graph. + * WHERE IT LIVES. In the backend's main dataset (`SEMAPPS_MAIN_DATASET`), in the DEFAULT graph. * Not in a dedicated named graph: that dataset is assembled from TDB2 graphs, and only * the graphs its assembler declares are TDB2-backed — a triple written to any other * named graph is held in memory by Fuseki and lost when Fuseki restarts (verified on diff --git a/backend/services/catalog.service.js b/backend/services/catalog.service.js index ee11d9b..dfca3e1 100644 --- a/backend/services/catalog.service.js +++ b/backend/services/catalog.service.js @@ -22,6 +22,19 @@ function arrayOf(value) { */ const isListable = item => hasListedPublicIntent(item); +/** + * The creator attribution a catalog item carries — `dc:creator` as the event + * resource serves it, publicly: a bare IRI string or an embedded `{ id }`. + * An item without one was indexed from a resource that names no creator; it + * can never match an owner filter. + */ +function creatorOf(item) { + const creator = item?.['dc:creator']; + if (typeof creator === 'string') return creator; + if (creator && typeof creator === 'object' && typeof creator.id === 'string') return creator.id; + return undefined; +} + module.exports = { name: 'catalog', mixins: [PodResourcesHandlerMixin], @@ -109,11 +122,16 @@ module.exports = { }, actions: { discover: { + // An `owner` narrows the listing to what that actor declared — the + // catalog snapshot IS the event resource as the pod served it, with its + // public `dc:creator` attribution, so the filter judges the same body the + // listing serves. Without `owner`, every listed item is served, unchanged. async handler(ctx) { + const { owner } = ctx.params ?? {}; const { items, invalid } = await listEntries(ctx, { dataset: CONFIG.MAIN_DATASET }); if (invalid.length > 0) this.logger.warn(`Catalog skipped unreadable entries: ${invalid.join(', ')}`); // Filtered on every read, whatever wrote the store: only listed public items are served. - const listed = items.filter(isListable); + const listed = items.filter(item => isListable(item) && (owner === undefined || creatorOf(item) === owner)); return { '@context': 'https://www.w3.org/ns/activitystreams', type: 'Collection', diff --git a/backend/services/catalog.service.test.js b/backend/services/catalog.service.test.js index 76de35b..13b8d25 100644 --- a/backend/services/catalog.service.test.js +++ b/backend/services/catalog.service.test.js @@ -403,6 +403,56 @@ describe('catalog listing — only listed public items are served, shape unchang }); }); +describe('catalog discover — the owner filter narrows the listing to what an actor declared', () => { + const rowOf = item => ({ uri: { value: item.id }, snapshot: { value: JSON.stringify(item) } }); + // Declared events carry the creator attribution the pod serves publicly, as + // a bare IRI or embedded — both forms must be matched. + const alices = { ...listedEvent(ALICE), 'dc:creator': ALICE }; + const alicesEmbedded = { ...listedEvent(ALICE), id: `${ALICE}/data/e2`, 'dc:creator': { id: ALICE } }; + const bobs = { ...listedEvent(BOB), 'dc:creator': BOB }; + const noCreator = listedEvent('http://localhost:3000/carol'); + // Not listed, even though it is Alice's: the owner filter applies AFTER the + // listing rule, so a non-public event of hers is never served to anyone. + const alicesUnlisted = { ...event(ALICE, { to: BOB, content: 'only for a friend' }), 'dc:creator': ALICE }; + const stored = () => [rowOf(alices), rowOf(alicesEmbedded), rowOf(bobs), rowOf(noCreator), rowOf(alicesUnlisted)]; + + test('with an owner, only their listed items are served — dc:creator as a string or an embedded id', async () => { + const { svc } = service(); + const ctx = Object.assign(store({ rows: stored() }), { params: { owner: ALICE } }); + const result = await catalog.actions.discover.handler.call(svc, ctx); + expect(result.items).toEqual([alices, alicesEmbedded]); + expect(result.totalItems).toBe(2); + expect(JSON.stringify(result)).not.toContain('only for a friend'); + }); + + test('another owner gets only their own; the unlisted and creator-less items never match', async () => { + const { svc } = service(); + const result = await catalog.actions.discover.handler.call( + svc, + Object.assign(store({ rows: stored() }), { params: { owner: BOB } }) + ); + expect(result.items).toEqual([bobs]); + expect(result.totalItems).toBe(1); + + // An owner nobody matches: an honest empty listing. + const nobody = await catalog.actions.discover.handler.call( + svc, + Object.assign(store({ rows: stored() }), { params: { owner: 'http://localhost:3000/dan' } }) + ); + expect(nobody.items).toEqual([]); + expect(nobody.totalItems).toBe(0); + }); + + test('without owner (or without params at all) every listed item is served, unchanged', async () => { + const { svc } = service(); + const all = [alices, alicesEmbedded, bobs, noCreator]; + const bare = await catalog.actions.discover.handler.call(svc, store({ rows: stored() })); + expect(bare.items).toEqual(all); + const emptyParams = await catalog.actions.discover.handler.call(svc, Object.assign(store({ rows: stored() }), { params: {} })); + expect(emptyParams.items).toEqual(all); + }); +}); + describe('catalog startup — entries it would not serve are removed from its store', () => { const rowOf = item => ({ uri: { value: item.id }, snapshot: { value: JSON.stringify(item) } }); diff --git a/backend/services/collection-attach.js b/backend/services/collection-attach.js index 71ad096..afebee5 100644 --- a/backend/services/collection-attach.js +++ b/backend/services/collection-attach.js @@ -1,5 +1,5 @@ -// The `createAndAttach` action every Festipod collection handler uses (attendees, contacts), in place -// of the one `PodCollectionsHandlerMixin` (@activitypods/app 2.3.2) gives them. +// The `createAndAttach` action every Festipod collection handler uses (attendees, contacts, +// participations), in place of the one `PodCollectionsHandlerMixin` (@activitypods/app 2.3.2) gives them. // // The mixin's version calls `pod-collections.createAndAttach`, then derives a WAC group slug from the // collection URI it returns. That call returns undefined when it attaches nothing — the resource diff --git a/backend/services/collection-handlers.test.js b/backend/services/collection-handlers.test.js index c78b5a3..124e4f3 100644 --- a/backend/services/collection-handlers.test.js +++ b/backend/services/collection-handlers.test.js @@ -2,6 +2,7 @@ const { test, expect, describe } = require('bun:test'); const { PodCollectionsHandlerMixin } = require('@activitypods/app'); const attendees = require('./attendees.service'); const contacts = require('./contacts.service'); +const participations = require('./participations.service'); const ALICE = 'http://localhost:3000/alice'; const MALLORY = 'http://localhost:3000/mallory'; @@ -11,7 +12,7 @@ const PROFILE = `${ALICE}/data/profiles/me`; const CREATE = `${ALICE}/data/activities/create-1`; /** A schema bound like moleculer binds it: mixin methods first, the service's own over them. */ -function bind(schema, pod, { attached, groupFails = false } = {}) { +function bind(schema, pod, { attached, groupFails = false, recordFails = false } = {}) { const logs = { info: [], warn: [], error: [] }; const calls = []; const ctx = { @@ -23,6 +24,7 @@ function bind(schema, pod, { attached, groupFails = false } = {}) { } if (action === 'pod-collections.createAndAttach') return attached; if (action === 'pod-wac-groups.create' && groupFails) throw new Error('group creation failed'); + if (action === 'public-read.recordCreated' && recordFails) throw new Error('record failed'); return undefined; } }; @@ -45,25 +47,25 @@ const created = objectUri => ({ id: CREATE, type: 'Create', actor: ALICE, object const actions = calls => calls.map(c => c.action); describe('attendees — a verified Create attaches the collection, then aligns its public read with the event', () => { - test('a public event: collection attached, group created, then public-read.reconcile on the event', async () => { + test('a public event: collection attached, recorded, then reconciled — NO WAC group (members are member URNs, not agents)', async () => { const { calls, emit } = bind(attendees, { [CREATE]: created(E), [E]: { id: E, type: 'Event', to: 'as:Public' } }, { attached: C }); await emit('create', created(E), ALICE); expect(actions(calls).filter(a => a !== 'pod-resources.get')).toEqual([ 'pod-collections.createAndAttach', 'public-read.recordCreated', - 'pod-wac-groups.create', 'public-read.reconcile' ]); + expect(actions(calls)).not.toContain('pod-wac-groups.create'); expect(calls.find(c => c.action === 'public-read.recordCreated').params).toEqual({ resourceUri: C, actorUri: ALICE }); expect(calls.find(c => c.action === 'public-read.reconcile').params).toEqual({ resourceUri: E, actorUri: ALICE }); }); - test('the collection is recorded as Festipod\'s even when the WAC group creation after the attach fails', async () => { - const { calls, emit, logs } = bind(attendees, { [CREATE]: created(E), [E]: { id: E, type: 'Event', name: 'private' } }, { attached: C, groupFails: true }); + test('the reconcile still runs when the recording right after the attach fails', async () => { + const { calls, emit, logs } = bind(attendees, { [CREATE]: created(E), [E]: { id: E, type: 'Event', name: 'private' } }, { attached: C, recordFails: true }); await emit('create', created(E), ALICE); const order = actions(calls).filter(a => a !== 'pod-resources.get'); - expect(order).toEqual(['pod-collections.createAndAttach', 'public-read.recordCreated', 'pod-wac-groups.create', 'public-read.reconcile']); - expect(logs.error.some(m => m.includes('group creation failed'))).toBe(true); + expect(order).toEqual(['pod-collections.createAndAttach', 'public-read.recordCreated', 'public-read.reconcile']); + expect(logs.error.some(m => m.includes('record failed'))).toBe(true); }); test('a PRIVATE event: its collection is reconciled too (the pod made it world-readable; it must not stay so)', async () => { @@ -125,3 +127,29 @@ describe('contacts — the webhook is a hint, and nothing attached creates no gr expect(logs.error).toEqual([]); }); }); + +describe('participations — attached at a sign-up only, through the guarded createAndAttach', () => { + const profile = { id: PROFILE, type: ['as:Profile', 'vcard:Individual'] }; + + test('a profile Create attaches nothing: the service handles no activity', () => { + expect(Object.keys(participations.activities)).toEqual([]); + }); + + test('createAndAttach on the profile, with the participations predicate, and no WAC group', async () => { + const { svc, calls } = bind(participations, { [PROFILE]: profile }, { attached: `${ALICE}/data/as/collection/p1` }); + const uri = await svc.actions.createAndAttach({ resourceUri: PROFILE, actorUri: ALICE }); + expect(uri).toBe(`${ALICE}/data/as/collection/p1`); + expect(calls.find(c => c.action === 'pod-collections.createAndAttach').params).toMatchObject({ + resourceUri: PROFILE, + attachPredicate: 'http://festipod.org/participations', + actorUri: ALICE + }); + expect(actions(calls)).not.toContain('pod-wac-groups.create'); + }); + + test('nothing attached: undefined, nothing thrown', async () => { + const { svc, logs } = bind(participations, { [PROFILE]: profile }, { attached: undefined }); + await expect(svc.actions.createAndAttach({ resourceUri: PROFILE, actorUri: ALICE })).resolves.toBeUndefined(); + expect(logs.error).toEqual([]); + }); +}); diff --git a/backend/services/collection-items.js b/backend/services/collection-items.js new file mode 100644 index 0000000..40294bb --- /dev/null +++ b/backend/services/collection-items.js @@ -0,0 +1,55 @@ +// The items of a pod collection, read and checked with the pod's answer SEEN. +// +// The platform's `pod-collections` service (@activitypods/app 2.3.2) hides a failure of the pod: +// `getItems` answers `[]` whatever the GET returned (it never looks at the status), and `add` / +// `remove` resolve normally when the pod refuses the PATCH (a status ≥ 400 is only logged). A +// decision taken on such an answer is wrong without anything saying so: a Leave read against a +// failed read finds nobody to remove, and an act whose write was refused is recorded as applied. +// +// So the backend reads a collection through `pod-resources.get`, where the status is visible, and +// verifies every write by reading the collection back. The writes themselves stay the platform's +// calls (`pod-collections.add` / `.remove`, through the collection handlers' `add` / `remove`). +// +// readItems(ctx, { collectionUri, actorUri }) → the item URIs; throws unless the pod answers 200 +// with that very collection, its items inline (a paged collection is not read here: its items +// are not in the root, and reading them as "none" is the defect this module exists to avoid). +// expectItem(ctx, { collectionUri, itemUri, actorUri, present }) → resolves when the collection, +// read again, holds `itemUri` (`present`) or does not (`!present`); throws otherwise — the write +// just made did not take effect. + +const { arrayOf } = require('@semapps/ldp'); +const { uriOf } = require('./emitted-activity'); + +const AS = 'https://www.w3.org/ns/activitystreams#'; + +/** The item URIs a collection node lists inline, under any spelling of `items` / `orderedItems`. */ +function itemsOf(collection) { + const keys = ['items', 'orderedItems', 'as:items', 'as:orderedItems', `${AS}items`, `${AS}orderedItems`]; + const value = keys.map(key => collection[key]).find(v => v !== undefined); + return arrayOf(value) + .map(uriOf) + .filter(uri => typeof uri === 'string'); +} + +/** Whether a collection root sends its items to pages (`first`) instead of listing them. */ +const isPaged = collection => + ['first', 'as:first', `${AS}first`].some(key => collection[key] !== undefined) && itemsOf(collection).length === 0; + +async function readItems(ctx, { collectionUri, actorUri }) { + const { status, body } = await ctx.call('pod-resources.get', { resourceUri: collectionUri, actorUri }); + if (status !== 200 || !body || typeof body !== 'object') { + throw new Error(`the pod does not return the collection ${collectionUri} (HTTP ${status})`); + } + if (uriOf(body) !== collectionUri) throw new Error(`the pod returned another resource for ${collectionUri}`); + if (isPaged(body)) throw new Error(`the collection ${collectionUri} is paged: its items cannot be read from its root`); + return itemsOf(body); +} + +async function expectItem(ctx, { collectionUri, itemUri, actorUri, present }) { + const holds = (await readItems(ctx, { collectionUri, actorUri })).includes(itemUri); + if (holds !== present) { + throw new Error(`${collectionUri} ${present ? 'does not hold' : 'still holds'} ${itemUri} after the ${present ? 'add' : 'remove'}: the pod did not apply it`); + } +} + +module.exports = { itemsOf, readItems, expectItem }; diff --git a/backend/services/collection-items.test.js b/backend/services/collection-items.test.js new file mode 100644 index 0000000..0f2f7de --- /dev/null +++ b/backend/services/collection-items.test.js @@ -0,0 +1,64 @@ +const { test, expect, describe } = require('bun:test'); +const { itemsOf, readItems, expectItem } = require('./collection-items'); + +const C = 'http://localhost:3000/alice/data/as/collection/c1'; +const ALICE = 'http://localhost:3000/alice'; +const A = 'urn:festipod:userref:aa'; +const B = 'urn:festipod:userref:bb'; + +/** A ctx whose `pod-resources.get` answers `reply` (a `{ status, body }`, or a function of the call). */ +const pod = reply => { + const calls = []; + return { + calls, + call: async (action, params) => { + calls.push({ action, params }); + if (action !== 'pod-resources.get') throw new Error(`unexpected call ${action}`); + return typeof reply === 'function' ? reply(params) : reply; + } + }; +}; +const collection = extra => ({ status: 200, body: { id: C, type: 'Collection', ...extra } }); + +describe('itemsOf — the item URIs a collection lists inline', () => { + test('every spelling of items / orderedItems; strings and nodes; none', () => { + expect(itemsOf({ items: [A, B] })).toEqual([A, B]); + expect(itemsOf({ items: A })).toEqual([A]); + expect(itemsOf({ items: [{ id: A }, { '@id': B }] })).toEqual([A, B]); + expect(itemsOf({ orderedItems: [A] })).toEqual([A]); + expect(itemsOf({ 'as:items': [A] })).toEqual([A]); + expect(itemsOf({ 'https://www.w3.org/ns/activitystreams#items': [{ '@id': A }] })).toEqual([A]); + expect(itemsOf({ totalItems: 0 })).toEqual([]); + }); +}); + +describe('readItems — a failed read throws, it never means "empty"', () => { + test('a 200 with the collection: its items, read as the given actor', async () => { + const ctx = pod(collection({ items: [A, B] })); + expect(await readItems(ctx, { collectionUri: C, actorUri: ALICE })).toEqual([A, B]); + expect(ctx.calls).toEqual([{ action: 'pod-resources.get', params: { resourceUri: C, actorUri: ALICE } }]); + expect(await readItems(pod(collection({ totalItems: 0 })), { collectionUri: C, actorUri: ALICE })).toEqual([]); + }); + + test('any other status, no body, another resource, a paged root: throws', async () => { + for (const status of [0, 401, 403, 404, 500]) { + await expect(readItems(pod({ status }), { collectionUri: C, actorUri: ALICE })).rejects.toThrow(`(HTTP ${status})`); + } + await expect(readItems(pod({ status: 200 }), { collectionUri: C, actorUri: ALICE })).rejects.toThrow('does not return the collection'); + await expect(readItems(pod({ status: 200, body: { id: `${C}-other`, items: [A] } }), { collectionUri: C, actorUri: ALICE })).rejects.toThrow('another resource'); + await expect(readItems(pod(collection({ first: `${C}?page=1`, totalItems: 3 })), { collectionUri: C, actorUri: ALICE })).rejects.toThrow('is paged'); + }); +}); + +describe('expectItem — a write is checked by reading the collection back', () => { + test('present after an add, absent after a remove: resolves', async () => { + await expect(expectItem(pod(collection({ items: [A] })), { collectionUri: C, itemUri: A, actorUri: ALICE, present: true })).resolves.toBeUndefined(); + await expect(expectItem(pod(collection({ items: [B] })), { collectionUri: C, itemUri: A, actorUri: ALICE, present: false })).resolves.toBeUndefined(); + }); + + test('a write that did not take effect, or a read-back that fails: throws', async () => { + await expect(expectItem(pod(collection({ items: [B] })), { collectionUri: C, itemUri: A, actorUri: ALICE, present: true })).rejects.toThrow(`does not hold ${A} after the add`); + await expect(expectItem(pod(collection({ items: [A] })), { collectionUri: C, itemUri: A, actorUri: ALICE, present: false })).rejects.toThrow(`still holds ${A} after the remove`); + await expect(expectItem(pod({ status: 500 }), { collectionUri: C, itemUri: A, actorUri: ALICE, present: false })).rejects.toThrow('(HTTP 500)'); + }); +}); diff --git a/backend/services/core/core.service.js b/backend/services/core/core.service.js index 47d4188..c5043cd 100644 --- a/backend/services/core/core.service.js +++ b/backend/services/core/core.service.js @@ -25,10 +25,12 @@ module.exports = { }, api: { port: CONFIG.PORT, - // In front of EVERY route — these below and the ones CoreService's services add (the LDP - // catch-all among them, which with `webacl: false` would serve the whole `settings` dataset, - // the app's private key included): only the allow-listed public endpoints pass, anything else - // is a 404 for every caller. See public-surface.js. + // In front of EVERY route — these below and the ones CoreService's services add, the LDP + // catch-all among them: only the allow-listed public endpoints pass, anything else is a 404 for + // every caller. WebACL already filters what the catch-all serves (the main dataset is a secure + // one); the gate is defence in depth, so that a resource whose rights are too wide is still not + // served over HTTP — the backend's own services reach its data through internal calls. See + // public-surface.js. use: [createPublicSurfaceGate(BASE_PATH)], routes: [ { @@ -81,12 +83,10 @@ module.exports = { } ] }, - webacl: false, void: false, - // No public SPARQL endpoint. CoreService mounts one at `/sparql` unless this is `false`, and - // with `webacl: false` it answers anonymous queries over the whole `settings` dataset — the - // app actor's key, the webhook listener URLs, the catalog store and, locally, the pod - // provider's accounts (observed 2026-10-12). Nothing in Festipod queries it. + // No public SPARQL endpoint. CoreService mounts one at `/sparql` unless this is `false`; WebACL + // would filter its answers by the caller's rights, but nothing in Festipod queries it, so it is + // not mounted at all (defence in depth, like the gate above). sparqlEndpoint: false } }; diff --git a/backend/services/emitted-activity.js b/backend/services/emitted-activity.js index 67dd7a2..032f339 100644 --- a/backend/services/emitted-activity.js +++ b/backend/services/emitted-activity.js @@ -71,7 +71,11 @@ function asTypesOf(node) { }); } -const hasAsType = (node, name) => asTypesOf(node).includes(AS + name); +// `name` is an AS name (`Event`), an `as:` name, or a full IRI: only bare names get the AS namespace. +const hasAsType = (node, name) => { + const iri = name.startsWith('as:') ? AS + name.slice('as:'.length) : name.includes(':') ? name : AS + name; + return asTypesOf(node).includes(iri); +}; const ACTIVITY_TYPES = new Set(['Create', 'Update', 'Delete', 'Join', 'Leave']); @@ -86,8 +90,8 @@ const ANY_POD = Symbol('any pod'); * `activity` is what the watcher handed over (a URI or a node — only its id is used). `type` is the * activity type the handler expects. `emitterUri` is the owner of the outbox the notification names, * or `null` for an inbox notification (the emitter is then the stored activity's actor). The object - * must lie in the pod of `objectOwnerUri`, or anywhere with `ANY_POD`. `objectType` is the - * ActivityStreams type the stored object must declare (`Event`, `Profile`; not checked for a Delete). + * must lie in the pod of `objectOwnerUri`, or anywhere with `ANY_POD`. `objectType` is the type the + * stored object must declare — an ActivityStreams name or a full IRI; not checked for a Delete. * `read(uri)` reads a resource as the box owner and resolves `{ status, body }` (`status` 0 when the * request itself failed). Never throws for a refusal; a throwing `read` propagates. */ @@ -195,7 +199,8 @@ function verifiedHandler(box, type, handle, verify) { * An `onEmit` (outbox handler) that runs `handle(ctx, verdict, actorUri)` only for an activity * `verifyActivity` accepts as emitted by `actorUri`, the outbox owner. `objectType` is the type the * stored object must declare; `objectIn` is `'emitter'` (default: the object is in the emitter's pod) - * or `'any'` (the handler checks where the object lies, e.g. the event a Join names). + * or `'any'` (the handler checks where the object lies, e.g. the meeting point a Join names, in its + * creator's pod). */ function verifiedEmit(type, handle, { objectType, objectIn = 'emitter' } = {}) { if (objectIn !== 'emitter' && objectIn !== 'any') throw new Error(`Unknown objectIn ${objectIn}`); diff --git a/backend/services/emitted-activity.test.js b/backend/services/emitted-activity.test.js index 63837ca..cf6fbc8 100644 --- a/backend/services/emitted-activity.test.js +++ b/backend/services/emitted-activity.test.js @@ -264,3 +264,37 @@ describe('verifiedReceive / verifiedEmit with objectIn "any"', () => { expect(svc.logger.w).toContain(`not in the pod of ${BOB}`); }); }); + +describe('verifiedEmit — a Join from a participant\'s outbox (the registration flow)', () => { + const MP = `${ALICE}/data/events/mp1`; + const JOIN = `${BOB}/outbox/join-1`; + const join = { id: JOIN, type: 'Join', actor: BOB, object: MP }; + + test('the activity AND the meeting point are read through the outbox owner\'s access, the stored object handed over', async () => { + const reads = []; + const stored = { [JOIN]: join, [MP]: { id: MP, type: 'Event', context: `${ALICE}/data/events/e1` } }; + const ctx = { + call: async (action, params) => { + reads.push([action, params.resourceUri, params.actorUri]); + const body = stored[params.resourceUri]; + return body ? { status: 200, body } : { status: 404 }; + } + }; + const ran = []; + const service = { name: 'test', logger: { info() {}, warn() {}, error() {} } }; + // The webhook body claims another object: only the stored one counts. + await verifiedEmit('Join', async (_ctx, verdict) => ran.push(verdict.object), { objectType: 'Event', objectIn: 'any' }) + .call(service, ctx, { ...join, object: { id: `${ALICE}/data/events/other`, type: 'Event' } }, BOB); + expect(reads).toEqual([['pod-resources.get', JOIN, BOB], ['pod-resources.get', MP, BOB]]); + expect(ran).toEqual([stored[MP]]); + }); + + test('a Join whose stored actor is not the outbox owner is refused', async () => { + const ctx = { call: async (_action, { resourceUri }) => (resourceUri === JOIN ? { status: 200, body: { ...join, actor: ALICE } } : { status: 200, body: { id: MP, type: 'Event' } }) }; + const ran = []; + const service = { name: 'test', logger: { info() {}, warn(m) { this.w = m; }, error() {} } }; + await verifiedEmit('Join', async () => ran.push(true), { objectType: 'Event', objectIn: 'any' }).call(service, ctx, join, BOB); + expect(ran).toEqual([]); + expect(service.logger.w).toContain('not attributed to'); + }); +}); diff --git a/backend/services/keyed-serializer.js b/backend/services/keyed-serializer.js index 2740d36..dcdba36 100644 --- a/backend/services/keyed-serializer.js +++ b/backend/services/keyed-serializer.js @@ -35,8 +35,10 @@ // 30 s: a serialized decision makes a handful of pod round-trips — read the object, read up to two // ACLs, write up to two (public-read); read, then one store write (catalog); a wait of at most 1.5 s -// for a fresh collection, a read and one write (attendance) — each answering in tens of milliseconds -// on the local stack, a few seconds at worst on a loaded one. 30 s is over ten times the slowest +// for a fresh collection, the participant's participations collection made ready (a profile and an +// ACL read; at its creation, the create-and-attach, a profile re-read, one ACL write and one group +// grant), a read, two writes and their two read-backs (attendance) — +// each answering in tens of milliseconds on the local stack, a few seconds at worst on a loaded one. 30 s is over ten times the slowest // legitimate run, and short enough that a stalled pod holds one object's decisions for half a minute // rather than until the backend restarts. const DEFAULT_TIMEOUT_MS = 30000; diff --git a/backend/services/member-urn.js b/backend/services/member-urn.js new file mode 100644 index 0000000..896b247 --- /dev/null +++ b/backend/services/member-urn.js @@ -0,0 +1,53 @@ +// The member URN an attendee list records for a participant, and the secret it is derived from +// (decision_2026-10-29_participation-privacy-mechanism). +// +// THE URN. `urn:festipod:userref:` + the lowercase-hex sha256 of the string +// " " (single spaces), where the event URI is the meeting +// point's anchor (`as:context`). It is the same for one person on every meeting point of one event — +// so the per-event count of distinct URNs is publicly computable — and unrelated from one event to +// another. Only whoever can read the secret can compute it: the person, their contacts, the app. The +// backend computes it from the secret; a client never supplies one, so it cannot inflate a count. +// ("festipod" here is the URN namespace, unrelated to the http://festipod.org/ vocabulary.) +// +// THE SECRET lives in the participant's `as:Profile` under `http://festipod.org/participationSecret`: +// 32 random bytes as 64 lowercase hex characters, written by the participant's browser before the +// first sign-up. Anything else — absent, several values, another length, uppercase — is no secret. + +const crypto = require('crypto'); + +const MEMBER_URN_PREFIX = 'urn:festipod:userref:'; +const PARTICIPATION_SECRET = 'http://festipod.org/participationSecret'; +const SECRET_PATTERN = /^[0-9a-f]{64}$/; + +const listOf = value => (value === undefined || value === null ? [] : Array.isArray(value) ? value : [value]); + +/** The string a JSON-LD value holds: a string, or a value node's `@value`; undefined otherwise. */ +const stringOf = value => { + if (typeof value === 'string') return value; + if (value && typeof value === 'object' && typeof value['@value'] === 'string') return value['@value']; + return undefined; +}; + +/** + * participationSecretOf(profile) → the participant's secret (64 lowercase hex characters), or + * undefined when the profile carries none that is usable. Reads the predicate under its full IRI or + * the `fp:` CURIE; exactly one value is accepted. + */ +function participationSecretOf(profile) { + if (!profile || typeof profile !== 'object') return undefined; + const values = listOf(profile[PARTICIPATION_SECRET] ?? profile['fp:participationSecret']); + if (values.length !== 1) return undefined; + const secret = stringOf(values[0]); + return secret !== undefined && SECRET_PATTERN.test(secret) ? secret : undefined; +} + +/** memberUrn({ participantUri, eventUri, secret }) → `urn:festipod:userref:`. */ +function memberUrn({ participantUri, eventUri, secret }) { + for (const [name, value] of Object.entries({ participantUri, eventUri, secret })) { + if (typeof value !== 'string' || value.length === 0) throw new Error(`memberUrn needs a ${name}`); + } + const digest = crypto.createHash('sha256').update(`${participantUri} ${eventUri} ${secret}`, 'utf8').digest('hex'); + return MEMBER_URN_PREFIX + digest; +} + +module.exports = { MEMBER_URN_PREFIX, PARTICIPATION_SECRET, participationSecretOf, memberUrn }; diff --git a/backend/services/member-urn.test.js b/backend/services/member-urn.test.js new file mode 100644 index 0000000..0ee1aa3 --- /dev/null +++ b/backend/services/member-urn.test.js @@ -0,0 +1,50 @@ +const { test, expect, describe } = require('bun:test'); +const crypto = require('crypto'); +const { MEMBER_URN_PREFIX, PARTICIPATION_SECRET, participationSecretOf, memberUrn } = require('./member-urn'); + +const BOB = 'http://localhost:3000/bob'; +const CAROL = 'http://localhost:3000/carol'; +const EVENT = 'http://localhost:3000/alice/data/events/e1'; +const OTHER_EVENT = 'http://localhost:3000/alice/data/events/e2'; +const SECRET = '0123456789abcdef'.repeat(4); + +describe('memberUrn — urn:festipod:userref: ")>', () => { + test('the contract: the lowercase-hex sha256 of the three values joined by single spaces', () => { + const expected = crypto.createHash('sha256').update(`${BOB} ${EVENT} ${SECRET}`).digest('hex'); + expect(memberUrn({ participantUri: BOB, eventUri: EVENT, secret: SECRET })).toBe(`urn:festipod:userref:${expected}`); + expect(MEMBER_URN_PREFIX).toBe('urn:festipod:userref:'); + expect(memberUrn({ participantUri: BOB, eventUri: EVENT, secret: SECRET })).toMatch(/^urn:festipod:userref:[0-9a-f]{64}$/); + }); + + test('deterministic for one person and one event; different for another event, person or secret', () => { + const base = { participantUri: BOB, eventUri: EVENT, secret: SECRET }; + const urn = memberUrn(base); + expect(memberUrn({ ...base })).toBe(urn); + expect(memberUrn({ ...base, eventUri: OTHER_EVENT })).not.toBe(urn); + expect(memberUrn({ ...base, participantUri: CAROL })).not.toBe(urn); + expect(memberUrn({ ...base, secret: 'f'.repeat(64) })).not.toBe(urn); + }); + + test('a missing value is a programming error, never a URN', () => { + expect(() => memberUrn({ participantUri: BOB, eventUri: undefined, secret: SECRET })).toThrow('eventUri'); + expect(() => memberUrn({ participantUri: BOB, eventUri: EVENT, secret: '' })).toThrow('secret'); + }); +}); + +describe('participationSecretOf — 64 lowercase hex characters under fp:participationSecret, or nothing', () => { + test('read under the full IRI, the CURIE, or as a value node', () => { + expect(PARTICIPATION_SECRET).toBe('http://festipod.org/participationSecret'); + expect(participationSecretOf({ [PARTICIPATION_SECRET]: SECRET })).toBe(SECRET); + expect(participationSecretOf({ 'fp:participationSecret': SECRET })).toBe(SECRET); + expect(participationSecretOf({ [PARTICIPATION_SECRET]: { '@value': SECRET } })).toBe(SECRET); + expect(participationSecretOf({ [PARTICIPATION_SECRET]: [SECRET] })).toBe(SECRET); + }); + + test('absent, malformed or ambiguous: no secret', () => { + for (const value of [undefined, '', SECRET.toUpperCase(), SECRET.slice(1), `${SECRET}0`, 'g'.repeat(64), 42, { id: SECRET }, [SECRET, 'f'.repeat(64)]]) { + expect(participationSecretOf({ [PARTICIPATION_SECRET]: value })).toBeUndefined(); + } + expect(participationSecretOf(undefined)).toBeUndefined(); + expect(participationSecretOf({ name: 'Bob' })).toBeUndefined(); + }); +}); diff --git a/backend/services/participation-world.js b/backend/services/participation-world.js new file mode 100644 index 0000000..8f3dddb --- /dev/null +++ b/backend/services/participation-world.js @@ -0,0 +1,294 @@ +// TEST SUPPORT ONLY (required by registration.service.test.js and participations.service.test.js): +// a fake ActivityPods stack for the participation flow — the pods' resources, collections and ACLs, +// the backend's attendance ledger and the notifications sent — with the registration and +// participations services bound to it the way moleculer binds them, so that a call from one service +// to the other runs the other's real code. Every call is recorded. +// +// The platform calls answer as @activitypods/app 2.3.2 does, failures included: `pod-resources.get` +// carries the pod's status (no body on a failure); `pod-collections.getItems` reads through it and +// answers `[]` whatever the status; `pod-collections.add` / `.remove` (and the attendees handler's +// `add` / `remove`, which run them) resolve normally when the pod refuses the PATCH; and +// `pod-collections.createAndAttach` returns the collection it created even when the pod refuses the +// PATCH that links it to the resource. + +const { PodCollectionsHandlerMixin } = require('@activitypods/app'); +const { arrayOf } = require('@semapps/ldp'); +const registration = require('./registration.service'); +const participations = require('./participations.service'); + +const HOST = 'http://localhost:3000'; +const APP = 'http://localhost:4000/as/actor/app'; +const ALICE = `${HOST}/alice`; // creates the meeting points +const BOB = `${HOST}/bob`; // participates +const CAROL = `${HOST}/carol`; // participates too +const MALLORY = `${HOST}/mallory`; + +const EVENT1 = `${HOST}/dave/data/events/festival`; +const EVENT2 = `${HOST}/dave/data/events/concert`; +const FP_SECRET = 'http://festipod.org/participationSecret'; +const FP_PARTICIPATIONS = 'http://festipod.org/participations'; +const SECRETS = { [BOB]: 'b0'.repeat(32), [CAROL]: 'c0'.repeat(32), [ALICE]: 'a0'.repeat(32) }; + +const profileOf = actorUri => `${actorUri}/data/profiles/me`; +const contactsOf = actorUri => `${actorUri}/contacts`; +const groupOf = actorUri => `${HOST}/_groups${new URL(actorUri).pathname}/contacts`; +const attendeesOf = meetingPointUri => `${meetingPointUri}-attendees`; + +const actor = (uri, extra = {}) => ({ id: uri, type: 'Person', url: profileOf(uri), 'apods:contacts': contactsOf(uri), ...extra }); +const profile = (uri, extra = {}) => ({ id: profileOf(uri), type: 'Profile', name: uri.split('/').pop(), [FP_SECRET]: SECRETS[uri], ...extra }); +const meetingPoint = (uri, extra = {}) => ({ + id: uri, + type: 'Event', + name: `Rendez-vous ${uri.split('/').pop()}`, + context: EVENT1, + 'dc:creator': ALICE, + 'apods:attendees': attendeesOf(uri), + to: 'as:Public', + ...extra +}); +// The pod stamps `published` on every activity posted to an outbox. +const activity = (type, actorUri, objectUri, published, n = 1) => ({ + id: `${actorUri}/data/activities/${type.toLowerCase()}-${objectUri.split('/').pop()}-${n}`, + type, + actor: actorUri, + object: objectUri, + published +}); + +/** + * The ACL the pod gives a collection the app creates: an OWN public read (observed 2026-10-12) and + * an OWN `#Control` for the app (observed 2026-10-29 on a participations collection). + */ +const createdCollectionAcl = uri => [ + { '@id': `${HOST}/_acl${new URL(uri).pathname}#Read`, 'acl:mode': 'acl:Read', 'acl:agentClass': 'foaf:Agent' }, + { '@id': `${HOST}/_acl${new URL(uri).pathname}#Control`, 'acl:mode': 'acl:Control', 'acl:agent': APP } +]; + +const ACT = 'http://festipod.org/attendanceAct'; +const MEMBER = 'http://festipod.org/attendanceMember'; + +/** + * world(options) → { ctx, calls, state, registration, participations, logs, emit } + * + * options: `stored` (uri → body; the default actors and profiles are added), `items` (collection → + * items; every collection a stored resource names under `apods:attendees` exists, empty when unset), + * `acls` (collection → authorizations), `ledger` (attendance subject → act with its member URN), + * `delays` (`read:`, `create`, `attendees.add`, `attendees.remove`, `pod-collections.add`, + * `pod-collections.remove` → ms), `fail`, `timeoutMs` (the registration lock's time limit). + * + * `fail` (read at each call, so a test may change it between acts): `read` (uri → the status a GET of + * it answers, with no body), `attendeesWrite` / `participationsWrite` (the pod refuses every PATCH of + * an attendee list / a participations collection: the call resolves, nothing changes, the attempt is + * kept in `state.refusedWrites`), `attach` (the pod creates the collection but refuses the PATCH that + * links it), `putStatus` (the status of an ACL PUT), `grant`, `aclRead`, `notify`. + * + * A collection (a key of `state.items`) answers a GET as the pod serves an unpaged collection: its + * `items` inline. + */ +function world({ stored = {}, items = {}, acls = {}, ledger = {}, delays = {}, fail = {}, timeoutMs } = {}) { + const calls = []; + const logs = { info: [], warn: [], error: [] }; + const logger = { info: m => logs.info.push(m), warn: m => logs.warn.push(m), error: m => logs.error.push(m) }; + const state = { + stored: { + [ALICE]: actor(ALICE), + [BOB]: actor(BOB), + [CAROL]: actor(CAROL), + [profileOf(ALICE)]: profile(ALICE), + [profileOf(BOB)]: profile(BOB), + [profileOf(CAROL)]: profile(CAROL), + ...stored + }, + items: JSON.parse(JSON.stringify(items)), + acls: JSON.parse(JSON.stringify(acls)), + ledger: { ...ledger }, + notifications: [], + created: [], + refusedWrites: [] + }; + // The attendees handler attached each meeting point's list when the meeting point was created. + for (const body of Object.values(state.stored)) { + const list = body && body['apods:attendees']; + if (typeof list === 'string' && !(list in state.items)) state.items[list] = []; + } + const wait = ms => (ms ? new Promise(resolve => setTimeout(resolve, ms)) : undefined); + const resourceOfAcl = url => url.replace(`${HOST}/_acl`, HOST); + /** A GET as the pod answers it (`pod-resources.get`): the status, and the body on a 200 only. */ + const read = uri => { + const failed = fail.read && fail.read[uri]; + if (failed) return { ok: false, status: failed }; + if (Object.prototype.hasOwnProperty.call(state.items, uri)) { + return { ok: true, status: 200, body: { id: uri, type: 'Collection', items: [...state.items[uri]] } }; + } + const body = state.stored[uri]; + return body ? { ok: true, status: 200, body } : { ok: false, status: 404 }; + }; + + let registrationSvc; + let participationsSvc; + const ctx = { + call: async (action, params) => { + calls.push({ action, params }); + if (action.startsWith('participations.')) { + return participationsSvc.actions[action.slice('participations.'.length)](params); + } + switch (action) { + case 'app.get': + return { id: APP }; + case 'pod-resources.get': + await wait(delays[`read:${params.resourceUri}`]); + return read(params.resourceUri); + case 'pod-collections.getItems': { + // As the platform does: the body's items, whatever the status — `[]` on a failed read. + const { body } = read(params.collectionUri); + return arrayOf(body?.items || body?.orderedItems); + } + case 'attendees.add': + case 'pod-collections.add': + case 'attendees.remove': + case 'pod-collections.remove': { + // The attendees handler's add/remove run `pod-collections.add`/`.remove` as the creator; the + // participations handler's, as the participant. A refused PATCH resolves, as on the platform. + await wait(delays[action]); + if (fail[action.startsWith('attendees.') ? 'attendeesWrite' : 'participationsWrite']) { + state.refusedWrites.push({ action, ...params }); + return undefined; + } + const list = (state.items[params.collectionUri] = state.items[params.collectionUri] || []); + if (action.endsWith('.add')) { + if (!list.includes(params.itemUri)) list.push(params.itemUri); + } else { + state.items[params.collectionUri] = list.filter(item => item !== params.itemUri); + } + return undefined; + } + case 'pod-collections.createAndAttach': { + // As the platform does: read the resource, then create, then attach — with a gap between + // the read and the attach, where a concurrent creation can slip in. The attach PATCH is not + // checked: the created collection's URI is returned even when the pod refused it. + const before = state.stored[params.resourceUri]; + await wait(delays.create === undefined ? 10 : delays.create); + if (!before || before[params.attachPredicate] !== undefined) return undefined; + const uri = `${params.actorUri}/data/as/collection/participations-${state.created.length + 1}`; + state.created.push(uri); + state.items[uri] = []; + state.acls[uri] = createdCollectionAcl(uri); + if (fail.attach) return uri; + const current = state.stored[params.resourceUri]; + const link = { id: uri }; + const existing = current[params.attachPredicate]; + state.stored[params.resourceUri] = { ...current, [params.attachPredicate]: existing === undefined ? link : [].concat(existing, link) }; + return uri; + } + case 'pod-wac-groups.getUriFromCollectionUri': { + const { origin, pathname } = new URL(params.collectionUri); + return `${origin}/_groups${pathname}`; + } + case 'pod-permissions.fetch': { + if (fail.aclRead) return { status: 500 }; + const authorizations = state.acls[resourceOfAcl(params.url)]; + return authorizations ? { status: 200, body: { '@graph': authorizations } } : { status: 404 }; + } + case 'pod-permissions.add': { + if (fail.grant) return false; + const acl = (state.acls[params.uri] = state.acls[params.uri] || []); + const id = `${HOST}/_acl${new URL(params.uri).pathname}#Read`; + let rule = acl.find(a => a['@id'] === id); + if (!rule) acl.push((rule = { '@id': id, 'acl:mode': 'acl:Read' })); + rule[params.agentPredicate] = [...new Set([].concat(rule[params.agentPredicate] ?? [], params.agentUri))]; + return true; + } + case 'signature.proxy.query': { + if (params.method !== 'PUT') throw new Error(`unexpected proxy ${params.method} ${params.url}`); + if (fail.putStatus) return { status: fail.putStatus }; + const uri = resourceOfAcl(params.url); + const inherited = (state.acls[uri] || []).filter(a => String(a['@id']).includes('#Default')); + state.acls[uri] = [...inherited, ...JSON.parse(params.body)['@graph']]; + return { status: 204 }; + } + case 'triplestore.query': { + // As the real SELECT, anchored on ` ?member`: no row for an entry without a member; + // the act fields unbound (absent) until an act is recorded. + const subject = /<(urn:festipod:attendance:[^>]+)>/.exec(params.query)[1]; + const last = state.ledger[subject]; + if (!last || last.member === undefined) return []; + const row = { member: { value: last.member } }; + if (last.activityUri !== undefined) Object.assign(row, { act: { value: last.activityUri }, published: { value: last.published }, change: { value: last.change } }); + return [row]; + } + case 'triplestore.update': { + const subject = /<(urn:festipod:attendance:[^>]+)>/.exec(params.query)[1]; + const entry = (state.ledger[subject] = state.ledger[subject] || {}); + // `recordAttendance`: replaces the act fields, leaves the member as persisted. + const act = new RegExp(`<${ACT}> <([^>]+)> ; <[^>]+> "([^"]*)" ; <[^>]+> "([^"]*)"`).exec(params.query); + if (act) { + Object.assign(entry, { activityUri: act[1], published: act[2], change: act[3] }); + return undefined; + } + // `persistMember`: INSERT … WHERE { FILTER NOT EXISTS { member } } — set only when absent. + const member = new RegExp(`<${MEMBER}> "([^"]*)"`).exec(params.query); + if (member && entry.member === undefined) entry.member = member[1]; + return undefined; + } + case 'pod-notifications.send': + if (fail.notify) throw new Error('the app outbox is down'); + state.notifications.push(params); + return undefined; + default: + throw new Error(`unexpected call ${action}`); + } + } + }; + + // The participations service, bound like collection-handlers.test.js binds a collection handler. + participationsSvc = { + name: participations.name, + settings: { ...PodCollectionsHandlerMixin.settings, ...participations.settings }, + logger, + actions: {} + }; + participations.created.call(participationsSvc); + for (const [name, fn] of Object.entries({ ...PodCollectionsHandlerMixin.methods, ...participations.methods })) { + participationsSvc[name] = fn.bind(participationsSvc); + } + for (const [name, def] of Object.entries({ ...PodCollectionsHandlerMixin.actions, ...participations.actions })) { + participationsSvc.actions[name] = (params, opts) => def.handler.call(participationsSvc, { ...opts, params, call: ctx.call }); + } + + registrationSvc = { name: registration.name, logger }; + registration.created.call(registrationSvc); + if (timeoutMs) { + const { createKeyedSerializer } = require('./keyed-serializer'); + registrationSvc.serialize = createKeyedSerializer({ timeoutMs }); + } + for (const [name, fn] of Object.entries(registration.methods)) registrationSvc[name] = fn.bind(registrationSvc); + + /** Notifies the registration service of an activity emitted in `actorUri`'s outbox. */ + const emit = (key, hint, actorUri) => registration.activities[key].onEmit.call(registrationSvc, ctx, hint, actorUri); + + return { ctx, calls, state, logs, registration: registrationSvc, participations: participationsSvc, emit }; +} + +module.exports = { + world, + activity, + meetingPoint, + actor, + profile, + profileOf, + contactsOf, + groupOf, + attendeesOf, + createdCollectionAcl, + HOST, + APP, + ALICE, + BOB, + CAROL, + MALLORY, + EVENT1, + EVENT2, + SECRETS, + FP_SECRET, + FP_PARTICIPATIONS +}; diff --git a/backend/services/participations.service.js b/backend/services/participations.service.js new file mode 100644 index 0000000..e753439 --- /dev/null +++ b/backend/services/participations.service.js @@ -0,0 +1,191 @@ +const urlJoin = require('url-join'); +const { PodCollectionsHandlerMixin } = require('@activitypods/app'); +const { arrayOf } = require('@semapps/ldp'); +const CONFIG = require('../config/config'); +const { isInActorPod } = require('./actor-pod'); +const { createKeyedSerializer } = require('./keyed-serializer'); +const { uriOf } = require('./emitted-activity'); +const { guardedCreateAndAttach } = require('./collection-attach'); +const { hasInheritedPublicRead, hasOwnPublicRead, revocationGraph, ownReaders, aclUriOf, readAcl, putOwnRights } = require('./public-read-acl'); + +const FP_PARTICIPATIONS = 'http://festipod.org/participations'; + +/** The collection URIs a profile links under `fp:participations` (full IRI or CURIE). */ +const participationsLinksOf = profile => + arrayOf(profile[FP_PARTICIPATIONS] ?? profile['fp:participations']) + .map(uriOf) + .filter(uri => typeof uri === 'string'); + +// A person's participations collection (decision_2026-10-29_participation-privacy-mechanism): the +// person-side record of the meeting points they joined, for themself and for their contacts. An +// unordered `as:Collection` in the participant's pod, attached to their `as:Profile` under +// `http://festipod.org/participations`, whose items are meeting point URIs — added on a Join and +// removed on a Leave by registration.service.js, acting as the participant. +// +// Who may read it: its owner, the app, and the participant's `/contacts` WAC group — through ONE +// `acl:agentGroup` grant on the collection's own `#Read` rule (the welcometomyplace pattern), the +// group URI derived from the `apods:contacts` collection (`pod-wac-groups.getUriFromCollectionUri`). +// The GROUP, not the `apods:contacts` LIST: a received `Accept` of a contact `Offer` is added to the +// list with no prior request checked (platform defect reported upstream), so the list is forgeable — +// a stranger could grant themself read; the group gains a member only through the person's OWN +// emitted activities (a contact request they send, an acceptance they emit), which a forged received +// activity cannot do. (The group does admit the target of a request the person SENT before it is +// accepted, and keeps a removed contact — platform behaviours, both deliberate here: see the e2e.) +// And never anyone else: the pod creates a collection world-readable (`acl:Read` for `foaf:Agent`, +// observed 2026-10-12 on the attendee lists), and a participations collection readable by strangers +// would list a person's events to anyone. +// +// `syncReaders` makes that true from the collection's ACL as the pod serves it NOW, read as the +// participant: the pod's own public read goes (the `revocationGraph` PUT of `public-read-acl.js` — +// `pod-permissions.remove` cannot do it, see there), then the `/contacts` group gets its grant if it +// has none (`pod-permissions.add`, the welcometomyplace grant call). It runs on every Join (`ensure`, +// before the meeting point is added). The grant names a STABLE group URI, so it never needs revisiting +// when the person's contacts change — the pod keeps the group's membership, nothing here to re-sync. +// Idempotent: on a collection already in that state, one ACL read and nothing written. A failure +// throws — the act that needed it is not recorded, the next one retries. +// +// Created at a person's first sign-up, never on a profile's Create (no activity handler here): a +// profile with no collection has no participation to list. One run at a time per person — two Joins of +// one person on two meeting points run concurrently and would otherwise both find no collection and +// attach one each. +module.exports = { + name: 'participations', + mixins: [PodCollectionsHandlerMixin], + settings: { + shapeTreeUri: urlJoin(CONFIG.SHAPE_REPOSITORY_URL, 'shapetrees/as/Profile'), + attachPredicate: FP_PARTICIPATIONS, + collectionOptions: { + ordered: false, + summary: 'Festipod participations' + }, + // Items are meeting points, not agents: no mirrored WAC group. + createWacGroup: false + }, + dependencies: ['pod-permissions'], + // Replaces the mixin's whole map (moleculer does not merge a custom schema key): no handler, so + // no collection is attached to a profile when it is created. + activities: {}, + created() { + this.serialize = createKeyedSerializer(); + }, + actions: { + // Nothing attached → no WAC group (see collection-attach.js). + createAndAttach: guardedCreateAndAttach, + /** The collection the participant's profile links now, or undefined (see `collectionOf`). */ + collectionOf: { + params: { + actorUri: { type: 'string' }, + profileUri: { type: 'string' } + }, + async handler(ctx) { + return this.collectionOf(ctx, ctx.params); + } + }, + /** The participant's collection, created if none and readable by their `/contacts` group only (see `ensure`). */ + ensure: { + params: { + actorUri: { type: 'string' }, + profileUri: { type: 'string' }, + contactsUri: { type: 'string', optional: true } + }, + async handler(ctx) { + return this.ensure(ctx, ctx.params); + } + } + }, + methods: { + /** + * The collection `profileUri` (the profile of `actorUri`) links NOW — read from the pod as the + * participant — or undefined when it links none. Throws when the profile cannot be read, links + * several, or links one outside the participant's pod (ignored: nothing is written to it). + */ + async collectionOf(ctx, { actorUri, profileUri }) { + if (!isInActorPod(profileUri, actorUri)) throw new Error(`the profile ${profileUri} is not in the pod of ${actorUri}`); + const { status, body } = await ctx.call('pod-resources.get', { resourceUri: profileUri, actorUri }); + if (status !== 200 || !body || uriOf(body) !== profileUri) { + throw new Error(`the pod does not return the profile ${profileUri} (HTTP ${status})`); + } + const links = participationsLinksOf(body); + if (links.length > 1) throw new Error(`the profile ${profileUri} links several participations collections`); + if (links.length === 1 && !isInActorPod(links[0], actorUri)) { + throw new Error(`the profile ${profileUri} links a participations collection outside the pod of ${actorUri}: ignored`); + } + return links[0]; + }, + /** + * The participant's collection, ready to receive a meeting point: the one the profile links, or + * one created and attached now when it links none; then readable by the participant's `/contacts` + * WAC group and by no one else (`syncReaders`). One run at a time per participant. Resolves the + * collection URI; throws when any of this cannot be made true — nothing may then be added to it. + * + * After an attach, the collection used is the one the profile links when READ AGAIN, never the + * URI the attach returned: the platform's `createAndAttach` returns the collection it created even + * when the pod refused the profile PATCH that links it (it does not check that write), and returns + * nothing when the profile gained a link meanwhile (another app). A created collection the profile + * does not link is left unused, empty — its contacts could never find it. + */ + async ensure(ctx, { actorUri, profileUri, contactsUri }) { + return this.serialize(actorUri, async signal => { + let collectionUri = await this.collectionOf(ctx, { actorUri, profileUri }); + if (!collectionUri) { + const attached = await this.actions.createAndAttach({ resourceUri: profileUri, actorUri }, { parentCtx: ctx }); + collectionUri = await this.collectionOf(ctx, { actorUri, profileUri }); + if (!collectionUri) { + throw new Error( + attached + ? `the pod created ${attached} but did not link it to ${profileUri}: left unused` + : `no participations collection could be attached to ${profileUri}` + ); + } + if (attached === collectionUri) this.logger.info(`Attached the participations collection ${collectionUri} to ${profileUri}`); + else if (attached) this.logger.warn(`${profileUri} links ${collectionUri}, not the collection ${attached} just created: that one is left unused`); + } + await this.syncReaders(ctx, { collectionUri, actorUri, contactsUri, signal }); + return collectionUri; + }); + }, + /** + * Makes `collectionUri` readable by the participant's `/contacts` WAC group (one `acl:agentGroup` + * grant on its own `#Read` rule, the group URI derived from their `apods:contacts` collection) and + * by no one else: the pod's own public read is removed first (the `revocationGraph` PUT, one call, + * the app keeping its `#Control`), then the group is granted read if it has none. The grant names a + * stable group URI whose membership the pod keeps, so it is set once and never re-synced. Gives up + * before any write once its time is out (`signal`). Idempotent: on a collection already in that + * state, one ACL read and nothing written. Throws when the ACL cannot be read, the pod refuses a + * change, or the collection stays world-readable through a rule inherited from its container (not + * removable here) — the Join that needed it is then not recorded, and retries. + */ + async syncReaders(ctx, { collectionUri, actorUri, contactsUri, signal }) { + if (!contactsUri || !isInActorPod(contactsUri, actorUri)) { + throw new Error(`${actorUri} names no contacts collection in their pod: who may read ${collectionUri} is unknown`); + } + const groupUri = await ctx.call('pod-wac-groups.getUriFromCollectionUri', { collectionUri: contactsUri }); + const acl = await readAcl(ctx, collectionUri, actorUri); + if (!acl.authorizations) throw new Error(`the ACL of ${collectionUri} could not be read (HTTP ${acl.status})`); + if (hasInheritedPublicRead(acl.authorizations)) { + throw new Error(`${collectionUri} is world-readable through a rule inherited from its container: not removable here`); + } + if (hasOwnPublicRead(acl.authorizations)) { + if (signal && signal.aborted) throw new Error(`out of time before removing the public read of ${collectionUri}`); + const document = revocationGraph(acl.authorizations, collectionUri, actorUri, aclUriOf(collectionUri)); + const status = await putOwnRights(ctx, collectionUri, document); + if (status !== 204 && status !== 200) { + throw new Error(`the pod refused to remove the public read of ${collectionUri} (HTTP ${status})`); + } + this.logger.info(`Removed the public read of ${collectionUri}`); + } + if (!ownReaders(acl.authorizations).agentGroup.includes(groupUri)) { + if (signal && signal.aborted) throw new Error(`out of time before granting the contacts group read on ${collectionUri}`); + const added = await ctx.call('pod-permissions.add', { + uri: collectionUri, + agentPredicate: 'acl:agentGroup', + agentUri: groupUri, + mode: 'acl:Read', + actorUri + }); + if (!added) throw new Error(`the pod refused the read grant of the contacts group ${groupUri} on ${collectionUri}`); + this.logger.info(`Granted the contacts group ${groupUri} read on ${collectionUri}`); + } + } + } +}; diff --git a/backend/services/participations.service.test.js b/backend/services/participations.service.test.js new file mode 100644 index 0000000..603d399 --- /dev/null +++ b/backend/services/participations.service.test.js @@ -0,0 +1,155 @@ +const { test, expect, describe } = require('bun:test'); +const participations = require('./participations.service'); +const { hasOwnPublicRead, ownReaders } = require('./public-read-acl'); +const { world, profile, profileOf, contactsOf, groupOf, createdCollectionAcl, APP, ALICE, BOB, MALLORY, FP_PARTICIPATIONS } = require('./participation-world'); + +const ensure = (w, extra = {}) => w.participations.actions.ensure({ actorUri: BOB, profileUri: profileOf(BOB), contactsUri: contactsOf(BOB), ...extra }); +const collectionOf = w => w.participations.actions.collectionOf({ actorUri: BOB, profileUri: profileOf(BOB) }); +const EXISTING = `${BOB}/data/as/collection/participations-existing`; +const linked = uri => ({ [profileOf(BOB)]: profile(BOB, { [FP_PARTICIPATIONS]: { id: uri } }) }); +const aclId = (uri, rule) => `http://localhost:3000/_acl${new URL(uri).pathname}#${rule}`; +const appControl = uri => ({ '@id': aclId(uri, 'Control'), 'acl:mode': 'acl:Control', 'acl:agent': APP }); +/** The /contacts WAC group that may read Bob's participations collection (what the grant names). */ +const GROUP = groupOf(BOB); +/** A collection readable by Bob's /contacts group, the app keeping its Control. */ +const groupRead = uri => ({ '@id': aclId(uri, 'Read'), 'acl:mode': 'acl:Read', 'acl:agentGroup': GROUP }); +const protectedAcl = uri => [groupRead(uri), appControl(uri)]; +/** The collection created at the first sign-up (the world names the first one `participations-1`). */ +const CREATED = `${BOB}/data/as/collection/participations-1`; +/** Who the collection's own #Read rule lets read, plus every inherited rule's readers. */ +const readersOf = (w, uri) => ownReaders(w.state.acls[uri]); +const writes = w => w.calls.filter(c => ['pod-collections.createAndAttach', 'pod-permissions.add', 'signature.proxy.query'].includes(c.action)); + +describe('participations — the collection is attached at the first sign-up, never on a profile Create', () => { + test('no activity handler, the full-IRI attach predicate, unordered, no mirrored group', () => { + expect(participations.activities).toEqual({}); + expect(participations.settings.attachPredicate).toBe('http://festipod.org/participations'); + expect(participations.settings.collectionOptions.ordered).toBe(false); + expect(participations.settings.createWacGroup).toBe(false); + }); +}); + +describe('participations.collectionOf — the collection the profile links now', () => { + test('none, one, one outside the pod, several, an unreadable profile', async () => { + expect(await collectionOf(world())).toBeUndefined(); + expect(await collectionOf(world({ stored: linked(EXISTING) }))).toBe(EXISTING); + expect(await collectionOf(world({ stored: { [profileOf(BOB)]: profile(BOB, { [FP_PARTICIPATIONS]: EXISTING }) } }))).toBe(EXISTING); // a plain IRI value + await expect(collectionOf(world({ stored: linked(`${MALLORY}/data/as/collection/x`) }))).rejects.toThrow('outside the pod'); + await expect(collectionOf(world({ stored: { [profileOf(BOB)]: profile(BOB, { [FP_PARTICIPATIONS]: [{ id: EXISTING }, { id: `${EXISTING}-2` }] }) } }))).rejects.toThrow('several'); + await expect(collectionOf(world({ stored: { [profileOf(BOB)]: undefined } }))).rejects.toThrow('does not return the profile'); + }); + + test('a profile outside the participant\'s pod is never read', async () => { + const w = world(); + await expect(w.participations.actions.collectionOf({ actorUri: BOB, profileUri: profileOf(MALLORY) })).rejects.toThrow('not in the pod'); + expect(w.calls.some(c => c.action === 'pod-resources.get')).toBe(false); + }); +}); + + +describe('participations.ensure — a collection readable by the participant\'s /contacts group', () => { + test('no collection: one is created and attached, the /contacts group granted read, the pod\'s public read removed', async () => { + const w = world(); + const uri = await ensure(w); + expect(uri).toBe(CREATED); + expect(w.state.created).toEqual([uri]); + expect(w.state.stored[profileOf(BOB)][FP_PARTICIPATIONS]).toEqual({ id: uri }); + const attach = w.calls.find(c => c.action === 'pod-collections.createAndAttach'); + expect(attach.params).toMatchObject({ resourceUri: profileOf(BOB), attachPredicate: FP_PARTICIPATIONS, actorUri: BOB }); + const grants = w.calls.filter(c => c.action === 'pod-permissions.add').map(c => c.params); + expect(grants).toEqual([{ uri, agentPredicate: 'acl:agentGroup', agentUri: GROUP, mode: 'acl:Read', actorUri: BOB }]); + expect(hasOwnPublicRead(w.state.acls[uri])).toBe(false); + expect(readersOf(w, uri)).toEqual({ agent: [], agentClass: [], agentGroup: [GROUP] }); + // The group URI is DERIVED from her apods:contacts collection; the list itself is never read. + expect(w.calls.find(c => c.action === 'pod-wac-groups.getUriFromCollectionUri').params).toEqual({ collectionUri: contactsOf(BOB) }); + expect(w.calls.some(c => c.action === 'pod-collections.getItems')).toBe(false); + }); + + test('the public read goes FIRST (one PUT, the app keeping its Control), then the group grant', async () => { + const w = world(); + const uri = await ensure(w); + const order = writes(w).map(c => c.action); + expect(order).toEqual(['pod-collections.createAndAttach', 'signature.proxy.query', 'pod-permissions.add']); + const put = w.calls.find(c => c.action === 'signature.proxy.query'); + expect(put.params.url).toBe(`http://localhost:3000/_acl${new URL(uri).pathname}`); + expect(put.params.actorUri).toBe(APP); + const graph = JSON.parse(put.params.body)['@graph']; + expect(JSON.stringify(graph)).not.toContain('foaf:Agent'); + expect(graph.some(n => n['@id'].endsWith('#Control') && n['acl:agent'] === APP)).toBe(true); + }); + + test('no contact yet: the group is granted all the same — its membership is the pod\'s business', async () => { + const w = world(); + const uri = await ensure(w); + expect(readersOf(w, uri)).toEqual({ agent: [], agentClass: [], agentGroup: [GROUP] }); + // No per-contact acl:agent grant is ever made; the group carries everyone. + expect(w.calls.every(c => c.action !== 'pod-permissions.add' || c.params.agentPredicate === 'acl:agentGroup')).toBe(true); + }); + + test('idempotent: on a collection already readable by the group, the ACL reads, nothing written', async () => { + const w = world({ stored: linked(EXISTING), acls: { [EXISTING]: protectedAcl(EXISTING) } }); + expect(await ensure(w)).toBe(EXISTING); + expect(await ensure(w)).toBe(EXISTING); + expect(writes(w)).toEqual([]); + expect(w.calls.filter(c => c.action === 'pod-permissions.fetch')).toHaveLength(2); + }); + + test('an existing collection still world-readable: reused, the public read removed, the group granted', async () => { + const w = world({ stored: linked(EXISTING), acls: { [EXISTING]: createdCollectionAcl(EXISTING) } }); + expect(await ensure(w)).toBe(EXISTING); + expect(w.state.created).toEqual([]); + expect(hasOwnPublicRead(w.state.acls[EXISTING])).toBe(false); + expect(readersOf(w, EXISTING)).toEqual({ agent: [], agentClass: [], agentGroup: [GROUP] }); + }); + + test('an existing collection granting the group but still world-readable: the public read goes, the grant is not repeated', async () => { + const bothOnRead = { '@id': aclId(EXISTING, 'Read'), 'acl:mode': 'acl:Read', 'acl:agentGroup': GROUP, 'acl:agentClass': 'foaf:Agent' }; + const w = world({ stored: linked(EXISTING), acls: { [EXISTING]: [bothOnRead, appControl(EXISTING)] } }); + await ensure(w); + expect(hasOwnPublicRead(w.state.acls[EXISTING])).toBe(false); + expect(readersOf(w, EXISTING)).toEqual({ agent: [], agentClass: [], agentGroup: [GROUP] }); + expect(writes(w).map(c => c.action)).toEqual(['signature.proxy.query']); // the PUT only, no repeated grant + }); + + test('one creation per participant: two concurrent calls attach ONE collection', async () => { + const w = world({ delays: { create: 30 } }); + const [a, b] = await Promise.all([ensure(w), ensure(w)]); + expect(a).toBe(b); + expect(w.state.created).toHaveLength(1); + }); + + test('nothing attached (the profile gained a link meanwhile): the linked collection is used', async () => { + const w = world({ stored: linked(EXISTING), acls: { [EXISTING]: protectedAcl(EXISTING) } }); + // collectionOf saw no link at first: simulate by an attach that finds one. + const original = w.participations.collectionOf; + let first = true; + w.participations.collectionOf = async (...args) => (first ? ((first = false), undefined) : original(...args)); + expect(await ensure(w)).toBe(EXISTING); + expect(w.state.created).toEqual([]); + }); + + test('a collection the pod creates but does not link (the profile PATCH refused): ensure throws, the collection is never used', async () => { + const w = world({ fail: { attach: true } }); + await expect(ensure(w)).rejects.toThrow(`the pod created ${CREATED} but did not link it`); + expect(w.state.created).toEqual([CREATED]); + expect(w.state.stored[profileOf(BOB)][FP_PARTICIPATIONS]).toBeUndefined(); + // Not protected, not granted: nothing is done with a collection no contact could find. + expect(writes(w).map(c => c.action)).toEqual(['pod-collections.createAndAttach']); + // The profile is read again after the attach: the link counts, not what the attach returned. + expect(w.calls.filter(c => c.action === 'pod-resources.get' && c.params.resourceUri === profileOf(BOB))).toHaveLength(2); + }); + + test('every failure throws — nothing may then be added to the collection', async () => { + await expect(ensure(world({ fail: { putStatus: 403 } }))).rejects.toThrow('refused to remove the public read'); + await expect(ensure(world({ stored: linked(EXISTING), acls: { [EXISTING]: [appControl(EXISTING)] }, fail: { grant: true } }))).rejects.toThrow('refused the read grant of the contacts group'); + await expect(ensure(world({ fail: { aclRead: true } }))).rejects.toThrow('could not be read'); + await expect(ensure(world(), { contactsUri: undefined })).rejects.toThrow('names no contacts collection'); + await expect(ensure(world(), { contactsUri: `${MALLORY}/contacts` })).rejects.toThrow('names no contacts collection'); + const inherited = world({ + stored: linked(EXISTING), + acls: { [EXISTING]: [...protectedAcl(EXISTING), { '@id': 'http://localhost:3000/_acl/bob/data/as/collection#DefaultRead', 'acl:mode': 'acl:Read', 'acl:agentClass': 'foaf:Agent' }] } + }); + await expect(ensure(inherited)).rejects.toThrow('inherited'); + expect(writes(inherited)).toEqual([]); + }); +}); diff --git a/backend/services/public-read-acl.js b/backend/services/public-read-acl.js index 8bcd129..3577182 100644 --- a/backend/services/public-read-acl.js +++ b/backend/services/public-read-acl.js @@ -14,7 +14,7 @@ // removing the foaf:Agent triple alone would leave the own set empty and the PUT would be refused. // `revocationGraph` therefore keeps the owner as `acl:agent` of `#Read` when nothing else remains — // the owner already reads via the default, so no right is gained or lost — and preserves any other -// own agent triples (e.g. a future per-contact grant) unchanged. +// own agent triples (e.g. the `/contacts` group a participations collection grants read to) unchanged. // // NARROW: only the public READ goes. The pod keys own rules by mode (`#Read`, `#Write`, `#Append`, // `#Control`); the `foaf:Agent` triple is removed from the `#Read` rule alone, so a `foaf:Agent` on @@ -28,6 +28,15 @@ // the compacted `foaf:Agent` the pod returns (removes nothing), and it drops any authorization // whose removed predicate becomes empty even when other agent predicates remain (would empty the // set → 400). This module PUTs a correct graph instead. +// +// `ownReaders` says who a resource's own `#Read` rule lets read (its agents, groups and classes): +// participations.service.js uses it to tell whether the `/contacts` WAC group it grants read to a +// participations collection is already granted. +// +// Two pod calls go with the graphs: `readAcl` (the ACL as the pod serves it to the app, a failure +// told apart from "no public read") and `putOwnRights` (the PUT, as the app actor). Every Festipod +// caller that reads or replaces an ACL goes through them: public-read (events and their attendee +// lists) and participations (a person's participations collection). const { arrayOf } = require('@semapps/ldp'); @@ -98,12 +107,13 @@ const aclContext = aclUri => ({ }); /** - * revocationGraph(authorizations, resourceUri, ownerUri) → a JSON-LD document `{ '@context', '@graph' }` - * to PUT on the resource's ACL so it keeps every one of its OWN agent triples EXCEPT - * `acl:agentClass foaf:Agent` on its `#Read` authorization (a `foaf:Agent` on any other own rule stays). Inherited `#Default*` rules are not emitted - * (a PUT does not touch them). When removing the public-read triple would leave the own set empty, - * the owner is emitted as `acl:agent` of `#Read` so the PUT is accepted without changing any right. - * `aclUri` is where the document will be PUT (used only for the context `@base`). + * revocationGraph(authorizations, resourceUri, ownerUri, aclUri) → a JSON-LD document `{ '@context', + * '@graph' }` to PUT on the resource's ACL so it keeps every one of its OWN agent triples EXCEPT + * `acl:agentClass foaf:Agent` on its `#Read` authorization (a `foaf:Agent` on any other own rule + * stays). The other own rules (`#Write`, `#Append`, `#Control`) stay exactly as they are. Inherited + * `#Default*` rules are not emitted (a PUT does not touch them). When removing the public-read triple + * would leave the own set empty, the owner is emitted as `acl:agent` of `#Read` so the PUT is accepted + * without changing any right. `aclUri` is where the document will be PUT (used only for the context `@base`). */ const revocationGraph = (authorizations, resourceUri, ownerUri, aclUri) => { const graph = []; @@ -134,13 +144,78 @@ const revocationGraph = (authorizations, resourceUri, ownerUri, aclUri) => { return { '@context': aclContext(aclUri), '@graph': graph }; }; +/** + * ownReaders(authorizations) → `{ agent, agentClass, agentGroup }`: the values (full IRIs, without + * duplicates) the resource's OWN `#Read` authorization grants read to — not the inherited rules. + */ +const ownReaders = authorizations => { + const readers = { agent: [], agentClass: [], agentGroup: [] }; + for (const authorization of arrayOf(authorizations)) { + if (suffixOf(authorization) !== 'Read' || !expandedValuesOf(authorization, 'mode').includes(ACL + 'Read')) continue; + for (const name of Object.keys(readers)) { + for (const iri of expandedValuesOf(authorization, name)) { + if (typeof iri === 'string' && !readers[name].includes(iri)) readers[name].push(iri); + } + } + } + return readers; +}; + +/** The ACL document URI of a pod resource: `{origin}/_acl{path}` (the pod's `getAclUriFromResourceUri`). */ +const aclUriOf = resourceUri => { + const { origin, pathname } = new URL(resourceUri); + return `${origin}/_acl${pathname}`; +}; + +/** + * readAcl(ctx, resourceUri, actorUri) → `{ status, authorizations }`, the authorizations only when + * the pod answered 200. Unlike `pod-permissions.get`, which answers `false` for ANY failure — + * indistinguishable from "no public read" — a failure here is reported, so a caller can tell "not + * public" from "unknown". Read where `putOwnRights` writes (`aclUriOf`), through the pod owner's + * access (`actorUri`). + */ +async function readAcl(ctx, resourceUri, actorUri) { + const { status, body } = + (await ctx.call('pod-permissions.fetch', { + url: aclUriOf(resourceUri), + headers: { Accept: 'application/ld+json' }, + actorUri + })) || {}; + if (status !== 200 || !body || typeof body !== 'object') return { status: typeof status === 'number' ? status : 0 }; + const graph = body['@graph'] !== undefined ? body['@graph'] : body['@id'] || body.id ? [body] : []; + return { status, authorizations: Array.isArray(graph) ? graph : [graph] }; +} + +/** + * putOwnRights(ctx, resourceUri, document) → the HTTP status of the PUT of `document` (a + * `revocationGraph`) on the resource's ACL, sent as the APP ACTOR through the platform's signature + * proxy — the actor that holds `acl:Control` on the resources Festipod grants or revokes on. + * Resolves the status (0 when none); the caller decides what a refusal means. + */ +async function putOwnRights(ctx, resourceUri, document) { + const app = await ctx.call('app.get'); + const { status } = + (await ctx.call('signature.proxy.query', { + url: aclUriOf(resourceUri), + method: 'PUT', + headers: { 'Content-Type': 'application/ld+json' }, + body: JSON.stringify(document), + actorUri: app.id || app['@id'] + })) || {}; + return typeof status === 'number' ? status : 0; +} + module.exports = { grantsPublicRead, hasOwnPublicRead, hasInheritedPublicRead, revocationGraph, + ownReaders, isPublicRead, expand, + aclUriOf, + readAcl, + putOwnRights, FOAF_AGENT, ACL }; diff --git a/backend/services/public-read.service.js b/backend/services/public-read.service.js index 150e5a0..94e77c1 100644 --- a/backend/services/public-read.service.js +++ b/backend/services/public-read.service.js @@ -5,15 +5,18 @@ const { hasPublicIntent } = require('./public-intent'); const { isInActorPod } = require('./actor-pod'); const { createKeyedSerializer } = require('./keyed-serializer'); const { neverThrowingMatcher, verifiedEmit, uriOf, singleUriOf, hasAsType } = require('./emitted-activity'); -const { grantsPublicRead, hasOwnPublicRead, hasInheritedPublicRead, revocationGraph, FOAF_AGENT } = require('./public-read-acl'); +const { + grantsPublicRead, + hasOwnPublicRead, + hasInheritedPublicRead, + revocationGraph, + aclUriOf, + readAcl, + putOwnRights, + FOAF_AGENT +} = require('./public-read-acl'); const { recordGrant, forgetGrant, isGrantedByFestipod } = require('./public-read-ledger'); -/** The ACL document URI of a pod resource: `{origin}/_acl{path}` (the pod's `getAclUriFromResourceUri`). */ -const aclUriOf = resourceUri => { - const { origin, pathname } = new URL(resourceUri); - return `${origin}/_acl${pathname}`; -}; - const APODS_ATTENDEES = 'http://activitypods.org/ns/core#attendees'; /** The attendees collection an event names (compacted or full-IRI key), when it names exactly one. */ @@ -165,22 +168,9 @@ module.exports = { this.logger.error(`Could not re-decide public read on ${resourceUri} after a late write: ${e.message}`); } }, - /** - * The resource's ACL as the pod serves it to the app: `{ status, authorizations }`, the - * authorizations only when the pod answered 200. Unlike `pod-permissions.get`, which answers - * `false` for ANY failure — indistinguishable from "no public read" — a failure here is reported, - * so a caller can tell "not public" from "unknown". Read where `revoke` writes (`aclUriOf`). - */ + /** The resource's ACL as the pod serves it to the app (`public-read-acl.js` `readAcl`). */ async readAcl(ctx, resourceUri, actorUri) { - const { status, body } = - (await ctx.call('pod-permissions.fetch', { - url: aclUriOf(resourceUri), - headers: { Accept: 'application/ld+json' }, - actorUri - })) || {}; - if (status !== 200 || !body || typeof body !== 'object') return { status: typeof status === 'number' ? status : 0 }; - const graph = body['@graph'] !== undefined ? body['@graph'] : body['@id'] || body.id ? [body] : []; - return { status, authorizations: Array.isArray(graph) ? graph : [graph] }; + return readAcl(ctx, resourceUri, actorUri); }, /** * Makes `resourceUri` world-readable and records it as FESTIPOD's grant — only when its ACL was @@ -277,17 +267,9 @@ module.exports = { return false; } - const aclUri = aclUriOf(resourceUri); - const document = revocationGraph(acl.authorizations, resourceUri, actorUri, aclUri); - const app = await ctx.call('app.get'); + const document = revocationGraph(acl.authorizations, resourceUri, actorUri, aclUriOf(resourceUri)); if (aborted()) return false; - const { status } = await ctx.call('signature.proxy.query', { - url: aclUri, - method: 'PUT', - headers: { 'Content-Type': 'application/ld+json' }, - body: JSON.stringify(document), - actorUri: app.id || app['@id'] - }); + const status = await putOwnRights(ctx, resourceUri, document); if (status !== 204 && status !== 200) { throw new Error(`The pod refused to revoke the public-read grant on ${resourceUri} (HTTP ${status})`); } diff --git a/backend/services/public-surface.js b/backend/services/public-surface.js index aa831cb..6fb6afd 100644 --- a/backend/services/public-surface.js +++ b/backend/services/public-surface.js @@ -1,15 +1,15 @@ // The backend's whole HTTP surface, as an allow-list checked in front of every route. // -// WHY. The backend runs SemApps' CoreService with `webacl: false`, so nothing checks rights on the -// resources it stores, and CoreService mounts routes Festipod never asked for — above all the LDP -// catch-all (`@semapps/ldp` `getCatchAllRoute`: `GET|POST|PUT|PATCH|DELETE /`, -// `authorization: false`), which served the backend's `settings` dataset to anyone: the app actor's -// PRIVATE key (`GET /key`, observed 2026-10-13), the user registrations and grants the app holds -// (`/interop/…`), the webhook listeners. A signed request is no better: any pod user can sign one. -// Rather than chase each route (deny-list), the gateway serves ONLY what a caller legitimately needs -// and refuses everything else with a 404 — for every caller, anonymous or signed, since none needs -// more over HTTP: the backend's own services reach its data through internal calls, never through -// these routes. +// WHY. CoreService mounts routes Festipod never asked for — above all the LDP catch-all +// (`@semapps/ldp` `getCatchAllRoute`: `GET|POST|PUT|PATCH|DELETE /`), over the dataset that +// holds the app actor's PRIVATE key (`/key`), the user registrations and grants the app holds +// (`/interop/…`), the catalog store and the ledgers. WebACL filters what those routes serve (the main +// dataset is a secure one, see core.service.js), so each resource is only as private as the rights +// its container gave it; this gate does not depend on those rights being right. A signed request is +// no better than an anonymous one here: any pod user can sign one. Rather than chase each route +// (deny-list), the gateway serves ONLY what a caller legitimately needs and refuses everything else +// with a 404 — for every caller, anonymous or signed, since none needs more over HTTP: the backend's +// own services reach its data through internal calls, never through these routes. // // WHAT IS PUBLIC, and who calls it (backend request log, 2026-10-09 → 2026-10-13, all e2e runs): // GET /app the app description — the Festipod front end and the pod (install) diff --git a/backend/services/registration.service.js b/backend/services/registration.service.js index c4b9c15..15c3d6e 100644 --- a/backend/services/registration.service.js +++ b/backend/services/registration.service.js @@ -1,53 +1,122 @@ -const { ACTIVITY_TYPES, OBJECT_TYPES, matchActivity } = require('@semapps/activitypub'); +const { ACTIVITY_TYPES, matchActivity } = require('@semapps/activitypub'); const { PodActivitiesHandlerMixin } = require('@activitypods/app'); const { arrayOf } = require('@semapps/ldp'); const CONFIG = require('../config/config'); const { isInActorPod } = require('./actor-pod'); const { createKeyedSerializer } = require('./keyed-serializer'); -const { isNewerAct, lastAttendance, recordAttendance } = require('./attendance-ledger'); -const { neverThrowingMatcher, verifiedEmit, verifiedReceive, singleUriOf, uriOf } = require('./emitted-activity'); +const { isNewerAct, lastAttendance, persistMember, recordAttendance } = require('./attendance-ledger'); +const { neverThrowingMatcher, verifiedEmit, singleUriOf, uriOf } = require('./emitted-activity'); +const { participationSecretOf, memberUrn } = require('./member-urn'); +const { readItems, expectItem } = require('./collection-items'); +const AS = 'https://www.w3.org/ns/activitystreams#'; const APODS_ATTENDEES = 'http://activitypods.org/ns/core#attendees'; const APODS_CONTACTS = 'http://activitypods.org/ns/core#contacts'; const DC_CREATOR = 'http://purl.org/dc/terms/creator'; -const JOIN_PATTERN = { type: ACTIVITY_TYPES.JOIN, object: { type: OBJECT_TYPES.EVENT } }; -const LEAVE_PATTERN = { type: ACTIVITY_TYPES.LEAVE, object: { type: OBJECT_TYPES.EVENT } }; - -const AS_PUBLISHED = 'https://www.w3.org/ns/activitystreams#published'; +// Routing matches the activity TYPE alone: routing is a hint, the verified handler re-reads the +// activity and its object from the pod and decides (see emitted-activity.js). +const JOIN_PATTERN = { type: ACTIVITY_TYPES.JOIN }; +const LEAVE_PATTERN = { type: ACTIVITY_TYPES.LEAVE }; /** The time the pod stamped on a stored activity (`published`, under any of its spellings). */ const publishedOf = activity => { if (!activity || typeof activity !== 'object') return undefined; - const value = activity.published ?? activity['as:published'] ?? activity[AS_PUBLISHED]; + const value = activity.published ?? activity['as:published'] ?? activity[`${AS}published`]; return value && typeof value === 'object' ? value['@value'] : value; }; -/** The single URI an event names under a compacted or full-IRI key. */ -const linkOf = (node, compacted, full) => singleUriOf(node[compacted] ?? node[full]); +/** The single URI a node names under the first of `keys` it carries (compacted, CURIE or full IRI). */ +const linkOf = (node, ...keys) => singleUriOf(keys.map(key => node[key]).find(value => value !== undefined)); -// Participation: a user joins (or leaves) a meeting point with a Join (Leave) posted to her outbox, -// addressed to its organizer. Two effects, each from one side's box: -// - EMITTED (the joiner's outbox): the organizer joins the joiner's contacts group, so the -// organizer may read her profile; -// - RECEIVED (the organizer's inbox): the joiner is added to (removed from) the meeting point's -// attendees collection. -// The webhook that reports either is a hint (emitted-activity.js): each handler acts only on the +/** The first string a property holds (a string, a value node, or a list of either). */ +const firstStringOf = value => + arrayOf(value) + .map(v => (typeof v === 'string' ? v : v && typeof v === 'object' ? v['@value'] : undefined)) + .find(v => typeof v === 'string' && v.trim().length > 0); + +/** + * What a Join/Leave targets: the stored object must be a meeting point — an `as:Event` (checked by + * `verifiedEmit`) anchored to an event by `as:context` — whose creator is its `dc:creator`, believed + * only because the meeting point lies in that creator's pod (the pod stamps the creator, and nobody + * can store a resource in someone else's pod). Resolves `{ ok, eventUri, creatorUri }` or a refusal. + */ +function meetingPointTarget(meetingPoint, meetingPointUri) { + const eventUri = linkOf(meetingPoint, 'context', 'as:context', `${AS}context`); + if (!eventUri) return { ok: false, reason: `the meeting point ${meetingPointUri} names no single as:context (its event)` }; + const creatorUri = linkOf(meetingPoint, 'dc:creator', DC_CREATOR); + if (!creatorUri) return { ok: false, reason: `the meeting point ${meetingPointUri} names no single dc:creator` }; + if (!isInActorPod(meetingPointUri, creatorUri)) { + return { ok: false, reason: `the meeting point ${meetingPointUri} is not in the pod of its creator ${creatorUri}` }; + } + return { ok: true, eventUri, creatorUri }; +} + +/** + * The notification template for the creator of a meeting point (`pod-notifications.send`, rendered in + * the creator's language): always ANONYMOUS, the meeting point named through `meetingPointName`, the + * link to its event's meeting points (`eventUri`). Every value travels as a template PARAMETER, never + * inside the template, so no user text is compiled. + * + * Never names the participant: naming would need a trustworthy signal that the creator is one of the + * participant's contacts, and the only one the app can read — the participant's `apods:contacts` list — + * is forgeable (a stranger's received `Accept` of a contact `Offer` is added to it with no prior + * request checked; platform defect reported upstream). Until that list can be trusted, every + * notification is anonymous. + */ +function notificationTemplate(change) { + const title = + change === 'join' + ? { + en: 'A participant joined your meeting point "{{{meetingPointName}}}"', + fr: 'Un participant a rejoint votre point de rencontre « {{{meetingPointName}}} »' + } + : { + en: 'A participant left your meeting point "{{{meetingPointName}}}"', + fr: 'Un participant a quitté votre point de rencontre « {{{meetingPointName}}} »' + }; + return { + title, + actions: [{ caption: { en: 'View', fr: 'Voir' }, link: '/events/{{encodeUri eventUri}}/meeting-points' }] + }; +} + +// Participation (decision_2026-10-29_participation-privacy-mechanism): a person joins (leaves) a +// meeting point with an `as:Join` (`as:Leave`) posted to their OWN outbox, naming the meeting point, +// addressed to no one — so only its author and the app read it. The creator's inbox receives nothing. +// The backend acts on EMISSION (`onEmit`, the welcometomyplace registration pattern), and records: +// - in the meeting point's `apods:attendees` collection (the creator's pod, acting as the creator): +// the participant's MEMBER URN, never their WebID — `member-urn.js`, computed from the secret in +// their profile. A Join whose author's profile carries no usable secret is refused, nothing written; +// - in the participant's participations collection (their pod, acting as the participant): the +// meeting point URI — the collection created at the first Join and kept readable by the +// participant's `/contacts` WAC group only (`participations.service.js`). +// Then the creator is notified ANONYMOUSLY — always: naming would need a trustworthy "is the creator a +// contact of the participant" signal, and the only one the app can read (the participant's +// `apods:contacts` list) is forgeable (platform defect reported upstream, see `notificationTemplate`). +// The creator has no other right on the participant: they learn a count and opaque URNs. +// The webhook that reports the act is a hint (emitted-activity.js): the handler acts only on the // activity and the meeting point as the pod stores them, and only for the people they really name: -// - the joiner is the actor whose pod holds the activity, never a value of the webhook body; -// - the organizer is the meeting point's `dc:creator`, accepted only when the meeting point lies in -// that creator's pod — the pod stamps the creator, and nobody can store a resource in someone -// else's pod; -// - the collection and the group written to are the ones the STORED meeting point and the -// joiner's STORED actor document name, and must lie in the pod of whoever owns them. +// - the participant is the owner of the outbox the webhook fired on, and the stored activity's actor; +// - the creator is the meeting point's `dc:creator`, accepted only when the meeting point lies in +// that creator's pod (`meetingPointTarget`); +// - the collections written to are the ones the STORED meeting point and the participant's STORED +// profile name, and must lie in the pod of whoever owns them. // Joins and leaves of one meeting point are processed one at a time (keyed-serializer.js), and the // order they reach that lock does not decide: under the lock, an act is applied only when it is newer — // by the time the participant's pod stamped on it — than the last act applied for that participant and -// meeting point (`attendance-ledger.js`, persisted). Whatever order the notifications run in, the -// participant ends in the state of her latest act. The collection is read when acting. +// meeting point (`attendance-ledger.js`, persisted, which also holds the member URN that act applied). Whatever order the notifications run in, the +// participant ends in the state of their latest act. The member URN is STICKY per (meeting point, +// participant): chosen once and persisted BEFORE any attendee-list write, so every later act reuses it — +// the pair is never listed under two URNs, even after a half-way failure and a secret rewrite. An act is +// recorded only once BOTH collections, READ BACK, show it (collection-items.js — the platform's own +// collection calls answer "empty" on a failed read and resolve on a refused write); one that fails +// half-way is not, nor notified, and the participant's next act on that meeting point re-applies it +// (the two writes are not atomic). module.exports = { name: 'registration', mixins: [PodActivitiesHandlerMixin], + dependencies: ['participations'], created() { this.serialize = createKeyedSerializer(); }, @@ -55,6 +124,65 @@ module.exports = { this.logger.info('Registration watcher subscribed'); }, methods: { + /** + * Handles one verified Join/Leave (`change`: 'join' | 'leave') of `participantUri`, the outbox + * owner: resolves the meeting point and the participant, applies the act, then notifies the + * creator when the act changed the participant's state. A refusal is logged; nothing is written. + */ + async onParticipation(ctx, change, { activity, objectUri: meetingPointUri, object: meetingPoint }, participantUri) { + const refuse = reason => this.logger.warn(`${this.name} refused the ${change} ${uriOf(activity)} of ${participantUri}: ${reason}`); + const target = meetingPointTarget(meetingPoint, meetingPointUri); + if (!target.ok) return refuse(target.reason); + const participant = await this.participantOf(ctx, participantUri); + if (!participant.ok) return refuse(participant.reason); + const outcome = await this.updateAttendance(ctx, { + change, + eventUri: target.eventUri, + secret: participant.secret, + meetingPointUri, + meetingPoint, + activity, + creatorUri: target.creatorUri, + participantUri, + profileUri: participant.profileUri, + contactsUri: participant.contactsUri + }); + if (outcome && outcome.changed) { + await this.notifyCreator(ctx, { + change, + meetingPointUri, + meetingPoint, + eventUri: target.eventUri, + creatorUri: target.creatorUri, + participantUri + }); + } + }, + /** + * The participant as their pod describes them, read as the participant: their actor document + * (its `url` — the `as:Profile`, which must lie in their pod — and `apods:contacts`), then the + * profile, which must carry a usable participation secret. Resolves `{ ok, profileUri, + * contactsUri, secret }` or a refusal. `contactsUri` is the participant's `apods:contacts` + * collection — whose `/contacts` WAC group is what may read their participations collection. + */ + async participantOf(ctx, participantUri) { + const read = async uri => { + const { status, body } = await ctx.call('pod-resources.get', { resourceUri: uri, actorUri: participantUri }); + return status === 200 && body && uriOf(body) === uri ? body : undefined; + }; + const actor = await read(participantUri); + if (!actor) return { ok: false, reason: `the pod does not return the actor ${participantUri}` }; + const profileUri = linkOf(actor, 'url', 'as:url', `${AS}url`); + if (!profileUri || !isInActorPod(profileUri, participantUri)) { + return { ok: false, reason: `${participantUri} names no single profile in their pod (${profileUri})` }; + } + const profile = await read(profileUri); + if (!profile) return { ok: false, reason: `the pod does not return the profile ${profileUri}` }; + const secret = participationSecretOf(profile); + if (!secret) return { ok: false, reason: `the profile ${profileUri} carries no usable participation secret` }; + const contactsUri = linkOf(actor, 'apods:contacts', APODS_CONTACTS); + return { ok: true, profileUri, contactsUri, secret }; + }, /** * The attendees collection of a meeting point of `actorUri`'s pod, from the STORED meeting point. * It is attached asynchronously when the meeting point is created (attendees service), so a @@ -79,11 +207,37 @@ module.exports = { return collectionUri; }, /** - * Applies one participant act (`join` / `leave`, the stored activity `activity`) to the meeting - * point's collection — under the meeting point's lock, and only when the act is newer than the last - * one applied for that participant there (see the header). A stale act changes nothing; an act - * without a pod stamp cannot be placed and changes nothing. The decision is recorded once the - * collection matches it. Gives up before any write once its time is out (`signal`). + * The participant's participations collection, under the meeting point's lock: for a Join, the one + * `participations.ensure` makes ready (created if none, contacts-only); for a Leave, the one the + * profile links now, if any. Resolves `{ ok, collectionUri }` — `collectionUri` undefined for a + * Leave without a collection — or `{ ok: false }` once the failure is logged: the act must then + * write nothing and stay unrecorded, so that the next act retries. + */ + async participationsCollectionOf(ctx, { change, participantUri, profileUri, contactsUri }) { + try { + const collectionUri = + change === 'join' + ? await ctx.call('participations.ensure', { actorUri: participantUri, profileUri, contactsUri }) + : await ctx.call('participations.collectionOf', { actorUri: participantUri, profileUri }); + return { ok: true, collectionUri }; + } catch (e) { + this.logger.error( + `The participations collection of ${participantUri} is not ready (${e.message}): the ${change} is NOT recorded, the next act retries` + ); + return { ok: false }; + } + }, + /** + * Applies one participant act (`join` / `leave`, the stored activity `activity`) — under the + * meeting point's lock, and only when the act is newer than the last one applied for that member + * there (see the header). A stale act changes nothing; an act without a pod stamp cannot be placed + * and changes nothing. The act is applied to the meeting point's attendees (as the creator), then + * to the participant's participations collection (as the participant), each write read back + * (`applyToAttendees`, `applyToParticipations`), and recorded once both show it; a failed read, a + * refused write or a write that does not show leaves the act unrecorded (logged). Gives up before + * any write once its time is out (`signal`). Resolves `{ changed }` when the act was applied — + * `changed` when it added or removed the member, or flipped the state the ledger held — and + * undefined when it was not. * * KNOWN LIMIT — a write in flight at the timeout: an add or remove ALREADY SENT when the time ran * out still lands, and is not recorded. If a newer act of the same participant was applied in the @@ -93,37 +247,116 @@ module.exports = { * is the ledger that is behind — re-applying the ledger would undo it, and the two cases cannot be * told apart here. Needs a pod slower than the 30 s limit. */ - async updateAttendance(ctx, { change, memberUri, meetingPointUri, meetingPoint, activity, actorUri }) { + async updateAttendance(ctx, { change, eventUri, secret, meetingPointUri, meetingPoint, activity, creatorUri, participantUri, profileUri, contactsUri }) { const act = { activityUri: uriOf(activity), published: publishedOf(activity), change }; if (Number.isNaN(Date.parse(act.published))) { - this.logger.warn(`${change} ${act.activityUri} of ${memberUri} carries no pod stamp (published): it cannot be ordered, unchanged`); - return; + this.logger.warn(`${change} ${act.activityUri} of ${participantUri} carries no pod stamp (published): it cannot be ordered, unchanged`); + return undefined; } - await this.serialize(meetingPointUri, async signal => { + return this.serialize(meetingPointUri, async signal => { const dataset = CONFIG.MAIN_DATASET; - const last = await lastAttendance(ctx, { dataset, meetingPointUri, memberUri }); + const last = await lastAttendance(ctx, { dataset, meetingPointUri, participantUri }); if (!isNewerAct(act, last)) { - this.logger.info(`${change} ${act.activityUri} of ${memberUri} on ${meetingPointUri} is not newer than the last act applied (${last.activityUri}, possibly the same act notified again): unchanged`); - return; + this.logger.info(`${change} ${act.activityUri} of ${participantUri} on ${meetingPointUri} is not newer than the last act applied (${last.activityUri}, possibly the same act notified again): unchanged`); + return undefined; } - const collectionUri = await this.attendeesCollectionOf(ctx, meetingPoint, meetingPointUri, actorUri); + const collectionUri = await this.attendeesCollectionOf(ctx, meetingPoint, meetingPointUri, creatorUri); if (!collectionUri) { this.logger.warn(`No attendees collection on ${meetingPointUri}, skipping ${change}`); + return undefined; + } + if (signal.aborted) return undefined; + const participations = await this.participationsCollectionOf(ctx, { change, participantUri, profileUri, contactsUri }); + if (!participations.ok || signal.aborted) return undefined; + // The member URN the act applies is STICKY per (meeting point, participant): the one the ledger + // already holds for the pair, else one computed from the secret on the profile now and persisted + // write-once BEFORE any attendee-list write — the act then applies whatever member the ledger holds + // after that write (another act's, if one landed first) — so that every later act (Join or Leave, + // after any half-way failure, timeout or secret rewrite) uses that same URN and the pair is never + // listed under two. + if (signal.aborted) return undefined; + let wrote; + try { + const memberUri = + last && last.member + ? last.member + : await persistMember(ctx, { dataset, meetingPointUri, participantUri, member: memberUrn({ participantUri, eventUri, secret }) }); + if (signal.aborted) return undefined; + wrote = await this.applyToAttendees(ctx, { change, collectionUri, memberUri, creatorUri, meetingPointUri, signal }); + await this.applyToParticipations(ctx, { change, collectionUri: participations.collectionUri, meetingPointUri, participantUri, signal }); + } catch (e) { + this.logger.error(`The ${change} ${act.activityUri} of ${participantUri} on ${meetingPointUri} is NOT recorded (${e.message}): the next act retries`); + return undefined; + } + if (signal.aborted) return undefined; + await recordAttendance(ctx, { dataset, meetingPointUri, participantUri, act }); + const wasAttending = Boolean(last && last.change === 'join'); + return { changed: wrote || wasAttending !== (change === 'join') }; + }); + }, + /** + * Applies `change` for `memberUri` to the meeting point's attendee list `collectionUri`, in the + * creator's pod and as the creator: reads the list — a failed read throws, it never means "not + * listed" — then adds the member on a Join when absent, removes it on a Leave when present (the + * attendees handler's `add` / `remove`, the reference-app calls) and reads the list back: throws + * unless the write shows. Resolves whether it wrote (false when the list already matched the act). + * Throws instead of writing once its time is out (`signal`). + */ + async applyToAttendees(ctx, { change, collectionUri, memberUri, creatorUri, meetingPointUri, signal }) { + const joining = change === 'join'; + const attending = (await readItems(ctx, { collectionUri, actorUri: creatorUri })).includes(memberUri); + if (attending === joining) { + this.logger.info(`${memberUri} already ${joining ? 'attends' : 'does not attend'} ${meetingPointUri}`); + return false; + } + if (signal.aborted) throw new Error(`out of time before the ${change} write to ${collectionUri}`); + await ctx.call(joining ? 'attendees.add' : 'attendees.remove', { collectionUri, itemUri: memberUri, actorUri: creatorUri }); + await expectItem(ctx, { collectionUri, itemUri: memberUri, actorUri: creatorUri, present: joining }); + return true; + }, + /** + * Applies `change` to the participant's participations collection `collectionUri`, in their pod and + * as them: adds the meeting point on a Join, removes it on a Leave (the participations handler's + * `add` / `remove`, the reference-app calls — adding an item already there or removing one that is + * not changes nothing, so no read first), then reads the collection back: throws unless it shows + * the act. Nothing to do on a Leave when the participant has no collection (`collectionUri` + * undefined). Throws instead of writing once its time is out (`signal`). + */ + async applyToParticipations(ctx, { change, collectionUri, meetingPointUri, participantUri, signal }) { + if (!collectionUri) { + this.logger.info(`${participantUri} has no participations collection: nothing to remove ${meetingPointUri} from`); + return; + } + const joining = change === 'join'; + if (signal.aborted) throw new Error(`out of time before the ${change} write to ${collectionUri}`); + await ctx.call(joining ? 'participations.add' : 'participations.remove', { collectionUri, itemUri: meetingPointUri, actorUri: participantUri }); + await expectItem(ctx, { collectionUri, itemUri: meetingPointUri, actorUri: participantUri, present: joining }); + }, + /** + * Tells the creator of the meeting point that a participant joined or left it — ALWAYS anonymously. + * The participant is never named: the only membership signal the app can read (the participant's + * `apods:contacts` list) is forgeable, so naming cannot be trusted (platform defect reported + * upstream, see `notificationTemplate`). The notification carries no `activity`: given one, + * `pod-notifications.send` fetches the emitter's profile. A creator acting on their own meeting + * point is not notified. A failure is logged, never thrown: the act stands. + */ + async notifyCreator(ctx, { change, meetingPointUri, meetingPoint, eventUri, creatorUri, participantUri }) { + try { + if (creatorUri === participantUri) { + this.logger.info(`${participantUri} acted on their own meeting point ${meetingPointUri}: no notification`); return; } - if (signal.aborted) return; - const attending = arrayOf(await ctx.call('pod-collections.getItems', { collectionUri, actorUri })).includes(memberUri); - if (signal.aborted) return; - if (change === 'join' && !attending) { - await ctx.call('attendees.add', { collectionUri, itemUri: memberUri, actorUri }); - } else if (change === 'leave' && attending) { - await ctx.call('attendees.remove', { collectionUri, itemUri: memberUri, actorUri }); - } else { - this.logger.info(`${memberUri} already ${change === 'join' ? 'attends' : 'does not attend'} ${meetingPointUri}`); - } - if (signal.aborted) return; - await recordAttendance(ctx, { dataset, meetingPointUri, memberUri, act }); - }); + this.logger.info(`Notifying ${creatorUri} of a ${change} on ${meetingPointUri}, anonymously`); + await ctx.call('pod-notifications.send', { + template: notificationTemplate(change), + recipientUri: creatorUri, + context: meetingPointUri, + meetingPointName: firstStringOf(meetingPoint.name ?? meetingPoint['as:name'] ?? meetingPoint[`${AS}name`]) ?? '', + eventUri + }); + } catch (e) { + this.logger.error(`Could not notify ${creatorUri} of a ${change} on ${meetingPointUri}: ${e.message}`); + } } }, activities: { @@ -131,48 +364,26 @@ module.exports = { match: neverThrowingMatcher(function (activity, fetcher) { return matchActivity(JOIN_PATTERN, activity, fetcher); }), - // The joiner's outbox: `actorUri` is the joiner. The meeting point lies in the organizer's pod. + // The participant's outbox: `actorUri` is the participant; the meeting point may lie in any pod + // (its creator's — checked by `meetingPointTarget`). onEmit: verifiedEmit( 'Join', - async function (ctx, { object: meetingPoint, objectUri: meetingPointUri }, actorUri) { - const organizerUri = linkOf(meetingPoint, 'dc:creator', DC_CREATOR); - if (!organizerUri || !isInActorPod(meetingPointUri, organizerUri)) { - this.logger.warn(`${meetingPointUri} is not in the pod of the creator it names: no contact added`); - return; - } - - const { body: actor } = await ctx.call('pod-resources.get', { resourceUri: actorUri, actorUri }); - const contactsUri = actor && linkOf(actor, 'apods:contacts', APODS_CONTACTS); - if (!contactsUri) return; - if (!isInActorPod(contactsUri, actorUri)) { - this.logger.warn(`${actorUri} names a contacts collection outside its pod: no contact added`); - return; - } - - const contactsGroupUri = await ctx.call('pod-wac-groups.getUriFromCollectionUri', { collectionUri: contactsUri }); - await ctx.call('pod-wac-groups.addMember', { groupUri: contactsGroupUri, memberUri: organizerUri, actorUri }); + async function (ctx, verdict, actorUri) { + await this.onParticipation(ctx, 'join', verdict, actorUri); }, { objectType: 'Event', objectIn: 'any' } - ), - // The organizer's inbox: `actorUri` is the organizer; the meeting point must lie in her pod. - onReceive: verifiedReceive( - 'Join', - async function (ctx, { activity, emitterUri, object, objectUri }, actorUri) { - await this.updateAttendance(ctx, { change: 'join', memberUri: emitterUri, meetingPointUri: objectUri, meetingPoint: object, activity, actorUri }); - }, - { objectType: 'Event' } ) }, leave: { match: neverThrowingMatcher(function (activity, fetcher) { return matchActivity(LEAVE_PATTERN, activity, fetcher); }), - onReceive: verifiedReceive( + onEmit: verifiedEmit( 'Leave', - async function (ctx, { activity, emitterUri, object, objectUri }, actorUri) { - await this.updateAttendance(ctx, { change: 'leave', memberUri: emitterUri, meetingPointUri: objectUri, meetingPoint: object, activity, actorUri }); + async function (ctx, verdict, actorUri) { + await this.onParticipation(ctx, 'leave', verdict, actorUri); }, - { objectType: 'Event' } + { objectType: 'Event', objectIn: 'any' } ) } } diff --git a/backend/services/registration.service.test.js b/backend/services/registration.service.test.js index df8b56d..6c80d0f 100644 --- a/backend/services/registration.service.test.js +++ b/backend/services/registration.service.test.js @@ -1,319 +1,796 @@ const { test, expect, describe } = require('bun:test'); const registration = require('./registration.service'); -const { createKeyedSerializer } = require('./keyed-serializer'); -const { lastAttendanceQuery, recordAttendanceUpdate, isNewerAct, attendanceSubject } = require('./attendance-ledger'); +const { memberUrn } = require('./member-urn'); +const { lastAttendanceQuery, isNewerAct, attendanceSubject } = require('./attendance-ledger'); +const { hasOwnPublicRead, ownReaders } = require('./public-read-acl'); +const { + world, + activity, + meetingPoint, + profile, + profileOf, + groupOf, + contactsOf, + attendeesOf, + createdCollectionAcl, + APP, + ALICE, + BOB, + CAROL, + MALLORY, + EVENT1, + EVENT2, + SECRETS, + FP_SECRET, + FP_PARTICIPATIONS +} = require('./participation-world'); -const ALICE = 'http://localhost:3000/alice'; // the organizer -const BOB = 'http://localhost:3000/bob'; // the joiner -const MALLORY = 'http://localhost:3000/mallory'; +// Alice created three meeting points: two on the festival (EVENT1), one on the concert (EVENT2). +const MP1 = `${ALICE}/data/events/mp1`; +const MP2 = `${ALICE}/data/events/mp2`; +const MP3 = `${ALICE}/data/events/mp3`; +const MEETING_POINTS = { [MP1]: meetingPoint(MP1), [MP2]: meetingPoint(MP2), [MP3]: meetingPoint(MP3, { context: EVENT2 }) }; +const EVENT_OF = { [MP1]: EVENT1, [MP2]: EVENT1, [MP3]: EVENT2 }; -const MP = `${ALICE}/data/events/mp1`; -const C = `${ALICE}/data/collections/mp1-attendees`; -const JOIN = `${BOB}/data/activities/join-1`; -const LEAVE = `${BOB}/data/activities/leave-1`; -const BOB_CONTACTS = `${BOB}/data/collections/contacts`; +const T0 = '2026-10-29T10:00:00.000Z'; +const T1 = '2026-10-29T10:00:05.000Z'; +const T2 = '2026-10-29T10:00:10.000Z'; +const join = (mp, published = T0, who = BOB, n = 1) => activity('Join', who, mp, published, n); +const leave = (mp, published = T1, who = BOB, n = 1) => activity('Leave', who, mp, published, n); -const meetingPoint = (extra = {}) => ({ id: MP, type: 'Event', name: 'Entrée nord', 'dc:creator': ALICE, 'apods:attendees': C, to: 'as:Public', ...extra }); -// The pod stamps `published` on every activity posted to an outbox. -const join = { id: JOIN, type: 'Join', actor: BOB, object: MP, to: ALICE, published: '2026-10-13T10:00:00.000Z' }; -const leave = { id: LEAVE, type: 'Leave', actor: BOB, object: MP, to: ALICE, published: '2026-10-13T10:00:05.000Z' }; +const urnOf = (who, mp = MP1) => memberUrn({ participantUri: who, eventUri: EVENT_OF[mp], secret: SECRETS[who] }); -/** - * A pod (uri → stored body, 404 otherwise) plus the collection's state and the backend's attendance - * ledger (answering exactly the queries `attendance-ledger.js` builds); records every call. - * `addDelay` makes `attendees.add` slow; `readDelays` (uri → ms) makes some pod reads slow, to expose - * interleavings. `ledger` seeds the last act applied per member. - */ -function world({ stored = {}, items = [], addDelay = 0, readDelays = {}, ledger = {} } = {}) { - const calls = []; - const state = { items: [...items], ledger: { ...ledger } }; - const members = [BOB, MALLORY, ALICE]; - // Every act the store could be asked to record: the stored Join/Leave activities. - const acts = Object.values(stored) - .filter(body => body.type === 'Join' || body.type === 'Leave') - .map(body => ({ activityUri: body.id, published: body.published, change: body.type.toLowerCase() })); - const ctx = { - call: async (action, params) => { - calls.push({ action, params }); - switch (action) { - case 'pod-resources.get': { - if (readDelays[params.resourceUri]) await new Promise(resolve => setTimeout(resolve, readDelays[params.resourceUri])); - const body = stored[params.resourceUri]; - return body ? { ok: true, status: 200, body } : { ok: false, status: 404 }; - } - case 'triplestore.query': { - const member = members.find(m => params.query === lastAttendanceQuery(MP, m)); - if (!member) throw new Error(`unexpected query ${params.query}`); - const last = state.ledger[member]; - return last ? [{ act: { value: last.activityUri }, published: { value: last.published }, change: { value: last.change } }] : []; - } - case 'triplestore.update': { - for (const m of members) { - const act = acts.find(a => params.query === recordAttendanceUpdate(MP, m, a)); - if (act) { - state.ledger[m] = act; - return undefined; - } - } - throw new Error(`unexpected update ${params.query}`); - } - case 'pod-collections.getItems': - return [...state.items]; - case 'attendees.add': - if (addDelay) await new Promise(resolve => setTimeout(resolve, addDelay)); - state.items.push(params.itemUri); - return undefined; - case 'attendees.remove': - state.items = state.items.filter(item => item !== params.itemUri); - return undefined; - case 'pod-wac-groups.getUriFromCollectionUri': - return `${params.collectionUri}-group`; - default: - return undefined; - } - } +/** The world with Alice's meeting points and the given stored activities. */ +function setup({ acts = [], stored = {}, ...options } = {}) { + return world({ stored: { ...MEETING_POINTS, ...Object.fromEntries(acts.map(a => [a.id, a])), ...stored }, ...options }); +} + +const emitJoin = (w, act, actorUri = act.actor) => w.emit('join', act, actorUri); +const emitLeave = (w, act, actorUri = act.actor) => w.emit('leave', act, actorUri); +const attendees = (w, mp = MP1) => w.state.items[attendeesOf(mp)] || []; +const participationsUri = (w, who = BOB) => { + const link = w.state.stored[profileOf(who)][FP_PARTICIPATIONS]; + return link && link.id; +}; +const participations = (w, who = BOB) => w.state.items[participationsUri(w, who)] || []; +const ledgerOf = (w, mp = MP1, who = BOB) => w.state.ledger[attendanceSubject(mp, who)]; + +const WRITES = [ + 'attendees.add', + 'attendees.remove', + 'pod-collections.add', + 'pod-collections.remove', + 'pod-collections.createAndAttach', + 'pod-permissions.add', + 'signature.proxy.query', + 'triplestore.update', + 'pod-notifications.send' +]; +const writes = calls => calls.filter(c => WRITES.includes(c.action)); + +/** An existing participations collection of `who`, linked from their profile, with the given ACL. */ +function existingCollection(who, acl) { + const uri = `${who}/data/as/collection/participations-existing`; + return { + uri, + stored: { [profileOf(who)]: profile(who, { [FP_PARTICIPATIONS]: { id: uri } }) }, + acls: { [uri]: acl }, + items: { [uri]: [] } }; - return { ctx, calls, state }; } +/** The ACL of a collection readable by the participant's `/contacts` WAC group, the app keeping its Control. */ +const protectedAcl = (uri, group = groupOf(BOB)) => [ + { '@id': `http://localhost:3000/_acl${new URL(uri).pathname}#Read`, 'acl:mode': 'acl:Read', 'acl:agentGroup': group }, + { '@id': `http://localhost:3000/_acl${new URL(uri).pathname}#Control`, 'acl:mode': 'acl:Control', 'acl:agent': APP } +]; -function service({ timeoutMs } = {}) { - const logs = { info: [], warn: [], error: [] }; - const svc = { name: 'registration', logger: { info: m => logs.info.push(m), warn: m => logs.warn.push(m), error: m => logs.error.push(m) } }; - if (registration.created) registration.created.call(svc); - if (timeoutMs) svc.serialize = createKeyedSerializer({ timeoutMs }); - for (const [name, fn] of Object.entries(registration.methods)) svc[name] = fn.bind(svc); - return { svc, logs }; -} +describe("registration — a Join emitted in the participant's outbox", () => { + test('the normal case: the member URN joins the list, the meeting point joins the participant\'s collection, the act is recorded', async () => { + const j = join(MP1); + const w = setup({ acts: [j] }); + await emitJoin(w, j); -const receiveJoin = (svc, ctx, hint) => registration.activities.join.onReceive.call(svc, ctx, hint, ALICE); -const receiveLeave = (svc, ctx, hint) => registration.activities.leave.onReceive.call(svc, ctx, hint, ALICE); -const emitJoin = (svc, ctx, hint) => registration.activities.join.onEmit.call(svc, ctx, hint, BOB); -const adds = calls => calls.filter(c => c.action === 'attendees.add').map(c => c.params); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(attendees(w)).not.toContain(BOB); // never the WebID + const add = w.calls.find(c => c.action === 'attendees.add'); + expect(add.params).toEqual({ collectionUri: attendeesOf(MP1), itemUri: urnOf(BOB), actorUri: ALICE }); -describe("registration — a Join received in the organizer's inbox adds the joiner the pod names", () => { - test('the normal case: the stored joiner is added to the STORED meeting point\'s collection', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint() } }); - await receiveJoin(service().svc, ctx, join); - expect(adds(calls)).toEqual([{ collectionUri: C, itemUri: BOB, actorUri: ALICE }]); + expect(w.state.created).toHaveLength(1); + expect(participations(w)).toEqual([MP1]); + const added = w.calls.find(c => c.action === 'pod-collections.add'); + expect(added.params).toEqual({ collectionUri: participationsUri(w), itemUri: MP1, actorUri: BOB }); + + expect(ledgerOf(w)).toEqual({ activityUri: j.id, published: T0, change: 'join', member: urnOf(BOB) }); + expect(w.state.notifications).toHaveLength(1); + expect(w.logs.error).toEqual([]); }); - test('the webhook body is ignored: neither its actor nor its embedded attendees collection is used', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint() } }); - const body = { id: JOIN, type: 'Join', actor: MALLORY, object: { id: MP, type: 'Event', 'apods:attendees': `${MALLORY}/data/c` } }; - await receiveJoin(service().svc, ctx, body); - expect(adds(calls)).toEqual([{ collectionUri: C, itemUri: BOB, actorUri: ALICE }]); + test('the webhook body is a hint: its actor and its embedded object are ignored', async () => { + const j = join(MP1); + const w = setup({ acts: [j] }); + await emitJoin(w, { ...j, actor: MALLORY, object: { id: MP2, type: 'Event', 'apods:attendees': `${MALLORY}/data/c` } }, BOB); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(attendees(w, MP2)).toEqual([]); + expect(w.state.items[`${MALLORY}/data/c`]).toBeUndefined(); }); - test('a Join the pod does not store (webhook only) adds no one', async () => { - const { ctx, calls } = world({ stored: { [MP]: meetingPoint() } }); - const { svc, logs } = service(); - await receiveJoin(svc, ctx, { ...join, object: meetingPoint() }); - expect(adds(calls)).toEqual([]); - expect(logs.warn[0]).toContain('ignored a Join'); - }); - - test('a Join about a meeting point outside the organizer\'s pod adds no one', async () => { - const bobsMp = `${BOB}/data/events/mp`; - const { ctx, calls } = world({ stored: { [JOIN]: { ...join, object: bobsMp }, [bobsMp]: { ...meetingPoint(), id: bobsMp } } }); - await receiveJoin(service().svc, ctx, join); - expect(adds(calls)).toEqual([]); - }); - - test('a stored meeting point naming a collection outside the organizer\'s pod: nothing written', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint({ 'apods:attendees': `${MALLORY}/data/c` }) } }); - const { svc, logs } = service(); - await receiveJoin(svc, ctx, join); - expect(adds(calls)).toEqual([]); - expect(logs.warn.some(m => m.includes('outside its pod'))).toBe(true); - }); - - test('a stored object that is not an event (a Note) adds no one', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: { id: MP, type: 'Note', 'apods:attendees': C } } }); - await receiveJoin(service().svc, ctx, join); - expect(adds(calls)).toEqual([]); - }); - - test('an already attending joiner is not added twice', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint() }, items: [BOB] }); - await receiveJoin(service().svc, ctx, join); - expect(adds(calls)).toEqual([]); + test('the act is handled on emission only: the creator\'s inbox has no handler', () => { + expect(registration.activities.join.onReceive).toBeUndefined(); + expect(registration.activities.leave.onReceive).toBeUndefined(); + expect(typeof registration.activities.join.onEmit).toBe('function'); + expect(typeof registration.activities.leave.onEmit).toBe('function'); }); }); -describe("registration — a Leave received in the organizer's inbox removes only its stored emitter", () => { - test('the stored leaver is removed; a body claiming another actor changes nothing to who is removed', async () => { - const { ctx, state } = world({ stored: { [LEAVE]: leave, [MP]: meetingPoint() }, items: [BOB, MALLORY] }); - await receiveLeave(service().svc, ctx, { ...leave, actor: MALLORY }); - expect(state.items).toEqual([MALLORY]); +describe('registration — refusals write nothing and record nothing', () => { + const refused = async (w, act, { log = 'warn', contains } = {}) => { + await emitJoin(w, act); + expect(writes(w.calls)).toEqual([]); + if (contains) expect(w.logs[log].some(m => m.includes(contains))).toBe(true); + }; + + test('a profile without a participation secret', async () => { + const j = join(MP1); + await refused(setup({ acts: [j], stored: { [profileOf(BOB)]: profile(BOB, { [FP_SECRET]: undefined }) } }), j, { contains: 'no usable participation secret' }); }); - test('a Leave the pod does not store removes no one', async () => { - const { ctx, state } = world({ stored: { [MP]: meetingPoint() }, items: [BOB] }); - await receiveLeave(service().svc, ctx, leave); - expect(state.items).toEqual([BOB]); + test('a malformed secret (uppercase, short, non-hex, several values)', async () => { + for (const secret of [SECRETS[BOB].toUpperCase(), SECRETS[BOB].slice(2), 'z'.repeat(64), [SECRETS[BOB], SECRETS[CAROL]]]) { + const j = join(MP1); + await refused(setup({ acts: [j], stored: { [profileOf(BOB)]: profile(BOB, { [FP_SECRET]: secret }) } }), j, { contains: 'no usable participation secret' }); + } }); - test('a Join and a Leave of one meeting point never interleave (the join cannot land after the leave)', async () => { - const { ctx, state } = world({ stored: { [JOIN]: join, [LEAVE]: leave, [MP]: meetingPoint() }, addDelay: 30 }); - const { svc } = service(); - await Promise.all([receiveJoin(svc, ctx, join), receiveLeave(svc, ctx, leave)]); - expect(state.items).toEqual([]); + test('a stored object that is not an Event (a Note)', async () => { + const j = join(MP1); + await refused(setup({ acts: [j], stored: { [MP1]: { ...meetingPoint(MP1), type: 'Note' } } }), j, { contains: 'is not a Event' }); + }); + + test('an Event with no as:context (no event to anchor the URN)', async () => { + const j = join(MP1); + await refused(setup({ acts: [j], stored: { [MP1]: meetingPoint(MP1, { context: undefined }) } }), j, { contains: 'as:context' }); + }); + + test('a meeting point not in the pod of its dc:creator, or naming no creator', async () => { + const j = join(MP1); + await refused(setup({ acts: [j], stored: { [MP1]: meetingPoint(MP1, { 'dc:creator': MALLORY }) } }), j, { contains: 'not in the pod of its creator' }); + await refused(setup({ acts: [j], stored: { [MP1]: meetingPoint(MP1, { 'dc:creator': undefined }) } }), j, { contains: 'dc:creator' }); + }); + + test('an actor whose profile lies outside their pod', async () => { + const j = join(MP1); + const w = setup({ acts: [j], stored: { [BOB]: { id: BOB, type: 'Person', url: profileOf(CAROL), 'apods:contacts': `${BOB}/contacts` } } }); + await refused(w, j, { contains: 'names no single profile in their pod' }); + }); + + test('a profile linking a participations collection outside the participant\'s pod: ignored, the act refused', async () => { + const j = join(MP1); + const foreign = `${MALLORY}/data/as/collection/x`; + const w = setup({ acts: [j], stored: { [profileOf(BOB)]: profile(BOB, { [FP_PARTICIPATIONS]: { id: foreign } }) } }); + await refused(w, j, { log: 'error', contains: 'NOT recorded' }); + expect(w.state.items[foreign]).toBeUndefined(); + }); + + test('an act without a pod stamp cannot be ordered', async () => { + const j = { ...join(MP1), published: undefined }; + await refused(setup({ acts: [j] }), j, { contains: 'no pod stamp' }); + }); + + test('a Join the pod does not store (webhook only)', async () => { + const j = join(MP1); + await refused(setup(), j, { contains: 'ignored a Join' }); }); }); -describe('registration — attendance follows the participant\'s LATEST act, whatever order notifications run in', () => { - // The reviewer's probe: the Join's verification read is slower, so the Leave reaches the lock first. - test('join then leave, the Leave handled first: ends NOT attending', async () => { - const { ctx, state } = world({ stored: { [JOIN]: join, [LEAVE]: leave, [MP]: meetingPoint() }, readDelays: { [JOIN]: 40 } }); - const { svc } = service(); - const j = receiveJoin(svc, ctx, { id: JOIN }); // the Join webhook first - await new Promise(resolve => setTimeout(resolve, 5)); // the Leave webhook 5 ms later - const l = receiveLeave(svc, ctx, { id: LEAVE }); - await Promise.all([j, l]); - expect(state.items).toEqual([]); +describe('registration — the member URN: one per person and event, computed by the backend', () => { + test('the same person on two meeting points of one event → the same URN; on another event → another', async () => { + const acts = [join(MP1), join(MP2), join(MP3)]; + const w = setup({ acts }); + for (const a of acts) await emitJoin(w, a); + expect(attendees(w, MP1)).toEqual([urnOf(BOB, MP1)]); + expect(attendees(w, MP2)).toEqual(attendees(w, MP1)); + expect(attendees(w, MP3)).toEqual([urnOf(BOB, MP3)]); + expect(attendees(w, MP3)).not.toEqual(attendees(w, MP1)); + expect(participations(w).sort()).toEqual([MP1, MP2, MP3].sort()); }); - test('leave then join, the Join handled first: ends attending', async () => { - const earlyLeave = { ...leave, published: '2026-10-13T09:00:00.000Z' }; // she left, then joined again - const { ctx, state } = world({ stored: { [JOIN]: join, [LEAVE]: earlyLeave, [MP]: meetingPoint() }, items: [BOB], readDelays: { [LEAVE]: 40 } }); - const { svc } = service(); - const l = receiveLeave(svc, ctx, { id: LEAVE }); + test('two people on one meeting point → two URNs, each derived from its own WebID and secret', async () => { + const acts = [join(MP1), join(MP1, T0, CAROL)]; + const w = setup({ acts }); + for (const a of acts) await emitJoin(w, a); + expect(attendees(w).sort()).toEqual([urnOf(BOB), urnOf(CAROL)].sort()); + expect(urnOf(BOB)).not.toBe(urnOf(CAROL)); + }); +}); + +describe('registration — the participations collection', () => { + test('created ONCE under two concurrent Joins of one participant (two meeting points, two locks)', async () => { + const acts = [join(MP1), join(MP2)]; + const w = setup({ acts, delays: { create: 30 } }); + await Promise.all(acts.map(a => emitJoin(w, a))); + expect(w.state.created).toHaveLength(1); + expect(w.state.stored[profileOf(BOB)][FP_PARTICIPATIONS]).toEqual({ id: w.state.created[0] }); + expect(participations(w).sort()).toEqual([MP1, MP2].sort()); + }); + + test('on creation: the pod\'s public read is removed, then the /contacts group granted read — before the meeting point is added', async () => { + const j = join(MP1); + const w = setup({ acts: [j] }); + await emitJoin(w, j); + const acl = w.state.acls[participationsUri(w)]; + expect(hasOwnPublicRead(acl)).toBe(false); + expect(ownReaders(acl)).toEqual({ agent: [], agentClass: [], agentGroup: [groupOf(BOB)] }); + const order = w.calls.map(c => c.action).filter(a => ['pod-permissions.add', 'signature.proxy.query', 'pod-collections.add'].includes(a)); + expect(order).toEqual(['signature.proxy.query', 'pod-permissions.add', 'pod-collections.add']); + const grant = w.calls.find(c => c.action === 'pod-permissions.add'); + expect(grant.params).toMatchObject({ agentPredicate: 'acl:agentGroup', agentUri: groupOf(BOB), mode: 'acl:Read', actorUri: BOB }); + }); + + test('an existing, already protected collection is reused: no creation, no ACL write', async () => { + const existing = existingCollection(BOB, null); + existing.acls[existing.uri] = protectedAcl(existing.uri); + const j = join(MP1); + const w = setup({ acts: [j], stored: existing.stored, acls: existing.acls, items: existing.items }); + await emitJoin(w, j); + expect(w.calls.some(c => c.action === 'pod-collections.createAndAttach')).toBe(false); + expect(w.calls.some(c => c.action === 'pod-permissions.add' || c.action === 'signature.proxy.query')).toBe(false); + expect(w.state.items[existing.uri]).toEqual([MP1]); + }); + + test('an existing collection still world-readable and not shared with the contacts is fixed at the Join', async () => { + const existing = existingCollection(BOB, null); + existing.acls[existing.uri] = createdCollectionAcl(existing.uri); + const j = join(MP1); + const w = setup({ acts: [j], stored: existing.stored, acls: existing.acls, items: existing.items }); + await emitJoin(w, j); + expect(w.calls.some(c => c.action === 'pod-collections.createAndAttach')).toBe(false); + expect(hasOwnPublicRead(w.state.acls[existing.uri])).toBe(false); + expect(w.state.items[existing.uri]).toEqual([MP1]); + }); + + test('a public read the pod refuses to remove: nothing written, NOT recorded, loudly logged — the next act retries', async () => { + const j = join(MP1); + const w = setup({ acts: [j], fail: { putStatus: 403 } }); + await emitJoin(w, j); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); + expect(w.calls.some(c => c.action === 'pod-collections.add')).toBe(false); + expect(ledgerOf(w)).toBeUndefined(); + expect(w.state.notifications).toEqual([]); + expect(w.logs.error.some(m => m.includes('public read') && m.includes('NOT recorded'))).toBe(true); + + // The pod accepts the change again: the same Join, notified again, is applied in full. + const retry = world({ stored: { ...w.state.stored }, items: w.state.items, acls: w.state.acls }); + await emitJoin(retry, j); + expect(attendees(retry)).toEqual([urnOf(BOB)]); + expect(hasOwnPublicRead(retry.state.acls[participationsUri(retry)])).toBe(false); + expect(participations(retry)).toEqual([MP1]); + expect(ledgerOf(retry)).toEqual({ activityUri: j.id, published: T0, change: 'join', member: urnOf(BOB) }); + }); + + test('a public read INHERITED from the container cannot be removed here: the act is not recorded', async () => { + const existing = existingCollection(BOB, null); + existing.acls[existing.uri] = [ + ...protectedAcl(existing.uri), + { '@id': `http://localhost:3000/_acl/bob/data/as/collection#DefaultRead`, 'acl:mode': 'acl:Read', 'acl:agentClass': 'foaf:Agent' } + ]; + const j = join(MP1); + const w = setup({ acts: [j], stored: existing.stored, acls: existing.acls, items: existing.items }); + await emitJoin(w, j); + expect(w.state.items[existing.uri]).toEqual([]); + expect(ledgerOf(w)).toBeUndefined(); + expect(w.logs.error.some(m => m.includes('inherited'))).toBe(true); + }); + + test('a refused group grant or an unreadable ACL: the act is not recorded', async () => { + for (const fail of [{ grant: true }, { aclRead: true }]) { + const j = join(MP1); + const w = setup({ acts: [j], fail }); + await emitJoin(w, j); + expect(attendees(w)).toEqual([]); + expect(ledgerOf(w)).toBeUndefined(); + expect(w.state.notifications).toEqual([]); + } + }); + + test('a participations write the pod refuses (the call resolves) leaves the act unrecorded (member sticky) and unnotified', async () => { + const j = join(MP1); + const w = setup({ acts: [j], fail: { participationsWrite: true } }); + await emitJoin(w, j); + expect(w.state.refusedWrites.map(r => r.action)).toEqual(['pod-collections.add']); + // The act (its URI/stamp/kind) is unrecorded, but the member URN was persisted before the writes: + // the entry carries only that sticky member, so the next act reuses it instead of a second URN. + expect(ledgerOf(w)).toEqual({ member: urnOf(BOB) }); + expect(w.state.notifications).toEqual([]); + expect(w.logs.error.some(m => m.includes('NOT recorded') && m.includes(`does not hold ${MP1}`))).toBe(true); + // The accepted residual: the list in the creator's pod was written; the next act re-applies both. + expect(attendees(w)).toEqual([urnOf(BOB)]); + const retry = world({ stored: { ...w.state.stored }, items: w.state.items, acls: w.state.acls }); + await emitJoin(retry, j); + expect(participations(retry)).toEqual([MP1]); + expect(ledgerOf(retry).change).toBe('join'); + expect(retry.state.notifications).toHaveLength(1); // the state the ledger held flips now + }); + + test('a Leave removes the meeting point from the participant\'s collection', async () => { + const j = join(MP1); + const l = leave(MP1); + const w = setup({ acts: [j, l] }); + await emitJoin(w, j); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); + expect(ledgerOf(w).change).toBe('leave'); + const removed = w.calls.find(c => c.action === 'pod-collections.remove'); + expect(removed.params).toEqual({ collectionUri: participationsUri(w), itemUri: MP1, actorUri: BOB }); + }); + + test('a Leave when the participant has no collection: the list is updated, nothing created, the act recorded', async () => { + const l = leave(MP1); + const w = setup({ acts: [l], items: { [attendeesOf(MP1)]: [urnOf(BOB)] } }); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(w.calls.some(c => ['pod-collections.createAndAttach', 'pod-collections.remove', 'pod-permissions.add'].includes(c.action))).toBe(false); + expect(ledgerOf(w).change).toBe('leave'); + }); +}); + +describe('registration — a pod failure the platform hides is never counted as applied', () => { + // The platform's `pod-collections.getItems` answers [] on a failed read, and its add/remove resolve + // when the pod refuses the PATCH: the backend reads with the status checked and reads every write back. + const listed = (w, mp = MP1) => ({ [attendanceSubject(mp, BOB)]: { activityUri: join(mp, '2026-10-29T09:00:00.000Z', BOB, 0).id, published: '2026-10-29T09:00:00.000Z', change: 'join', member: urnOf(BOB, mp) } }); + const notRecorded = (w, contains) => expect(w.logs.error.some(m => m.includes('NOT recorded') && m.includes(contains))).toBe(true); + + test("a Leave while the creator's pod fails the list read: NOT recorded, the URN stays, nobody notified — the same Leave, notified again, applies it", async () => { + const l = leave(MP1); + const existing = existingCollection(BOB, protectedAcl(`${BOB}/data/as/collection/participations-existing`)); + existing.items[existing.uri] = [MP1]; + const fail = { read: { [attendeesOf(MP1)]: 500 } }; + const w = setup({ acts: [l], stored: existing.stored, acls: existing.acls, items: { ...existing.items, [attendeesOf(MP1)]: [urnOf(BOB)] }, ledger: listed(), fail }); + // What the platform's own read would have said: nobody listed. + expect(await w.ctx.call('pod-collections.getItems', { collectionUri: attendeesOf(MP1), actorUri: ALICE })).toEqual([]); + await emitLeave(w, l); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(w.state.items[existing.uri]).toEqual([MP1]); // nothing written to either collection + expect(writes(w.calls)).toEqual([]); + expect(ledgerOf(w).change).toBe('join'); + expect(w.state.notifications).toEqual([]); + notRecorded(w, `${attendeesOf(MP1)} (HTTP 500)`); + + delete fail.read; + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(w.state.items[existing.uri]).toEqual([]); + expect(ledgerOf(w)).toMatchObject({ activityUri: l.id, change: 'leave' }); + expect(w.state.notifications).toHaveLength(1); + }); + + test('a Join whose list write the pod refuses: NOT recorded, nothing notified, the meeting point kept out of the participant\'s collection — the same Join, notified again, applies it', async () => { + const j = join(MP1); + const fail = { attendeesWrite: true }; + const w = setup({ acts: [j], fail }); + await emitJoin(w, j); + expect(w.state.refusedWrites.map(r => r.action)).toEqual(['attendees.add']); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); + expect(w.calls.some(c => c.action === 'pod-collections.add')).toBe(false); + expect(ledgerOf(w)).toEqual({ member: urnOf(BOB) }); // the sticky member only + expect(w.state.notifications).toEqual([]); + notRecorded(w, `does not hold ${urnOf(BOB)}`); + + fail.attendeesWrite = false; + await emitJoin(w, j); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(participations(w)).toEqual([MP1]); + expect(ledgerOf(w)).toEqual({ activityUri: j.id, published: T0, change: 'join', member: urnOf(BOB) }); + expect(w.state.notifications).toHaveLength(1); + }); + + test('a Leave whose list removal the pod refuses: NOT recorded, the URN stays, nobody notified', async () => { + const l = leave(MP1); + const w = setup({ acts: [l], items: { [attendeesOf(MP1)]: [urnOf(BOB)] }, ledger: listed(), fail: { attendeesWrite: true } }); + await emitLeave(w, l); + expect(w.state.refusedWrites.map(r => r.action)).toEqual(['attendees.remove']); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(ledgerOf(w).change).toBe('join'); + expect(w.state.notifications).toEqual([]); + notRecorded(w, `still holds ${urnOf(BOB)}`); + }); + + test('a Leave whose participations removal the pod refuses: NOT recorded, not notified; the list removal stands (the accepted residual) and the next Leave completes it', async () => { + const j = join(MP1); + const l = leave(MP1); + const fail = {}; + const w = setup({ acts: [j, l], fail }); + await emitJoin(w, j); + fail.participationsWrite = true; + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([MP1]); + expect(ledgerOf(w).change).toBe('join'); + expect(w.state.notifications).toHaveLength(1); // the Join's only + notRecorded(w, `still holds ${MP1}`); + + fail.participationsWrite = false; + await emitLeave(w, l); + expect(participations(w)).toEqual([]); + expect(ledgerOf(w).change).toBe('leave'); + expect(w.state.notifications).toHaveLength(2); // the state the ledger held flips now + }); + + test('a write that cannot be read back is not counted: NOT recorded, not notified', async () => { + const j = join(MP1); + const w = setup({ acts: [j], fail: { read: { [`${BOB}/data/as/collection/participations-1`]: 403 } } }); + await emitJoin(w, j); + expect(participations(w)).toEqual([MP1]); // the write landed, but nothing could show it + expect(ledgerOf(w)).toEqual({ member: urnOf(BOB) }); + expect(w.state.notifications).toEqual([]); + notRecorded(w, 'participations-1 (HTTP 403)'); + }); + + test('a collection the pod creates but does not link to the profile is never used: nothing written, nothing recorded — the next Join links a new one', async () => { + const j = join(MP1); + const fail = { attach: true }; + const w = setup({ acts: [j], fail }); + await emitJoin(w, j); + expect(w.state.created).toHaveLength(1); + expect(participationsUri(w)).toBeUndefined(); + expect(w.state.items[w.state.created[0]]).toEqual([]); + expect(attendees(w)).toEqual([]); + expect(w.calls.some(c => ['attendees.add', 'pod-collections.add', 'pod-permissions.add', 'signature.proxy.query'].includes(c.action))).toBe(false); + expect(ledgerOf(w)).toBeUndefined(); + expect(w.state.notifications).toEqual([]); + expect(w.logs.error.some(m => m.includes('NOT recorded') && m.includes('did not link it'))).toBe(true); + + fail.attach = false; + await emitJoin(w, j); + expect(w.state.created).toHaveLength(2); + expect(participationsUri(w)).toBe(w.state.created[1]); + expect(participations(w)).toEqual([MP1]); + expect(w.state.items[w.state.created[0]]).toEqual([]); // the unlinked one stays unused + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(ledgerOf(w).change).toBe('join'); + }); +}); + +describe("registration — attendance follows the participant's LATEST act, whatever order notifications run in", () => { + test('a stale act (the ledger holds a newer Leave) changes nothing and notifies no one', async () => { + const j = join(MP1); + const l = leave(MP1); + const w = setup({ acts: [j, l], ledger: { [attendanceSubject(MP1, BOB)]: { activityUri: l.id, published: T1, change: 'leave', member: urnOf(BOB) } } }); + await emitJoin(w, j); + expect(writes(w.calls)).toEqual([]); + expect(w.logs.info.some(m => m.includes('not newer than the last act applied'))).toBe(true); + }); + + test('the same Join notified twice (in turn, then concurrently): applied once, notified once', async () => { + const j = join(MP1); + let w = setup({ acts: [j] }); + await emitJoin(w, j); + await emitJoin(w, j); + expect(w.calls.filter(c => c.action === 'attendees.add')).toHaveLength(1); + expect(w.state.notifications).toHaveLength(1); + w = setup({ acts: [j] }); + await Promise.all([emitJoin(w, j), emitJoin(w, j)]); + expect(w.calls.filter(c => c.action === 'attendees.add')).toHaveLength(1); + expect(w.state.notifications).toHaveLength(1); + }); + + test('join then leave, the Leave handled first: ends NOT attending, out of the collection', async () => { + const j = join(MP1); + const l = leave(MP1); + const w = setup({ acts: [j, l], delays: { [`read:${j.id}`]: 40 } }); + const joining = emitJoin(w, j); await new Promise(resolve => setTimeout(resolve, 5)); - const j = receiveJoin(svc, ctx, { id: JOIN }); - await Promise.all([l, j]); - expect(state.items).toEqual([BOB]); + await Promise.all([joining, emitLeave(w, l)]); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); + expect(ledgerOf(w).change).toBe('leave'); }); - test('a replayed older Join after a later Leave changes nothing (the ledger says the Leave is newer)', async () => { - const { ctx, state, calls } = world({ - stored: { [JOIN]: join, [LEAVE]: leave, [MP]: meetingPoint() }, - ledger: { [BOB]: { activityUri: LEAVE, published: leave.published, change: 'leave' } } - }); - const { svc, logs } = service(); - await receiveJoin(svc, ctx, { id: JOIN }); - expect(state.items).toEqual([]); - expect(adds(calls)).toEqual([]); - expect(logs.info.some(m => m.includes('not newer than the last act applied'))).toBe(true); + test('leave then join, the Join handled first: ends attending, in the collection', async () => { + const l = leave(MP1, T0); + const j = join(MP1, T1); + const w = setup({ acts: [j, l], delays: { [`read:${l.id}`]: 60 } }); + const leaving = emitLeave(w, l); + await new Promise(resolve => setTimeout(resolve, 5)); + await Promise.all([leaving, emitJoin(w, j)]); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(participations(w)).toEqual([MP1]); + expect(ledgerOf(w).change).toBe('join'); }); - test('every applied act is recorded, even when the collection already matched it', async () => { - const { ctx, state } = world({ stored: { [JOIN]: join, [MP]: meetingPoint() }, items: [BOB] }); - await receiveJoin(service().svc, ctx, { id: JOIN }); - expect(state.ledger[BOB]).toEqual({ activityUri: JOIN, published: join.published, change: 'join' }); + test('a newer Join while already attending is recorded but notifies no one; so is a Leave of someone who never joined', async () => { + const j1 = join(MP1, T0); + const j2 = join(MP1, T1, BOB, 2); + let w = setup({ acts: [j1, j2] }); + await emitJoin(w, j1); + await emitJoin(w, j2); + expect(ledgerOf(w).activityUri).toBe(j2.id); + expect(w.state.notifications).toHaveLength(1); + const l = leave(MP1); + w = setup({ acts: [l] }); + await emitLeave(w, l); + expect(ledgerOf(w).change).toBe('leave'); + expect(w.state.notifications).toEqual([]); + }); +}); + +describe('registration — the creator is notified ALWAYS anonymously (the contacts list is forgeable)', () => { + const notified = async ({ change = 'join', fail } = {}) => { + const j = join(MP1); + const l = leave(MP1); + const w = setup({ acts: [j, l], fail }); + await emitJoin(w, j); + if (change === 'leave') await emitLeave(w, l); + return w; + }; + + test('a Join: anonymous — no name, no WebID, no activity; the participant\'s contacts list is never read', async () => { + const w = await notified(); + const [n] = w.state.notifications; + expect(n.recipientUri).toBe(ALICE); // Alice is the creator; Bob the participant + expect(n.template.title.fr).toContain('Un participant a rejoint'); + expect(n.template.title.en).toContain('A participant joined'); + expect(JSON.stringify(n.template)).not.toContain('participantName'); + expect(n).not.toHaveProperty('participantName'); + expect(n).not.toHaveProperty('activity'); + expect(JSON.stringify(n)).not.toContain(BOB); // never the participant's WebID + // The only read of a /contacts collection a naming notification would have made is gone. + const readsOf = uri => w.calls.filter(c => ['pod-resources.get', 'pod-collections.getItems'].includes(c.action) && (c.params.resourceUri ?? c.params.collectionUri) === uri); + expect(readsOf(contactsOf(BOB))).toEqual([]); }); - test('an act without a pod stamp cannot be ordered: nothing written', async () => { - const unstamped = { ...join, published: undefined }; - const { ctx, calls } = world({ stored: { [JOIN]: unstamped, [MP]: meetingPoint() } }); - const { svc, logs } = service(); - await receiveJoin(svc, ctx, { id: JOIN }); - expect(adds(calls)).toEqual([]); - expect(calls.some(c => c.action === 'triplestore.update')).toBe(false); - expect(logs.warn.some(m => m.includes('no pod stamp'))).toBe(true); + test('a Leave: the withdrawal wording, also anonymous', async () => { + const w = await notified({ change: 'leave' }); + const n = w.state.notifications[1]; + expect(n.template.title.fr).toContain('Un participant a quitté'); + expect(n.template.title.en).toContain('A participant left'); + expect(n).not.toHaveProperty('participantName'); + expect(n).not.toHaveProperty('activity'); + }); + + test('the meeting point is named through template parameters; the link opens its event\'s meeting points', async () => { + const w = await notified(); + const [n] = w.state.notifications; + expect(n.meetingPointName).toBe('Rendez-vous mp1'); + expect(n.eventUri).toBe(EVENT1); + expect(n.context).toBe(MP1); + expect(n.template.title.fr).toContain('{{{meetingPointName}}}'); + expect(n.template.title.en).toContain('{{{meetingPointName}}}'); + expect(n.template.actions).toEqual([{ caption: { en: 'View', fr: 'Voir' }, link: '/events/{{encodeUri eventUri}}/meeting-points' }]); + }); + + test('a notification failure does not fail the act', async () => { + const w = await notified({ fail: { notify: true } }); + expect(ledgerOf(w).change).toBe('join'); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(w.logs.error.some(m => m.includes('Could not notify'))).toBe(true); + }); + + test('a creator joining their own meeting point is not notified', async () => { + const j = join(MP1, T0, ALICE); + const w = setup({ acts: [j] }); + await emitJoin(w, j); + expect(attendees(w)).toEqual([urnOf(ALICE)]); + expect(w.state.notifications).toEqual([]); }); }); describe('registration — a write in flight at the timeout (no re-alignment: decided limit)', () => { // Bob joined then left (Leave L0 recorded). He acts once more; that act's write is sent before the - // 50 ms timeout and lands at 120 ms; nothing follows. The late write is the latest act: it must stand. - const L0 = { id: `${BOB}/data/activities/leave-0`, type: 'Leave', actor: BOB, object: MP, to: ALICE, published: '2026-10-13T09:00:00.000Z' }; - const J0 = { id: `${BOB}/data/activities/join-0`, type: 'Join', actor: BOB, object: MP, to: ALICE, published: '2026-10-13T09:00:00.000Z' }; + // timeout and lands after it; nothing follows. The late write is the latest act: it must stand. + const L0 = leave(MP1, '2026-10-29T09:00:00.000Z', BOB, 0); + const J0 = join(MP1, '2026-10-29T09:00:00.000Z', BOB, 0); + const subject = () => attendanceSubject(MP1, BOB); test('a late, unrecorded REJOIN is not undone by the older recorded Leave: ends attending', async () => { - const { ctx, state } = world({ - stored: { [JOIN]: join, [MP]: meetingPoint(), [L0.id]: L0 }, - addDelay: 120, - ledger: { [BOB]: { activityUri: L0.id, published: L0.published, change: 'leave' } } - }); - const { svc } = service({ timeoutMs: 50 }); - await receiveJoin(svc, ctx, join); + const j = join(MP1); + const w = setup({ acts: [j, L0], delays: { 'attendees.add': 150 }, timeoutMs: 80, ledger: { [subject()]: { activityUri: L0.id, published: L0.published, change: 'leave', member: urnOf(BOB) } } }); + await emitJoin(w, j); await new Promise(resolve => setTimeout(resolve, 300)); - expect(state.items).toEqual([BOB]); + expect(attendees(w)).toEqual([urnOf(BOB)]); }); test('the mirror case: a late, unrecorded LEAVE is not undone by the older recorded Join: ends NOT attending', async () => { - const slowRemove = world({ - stored: { [LEAVE]: leave, [MP]: meetingPoint(), [J0.id]: J0 }, - items: [BOB], - ledger: { [BOB]: { activityUri: J0.id, published: J0.published, change: 'join' } } + const l = leave(MP1); + const w = setup({ + acts: [l, J0], + items: { [attendeesOf(MP1)]: [urnOf(BOB)] }, + delays: { 'attendees.remove': 150 }, + timeoutMs: 80, + ledger: { [subject()]: { activityUri: J0.id, published: J0.published, change: 'join', member: urnOf(BOB) } } }); - const { ctx, state } = slowRemove; - const call = ctx.call; - ctx.call = async (action, params) => { - if (action === 'attendees.remove') await new Promise(resolve => setTimeout(resolve, 120)); // lands late - return call(action, params); - }; - const { svc } = service({ timeoutMs: 50 }); - await receiveLeave(svc, ctx, leave); + await emitLeave(w, l); await new Promise(resolve => setTimeout(resolve, 300)); - expect(state.items).toEqual([]); + expect(attendees(w)).toEqual([]); }); test('KNOWN LIMIT (documented in updateAttendance): an older Join whose add lands after a newer Leave stays applied until the next act', async () => { - const { ctx, state } = world({ stored: { [JOIN]: join, [LEAVE]: leave, [MP]: meetingPoint() }, addDelay: 120 }); - const { svc } = service({ timeoutMs: 50 }); - const j = receiveJoin(svc, ctx, join); + const j = join(MP1); + const l = leave(MP1); + const w = setup({ acts: [j, l], delays: { 'attendees.add': 150 }, timeoutMs: 80 }); + const joining = emitJoin(w, j); await new Promise(resolve => setTimeout(resolve, 10)); - const l = receiveLeave(svc, ctx, leave); - await Promise.all([j, l]); - await new Promise(resolve => setTimeout(resolve, 250)); - expect(state.ledger[BOB].change).toBe('leave'); // the newer act is the recorded one - expect(state.items).toEqual([BOB]); // the late add of the older Join stands — no re-alignment + await Promise.all([joining, emitLeave(w, l)]); + await new Promise(resolve => setTimeout(resolve, 300)); + expect(ledgerOf(w).change).toBe('leave'); // the newer act is the recorded one + expect(attendees(w)).toEqual([urnOf(BOB)]); // the late add of the older Join stands — no re-alignment }); }); -describe("registration — a Join emitted from the joiner's outbox adds the meeting point's real organizer to her contacts", () => { - const bobActor = { id: BOB, type: 'Person', 'apods:contacts': BOB_CONTACTS }; - const added = calls => calls.filter(c => c.action === 'pod-wac-groups.addMember').map(c => c.params); +describe('registration — a participant who rewrites their profile secret between acts stays ONE member', () => { + const rotate = (w, who, secret) => { + w.state.stored[profileOf(who)] = profile(who, { [FP_SECRET]: secret }); + }; + const urnWith = (who, secret, mp = MP1) => memberUrn({ participantUri: who, eventUri: EVENT_OF[mp], secret }); + const secretN = n => String(n).repeat(64); - test('the normal case: the stored creator of a meeting point in her own pod', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint(), [BOB]: bobActor } }); - await emitJoin(service().svc, ctx, join); - expect(added(calls)).toEqual([{ groupUri: `${BOB_CONTACTS}-group`, memberUri: ALICE, actorUri: BOB }]); + test('Join, rotate, Join: one URN in the list; then Leave empties it', async () => { + const acts = [1, 2, 3, 4, 5].map(n => join(MP1, `2026-10-29T10:00:0${n}.000Z`, BOB, n)); + const l = leave(MP1, '2026-10-29T10:00:09.000Z', BOB, 9); + const w = setup({ acts: [...acts, l] }); + for (const [i, a] of acts.entries()) { + rotate(w, BOB, secretN(i + 1)); + await emitJoin(w, a); + } + expect(attendees(w)).toEqual([urnWith(BOB, secretN(1))]); + expect(w.state.notifications).toHaveLength(1); + expect(ledgerOf(w)).toEqual({ activityUri: acts[4].id, published: acts[4].published, change: 'join', member: urnWith(BOB, secretN(1)) }); + rotate(w, BOB, secretN(6)); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); + expect(ledgerOf(w)).toEqual({ activityUri: l.id, published: l.published, change: 'leave', member: urnWith(BOB, secretN(1)) }); }); - test('a creator named in the webhook body is ignored (Mallory cannot get into Bob\'s contacts)', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint(), [BOB]: bobActor } }); - await emitJoin(service().svc, ctx, { ...join, object: { id: MP, type: 'Event', 'dc:creator': MALLORY } }); - expect(added(calls).map(p => p.memberUri)).toEqual([ALICE]); + test('Join, rotate, Leave, Join: still the FIRST URN — the member is sticky per pair, never recomputed', async () => { + const j1 = join(MP1, T0, BOB, 1); + const l = leave(MP1, T1, BOB, 1); + const j2 = join(MP1, T2, BOB, 2); + const w = setup({ acts: [j1, l, j2] }); + await emitJoin(w, j1); + rotate(w, BOB, secretN(7)); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + await emitJoin(w, j2); + // The ledger kept the URN chosen at the first Join; the rotated secret is never hashed again. + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(attendees(w)).not.toContain(urnWith(BOB, secretN(7))); }); - test('a stored creator who does not own the pod holding the meeting point is refused', async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint({ 'dc:creator': MALLORY }), [BOB]: bobActor } }); - await emitJoin(service().svc, ctx, join); - expect(added(calls)).toEqual([]); + // THE DEFECT the sticky member fixes: a Join whose list add lands but a later step fails is left + // unrecorded; the participant rewrites their secret and joins again — that must not list a second URN. + const onEmitWith = (w, ctx, key, act) => registration.activities[key].onEmit.call(w.registration, ctx, act, act.actor); + + test('partial failure (the pod refuses the participations write after the list add) + secret rewrite + Join: ONE URN; a Leave empties the list', async () => { + const j1 = join(MP1, T0, BOB, 1); + const j2 = join(MP1, T1, BOB, 2); + const l = leave(MP1, T2, BOB, 3); + const fail = { participationsWrite: true }; + const w = setup({ acts: [j1, j2, l], fail }); + await emitJoin(w, j1); + expect(attendees(w)).toEqual([urnOf(BOB)]); // the add landed… + expect(ledgerOf(w).activityUri).toBeUndefined(); // …the act did not get recorded + fail.participationsWrite = false; + rotate(w, BOB, secretN(4)); + await emitJoin(w, j2); + expect(attendees(w)).toEqual([urnOf(BOB)]); // ONE URN — not a second one from the new secret + expect(ledgerOf(w)).toEqual({ activityUri: j2.id, published: T1, change: 'join', member: urnOf(BOB) }); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + expect(participations(w)).toEqual([]); }); - test('a Join stored in another actor\'s pod is not Bob\'s', async () => { - const forged = `${MALLORY}/data/activities/j`; - const { ctx, calls } = world({ stored: { [forged]: { ...join, id: forged }, [MP]: meetingPoint(), [BOB]: bobActor } }); - await emitJoin(service().svc, ctx, forged); - expect(added(calls)).toEqual([]); + test('partial failure at the ledger record (after both writes) + secret rewrite + Join: ONE URN; a Leave empties the list', async () => { + const j1 = join(MP1, T0, BOB, 1); + const j2 = join(MP1, T1, BOB, 2); + const l = leave(MP1, T2, BOB, 3); + const w = setup({ acts: [j1, j2, l] }); + let failRecord = true; + const ctx = { + call: async (action, params) => { + if (action === 'triplestore.update' && failRecord && params.query.includes('attendanceAct')) { + failRecord = false; + throw new Error('the ledger record failed'); + } + return w.ctx.call(action, params); + } + }; + await onEmitWith(w, ctx, 'join', j1); + expect(attendees(w)).toEqual([urnOf(BOB)]); + expect(ledgerOf(w).activityUri).toBeUndefined(); + rotate(w, BOB, secretN(5)); + await onEmitWith(w, ctx, 'join', j2); + expect(attendees(w)).toEqual([urnOf(BOB)]); + await onEmitWith(w, ctx, 'leave', l); + expect(attendees(w)).toEqual([]); }); - test("a contacts collection outside the joiner's pod is not written", async () => { - const { ctx, calls } = world({ stored: { [JOIN]: join, [MP]: meetingPoint(), [BOB]: { ...bobActor, 'apods:contacts': `${MALLORY}/data/c` } } }); - await emitJoin(service().svc, ctx, join); - expect(added(calls)).toEqual([]); + test('a member persist still in flight at the timeout + secret rewrite + Join: the late write replaces nothing — ONE URN; a Leave empties the list', async () => { + const j1 = join(MP1, T0, BOB, 1); + const j2 = join(MP1, T1, BOB, 2); + const l = leave(MP1, T2, BOB, 3); + const w = setup({ acts: [j1, j2, l], timeoutMs: 80 }); + let slowOnce = true; + const ctx = { + call: async (action, params) => { + if (action === 'triplestore.update' && slowOnce && !params.query.includes('attendanceAct')) { + slowOnce = false; + await new Promise(resolve => setTimeout(resolve, 150)); // lands after the 80 ms limit + } + return w.ctx.call(action, params); + } + }; + const first = onEmitWith(w, ctx, 'join', j1); // abandoned at 80 ms, its member write still in flight + await new Promise(resolve => setTimeout(resolve, 100)); + rotate(w, BOB, secretN(6)); + await onEmitWith(w, ctx, 'join', j2); // persists, lists and records the NEW secret's URN + await first; + await new Promise(resolve => setTimeout(resolve, 150)); + expect(attendees(w)).toEqual([urnWith(BOB, secretN(6))]); + expect(ledgerOf(w).member).toBe(urnWith(BOB, secretN(6))); // the late write was a no-op + await onEmitWith(w, ctx, 'leave', l); + expect(attendees(w)).toEqual([]); + }); + + test('a Join of an attending participant re-adds the recorded URN when it is missing from the list', async () => { + const j1 = join(MP1, T0, BOB, 1); + const j2 = join(MP1, T1, BOB, 2); + const w = setup({ acts: [j1, j2] }); + await emitJoin(w, j1); + w.state.items[attendeesOf(MP1)] = []; + rotate(w, BOB, secretN(8)); + await emitJoin(w, j2); + expect(attendees(w)).toEqual([urnOf(BOB)]); + }); + + test('a Leave with no Join recorded computes the URN from the current secret', async () => { + const l = leave(MP1); + const w = setup({ acts: [l], items: { [attendeesOf(MP1)]: [urnOf(BOB)] } }); + await emitLeave(w, l); + expect(attendees(w)).toEqual([]); + }); + + test('two participants never share an entry', async () => { + const jb = join(MP1, T0, BOB); + const jc = join(MP1, T0, CAROL); + const w = setup({ acts: [jb, jc] }); + await emitJoin(w, jb); + await emitJoin(w, jc); + expect(attendanceSubject(MP1, BOB)).not.toBe(attendanceSubject(MP1, CAROL)); + expect(ledgerOf(w, MP1, BOB).member).toBe(urnOf(BOB)); + expect(ledgerOf(w, MP1, CAROL).member).toBe(urnOf(CAROL)); + }); + + test('an entry under the old (meeting point, URN) key is not found: nothing recorded', async () => { + const j = join(MP1); + const old = attendanceSubject(MP1, urnOf(BOB)); + const w = setup({ acts: [j], ledger: { [old]: { activityUri: `${BOB}/zz`, published: '2030-01-01T00:00:00.000Z', change: 'leave', member: urnOf(BOB) } } }); + await emitJoin(w, j); + expect(attendees(w)).toEqual([urnOf(BOB)]); }); }); describe('registration — matchers never throw', () => { - test('a fetch failure while matching reports no match', async () => { - const { svc, logs } = service(); + test('routing is type-only: the object is never fetched; a garbage activity reports no match', async () => { + const logs = { error: [] }; + const svc = { name: 'registration', logger: { error: m => logs.error.push(m) } }; const failing = async () => { throw new Error('proxy unreachable'); }; - for (const key of ['join', 'leave']) { - const result = await registration.activities[key].match.call(svc, { type: key === 'join' ? 'Join' : 'Leave', object: MP }, failing); - expect(result.match).toBe(false); + for (const [key, type] of [['join', 'Join'], ['leave', 'Leave']]) { + const routed = await registration.activities[key].match.call(svc, { type, object: MP1 }, failing); + expect(routed.match).toBe(true); } - expect(logs.error).toHaveLength(2); + const unmatched = await registration.activities.join.match.call(svc, { type: 'Create', object: MP1 }, failing); + expect(unmatched.match).toBe(false); + expect(logs.error).toHaveLength(0); }); }); describe('attendance-ledger — the order of acts', () => { - const at = (published, activityUri = JOIN) => ({ activityUri, published }); + const at = (published, activityUri = join(MP1).id) => ({ activityUri, published }); test('a later stamp is newer; an earlier one is not; a tie is broken by the activity URI', () => { expect(isNewerAct(at('2026-10-13T10:00:01Z'), at('2026-10-13T10:00:00Z'))).toBe(true); expect(isNewerAct(at('2026-10-13T09:59:59Z'), at('2026-10-13T10:00:00Z'))).toBe(false); @@ -325,9 +802,9 @@ describe('attendance-ledger — the order of acts', () => { expect(isNewerAct(at(undefined), undefined)).toBe(false); expect(isNewerAct(at('not a date'), undefined)).toBe(false); }); - test('one entry per (meeting point, participant), under a URN the store accepts', () => { - expect(attendanceSubject(MP, BOB)).not.toBe(attendanceSubject(MP, MALLORY)); - expect(attendanceSubject(MP, BOB)).toMatch(/^urn:festipod:attendance:[^<>"{}|^`\\ ]+$/); - expect(() => lastAttendanceQuery(MP, BOB)).not.toThrow(); + test('one entry per (meeting point, member URN), under a URN the store accepts', () => { + expect(attendanceSubject(MP1, BOB)).not.toBe(attendanceSubject(MP1, CAROL)); + expect(attendanceSubject(MP1, BOB)).toMatch(/^urn:festipod:attendance:[^<>"{}|^`\\ ]+$/); + expect(() => lastAttendanceQuery(MP1, BOB)).not.toThrow(); }); }); diff --git a/docker-compose.coolify.yml b/docker-compose.coolify.yml index b4a2ada..2c708bc 100644 --- a/docker-compose.coolify.yml +++ b/docker-compose.coolify.yml @@ -22,8 +22,17 @@ # backend request would be refused (404). # # The backend registers its app actor in its main dataset on the first boot, with the -# domain it had at that time: set the domains in Coolify BEFORE the first deployment. If -# they change later, delete the two datasets in Fuseki and redeploy. +# domain it had at that time: set the domains in Coolify BEFORE the first deployment. The +# main dataset must be a SECURE one (WebACL is on): the backend creates it so when it does +# not exist, and refuses to start on an existing one that is not secure. To start again from +# nothing (the domains changed, or the main dataset was created before WebACL was on): +# 1. delete the two datasets in Fuseki. Fuseki's delete leaves a secure dataset's files on +# disk — remove `databases/
`, `databases/
Acl`, `databases/
Mirror` and +# `configuration/
.ttl` under the Fuseki base too, or a dataset created again under +# the same name reopens the old data; +# 2. empty this stack's Redis (the `redis-data` volume): its cache outlives the datasets and +# would keep serving the old app actor, keys and access needs; +# 3. redeploy. # # Fuseki is the one shared with the other apps (shared-infra, in the "infra" project): the # backend joins the "coolify" network to reach it, with its own pair of datasets. Redis diff --git a/docs/cucumber-integration.md b/docs/cucumber-integration.md index 039203b..f47ffd7 100644 --- a/docs/cucumber-integration.md +++ b/docs/cucumber-integration.md @@ -241,7 +241,7 @@ Alors une erreur de validation est affichée pour "Date" Alors je peux voir la liste des participants Alors l'écran affiche les informations de l'événement Alors je peux m'inscrire à l'événement -Alors je peux voir le QR code +Alors je peux voir le lien de partage ``` ## Test Outcomes diff --git a/reports/cucumber-report.html b/reports/cucumber-report.html index 53013da..814c5d0 100644 --- a/reports/cucumber-report.html +++ b/reports/cucumber-report.html @@ -50,7 +50,7 @@