ExtantApe

payload plugin sharing

by ExtantApe
Roles & permissions
v3
^3.80.0
MIT

Overview

Summary generated from the README

Adds share-groups and share-members collections so users and organizations can share records under host-defined access rules. Host collections get a group relation field plus helpers for list and document access. It enforces a last-Owner rule, keeps an append-only history, and requires Payload 3.80 or later and a database with transactions such as a MongoDB replica set.

Features

  • Groups with invited, active and removed members at Owner, Manager or Viewer level
  • Fail-closed host hooks for creating groups, inviting, changing level, removing and vetoing members
  • Group field and helpers sharedWhere, canView and canEdit for access functions, with parent-based access
  • Organizations as members with a per-person veto and recheck helpers
  • Append-only member event history with audit hooks and an Owner change hook
  • Membership expiry pruning and user erasure replaced by a placeholder user

Use cases

  • Let users share notes or albums with family, teams or organizations at read or edit level
  • Keep minors out of selected group kinds through a veto applied on accept and level change
  • Erase a deleted user from sharing records while keeping group history intact

From the author

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

Installation

npm i @extantape/payload-plugin-sharing

0

Stars

0

Forks

0

Open Issues

3 days ago

Last Updated

425

Weekly Downloads

v0.3.0

npm Version

150.8 KB

Unpacked Size

0

Dependencies

GitHub stars

00 since Nov 22

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20260
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
npm weekly downloads

434+434 since Nov 25

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 2026434
Dec 5, 2026418
Dec 4, 2026487
Dec 3, 2026512
Dec 2, 2026650
Dec 1, 2026633
Nov 30, 2026455
Nov 29, 2026433
Nov 28, 2026413
Nov 27, 2026206
Nov 26, 2026165
Nov 25, 20260

Each point is npm's rolling 7-day download count.

Health Score

