Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,18 @@

## Unreleased

- The repo, with the standard Payload plugin kit and an empty plugin. Nothing to install yet. Public since 2026-11-22.
- The repo, with the standard Payload plugin kit. Public since 2026-11-22.
- The first version of the plugin (for Captive Origins' business accounts):
- `share-groups` and `share-members` collections, with Owner, Manager and Viewer levels the host can rename, and member types the host can extend to organizations.
- A group always keeps an active Owner. The last Owner can't leave or be demoted, and two Owners changing each other at once leave one.
- Host hooks `canCreateGroup`, `canInvite`, `canChangeLevel`, `canRemove` and `canAccept`, all failing closed on anything but an exact `true`.
- A required `refuseMember` veto (or an explicit `false`) on invite, accept and level change, applied to server code too. The reason is shown to the person refused, so the README warns against reasons that reveal an age.
- An append-only `share-member-events` history of every invite, accept, level change and removal, written in the same transaction.
- Second review fixes: `notes`, `invitedBy` and `removedBy` are readable by Owners and Managers only (notes capped at 500); a user accepts only their own invitation and `canAccept` is for organizations; a throwing `identities` hook refuses before any host hook runs; `refuseMember` runs for each person behind an organization (`peopleOf`, required with organizations); the plugin refuses to start without database transactions; bulk member updates are refused.
- Deletes always throw, even with `overrideAccess`. Hooks receive plain ids and references, and the `id` and `data` of the change. Viewers see only Owners and Managers by default.
- Audit hooks for invite, accept, change level and remove.
- `shareGroupField`, `canView`, `canEdit` and `sharedWhere` for host collections.
- Nothing is deleted; removal is a status, and a unique key stops a second live row for the same group and member.
- Third review fixes: `canRead` can only add rows to the default rules (`true`, `{}` and a throw add nothing); the transactions check opens and rolls back a real transaction, so an adapter with `transactionOptions: false` is refused, with an `allowWithoutTransactions` opt-out; self-accept and self-leave can't overwrite staff notes; a removal can't carry a level change; accept with a level change records both events; the veto runs before the already-a-member check; `invitedBy` ignores users from other auth collections; `@payloadcms/graphql` pinned. After the re-review: `identities` keeps an organization only when `peopleOf` lists the user (asked once per request, dropped on a throw); `invitedBy` is always the acting user or none; member changes refuse without a request transaction (`disableTransaction`); non-staff can't write notes on an organization's row they act for or on a new invitation; the transaction check awaits the transaction and covers group creation. Documented: `peopleOf` must cover everyone `identities` maps, the veto isn't given current members, and a group's founding owner stays visible.
- Tested: 100 tests against real Payload 3.92 with an in-memory MongoDB replica set, covering each path above, refusals over REST, GraphQL and bulk update, server-code attempts to revive or widen a membership, repeated two-at-once runs for the last-Owner and duplicate-invite rules, a real adapter started with `transactionOptions: false` (refused), the history rows and who can read them, members keyed by collection, what a Viewer sees of other members, and clean-up of the database and server at the end.
- Not tested: a hosted production database, a live site, the admin screens in a browser, and a very large number of members.
84 changes: 80 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,91 @@

Sharing for Payload: people share records with other users and organizations, under access rules the host passes in.

**Status:** a skeleton. The plugin does nothing yet; its pieces land as separate pull requests once the scope is agreed. One test checks the empty plugin leaves a config alone.
**Status:** first version, version 0.x, not on npm yet. It is tested against real Payload 3.92 with an in-memory MongoDB replica set (72 tests, including two requests at once and refusals over REST, GraphQL and bulk update). It has not been used in a live site yet, and the admin screens have not been checked in a browser. It needs a database that supports transactions (a MongoDB replica set), because the last-Owner rule and the history rely on them. On start it checks, and refuses to run without them.

## What it does

Nothing yet. The plugin will hold no roles of its own: who may share, what, and with whom is whatever the host passes in, and each defaults to nobody.
The plugin adds two collections.

## Install or build
- **`share-groups`**: a name, a kind you define (for example `hobby`, `family`, `brand`) and the owner it started with.
- **`share-members`**: who is in a group (a user, or a document from another collection such as organizations), at which level, with a status of invited, active or removed.

Not on npm yet. To work on it:
The levels are **Owner**, **Manager** and **Viewer**. You can rename them. A Viewer reads, a Manager reads and edits, an Owner does both and is who the host usually lets manage people.

Rules the plugin enforces itself, for server code as well as for clients:

- A group always has an active Owner. The last Owner can't leave or be demoted. Two Owners demoting each other at the same moment leave one.
- An invited member has no access until they accept. A user accepts their own invitation. Anyone can leave.
- A removed member stays on record. Nothing is deleted, not even by server code that skips access (every delete throws), and a second live row for the same group and member can't exist.
- Group kind and first owner can't change after the group is made.
- Level, status and notes are the only fields that change on a membership.

Everything else is the host's call, and every host hook fails closed. With no hooks, nobody can make a group or invite anyone.

## Install and set up

```
npm install @extantape/payload-plugin-sharing
```

```ts
import { sharing, shareGroupField, sharedWhere } from '@extantape/payload-plugin-sharing'

export default buildConfig({
plugins: [
sharing({
kinds: [{ value: 'hobby' }, { value: 'family' }, { value: 'brand' }],
memberTypes: ['organizations'], // besides users
identities: ({ user }) => [], // organizations this user acts for
canCreateGroup: ({ user }) => user.canMakeGroups === true,
canInvite: ({ actorRole, member }) => actorRole === 'owner' || (actorRole === 'manager' && member.level === 'viewer'),
canChangeLevel: ({ actorRole }) => actorRole === 'owner',
refuseMember: ({ subject, group }) => (subject.minor && group.kind !== 'family' ? 'Not available for this account.' : null),
}),
],
collections: [
{
slug: 'notes',
fields: [shareGroupField()],
access: { read: async ({ req }) => (await sharedWhere(req)) || false },
},
],
})
```

### Options

- `kinds`: the group kinds. With none, no group can be made.
- `levels`: rename or relabel `owner`, `manager` and `viewer`. The stored values must differ.
- `memberTypes`, `identities`: let organizations be members, and say which ones a signed-in user acts for. A membership held by an identity counts for the user.
- `peopleOf`: required with organizations (or `false`). Lists the people behind an organization, so `refuseMember` runs for each of them, with `via` set to the organization and `actor` set to who is making the change. **When `peopleOf` is a function, `identities` keeps an organization only when it lists the user for it** (asked once per organization per request; if it throws, the organization is dropped), so someone `identities` maps but `peopleOf` leaves out gets no access through it. With `peopleOf: false` there is no such check and every organization `identities` maps counts. A `peopleOf` that returns something other than a list drops the organization too. An empty list checks nobody. **Risk:** only the people listed at that moment are checked. Someone who joins the organization later gets the group's access through it without the veto being asked, so ask your veto again when people join, or keep organizations out of groups where it matters, such as anything with children.
- `canCreateGroup`, `canInvite`, `canChangeLevel`: only an exact `true` allows. A truthy value, a throw or no hook is a no. `canRemove` (default: `canChangeLevel`) and `canAccept` (default: nobody; for organization members only) work the same way. A user member can only ever accept their own invitation. If the `identities` hook throws, every host hook is skipped and the change is refused. Each gets the group, the membership and `actorRole`, the asker's own role in the group.
- `refuseMember`: required. A veto asked on every invitation, acceptance and level change, even from server code. Return `null` to go ahead, or a reason to refuse. Anything else refuses with a general message. A host can use it to keep minors out of every group kind except family. Pass `refuseMember: false` to say you have no veto.
**Warning:** the reason is shown to whoever was refused. Don't write a reason that gives away something private, such as an age or a guardian link. Return a general one like `Not available for this account.` The veto is given the group (`group.id`), not its current members. If your rule depends on who is already in, query `share-members` for that group yourself. On an invitation the veto runs before the already-a-member check, so a refused person gets the same answer whether or not they are in the group.
- `canRead`: who reads memberships. Default: your own rows, every row in groups where you are Owner or Manager, and only the Owners and Managers of groups where you are a Viewer. Those rules always apply. A `where` you return is ORed with them and can only add rows. `true`, `false`, an empty `where` and a throw add nothing, so no answer opens every row, children's included.
- `allowWithoutTransactions`: the plugin checks at start that the database can open a transaction and refuses to run if it can't (a MongoDB adapter with `transactionOptions: false` can't). This opts out. It is not safe: two Owners leaving at once can both pass the last-Owner check, and a change can be saved without its history row.
- `audit`: `before` and `after` hooks for invite, accept, change level and remove. A `before` hook that throws stops the change. Separately, every one of those changes is written to `share-member-events`, an append-only history that can't be edited or deleted, and that Owners can read.

### Helpers

- `shareGroupField({ name?, hasMany? })`: the relation a host collection adds. Setting or moving it needs Owner or Manager in the group the record goes into and the one it leaves. A change that isn't allowed is dropped.
- `canView(req, doc)` and `canEdit(req, doc)`: for the host's access functions. Both return false on any error.
- `sharedWhere(req, { need })`: a `where` for list access, or false.
- `membershipsOf`, `roleIn`, `groupIdsFor`, `identitiesOf`: lower-level reads. These throw on a read error, so wrap them if you use them directly.

## Limits

- A record can be in one group (or several, with `hasMany`). Records don't inherit from parent groups.
- Hooks get plain ids and `{ relationTo, value }` references, plus the `id` and `data` of the change.
- `notes`, `invitedBy` and `removedBy` on a membership are readable by the group's Owners and Managers only, and notes are capped at 500 characters.
- Someone changing their own row (accepting or leaving) can't write its notes (on a new invitation either), and neither can someone acting for an organization on its row, unless they are an Owner or Manager of the group. Server code can.
- Member changes need the request's transaction. Server code that passes `disableTransaction` is refused (unless you set `allowWithoutTransactions`).
- A removal can't carry a level change in the same update; do them in two steps, so each is checked and recorded.
- A group's `owner` field names who it started with, and every member who can read the group can see it, even after that person has left. Use the memberships for who the Owners are now.
- Memberships change one at a time; a bulk update is refused.
- Invitations are rows in `share-members`. The plugin sends no email.