76/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1468358523-root.svg)](https://payloaddirectory.dev/plugins/1468358523-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1468358523-root"><img src="https://payloaddirectory.dev/badge/1468358523-root.svg" alt="Payload Directory"></a>
Updated Dec 2, 2026Created Nov 23, 2026Published Dec 2, 2026

README

payload-plugin-sharing

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

Status: version 0.x, on npm. It is tested against real Payload 3.92 with an in-memory MongoDB replica set (321 tests: 321 passed, 0 skipped; they include two requests at once, and refusals over REST, GraphQL, bulk update and duplicate). Erasure, expiry, rechecks and the batch helper have been tested only in that in-memory suite. The plugin 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

The plugin adds two collections.

  • 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.

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.
  • Duplicating is off for share-groups, share-members and share-member-events, for everyone, server code included. Make a new record the ordinary way. A create that carries duplicateFromID is refused before anything is read, even if another plugin turns Payload's duplicate setting back on.
  • The three sharing collections accept only plain field names: a name with a dot, or one starting with $, is refused. Send nested values as objects, such as owner: { relationTo, value }.
  • When access rules apply to a create, the saved record must match what they checked: a group's name (spaces trimmed), kind and first owner (you, if none is sent), or a membership's group, member and level, saved as an invitation. If a field default or another hook changes one of these, the create is rolled back. Send those values yourself.

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

On its own, and with others

On its own: Sharing needs only Payload, a database with transactions, your refuseMember and your access hooks. It keeps its settings on config.custom.sharing and doesn't depend on any other plugin.

Needs: Payload ^3.80.0 as a peer dependency. No other EXTANT APE plugin is required.

Works with:

  • Organizations: set memberTypes: ['organizations'], and write identities and peopleOf from that plugin's members, so an organization can join a group and the veto is asked for each person behind it.
  • Age Gate or Guardians: refuseMember can keep minors out of every group kind but family, using Age Gate's isMinor or the isMinor you give Guardians. Your site wires it.

Color Theory: none needed. It has no screens of its own, and its collections use Payload's standard admin, which takes Color Theory's admin colors when its applyToAdmin option is on.

Install and set up

npm install @extantape/payload-plugin-sharing
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 (a function, or exactly false; null, 0, an empty string and true stop the plugin from starting). 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. An organization is never refused for a person behind it when a signed-in person founds a group for it or accepts for it. The organization joins, a person the veto refuses is left out of it for that group (they get no access through it), and the person acting sees the same result either way. The reason is never kept or shown. Server code is still told the reason. Risk: who is left out is decided when the organization joins (at accept, at founding, and again when the level of an active row changes) and is never re-checked otherwise. Three cases follow. Someone who joins the organization later gets the group's access through it, without the veto being asked. A minor who turns adult stays out, which fails closed. An adult who later becomes vetoed keeps access until the next level change on that row, which adds them to the left-out list. Call recheckOrganization when people join (see Helpers), or keep organizations out of groups where it matters, such as anything with children. The left-out list is never passed to the audit hooks.
  • 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 when a member accepts, and when the level of an active member changes, even from server code. It is not asked when someone invites, so an inviter can't learn from the answer who it refuses (a minor, say): the invitation always succeeds, looks the same for everyone, and the reason goes to the person accepting. A level change on an invited row doesn't ask it either; acceptance decides. When it refuses a level change on an active row, a signed-in caller gets the same plain refusal as a canChangeLevel no, with nothing written. Server code (no signed-in user), and a group's founding Owner, are still asked on invite and see the reasons (an organization founding a group, with a signed-in person acting, follows the organization rule under peopleOf). 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. The veto is also given kind (the group's kind, checked against your configured kinds), members (every invited and active row of the group as it stands in this transaction, before the change: id, member, level, role and status, all frozen, with an organization listed as the organization) and membershipId (the row being judged, or null when the change creates it), so a minors rule can look at who is already in. The members are read once per round and every call in it gets the same list. If they can't be read in full, or the group's kind is no longer configured, the veto is not asked and the change is refused. A signed-in level change gets the same plain 403 in that case. When refuseMember is a function, every invite, accept, level change and removal takes the group's lock first, so a guardian leaving and a minor accepting at once can't both pass; the loser is turned back with "This group is changing right now. Try again in a moment." Pass refuseMember: false to say you have no veto. Only a function or exactly false is accepted; null, 0 and an empty string stop the plugin from starting, so a typo can't turn the veto off. Two limits that can't be removed. First, a vetoed member's row stays invited: they can't accept, and a person who can read that row (an Owner or Manager) sees it still waiting. Second, with a veto that depends on the level, an Owner changing the level of an active user can tell a refused change from an allowed one, and so learn something about that user. The refusal looks like a canChangeLevel no, but the difference between a refusal and a success is visible. This applies to user rows only. On an organization's row a person behind it who is refused is left out and the change goes ahead, so the answer is the same whoever is behind it. A level change on an invited row isn't asked at all. 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. "That member is already in this group" is said only to someone who can read that row. To anyone else, such as a Viewer the host lets invite, a hidden invited row gets the same general refusal for every person.
  • 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.
  • erasure: { eraser: sharingEraser(), placeholder: { relationTo: 'users', value } }, or exactly false (the default). Turns on the hidden share-erasures collection and lets the one eraser object you pass here erase a deleted user (see Helpers). The placeholder is a user you made once, to stand in for erased people. It can't found a group, join one, be invited, hold access or be erased, even by server code. Anything else for this option stops the plugin from starting, and so does turning versions on for the three sharing collections, because old versions would keep what erasure removes.
  • onOwnerChange: a function called inside the transaction whenever a group's set of active Owners changes: founding, accepting an Owner invitation, a level change to or from Owner, removal, expiry and erasure. It gets req, the group (id, kind), added, removed, every owners entry after the change, the cause and by. If it throws, or the Owners can't be read in full, the change is refused and rolled back with its history row. It is not called for Viewers and Managers. An organization's left-out people are not part of owners. A group's lock is taken before it runs.
  • canChangeExpiry: who may change a membership's expiresAt. Default: whoever canChangeLevel allows. Only an exact true allows. Anyone accepting or leaving can't write the expiry.
  • cacheMemberships: default true. Keeps a signed-in person's memberships for the rest of one request (at most 10 seconds), so five access checks in one request read them once. A change made with the same request clears it, and a failed read is never kept. Pass false to read every time. The cache never crosses requests or users.
  • 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. Restoring a version that would make a change that isn’t allowed is refused as a whole. When someone duplicates a record under access rules, they need to be an Owner or Manager in every group on the record they copy and in every group the copy would have, even if the data they send names other groups. Otherwise the copy is made without a group. Server code that skips access keeps it. If the field is required, such a duplicate fails validation.
  • 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.
  • sharedWhere, canView and canEdit take through: { collection, field } for records that get their group from a parent, such as photos in an album. field is a top-level relationship on collection with one relationTo, no hasMany and no localization, and the parent must have shareGroupField (the field option names it there). One hop only. Access follows the parent's groups, read from the database. A record with no parent or a missing one gets nothing. A setup that doesn't meet these rules, or a nested through, returns false everywhere (and sharedWhere returns false), so nothing opens. The query is { '<field>.<groupField>': { in: ids } }.
  • sharingEraser(): the one object that can erase a user. Delete the user first, then call eraser.erase({ req, member, requestId }) in the same transaction, from server code only (REST and GraphQL are refused). It replaces the person with the placeholder in every membership, in who invited and who removed others, in organizations' left-out lists, in the history rows about them and by them, and in the group's owner field when they founded the group. It clears their notes and ends their live rows with an erase event. It refuses while the user still exists, when they are the last Owner of a group (make someone else Owner first, in the same transaction), when the placeholder is missing, and when anything can't be read. It runs once per requestId: a second call for the same user changes nothing and returns repeated: true. The same requestId for a different user is refused with an error and changes nothing, so use a new one per user. The requestId is your own reference, 1 to 200 letters, digits, -, _ or :, and is stored. Put no name or email in it. The share-erasures record holds the requestId, a keyed hash of the user's id (used only to tell a repeat from a reused requestId; anyone who holds your Payload secret and a candidate id can check whether it matches, so treat the record as pseudonymous, and it stops matching if your secret changes) and three counts, nothing else. It can't be read, made, changed or deleted through the API. What it doesn't do: it doesn't delete the user, doesn't touch your own collections or any copy outside the database (backups, logs, your audit hooks' own stores), and the owner change isn't counted in the counts it returns. If onOwnerChange is set it is told, with the placeholder as removed.
  • pruneExpired({ req, limit? }): removes live memberships whose expiresAt has passed, oldest first, 100 at a time (at most 1000), through the normal update with an expire event. Returns { removed, more }. Server code only, in a transaction. Run it from a scheduled job. An expired row gives no access from the moment it passes, whether or not the job has run, and it isn't in the members list refuseMember sees, so an expired guardian doesn't satisfy a rule that needs one. Giving an expired active row a new expiry, or clearing it, brings its access back, so it counts as a new grant and refuseMember is asked again (action accept). An Owner can't have an expiry, and an invitation that has expired can't be accepted.
  • recheckOrganization({ req, organization, mode? }): asks refuseMember again, with action recheck, for every live row the organization holds and every person peopleOf lists now. Call it from your hook when someone joins an organization, in the same transaction. Mode add-only (the default) can only take access away and works from any request. Mode recompute also lets people back in, and is server code only. If the veto refuses the organization itself, its rows are removed. If the veto throws for the organization, or peopleOf is broken, nothing changes and it throws, so the person joining is rolled back. A person whose own veto throws is left out. Returns { rows, leftOut, letBackIn }. There is no mode that cuts people off without asking. recheckAllOrganizations({ req, after?, limit? }) runs add-only for every organization in pages, for hosts that can't hook their organizations, and returns a cursor next (null at the end). An organization the plugin can't judge (one that was deleted, or whose veto or peopleOf throws) is left as it was and listed in skipped ({ organization, reason }, no personal data), and the job goes on to the next one. Until it runs, someone who joined an organization keeps the access it gives.
  • sharingBatch(req, fn): runs fn(req) so every change in it commits together or not at all. With a transaction already on req it joins that and leaves the commit to you. Without one it opens a transaction, commits when fn returns and rolls back when it throws. If none can be opened it refuses, whatever allowWithoutTransactions says. Every call inside is ordinary, so every rule applies. Example, a person turning 18:
await sharingBatch(req, async (r) => {
  await payload.update({ collection: 'users', id, data: { minor: false }, overrideAccess: true, req: r })
  await recheckOrganization({ req: r, organization, mode: 'recompute' })
})

If the recheck throws, the birthday is undone too.

  • 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 inherit a parent's groups only through one through hop, never two.
  • When someone leaves a group, nobody asks the veto again for the people still in it. A minors rule that depends on who else is present (a guardian) is checked when someone accepts or changes level, and not when a guardian leaves. Use onOwnerChange or your own audit hook if you need to react to a departure.
  • Erasure removes a person from the plugin's own collections only. Backups, logs and your own records stay yours to clear.
  • Expiry is checked when memberships are read. A host that caches its own answers must clear them when an expiry passes.
  • Put shareGroupField at the top level of a collection, or inside a group or named tab (rows, collapsibles and unnamed tabs are fine too). The plugin refuses to start if the field is in an array or blocks, or if the field or anything around it is localized.
  • On a collection that uses shareGroupField, every top-level name in a write has to be an ordinary field name, and the groups and tabs around the field have to be sent as objects. Other writes are refused, server code included.
  • The field option of canView and canEdit reads a top-level key only. For a nested field, pass them the object that holds it.
  • With allowWithoutTransactions and no transaction, a create that is rolled back for not matching what was checked stays saved.
  • 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
npm test
npm run build

License

MIT. Copyright (c) 2026 EXTANT APE. See LICENSE.

Contributions arrive as pull requests from co/ branches in this repo. Only the owner merges.

Similar plugins