## Build and test

```
npm install
Expand Down
9 changes: 8 additions & 1 deletion docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,11 @@
Dated decisions for this repo, newest last.

- 2026-11-22: created from the ops starter kit, area `co-plugins`.
- 2026-11-22: created as a skeleton on our side (Simon's go, for Captive Origins' business accounts). npm name @extantape/payload-plugin-sharing (D131). MIT, EXTANT APE. Contributions from co/ branches; only the owner merges (D256).
- 2026-11-22: created as a skeleton on our side (for Captive Origins' business accounts). npm name @extantape/payload-plugin-sharing. MIT, EXTANT APE. Contributions from co/ branches; only the owner merges.
- 2026-11-22: first version built for Captive Origins' business accounts, following three Captive Origins rules: shared collections with Owner, Manager and Viewer and at least one Owner; business accounts and brands; and a minor may be in a shared collection only through a family group with a linked guardian. The plugin stays agnostic: the minors rule is the host's `refuseMember` veto, not built in.
- 2026-11-22: invitations start as `invited` and a user accepts their own; organizations accept only through a host `canAccept` hook. Removal is a status, never a delete. The last-Owner rule is enforced in hooks with a lock write to the group inside the request's transaction, so it needs a MongoDB replica set.
- 2026-11-22: a group's kind and first owner are fixed after creation, because host rules (such as the minors rule) can depend on the kind.
- 2026-11-22: after EXTANT APE's review of the positions PR, `refuseMember` is required (`false` opts out), deletes always throw, member changes go to an append-only `share-member-events` history, and Viewers see only Owners and Managers by default (kids come first; `canRead` widens it).
- 2026-11-22: after EXTANT APE's second review: private member fields are Owner and Manager only, organization acceptance goes through `canAccept` and user acceptance is the user alone, organizations are vetoed per person through `peopleOf`, the plugin refuses to run without transactions, and bulk member updates are refused.
- 2026-11-23: after EXTANT APE's third review: `canRead` only adds rows to the default rules; the transactions check opens and rolls back a real transaction (`allowWithoutTransactions` opts out); self-accept and self-leave can't write notes; a removal can't carry a level change. The veto still isn't run when `identities` resolves and isn't given current members: the README says `peopleOf` must cover everyone `identities` maps and that the host queries members itself, because the veto has no group or level to judge at that point.
- 2026-11-23: after the re-review: `identities` keeps an organization only when `peopleOf` lists the user (asked once per request, dropped on a throw), `invitedBy` is always the acting user or none, member changes refuse without a request transaction, and non-staff can't write notes on an organization's row they act for. Someone who joins an organization after it was invited is still not vetoed until acceptance; documented.
2 changes: 1 addition & 1 deletion docs/first-public-push-audit.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# First public push audit

2026-11-22, before the repo went public (owner's words via Simon: "Prioritize that repo work for now then continue your other things"; D259 weekly grant).
2026-11-22, before the repo went public (owner's words: "Prioritize that repo work for now then continue your other things").

- **Leak check:** `scripts/leak-check.sh` passed on 18 files.
- **Secrets:** no keys, passwords, tokens or private addresses in any commit's files or diffs. Pattern hits were only version numbers such as 10.0.1 in the lockfile.
Expand Down
13 changes: 13 additions & 0 deletions docs/test-audit.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,19 @@

Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". Newest first.

## 2026-11-23: third review

- Promises: `canRead` only adds rows; the plugin refuses to start without transactions; a member can't write staff notes on their own row; a removal can't carry a level change; the veto runs before the duplicate check; hidden fields can't be searched.
- Covered: each of those in `test/plugin.test.ts` (100 tests), including a real adapter started with `transactionOptions: false`, and a Viewer's `where` and `sort` on notes. The weak tests (audit ids, per-person veto on accept, family group with an organization, the after-hook case) now assert what their names say.
- Also covered after the re-review: the history rows (every event, none for a refused change, no writes or edits, Owners read), members keyed by collection, what a Viewer sees of others, `identities` dropping organizations `peopleOf` doesn't list (and on a throw, cached per request), forged `invitedBy`, `disableTransaction`, notes on an organization's row, and the veto asked for a level change from server code.
- Gaps skipped (and why): someone who joins an organization after it was invited isn't vetoed until acceptance (documented).

## 2026-11-22: first version

- Promises: groups start with an active Owner; host hooks fail closed (exact `true`); the host veto applies to server code and on invite, accept and level change; a group always keeps an Owner, also under two changes at once; no duplicate live rows; no deletes; invited members have no access; accepting, leaving and removal rules; `canView`, `canEdit` and `sharedWhere` return false on error; the record's group field can only be set by Owners and Managers; levels can be renamed.
- Covered: each of those, in `test/plugin.test.ts` (100 tests, after the second review's field read, accept, identities-throw, per-person veto, transactions and bulk cases, and after EXTANT APE's review of the positions PR: server-code revive and widen attempts, deletes with overrideAccess, plain ids to hooks, the history, REST, GraphQL and bulk refusals, collection-keyed members). The two concurrency tests repeat four rounds for the last-Owner rule.
- Gaps skipped (and why): admin screens (no browser test yet); a standalone database without transactions (documented as unsupported); large member counts (no promise made).

## 2026-11-22: first audit (starter kit)

- Promises: none yet.
Expand Down
Loading
Loading