From 1a944d71443d68ce9c6fba94dd6a179cf72e3506 Mon Sep 17 00:00:00 2001 From: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:32:48 -0700 Subject: [PATCH 1/7] Add share groups, members, access helpers and host hooks Business accounts and brands need people to share records under rules the host passes in. This adds the two collections, the last-Owner guard, the fail-closed host hooks, the refuseMember veto, audit hooks and the canView, canEdit and sharedWhere helpers. Tested against real Payload with in-memory MongoDB (45 tests, including two requests at once). Not tested: a database without transactions, a live site, the admin screens in a browser. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +- README.md | 75 +++++- docs/decisions.md | 3 + docs/test-audit.md | 6 + package.json | 2 +- src/groups.ts | 124 ++++++++++ src/helpers.ts | 157 +++++++++++++ src/index.ts | 57 ++++- src/members.ts | 302 +++++++++++++++++++++++++ src/types.ts | 138 +++++++++++ test/plugin.test.ts | 540 +++++++++++++++++++++++++++++++++++++++++++- 11 files changed, 1393 insertions(+), 23 deletions(-) create mode 100644 src/groups.ts create mode 100644 src/helpers.ts create mode 100644 src/members.ts create mode 100644 src/types.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a0e714b..08c12dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,4 +2,14 @@ ## 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 (Captive Origins K5228, account model T5; follows D5228, D5234 and D5239): + - `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 `refuseMember` veto on invite, accept and level change, applied to server code too. + - 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. +- Tested: 45 tests against real Payload 3.92 with an in-memory MongoDB replica set, covering each path above, repeated two-at-once runs for the last-Owner and duplicate-invite rules, and clean-up of the database and server at the end. +- Not tested: a database without transactions (the last-Owner guard needs a replica set), a live site, the admin screens in a browser, and a very large number of members. diff --git a/README.md b/README.md index 78c8194..d393013 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,82 @@ 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 (45 tests, including two requests at once). 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 relies on one. ## 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, 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. +- `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 organizations) work the same way. Each gets the group, the membership and `actorRole`, the asker's own role in the group. +- `refuseMember`: 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. +- `canRead`: who reads memberships. Default is your own rows and every row in groups you are active in. +- `audit`: `before` and `after` hooks for invite, accept, change level and remove. A `before` hook that throws stops the change. + +### 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. +- Viewers can read the other members of their group by default. Narrow that with `canRead`. +- Invitations are rows in `share-members`. The plugin sends no email. + +## Build and test ``` npm install diff --git a/docs/decisions.md b/docs/decisions.md index 24dc5eb..8ca83e9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -4,3 +4,6 @@ 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: first version built for Captive Origins K5228 (account model T5), following Captive Origins D5228 (shared collections with Owner, Manager and Viewer, at least one Owner), D5234 (business accounts and brands) and D5239 (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. diff --git a/docs/test-audit.md b/docs/test-audit.md index 4913c2c..f78e260 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -2,6 +2,12 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". Newest first. +## 2026-11-22: first version (K5228) + +- 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` (45 tests). 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. diff --git a/package.json b/package.json index fd9a962..e2bbfb2 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "@extantape/payload-plugin-sharing", "version": "0.0.0", "private": true, - "description": "Sharing for Payload: people share records with other users and organizations, under access rules the host passes in. A skeleton for now.", + "description": "Sharing for Payload: people share records with other users and organizations, under access rules the host passes in.", "keywords": [ "payload", "payload-plugin", diff --git a/src/groups.ts b/src/groups.ts new file mode 100644 index 0000000..96e0ff1 --- /dev/null +++ b/src/groups.ts @@ -0,0 +1,124 @@ +import { APIError, type CollectionConfig, type PayloadRequest } from 'payload' + +import { groupIdsFor, identitiesOf, idOf, refOf, sameRef, signedIn } from './helpers.js' +import { GROUPS, MEMBERS, type ResolvedSharing, type ShareGroup, type SharingOptions } from './types.js' + +export const refuse = (message: string) => new APIError(message, 403, undefined, true) + +/** Only an exact `true` passes. A throw, a rejection or any other answer is a no. */ +export async function exactlyTrue(check: () => unknown): Promise { + try { + return (await check()) === true + } catch { + return false + } +} + +export function groupsCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { + const memberTypes = s.memberTypes + return { + slug: GROUPS, + labels: { singular: 'Share group', plural: 'Share groups' }, + admin: { + group: opts.adminGroup ?? 'Sharing', + useAsTitle: 'name', + defaultColumns: ['name', 'kind', 'owner'], + description: 'A group of people and organizations who share records. Groups are never deleted, and always keep an Owner.', + }, + access: { + create: async ({ req, data }) => { + const user = signedIn(req, s) + if (!user || !opts.canCreateGroup) return false + if (!(await exactlyTrue(() => opts.canCreateGroup!({ req, user, data: data as Partial })))) return false + // Nobody makes a group that starts with someone else as Owner. + try { + const owner = refOf((data as { owner?: unknown })?.owner) ?? { relationTo: s.users, value: user.id } + return (await identitiesOf(req, s)).some((r) => sameRef(r, owner)) + } catch { + return false + } + }, + read: async ({ req }) => { + try { + if (!signedIn(req, s)) return false + return { id: { in: await groupIdsFor(req, 'view') } } + } catch { + return false + } + }, + update: async ({ req }) => { + try { + if (!signedIn(req, s)) return false + return { id: { in: await groupIdsFor(req, 'own') } } + } catch { + return false + } + }, + delete: () => false, + }, + fields: [ + { name: 'name', type: 'text', required: true }, + { + name: 'kind', + type: 'select', + required: true, + index: true, + options: s.kinds.map((k) => ({ label: k.label ?? k.value, value: k.value })), + admin: { description: 'Set when the group is made and fixed after, because host rules can depend on it.' }, + }, + { + name: 'owner', + type: 'relationship', + relationTo: memberTypes, + required: true, + index: true, + admin: { description: 'Who the group started with as its first Owner. After that, Owners are the active members at the Owner level.' }, + }, + // Every Owner change writes this first, inside its transaction, so two changes at once can't both pass the last-Owner check. + { name: 'lock', type: 'number', hidden: true, admin: { disabled: true }, access: { create: () => false, update: () => false } }, + ], + hooks: { + beforeChange: [ + async ({ data, originalDoc, operation, req }) => { + if (operation === 'create') { + if (typeof data.name !== 'string' || !data.name.trim()) throw refuse('A group needs a name.') + data.name = data.name.trim() + if (!s.kinds.some((k) => k.value === data.kind)) throw refuse('Unknown kind of group.') + let owner = refOf(data.owner) + if (!owner) { + const user = signedIn(req, s) + if (!user) throw refuse('A group needs an owner.') + owner = { relationTo: s.users, value: user.id } + } + if (!memberTypes.includes(owner.relationTo)) throw refuse('That kind of owner isn’t allowed.') + data.owner = owner + data.lock = 0 + return data + } + if ('kind' in data && data.kind !== originalDoc.kind) throw refuse('A group’s kind can’t be changed.') + if ('owner' in data) { + const a = refOf(data.owner) + const b = refOf(originalDoc.owner) + if (!a || !b || !sameRef(a, b)) throw refuse('A group’s first owner can’t be changed. Change levels instead.') + } + if ('name' in data && (typeof data.name !== 'string' || !data.name.trim())) throw refuse('A group needs a name.') + return data + }, + ], + afterChange: [ + async ({ doc, operation, req }) => { + if (operation !== 'create') return doc + const owner = refOf(doc.owner)! + // The founding Owner joins in the same transaction. If that is vetoed, the group isn't made. + await req.payload.create({ + collection: MEMBERS as never, + data: { group: doc.id, member: owner, level: s.levels.owner.value } as never, + overrideAccess: true, + req: req as PayloadRequest, + }) + return doc + }, + ], + }, + } +} diff --git a/src/helpers.ts b/src/helpers.ts new file mode 100644 index 0000000..ae010bd --- /dev/null +++ b/src/helpers.ts @@ -0,0 +1,157 @@ +import type { Field, PayloadRequest, Where } from 'payload' + +import { GROUPS, MEMBERS, type MemberRef, type ResolvedSharing, type Role, type ShareMember } from './types.js' + +/** The id of a document given as a document, an id, or nothing. */ +export const idOf = (value: unknown): string | number | null => { + if (value === null || value === undefined) return null + if (typeof value === 'object') return idOf((value as { id?: unknown }).id) + return typeof value === 'string' || typeof value === 'number' ? value : null +} + +/** A member reference from `{ relationTo, value }` where value may be an id or a populated document. */ +export const refOf = (value: unknown): MemberRef | null => { + if (!value || typeof value !== 'object') return null + const v = value as { relationTo?: unknown; value?: unknown } + const id = idOf(v.value) + return typeof v.relationTo === 'string' && id !== null ? { relationTo: v.relationTo, value: id } : null +} + +export const sameRef = (a: MemberRef, b: MemberRef) => a.relationTo === b.relationTo && String(a.value) === String(b.value) + +export function settings(req: Pick): ResolvedSharing { + const s = (req.payload.config.custom as { sharing?: ResolvedSharing } | undefined)?.sharing + if (!s) throw new Error('payload-plugin-sharing is not installed') + return s +} + +export const roleOf = (s: ResolvedSharing, level: unknown): Role | null => + (Object.keys(s.levels) as Role[]).find((r) => s.levels[r].value === level) ?? null + +/** The signed-in user, only if they come from the users collection. */ +export const signedIn = (req: PayloadRequest, s: ResolvedSharing) => { + const user = req.user as ({ id: string | number; collection?: string } & Record) | null + return user && user.collection === s.users && idOf(user) !== null ? user : null +} + +/** The user plus whatever the host's `identities` hook adds. Throws if the hook throws; callers fail closed. */ +export async function identitiesOf(req: PayloadRequest, s = settings(req)): Promise { + const user = signedIn(req, s) + if (!user) return [] + const refs: MemberRef[] = [{ relationTo: s.users, value: user.id }] + if (s.identities) { + for (const raw of await s.identities({ req, user })) { + const ref = refOf(raw) + if (ref && s.memberTypes.includes(ref.relationTo) && !refs.some((r) => sameRef(r, ref))) refs.push(ref) + } + } + return refs +} + +export const whereRefs = (refs: MemberRef[]): Where => + ({ or: refs.map((r) => ({ and: [{ 'member.relationTo': { equals: r.relationTo } }, { 'member.value': { equals: r.value } }] })) }) as unknown as Where + +export type Membership = { id: string | number; group: string | number; level: string; role: Role } + +/** The active memberships the signed-in user has, directly or through an identity. Throws on a read error. */ +export async function membershipsOf(req: PayloadRequest, options: { group?: string | number } = {}): Promise { + const s = settings(req) + const refs = await identitiesOf(req, s) + if (!refs.length) return [] + const and: Where[] = [{ status: { equals: 'active' } }, whereRefs(refs)] + if (options.group !== undefined) and.push({ group: { equals: options.group } }) + const found = await req.payload.find({ collection: MEMBERS as never, where: { and }, pagination: false, depth: 0, overrideAccess: true, req }) + const out: Membership[] = [] + for (const d of found.docs as unknown as ShareMember[]) { + const role = roleOf(s, d.level) + const group = idOf(d.group) + if (role && group !== null) out.push({ id: d.id as string | number, group, level: d.level, role }) + } + return out +} + +const RANK: Record = { viewer: 1, manager: 2, owner: 3 } +const best = (rows: Membership[]): Role | null => rows.reduce((a, m) => (a === null || RANK[m.role] > RANK[a] ? m.role : a), null) + +/** The highest role the signed-in user holds in one group, or null. Throws on a read error. */ +export async function roleIn(req: PayloadRequest, group: string | number): Promise { + return best(await membershipsOf(req, { group })) +} + +type Need = 'view' | 'edit' | 'own' +const allows = (role: Role, need: Need) => (need === 'view' ? true : need === 'edit' ? role !== 'viewer' : role === 'owner') + +/** Ids of the groups where the signed-in user has at least this much access. Throws on a read error. */ +export async function groupIdsFor(req: PayloadRequest, need: Need = 'view'): Promise<(string | number)[]> { + const ids = new Set() + for (const m of await membershipsOf(req)) if (allows(m.role, need)) ids.add(m.group) + return [...ids] +} + +export type HelperOptions = { /** The field on the record that holds its group or groups. Default `shareGroup`. */ field?: string } + +const groupsOf = (doc: unknown, field: string): (string | number)[] => { + const v = doc && typeof doc === 'object' ? (doc as Record)[field] : null + return (Array.isArray(v) ? v : [v]).map(idOf).filter((x): x is string | number => x !== null) +} + +async function can(req: PayloadRequest, doc: unknown, need: Need, field: string): Promise { + try { + const groups = groupsOf(doc, field) + if (!groups.length) return false + const mine = new Set((await groupIdsFor(req, need)).map(String)) + return groups.some((g) => mine.has(String(g))) + } catch { + return false + } +} + +/** Whether the signed-in user may see a record, because they are active in one of its groups. Any error is false. */ +export const canView = (req: PayloadRequest, doc: unknown, options: HelperOptions = {}) => can(req, doc, 'view', options.field ?? 'shareGroup') + +/** Whether the signed-in user may edit a record: Owner or Manager in one of its groups. Any error is false. */ +export const canEdit = (req: PayloadRequest, doc: unknown, options: HelperOptions = {}) => can(req, doc, 'edit', options.field ?? 'shareGroup') + +/** + * A `where` for the host's read or update access: the records in groups the user may view (or edit). Returns false when + * there are none or on any error. Combine it with the host's own rules using `or`. + */ +export async function sharedWhere(req: PayloadRequest, options: HelperOptions & { need?: 'view' | 'edit' } = {}): Promise { + try { + const ids = await groupIdsFor(req, options.need ?? 'view') + return ids.length ? ({ [options.field ?? 'shareGroup']: { in: ids } } as Where) : false + } catch { + return false + } +} + +/** + * The field a host collection adds to put its records in a group. Setting or changing it needs Owner or Manager in the + * group the record goes into and in the one it leaves. A change that isn't allowed is dropped, not applied. + */ +export function shareGroupField(options: { name?: string; hasMany?: boolean; label?: string } = {}): Field { + const name = options.name ?? 'shareGroup' + const allowed = async ({ req, siblingData, doc }: { req: PayloadRequest; siblingData?: unknown; doc?: unknown }) => { + try { + const next = groupsOf(siblingData, name) + const now = groupsOf(doc, name) + const touched = [...next, ...now] + if (!touched.length) return true + if (next.length === now.length && next.every((g) => now.some((n) => String(n) === String(g)))) return true + const mine = new Set((await groupIdsFor(req, 'edit')).map(String)) + return touched.every((g) => mine.has(String(g))) + } catch { + return false + } + } + return { + name, + type: 'relationship', + relationTo: GROUPS, + hasMany: options.hasMany ?? false, + index: true, + label: options.label ?? 'Shared with', + access: { create: allowed as never, update: allowed as never }, + admin: { description: 'The share group this record belongs to. Members of the group see it at their level.' }, + } as Field +} diff --git a/src/index.ts b/src/index.ts index 06d1246..3de94e7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,17 +1,56 @@ import type { Config, Plugin } from 'payload' -/** - * Sharing for Payload. A skeleton for now: the pieces land in their own pull requests. Who may share what, and with - * whom, is always the host's to pass in; nothing here grants anything by default. - */ -export type SharingOptions = { - /** Turn the plugin off without removing it. Default true. */ - enabled?: boolean +import { groupsCollection } from './groups.js' +import { membersCollection } from './members.js' +import type { ResolvedSharing, Role, SharingOptions } from './types.js' + +export { + canEdit, + canView, + groupIdsFor, + identitiesOf, + membershipsOf, + roleIn, + shareGroupField, + sharedWhere, + type HelperOptions, + type Membership, +} from './helpers.js' +export * from './types.js' + +const DEFAULT_LEVELS: Record = { + owner: { value: 'owner', label: 'Owner' }, + manager: { value: 'manager', label: 'Manager' }, + viewer: { value: 'viewer', label: 'Viewer' }, } +/** + * Sharing for Payload. Two collections, `share-groups` and `share-members`: a group has members, each at a level. + * The plugin knows nothing about the host's records or rules. The host adds `shareGroupField` to its collections, asks + * `canView` and `canEdit` in its access functions, and decides who may invite and change levels. With no hooks, nobody can. + */ export const sharing = - (options: SharingOptions = {}): Plugin => + (options: SharingOptions): Plugin => (config: Config): Config => { if (options.enabled === false) return config - return config + const users = options.users ?? config.admin?.user ?? 'users' + const levels = { ...DEFAULT_LEVELS } + for (const role of Object.keys(levels) as Role[]) { + const given = options.levels?.[role] + levels[role] = { value: given?.value ?? levels[role].value, label: given?.label ?? levels[role].label } + } + const values = Object.values(levels).map((l) => l.value) + if (new Set(values).size !== values.length) throw new Error('payload-plugin-sharing: the three levels need different values') + const resolved: ResolvedSharing = { + users, + memberTypes: [...new Set([users, ...(options.memberTypes ?? [])])], + levels, + kinds: options.kinds ?? [], + identities: options.identities, + } + return { + ...config, + custom: { ...config.custom, sharing: resolved }, + collections: [...(config.collections ?? []), groupsCollection(resolved, options), membersCollection(resolved, options)], + } } diff --git a/src/members.ts b/src/members.ts new file mode 100644 index 0000000..b033808 --- /dev/null +++ b/src/members.ts @@ -0,0 +1,302 @@ +import type { CollectionConfig, PayloadRequest, Where } from 'payload' + +import { exactlyTrue, refuse } from './groups.js' +import { idOf, identitiesOf, refOf, roleIn, roleOf, sameRef, signedIn, whereRefs, groupIdsFor } from './helpers.js' +import { + GROUPS, + MEMBERS, + type AuditEvent, + type AuditHook, + type MemberArgs, + type MemberRef, + type MemberStatus, + type ResolvedSharing, + type Role, + type ShareGroup, + type ShareMember, + type SharingOptions, +} from './types.js' + +const GENERAL = 'This person can’t be added to this group.' +const LIVE: MemberStatus[] = ['invited', 'active'] +type GroupDoc = ShareGroup & { id: string | number } + +const normalize = (doc: Record): ShareMember => ({ + ...(doc as unknown as ShareMember), + group: idOf(doc.group) as string | number, + member: refOf(doc.member) as MemberRef, + invitedBy: idOf(doc.invitedBy), + removedBy: idOf(doc.removedBy), +}) + +export function membersCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { + const levels = Object.values(s.levels) + const by = (req: PayloadRequest) => idOf(req.user) + + const loadGroup = async (req: PayloadRequest, id: unknown): Promise => { + const gid = idOf(id) + if (gid === null) return null + return (await req.payload + .findByID({ collection: GROUPS as never, id: gid, depth: 0, overrideAccess: true, req }) + .catch(() => null)) as unknown as GroupDoc | null + } + + /** The asker's hook, with the group and their own role in it. No signed-in user, no hook, or no exact true is a no. */ + const ask = async (fn: ((a: MemberArgs) => boolean | Promise) | undefined, req: PayloadRequest, member: Partial, to?: string) => { + const user = signedIn(req, s) + if (!user || !fn) return false + try { + const group = await loadGroup(req, member.group) + if (!group) return false + const actorRole = await roleIn(req, group.id).catch(() => null) + return await exactlyTrue(() => fn({ req, user, group, member, actorRole, to })) + } catch { + return false + } + } + + const isSelf = (req: PayloadRequest, ref: MemberRef) => { + const user = signedIn(req, s) + return !!user && ref.relationTo === s.users && String(ref.value) === String(user.id) + } + + const run = async (hook: AuditHook | undefined, event: AuditEvent, mustPass: boolean) => { + if (!hook) return + try { + await hook(event) + } catch (error) { + if (mustPass) throw refuse('This change can’t be recorded right now, so it wasn’t made.') + event.req.payload.logger.error(`sharing: the ${event.event} audit hook failed: ${(error as Error).message}`) + } + } + + /** The host's veto. Only `null` or nothing goes ahead. */ + async function vetoed(req: PayloadRequest, group: GroupDoc, ref: MemberRef, level: string, action: 'invite' | 'accept' | 'change-level') { + if (!opts.refuseMember) return + const subject = await req.payload.findByID({ collection: ref.relationTo as never, id: ref.value, depth: 0, overrideAccess: true, req }).catch(() => null) + if (!subject) throw refuse(GENERAL) + let why: unknown + try { + why = await opts.refuseMember({ req, group, subject: subject as never, ref, level, action }) + } catch { + throw refuse(GENERAL) + } + if (why === null || why === undefined) return + throw refuse(typeof why === 'string' && why.trim() ? why : GENERAL) + } + + /** + * Takes the group's lock and checks that an Owner is left once this one goes. Writing the group first means two + * Owners leaving or demoting each other at once collide, and one of them is turned back. + */ + async function keepAnOwner(req: PayloadRequest, group: GroupDoc, leaving: string | number) { + try { + const fresh = (await req.payload.findByID({ collection: GROUPS as never, id: group.id, depth: 0, overrideAccess: true, req })) as unknown as { lock?: number } + await req.payload.update({ collection: GROUPS as never, id: group.id, data: { lock: (fresh.lock ?? 0) + 1 } as never, overrideAccess: true, req }) + const others = await req.payload.find({ + collection: MEMBERS as never, + where: { and: [{ group: { equals: group.id } }, { status: { equals: 'active' } }, { level: { equals: s.levels.owner.value } }, { id: { not_equals: leaving } }] }, + limit: 1, + depth: 0, + overrideAccess: true, + req, + }) + if (!others.docs.length) throw refuse('A group always keeps an Owner. Make someone else an Owner first.') + } catch (error) { + if ((error as { isPublic?: boolean }).isPublic) throw error + throw refuse('This group is changing right now. Try again in a moment.') + } + } + + return { + slug: MEMBERS, + labels: { singular: 'Share member', plural: 'Share members' }, + admin: { + group: opts.adminGroup ?? 'Sharing', + useAsTitle: 'level', + defaultColumns: ['group', 'member', 'level', 'status'], + description: 'Who is in which group, and at what level. Leave by setting the status to Removed; rows are never deleted, so the record stays.', + }, + access: { + create: ({ req, data }) => ask(opts.canInvite, req, (data ?? {}) as Partial), + update: async ({ req, id, data }) => { + try { + if (id === undefined || id === null || !signedIn(req, s)) return false + const doc = (await req.payload.findByID({ collection: MEMBERS as never, id, depth: 0, overrideAccess: true, req })) as unknown as Record + const before = normalize(doc) + const next = (data ?? {}) as Partial + const asks: Promise[] = [] + if (next.level !== undefined && next.level !== before.level) asks.push(ask(opts.canChangeLevel, req, before, String(next.level))) + if (next.status !== undefined && next.status !== before.status) { + if (next.status === 'active') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canAccept, req, before)) + else if (next.status === 'removed') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canRemove ?? opts.canChangeLevel, req, before)) + else return false + } + if (!asks.length) return ask(opts.canChangeLevel, req, before, before.level) + return (await Promise.all(asks)).every(Boolean) + } catch { + return false + } + }, + delete: () => false, + read: async ({ req }) => { + const user = signedIn(req, s) + if (!user) return false + try { + if (opts.canRead) { + const answer = await opts.canRead({ req, user }) + return answer === true ? true : answer && typeof answer === 'object' ? answer : false + } + const refs = await identitiesOf(req, s) + const groups = await groupIdsFor(req, 'view') + return { or: [whereRefs(refs), ...(groups.length ? [{ group: { in: groups } }] : [])] } as Where + } catch { + return false + } + }, + }, + fields: [ + { name: 'group', type: 'relationship', relationTo: GROUPS, required: true, index: true }, + { + name: 'member', + type: 'relationship', + relationTo: s.memberTypes, + required: true, + index: true, + admin: { description: 'A user or an organization.' }, + }, + { + name: 'level', + type: 'select', + required: true, + index: true, + options: levels.map((l) => ({ label: l.label, value: l.value })), + }, + { + name: 'status', + type: 'select', + required: true, + defaultValue: 'invited', + index: true, + options: [ + { label: 'Invited', value: 'invited' }, + { label: 'Active', value: 'active' }, + { label: 'Removed', value: 'removed' }, + ], + admin: { description: 'An invited member gets nothing until they accept. Removed is final: invite again to bring them back.' }, + }, + { name: 'invitedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true } }, + { name: 'acceptedAt', type: 'date', admin: { readOnly: true } }, + { name: 'removedAt', type: 'date', admin: { readOnly: true } }, + { name: 'removedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true } }, + { name: 'notes', type: 'textarea' }, + // Makes a second live membership for the same group and member fail in the database, not just in a check. + { name: 'liveKey', type: 'text', unique: true, index: true, hidden: true, admin: { disabled: true } }, + ], + hooks: { + beforeChange: [ + async ({ data, originalDoc, operation, req }) => { + const now = new Date().toISOString() + if (operation === 'create') { + const group = await loadGroup(req, data.group) + if (!group) throw refuse('Unknown group.') + const ref = refOf(data.member) + if (!ref || !s.memberTypes.includes(ref.relationTo)) throw refuse('Unknown member.') + if (!roleOf(s, data.level)) throw refuse('Unknown level.') + const asker = by(req) + const owner = refOf(group.owner) + const empty = !(await req.payload.count({ collection: MEMBERS as never, where: { group: { equals: group.id } }, overrideAccess: true, req })).totalDocs + // The founding Owner is the only member who starts active: the first row of a new group, for its owner. + const founding = empty && !!owner && sameRef(owner, ref) && data.level === s.levels.owner.value + data.group = group.id + data.member = ref + data.status = founding ? 'active' : 'invited' + data.acceptedAt = founding ? now : null + data.removedAt = null + data.removedBy = null + if (asker !== null) data.invitedBy = asker + const dup = await req.payload.find({ + collection: MEMBERS as never, + where: { and: [{ group: { equals: group.id } }, { 'member.relationTo': { equals: ref.relationTo } }, { 'member.value': { equals: ref.value } }, { status: { in: LIVE } }] }, + limit: 1, + depth: 0, + overrideAccess: true, + req, + }) + if (dup.docs.length) throw refuse('That member is already in this group.') + await vetoed(req, group, ref, data.level, 'invite') + // The database's unique index on this key is what stops two requests at once. + data.liveKey = JSON.stringify([group.id, ref.relationTo, ref.value]) + await run(opts.audit?.beforeInvite, { event: 'invite', phase: 'before', membership: normalize(data), by: asker, req }, true) + return data + } + + // An update. Group, member and who invited never change; only level, status and notes do. + const before = normalize(originalDoc) + for (const f of ['group', 'member', 'invitedBy'] as const) { + if (!(f in data)) continue + const a = f === 'member' ? refOf(data[f]) : idOf(data[f]) + const b = before[f] + const same = f === 'member' ? !!a && !!b && sameRef(a as MemberRef, b as MemberRef) : String(a ?? '') === String(b ?? '') + if (!same) throw refuse('Only the level, status and notes can be changed.') + } + for (const f of ['liveKey', 'acceptedAt', 'removedAt', 'removedBy']) delete data[f] + const level: string = data.level ?? before.level + const status = (data.status ?? before.status) as MemberStatus + if (!roleOf(s, level)) throw refuse('Unknown level.') + if (!['invited', 'active', 'removed'].includes(status)) throw refuse('Unknown status.') + const levelChanged = level !== before.level + const statusChanged = status !== before.status + if (!levelChanged && !statusChanged) return data + if (before.status === 'removed') throw refuse('A removed member is final. Invite them again.') + if (statusChanged && !(before.status === 'invited' && (status === 'active' || status === 'removed')) && !(before.status === 'active' && status === 'removed')) + throw refuse('That status change isn’t allowed.') + const group = await loadGroup(req, before.group) + if (!group) throw refuse('Unknown group.') + const asker = by(req) + const wasOwner = before.status === 'active' && before.level === s.levels.owner.value + if (wasOwner && (status === 'removed' || level !== before.level)) await keepAnOwner(req, group, before.id as string | number) + const after = { ...before, ...normalize({ ...originalDoc, ...data }), level, status } + if (status === 'removed') { + data.liveKey = `ended:${String(originalDoc.id)}` + data.removedAt = now + data.removedBy = asker + await run(opts.audit?.beforeRemove, { event: 'remove', phase: 'before', membership: after, previous: before, by: asker, req }, true) + return data + } + if (status === 'active' && statusChanged) { + data.acceptedAt = now + await vetoed(req, group, before.member, level, 'accept') + await run(opts.audit?.beforeAccept, { event: 'accept', phase: 'before', membership: after, previous: before, by: asker, req }, true) + } + if (levelChanged) { + await vetoed(req, group, before.member, level, 'change-level') + await run(opts.audit?.beforeChangeLevel, { event: 'change-level', phase: 'before', membership: after, previous: before, by: asker, req }, true) + } + return data + }, + ], + afterChange: [ + async ({ doc, previousDoc, operation, req }) => { + const membership = normalize(doc) + const asker = by(req) + if (operation === 'create') { + await run(opts.audit?.afterInvite, { event: 'invite', phase: 'after', membership, by: asker, req }, false) + return doc + } + if (!previousDoc) return doc + const previous = normalize(previousDoc) + if (previous.status !== membership.status) { + if (membership.status === 'removed') await run(opts.audit?.afterRemove, { event: 'remove', phase: 'after', membership, previous, by: asker, req }, false) + else if (membership.status === 'active') await run(opts.audit?.afterAccept, { event: 'accept', phase: 'after', membership, previous, by: asker, req }, false) + } + if (previous.level !== membership.level && membership.status !== 'removed') + await run(opts.audit?.afterChangeLevel, { event: 'change-level', phase: 'after', membership, previous, by: asker, req }, false) + return doc + }, + ], + }, + } +} + +export type { Role } diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..71692c0 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,138 @@ +import type { Payload, PayloadRequest, Where } from 'payload' + +export const GROUPS = 'share-groups' +export const MEMBERS = 'share-members' + +export type Role = 'owner' | 'manager' | 'viewer' +export type MemberStatus = 'invited' | 'active' | 'removed' + +/** Who a membership belongs to: a document in one of the host's member collections (users, organizations). */ +export type MemberRef = { relationTo: string; value: string | number } + +export type LevelConfig = { value?: string; label?: string } + +/** What the plugin settled on, kept in `config.custom.sharing` so the helpers need no global state. */ +export type ResolvedSharing = { + users: string + memberTypes: string[] + levels: Record + kinds: { value: string; label?: string }[] + identities?: SharingOptions['identities'] +} + +export type ShareGroup = { + id?: string | number + name: string + kind: string + owner: MemberRef +} + +export type ShareMember = { + id?: string | number + group: string | number + member: MemberRef + /** The stored level value (by default `owner`, `manager` or `viewer`). */ + level: string + status: MemberStatus + invitedBy?: string | number | null + acceptedAt?: string | null + removedAt?: string | null + removedBy?: string | number | null + notes?: string | null +} + +type User = { id: string | number; collection?: string } & Record + +export type GroupArgs = { + req: PayloadRequest + user: User + /** The group being created. */ + data: Partial +} + +export type MemberArgs = { + req: PayloadRequest + user: User + group: ShareGroup & { id: string | number } + /** The membership being created, or (for a change) the membership as it is now. */ + member: Partial + /** The role the asker holds in this group (through themselves or an identity), or null if none. */ + actorRole: Role | null + /** For `canChangeLevel`: the level it would become. */ + to?: string +} + +export type RefuseArgs = { + req: PayloadRequest + group: ShareGroup & { id: string | number } + /** The member's own document (the user or organization). */ + subject: Record & { id: string | number } + ref: MemberRef + level: string + action: 'invite' | 'accept' | 'change-level' +} + +export type AuditEvent = { + event: 'invite' | 'accept' | 'change-level' | 'remove' + phase: 'before' | 'after' + membership: ShareMember + /** The membership as it was. Absent for an invitation. */ + previous?: ShareMember + /** The signed-in user's id, or null for server code. */ + by: string | number | null + req: PayloadRequest +} +export type AuditHook = (event: AuditEvent) => void | Promise + +type Check = (args: A) => boolean | Promise + +export type SharingOptions = { + /** Turn the plugin off without removing it. Default true. */ + enabled?: boolean + /** The users collection. Default `users`. */ + users?: string + /** Collections a member can come from. Default `[users]`. Add an organizations collection here. */ + memberTypes?: string[] + /** The kinds of group the host offers, such as hobby, family or brand. With none, no group can be made. */ + kinds: { value: string; label?: string }[] + /** Rename or relabel the three levels. The stored values default to `owner`, `manager` and `viewer`. */ + levels?: Partial> + /** + * Other identities the signed-in user acts as, such as the organizations they work for. A membership held by any of + * them counts for the user. A throw means access is refused. Default: only the user. + */ + identities?: (args: { req: PayloadRequest; user: User }) => MemberRef[] | Promise + /** Who may make a group. Only an exact `true` counts. The group's owner must also be the asker or one of their identities. */ + canCreateGroup?: Check + /** Who may invite someone to a group. Only an exact `true` counts; a throw, a truthy value or no hook is a no. */ + canInvite?: Check + /** Who may change a member's level. Same rule: only an exact `true`. */ + canChangeLevel?: Check + /** Who may remove someone else. Default: whoever `canChangeLevel` allows. Anyone may always leave or decline for themselves. */ + canRemove?: Check + /** Who may accept an invitation for an organization. A user always accepts their own. Default: nobody. */ + canAccept?: Check + /** Who may read memberships. Default: your own, and every membership in groups you are active in. May return a `where`. */ + canRead?: (args: { req: PayloadRequest; user: User }) => boolean | Where | Promise + /** + * A veto the host controls, asked on every invitation, acceptance and level change, even for server code that skips + * access. Return `null` or nothing to go ahead, or a reason to refuse. A throw, `false` or anything else refuses with + * a general reason. + */ + refuseMember?: (args: RefuseArgs) => string | null | undefined | Promise + /** Audit hooks. A `before` hook that throws stops the change. An `after` hook that throws is logged and ignored. */ + audit?: { + beforeInvite?: AuditHook + afterInvite?: AuditHook + beforeAccept?: AuditHook + afterAccept?: AuditHook + beforeChangeLevel?: AuditHook + afterChangeLevel?: AuditHook + beforeRemove?: AuditHook + afterRemove?: AuditHook + } + /** The admin group the collections sit in. Default `Sharing`. */ + adminGroup?: string +} + +export type PayloadLike = Payload | { payload: Payload } diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 6bfbb14..c3ce527 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -1,10 +1,534 @@ -import { describe, expect, it } from 'vitest' -import { sharing } from '../src/index.js' - -describe('sharing', () => { - it('leaves a config unchanged while it is a skeleton, and when turned off', () => { - const config = { collections: [], secret: 'made-up' } as never - expect(sharing()(config)).toEqual(config) - expect(sharing({ enabled: false })(config)).toBe(config) +import { mongooseAdapter } from '@payloadcms/db-mongodb' +import { MongoMemoryReplSet } from 'mongodb-memory-server' +import { buildConfig, getPayload, type Payload } from 'payload' +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' + +import { canEdit, canView, groupIdsFor, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' + +/** + * A made-up site: users (staff may make groups, some belong to organizations, one is flagged `minor`), organizations, + * and notes that can be put in a group. The host's rules are small functions over the role the asker holds. + */ +const PW = 'correct-horse-battery' +let payload: Payload +let mongo: MongoMemoryReplSet +const log: string[] = [] +const answers: { refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} + +type U = { id: string | number } +let ann: U, ben: U, cat: U, dan: U, kid: U, org: U +let group: { id: string | number } + +const as = (user: U) => ({ ...user, collection: 'users' }) as never +const make = (email: string, extra: Record = {}) => + payload.create({ collection: 'users', data: { email, password: PW, ...extra } as never }) as unknown as Promise +const ref = (u: U, relationTo = 'users') => ({ relationTo, value: u.id }) +const reqFor = (user: U | null) => ({ payload, user: user ? as(user) : null }) as never +const refused = async (p: Promise) => { + try { + await p + return null + } catch (e) { + return (e as Error).message + } +} +const newGroup = (user: U, extra: Record = {}) => + payload.create({ collection: 'share-groups' as never, data: { name: 'Pond keepers', kind: 'hobby', ...extra } as never, user: as(user), overrideAccess: false }) as unknown as Promise<{ + id: string | number + }> +const invite = (user: U | null, data: Record) => + payload.create({ collection: 'share-members' as never, data: { group: group.id, ...data } as never, user: user ? as(user) : undefined, overrideAccess: false }) as unknown as Promise> +const change = (user: U | null, id: unknown, data: Record) => + payload.update({ collection: 'share-members' as never, id: id as never, data: data as never, user: user ? as(user) : undefined, overrideAccess: false }) as unknown as Promise> +const rows = (where: Record = {}) => payload.find({ collection: 'share-members' as never, where: where as never, pagination: false, overrideAccess: true }) +const rowOf = async (u: U, relationTo = 'users') => { + const found = await rows({ and: [{ group: { equals: group.id } }, { 'member.value': { equals: u.id } }, { 'member.relationTo': { equals: relationTo } }] }) + return found.docs[0] as unknown as { id: string | number; level: string; status: string } +} +/** Invite then accept, so a member is active at a level. */ +const join = async (u: U, level: string) => { + await invite(ann, { member: ref(u), level }) + const r = await rowOf(u) + await change(u, r.id, { status: 'active' }) + return r +} +const record = (e: AuditEvent) => { + log.push(`${e.phase}:${e.event}`) +} + +beforeAll(async () => { + mongo = await MongoMemoryReplSet.create({ replSet: { count: 1, storageEngine: 'wiredTiger' } }) + const config = await buildConfig({ + secret: 'test-secret-not-for-production', + telemetry: false, + typescript: { autoGenerate: false }, + db: mongooseAdapter({ url: mongo.getUri('sharing'), ensureIndexes: true }), + collections: [ + { + slug: 'users', + auth: true, + fields: [ + { name: 'staff', type: 'checkbox' }, + { name: 'minor', type: 'checkbox' }, + { name: 'org', type: 'relationship', relationTo: 'organizations' }, + ], + }, + { slug: 'organizations', fields: [{ name: 'name', type: 'text' }] }, + { + slug: 'notes', + fields: [{ name: 'title', type: 'text' }, shareGroupField()], + access: { + read: async ({ req }) => { + if (!req.user) return false + return (await sharedWhere(req)) || false + }, + update: async ({ req }) => (await sharedWhere(req, { need: 'edit' })) || false, + create: ({ req }) => !!req.user, + delete: () => false, + }, + }, + ], + plugins: [ + sharing({ + memberTypes: ['organizations'], + kinds: [{ value: 'hobby' }, { value: 'family' }, { value: 'brand', label: 'Brand' }], + identities: ({ user }) => { + if (answers.identities) return answers.identities() as never + const org = (user as { org?: unknown }).org + return org ? [{ relationTo: 'organizations', value: ((org as { id?: unknown }).id ?? org) as string }] : [] + }, + canCreateGroup: ({ user }) => (user as { staff?: boolean }).staff === true, + canInvite: ({ actorRole, member, group: g }) => { + if (answers.canInvite) return answers.canInvite() as boolean + if (actorRole === 'owner') return true + return actorRole === 'manager' && member.level === 'viewer' && g.kind !== 'family' + }, + canChangeLevel: ({ actorRole }) => actorRole === 'owner', + refuseMember: ({ subject, group: g }) => { + if (answers.refuse) return answers.refuse() as string | null + return (subject as { minor?: boolean }).minor && g.kind !== 'family' ? 'Not available for this account.' : null + }, + audit: { + beforeInvite: (e) => { + if (answers.beforeInvite) answers.beforeInvite() + record(e) + }, + afterInvite: record, + beforeAccept: record, + afterAccept: record, + beforeChangeLevel: record, + afterChangeLevel: record, + beforeRemove: record, + afterRemove: record, + }, + }), + ], + }) + payload = await getPayload({ config }) +}) + +afterAll(async () => { + await payload?.db?.destroy?.() + await mongo?.stop() +}) + +beforeEach(async () => { + for (const key of Object.keys(answers)) delete (answers as Record)[key] + log.length = 0 + for (const c of ['notes', 'share-members', 'share-groups', 'users', 'organizations']) + await payload.delete({ collection: c as never, where: { id: { exists: true } }, overrideAccess: true }) + org = (await payload.create({ collection: 'organizations', data: { name: 'Made-up Co' } as never })) as unknown as U + ann = await make('ann@example.com', { staff: true }) + ben = await make('ben@example.com') + cat = await make('cat@example.com', { org: org.id }) + dan = await make('dan@example.com') + kid = await make('kid@example.com', { minor: true }) + group = await newGroup(ann) + log.length = 0 +}) + +describe('groups', () => { + it('starts with its maker as the active Owner, in one step', async () => { + const r = await rowOf(ann) + expect(r.level).toBe('owner') + expect(r.status).toBe('active') + expect(await roleIn(reqFor(ann), group.id)).toBe('owner') + }) + + it('refuses to make a group without the host hook, or for a user it doesn’t allow', async () => { + expect(await refused(newGroup(ben))).toBeTruthy() + expect((await payload.find({ collection: 'share-groups' as never, overrideAccess: true })).totalDocs).toBe(1) + }) + + it('refuses a group that starts with someone else as Owner', async () => { + expect(await refused(newGroup(ann, { owner: ref(ben) }))).toBeTruthy() + }) + + it('refuses an unknown kind or a blank name', async () => { + expect(await refused(newGroup(ann, { kind: 'galaxy' }))).toBeTruthy() + expect(await refused(newGroup(ann, { name: ' ' }))).toMatch(/needs a name/) + }) + + it('rolls the group back if the veto stops its founding Owner', async () => { + answers.refuse = () => 'No.' + const before = (await payload.find({ collection: 'share-groups' as never, overrideAccess: true })).totalDocs + expect(await refused(newGroup(ann))).toBeTruthy() + expect((await payload.find({ collection: 'share-groups' as never, overrideAccess: true })).totalDocs).toBe(before) + }) + + it('lets only an Owner rename it, and never change its kind or first owner', async () => { + await join(ben, 'manager') + const upd = (user: U, data: Record) => + payload.update({ collection: 'share-groups' as never, id: group.id as never, data: data as never, user: as(user), overrideAccess: false }) + expect(await refused(upd(ben, { name: 'Mine now' }))).toBeTruthy() + await upd(ann, { name: 'Renamed' }) + expect(await refused(upd(ann, { kind: 'family' }))).toMatch(/kind/) + expect(await refused(upd(ann, { owner: ref(ben) }))).toMatch(/first owner/) + }) + + it('is never deleted', async () => { + expect(await refused(payload.delete({ collection: 'share-groups' as never, id: group.id as never, user: as(ann), overrideAccess: false }))).toBeTruthy() + expect(await refused(payload.delete({ collection: 'share-members' as never, id: (await rowOf(ann)).id as never, user: as(ann), overrideAccess: false }))).toBeTruthy() + }) + + it('shows a group only to its active members', async () => { + const see = async (u: U) => + (await payload.find({ collection: 'share-groups' as never, user: as(u), overrideAccess: false })).totalDocs + expect(await see(ann)).toBe(1) + expect(await see(ben)).toBe(0) + await invite(ann, { member: ref(ben), level: 'viewer' }) + expect(await see(ben)).toBe(0) // invited is not in yet + await change(ben, (await rowOf(ben)).id, { status: 'active' }) + expect(await see(ben)).toBe(1) + }) +}) + +describe('inviting', () => { + it('fails closed: no hook, a truthy answer, a throw or a signed-out asker all refuse', async () => { + answers.canInvite = () => 'yes' + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toBeTruthy() + answers.canInvite = () => { + throw new Error('boom') + } + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toBeTruthy() + delete answers.canInvite + expect(await refused(invite(null, { member: ref(ben), level: 'viewer' }))).toBeTruthy() + expect((await rows({ status: { equals: 'invited' } })).totalDocs).toBe(0) + }) + + it('lets the host decide by role: a Manager invites Viewers only, a Viewer no one', async () => { + await join(ben, 'manager') + await invite(ben, { member: ref(cat), level: 'viewer' }) + expect(await refused(invite(ben, { member: ref(dan), level: 'manager' }))).toBeTruthy() + await join(dan, 'viewer') + expect(await refused(invite(dan, { member: ref(kid), level: 'viewer' }))).toBeTruthy() + }) + + it('starts invited whatever the client sends, and records who invited', async () => { + const r = (await invite(ann, { member: ref(ben), level: 'viewer', status: 'active', invitedBy: dan.id, acceptedAt: new Date().toISOString() })) as Record + expect(r.status).toBe('invited') + expect(String((r.invitedBy as { id?: unknown })?.id ?? r.invitedBy)).toBe(String(ann.id)) + expect(r.acceptedAt ?? null).toBeNull() + expect(log).toEqual(['before:invite', 'after:invite']) + }) + + it('refuses unknown levels, unknown groups and unknown member kinds', async () => { + expect(await refused(invite(ann, { member: ref(ben), level: 'admin' }))).toBeTruthy() + expect(await refused(invite(ann, { member: { relationTo: 'notes', value: 'x' }, level: 'viewer' }))).toBeTruthy() + expect(await refused(invite(ann, { group: 'nope', member: ref(ben), level: 'viewer' }))).toBeTruthy() + }) + + it('refuses a second live row for the same member, but allows it after removal', async () => { + await invite(ann, { member: ref(ben), level: 'viewer' }) + expect(await refused(invite(ann, { member: ref(ben), level: 'manager' }))).toMatch(/already/) + const r = await rowOf(ben) + await change(ann, r.id, { status: 'removed' }) + await invite(ann, { member: ref(ben), level: 'viewer' }) + }) + + it('lets an organization be a member', async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) + expect((await rowOf(org, 'organizations')).status).toBe('invited') + }) + + it('starts an invited Owner as invited, not active, in a group that already has members', async () => { + const r = (await invite(ann, { member: ref(ben), level: 'owner' })) as Record + expect(r.status).toBe('invited') + }) +}) + +describe('the host veto', () => { + it('blocks a minor outside a family group on invite, even for server code that skips access', async () => { + expect(await refused(invite(ann, { member: ref(kid), level: 'viewer' }))).toBe('Not available for this account.') + expect( + await refused(payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(kid), level: 'viewer' } as never, overrideAccess: true })), + ).toBe('Not available for this account.') + }) + + it('lets a minor into a family group', async () => { + const fam = await newGroup(ann, { kind: 'family', name: 'Family' }) + await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(kid), level: 'viewer' } as never, user: as(ann), overrideAccess: false }) + }) + + it('refuses on a throw, on false and on a blank reason, with a general message', async () => { + for (const answer of [ + () => { + throw new Error('boom') + }, + () => false, + () => ' ', + ]) { + answers.refuse = answer + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toBe('This person can’t be added to this group.') + } + }) + + it('is asked again on accept and on a level change', async () => { + await invite(ann, { member: ref(ben), level: 'viewer' }) + answers.refuse = () => 'Paused.' + expect(await refused(change(ben, (await rowOf(ben)).id, { status: 'active' }))).toBe('Paused.') + delete answers.refuse + await change(ben, (await rowOf(ben)).id, { status: 'active' }) + answers.refuse = () => 'Paused.' + expect(await refused(change(ann, (await rowOf(ben)).id, { level: 'manager' }))).toBe('Paused.') + }) + + it('stops the change when a before audit hook throws, and logs an after hook that throws', async () => { + answers.beforeInvite = () => { + throw new Error('audit down') + } + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toMatch(/can’t be recorded/) + expect((await rows({ status: { equals: 'invited' } })).totalDocs).toBe(0) + }) +}) + +describe('accepting, changing levels and leaving', () => { + it('lets a user accept their own invitation and nobody else’s', async () => { + await invite(ann, { member: ref(ben), level: 'viewer' }) + const r = await rowOf(ben) + expect(await refused(change(dan, r.id, { status: 'active' }))).toBeTruthy() + expect(await refused(change(ann, r.id, { status: 'active' }))).toBeTruthy() // the host gave no canAccept + await change(ben, r.id, { status: 'active' }) + expect((await rowOf(ben)).status).toBe('active') + expect(log).toEqual(['before:invite', 'after:invite', 'before:accept', 'after:accept']) + }) + + it('leaves accepting for an organization to the host: nobody without canAccept', async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) + const r = await rowOf(org, 'organizations') + expect(await refused(change(cat, r.id, { status: 'active' }))).toBeTruthy() + }) + + it('changes a level only if canChangeLevel returns exactly true', async () => { + await join(ben, 'viewer') + const r = await rowOf(ben) + expect(await refused(change(ben, r.id, { level: 'owner' }))).toBeTruthy() // self-promotion + expect(await refused(change(dan, r.id, { level: 'owner' }))).toBeTruthy() + await change(ann, r.id, { level: 'manager' }) + expect((await rowOf(ben)).level).toBe('manager') + expect(log.slice(-2)).toEqual(['before:change-level', 'after:change-level']) + }) + + it('refuses a call with no id (a bulk update) and unknown levels or statuses', async () => { + const r = await join(ben, 'viewer') + expect(await refused(change(ann, r.id, { level: 'admin' }))).toBeTruthy() + expect(await refused(change(ann, r.id, { status: 'invited' }))).toBeTruthy() + await refused(payload.update({ collection: 'share-members' as never, where: { level: { equals: 'viewer' } } as never, data: { level: 'manager' } as never, user: as(ann), overrideAccess: false })) + expect((await rowOf(ben)).level).toBe('viewer') + }) + + it('never changes group, member or inviter', async () => { + const r = await join(ben, 'viewer') + expect(await refused(change(ann, r.id, { member: ref(dan) }))).toBeTruthy() + expect(await refused(change(ann, r.id, { group: 'other' }))).toBeTruthy() + }) + + it('lets anyone leave, lets the host remove others, and makes removal final', async () => { + const r = await join(ben, 'viewer') + const c = await join(dan, 'viewer') + await change(ben, r.id, { status: 'removed' }) + expect(await refused(change(ben, c.id, { status: 'removed' }))).toBeTruthy() + await change(ann, c.id, { status: 'removed' }) + const gone = await rowOf(ben) + expect(gone.status).toBe('removed') + expect(await refused(change(ann, gone.id, { status: 'active' }))).toBeTruthy() + expect(log.filter((l) => l.endsWith('remove'))).toEqual(['before:remove', 'after:remove', 'before:remove', 'after:remove']) + }) + + it('refuses a stranger who tries to remove someone', async () => { + const r = await join(ben, 'viewer') + expect(await refused(change(dan, r.id, { status: 'removed' }))).toBeTruthy() + }) +}) + +describe('a group always keeps an Owner', () => { + it('stops the last Owner leaving or being demoted', async () => { + const r = await rowOf(ann) + expect(await refused(change(ann, r.id, { status: 'removed' }))).toMatch(/keeps an Owner/) + expect(await refused(change(ann, r.id, { level: 'manager' }))).toMatch(/keeps an Owner/) + expect((await rowOf(ann)).level).toBe('owner') + }) + + it('stops server code too', async () => { + const r = await rowOf(ann) + expect(await refused(payload.update({ collection: 'share-members' as never, id: r.id as never, data: { status: 'removed' } as never, overrideAccess: true }))).toMatch(/keeps an Owner/) + }) + + it('does not count an invited Owner as one', async () => { + await invite(ann, { member: ref(ben), level: 'owner' }) + expect(await refused(change(ann, (await rowOf(ann)).id, { level: 'viewer' }))).toMatch(/keeps an Owner/) + }) + + it('lets an Owner step down once another Owner is active', async () => { + await join(ben, 'owner') + await change(ann, (await rowOf(ann)).id, { level: 'manager' }) + expect((await rowOf(ann)).level).toBe('manager') + expect(await refused(change(ben, (await rowOf(ben)).id, { status: 'removed' }))).toMatch(/keeps an Owner/) + }) + + it('keeps one Owner when two Owners demote each other at once', async () => { + for (let i = 0; i < 4; i++) { + await payload.delete({ collection: 'share-members' as never, where: { id: { exists: true } }, overrideAccess: true }) + await payload.delete({ collection: 'share-groups' as never, where: { id: { exists: true } }, overrideAccess: true }) + group = await newGroup(ann) + await join(ben, 'owner') + const a = (await rowOf(ann)).id + const b = (await rowOf(ben)).id + const results = await Promise.allSettled([ + payload.update({ collection: 'share-members' as never, id: a as never, data: { level: 'viewer' } as never, user: as(ben), overrideAccess: false }), + payload.update({ collection: 'share-members' as never, id: b as never, data: { level: 'viewer' } as never, user: as(ann), overrideAccess: false }), + ]) + const owners = (await rows({ and: [{ group: { equals: group.id } }, { level: { equals: 'owner' } }, { status: { equals: 'active' } }] })).totalDocs + expect(owners).toBeGreaterThanOrEqual(1) + expect(results.filter((r) => r.status === 'fulfilled').length).toBeLessThanOrEqual(1) + } + }) + + it('creates one row when the same invitation is sent twice at once', async () => { + const results = await Promise.allSettled([invite(ann, { member: ref(ben), level: 'viewer' }), invite(ann, { member: ref(ben), level: 'viewer' })]) + expect(results.filter((r) => r.status === 'fulfilled')).toHaveLength(1) + expect((await rows({ and: [{ 'member.value': { equals: ben.id } }, { status: { in: ['invited', 'active'] } }] })).totalDocs).toBe(1) + }) +}) + +describe('what members can read', () => { + it('shows a member their own rows and their groups’ rows, and nothing from other groups', async () => { + await join(ben, 'viewer') + const other = await newGroup(ann, { name: 'Elsewhere' }) + await payload.create({ collection: 'share-members' as never, data: { group: other.id, member: ref(dan), level: 'viewer' } as never, user: as(ann), overrideAccess: false }) + const seen = (await payload.find({ collection: 'share-members' as never, user: as(ben), overrideAccess: false, pagination: false })).docs as unknown as { group: unknown }[] + expect(seen.length).toBe(2) + expect(seen.every((d) => String((d.group as { id?: unknown })?.id ?? d.group) === String(group.id))).toBe(true) + expect((await payload.find({ collection: 'share-members' as never, user: as(dan), overrideAccess: false, pagination: false })).totalDocs).toBe(1) // only his own invitation + }) + + it('shows nothing when signed out', async () => { + expect(await refused(payload.find({ collection: 'share-members' as never, overrideAccess: false }))).toBeTruthy() + }) +}) + +describe('records in a group', () => { + const note = (data: Record, user: U | null = ann) => + payload.create({ collection: 'notes' as never, data: data as never, user: user ? as(user) : undefined, overrideAccess: false }) as unknown as Promise<{ id: string | number; shareGroup?: unknown }> + + it('lets canView and canEdit follow the level', async () => { + await join(ben, 'viewer') + await join(dan, 'manager') + const n = await note({ title: 'pond log', shareGroup: group.id }) + const doc = await payload.findByID({ collection: 'notes' as never, id: n.id as never, depth: 0, overrideAccess: true }) + expect(await canView(reqFor(ann), doc)).toBe(true) + expect(await canEdit(reqFor(ann), doc)).toBe(true) + expect(await canView(reqFor(ben), doc)).toBe(true) + expect(await canEdit(reqFor(ben), doc)).toBe(false) + expect(await canEdit(reqFor(dan), doc)).toBe(true) + expect(await canView(reqFor(cat), doc)).toBe(false) + expect(await canView(reqFor(null), doc)).toBe(false) + expect(await canView(reqFor(ann), { shareGroup: null })).toBe(false) + }) + + it('gives nothing to an invited or removed member', async () => { + await invite(ann, { member: ref(ben), level: 'viewer' }) + const n = await note({ title: 'x', shareGroup: group.id }) + const doc = await payload.findByID({ collection: 'notes' as never, id: n.id as never, depth: 0, overrideAccess: true }) + expect(await canView(reqFor(ben), doc)).toBe(false) + await change(ben, (await rowOf(ben)).id, { status: 'active' }) + expect(await canView(reqFor(ben), doc)).toBe(true) + await change(ben, (await rowOf(ben)).id, { status: 'removed' }) + expect(await canView(reqFor(ben), doc)).toBe(false) + }) + + it('counts a membership held by an organization the user acts for', async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'manager' }) + await payload.update({ collection: 'share-members' as never, id: (await rowOf(org, 'organizations')).id as never, data: { status: 'active' } as never, overrideAccess: true }) + const n = await note({ title: 'x', shareGroup: group.id }) + const doc = await payload.findByID({ collection: 'notes' as never, id: n.id as never, depth: 0, overrideAccess: true }) + expect(await canEdit(reqFor(cat), doc)).toBe(true) + expect(await canView(reqFor(dan), doc)).toBe(false) + }) + + it('answers false on any error, including a throwing identities hook', async () => { + const n = await note({ title: 'x', shareGroup: group.id }) + const doc = await payload.findByID({ collection: 'notes' as never, id: n.id as never, depth: 0, overrideAccess: true }) + answers.identities = () => { + throw new Error('boom') + } + expect(await canView(reqFor(ann), doc)).toBe(false) + expect(await sharedWhere(reqFor(ann))).toBe(false) + await expect(groupIdsFor(reqFor(ann))).rejects.toThrow() + }) + + it('narrows list access with sharedWhere', async () => { + await join(ben, 'viewer') + await note({ title: 'shared', shareGroup: group.id }) + await note({ title: 'loose' }) + const mine = await payload.find({ collection: 'notes' as never, user: as(ben), overrideAccess: false }) + expect(mine.docs.map((d) => (d as unknown as { title: string }).title)).toEqual(['shared']) + expect((await payload.find({ collection: 'notes' as never, user: as(dan), overrideAccess: false }).catch(() => ({ docs: [] }))).docs).toHaveLength(0) + }) + + it('lets only an Owner or Manager put a record into a group or move it out', async () => { + await join(ben, 'viewer') + const other = await newGroup(ann, { name: 'Elsewhere' }) + const stray = await note({ title: 'x', shareGroup: group.id }, ben) + expect(stray.shareGroup ?? null).toBeNull() // a Viewer's group value is dropped + const n = await note({ title: 'x', shareGroup: group.id }, ann) + expect((n.shareGroup as { id?: unknown })?.id ?? n.shareGroup).toBeTruthy() + const moved = (await payload.update({ collection: 'notes' as never, id: n.id as never, data: { shareGroup: other.id } as never, user: as(ben), overrideAccess: false }).catch(() => null)) as { shareGroup?: unknown } | null + expect(moved).toBeNull() // a Viewer can't even edit it + const kept = await payload.findByID({ collection: 'notes' as never, id: n.id as never, depth: 0, overrideAccess: true }) + expect(String(kept.shareGroup)).toBe(String(group.id)) + const out = (await payload.update({ collection: 'notes' as never, id: n.id as never, data: { shareGroup: other.id } as never, user: as(ann), overrideAccess: false })) as { shareGroup?: unknown } + expect(String((out.shareGroup as { id?: unknown })?.id ?? out.shareGroup)).toBe(String(other.id)) + }) + + it('refuses to put a record in a group the user has no part in', async () => { + const theirs = await newGroup(ann, { name: 'Private' }) + const n = await note({ title: 'x', shareGroup: theirs.id }, dan) + expect(n.shareGroup ?? null).toBeNull() + }) +}) + +describe('configuration', () => { + it('stores the levels under the names the host gave them', () => { + const cfg = sharing({ kinds: [{ value: 'hobby' }], levels: { owner: { value: 'steward', label: 'Steward' }, viewer: { label: 'Reader' } } })({ collections: [] } as never) as unknown as { + collections: { slug: string; fields: { name: string; options?: { value: string; label: string }[] }[] }[] + custom: { sharing: { levels: Record } } + } + const level = cfg.collections.find((c) => c.slug === 'share-members')!.fields.find((f) => f.name === 'level')! + expect(level.options).toEqual([ + { label: 'Steward', value: 'steward' }, + { label: 'Manager', value: 'manager' }, + { label: 'Reader', value: 'viewer' }, + ]) + expect(cfg.custom.sharing.levels.owner?.value).toBe('steward') + }) + + it('is off when disabled', () => { + const cfg = sharing({ enabled: false, kinds: [] })({ collections: [] } as never) as { collections: unknown[] } + expect(cfg.collections).toHaveLength(0) + }) + + it('refuses two levels with the same stored value', () => { + expect(() => sharing({ kinds: [], levels: { viewer: { value: 'owner' } } })({ collections: [] } as never)).toThrow(/different values/) }) }) From 512ef1d05fbb254efa58aa483025babe9d618422 Mon Sep 17 00:00:00 2001 From: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:39:01 -0700 Subject: [PATCH 2/7] Close the review gaps: required veto, no deletes, history, tighter reads EXTANT APE's review of the positions PR found problems that could apply here. This checks each against sharing and fixes them: refuseMember is required (false opts out), every delete throws even with overrideAccess, hooks get plain ids plus the id and data of the change, member changes go to an append-only share-member-events history, and Viewers see only Owners and Managers by default. Adds tests for REST, GraphQL, bulk update, server-code revive and widen attempts, and same-id users and organizations. Tested: 61 tests against real Payload with in-memory MongoDB. Not tested: a database without transactions, a live site, the admin screens. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- README.md | 13 +-- docs/decisions.md | 1 + docs/test-audit.md | 2 +- package-lock.json | 37 +++++++ package.json | 1 + src/groups.ts | 11 ++- src/index.ts | 6 +- src/members.ts | 120 ++++++++++++++++++++--- src/types.ts | 19 +++- test/plugin.test.ts | 234 ++++++++++++++++++++++++++++++++++++++++++-- vitest.config.ts | 10 +- 12 files changed, 422 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 08c12dd..d48d313 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,11 @@ - `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 `refuseMember` veto on invite, accept and level change, applied to server code too. + - 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. + - 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. -- Tested: 45 tests against real Payload 3.92 with an in-memory MongoDB replica set, covering each path above, repeated two-at-once runs for the last-Owner and duplicate-invite rules, and clean-up of the database and server at the end. +- Tested: 61 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, and clean-up of the database and server at the end. - Not tested: a database without transactions (the last-Owner guard needs a replica set), a live site, the admin screens in a browser, and a very large number of members. diff --git a/README.md b/README.md index d393013..0a49085 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Sharing for Payload: people share records with other users and organizations, under access rules the host passes in. -**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 (45 tests, including two requests at once). 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 relies on one. +**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 (61 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 relies on one. ## What it does @@ -17,7 +17,7 @@ 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, and a second live row for the same group and member can't exist. +- 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. @@ -60,9 +60,10 @@ export default buildConfig({ - `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. - `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 organizations) work the same way. Each gets the group, the membership and `actorRole`, the asker's own role in the group. -- `refuseMember`: 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. -- `canRead`: who reads memberships. Default is your own rows and every row in groups you are active in. -- `audit`: `before` and `after` hooks for invite, accept, change level and remove. A `before` hook that throws stops the change. +- `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.` +- `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. Return a `where` to widen it. +- `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 @@ -74,7 +75,7 @@ export default buildConfig({ ## Limits - A record can be in one group (or several, with `hasMany`). Records don't inherit from parent groups. -- Viewers can read the other members of their group by default. Narrow that with `canRead`. +- Hooks get plain ids and `{ relationTo, value }` references, plus the `id` and `data` of the change. - Invitations are rows in `share-members`. The plugin sends no email. ## Build and test diff --git a/docs/decisions.md b/docs/decisions.md index 8ca83e9..d7c9597 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -7,3 +7,4 @@ Dated decisions for this repo, newest last. - 2026-11-22: first version built for Captive Origins K5228 (account model T5), following Captive Origins D5228 (shared collections with Owner, Manager and Viewer, at least one Owner), D5234 (business accounts and brands) and D5239 (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). diff --git a/docs/test-audit.md b/docs/test-audit.md index f78e260..5e7d1ba 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -5,7 +5,7 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". ## 2026-11-22: first version (K5228) - 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` (45 tests). The two concurrency tests repeat four rounds for the last-Owner rule. +- Covered: each of those, in `test/plugin.test.ts` (61 tests, 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) diff --git a/package-lock.json b/package-lock.json index 7af0d43..480d6e7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "license": "MIT", "devDependencies": { "@payloadcms/db-mongodb": "3.92.1", + "@payloadcms/graphql": "^3.92.1", "@types/node": "^24.0.0", "graphql": "^16.14.2", "mongodb-memory-server": "^11.3.0", @@ -634,6 +635,26 @@ "payload": "3.92.1" } }, + "node_modules/@payloadcms/graphql": { + "version": "3.92.1", + "resolved": "https://registry.npmjs.org/@payloadcms/graphql/-/graphql-3.92.1.tgz", + "integrity": "sha512-JBDgK5HnjwbJ0IIP5nVXZahpFRLNm5QMoewcvbpulPbTAVsmIAaSieY+EPoX6jYQ3ErNPEo9VkTYN102hbpGAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "graphql-scalars": "1.22.2", + "pluralize": "8.0.0", + "ts-essentials": "10.0.3", + "tsx": "4.23.15" + }, + "bin": { + "payload-graphql": "bin.js" + }, + "peerDependencies": { + "graphql": "^16.8.1", + "payload": "3.92.1" + } + }, "node_modules/@payloadcms/translations": { "version": "3.92.1", "resolved": "https://registry.npmjs.org/@payloadcms/translations/-/translations-3.92.1.tgz", @@ -1734,6 +1755,22 @@ "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" } }, + "node_modules/graphql-scalars": { + "version": "1.22.2", + "resolved": "https://registry.npmjs.org/graphql-scalars/-/graphql-scalars-1.22.2.tgz", + "integrity": "sha512-my9FB4GtghqXqi/lWSVAOPiTzTnnEzdOXCsAC2bb5V7EFNQjVjwy3cSSbUvgYOtDuDibd+ZsCDhz+4eykYOlhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "tslib": "^2.5.0" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0" + } + }, "node_modules/help-me": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", diff --git a/package.json b/package.json index e2bbfb2..9612b4d 100644 --- a/package.json +++ b/package.json @@ -51,6 +51,7 @@ }, "devDependencies": { "@payloadcms/db-mongodb": "3.92.1", + "@payloadcms/graphql": "^3.92.1", "@types/node": "^24.0.0", "graphql": "^16.14.2", "mongodb-memory-server": "^11.3.0", diff --git a/src/groups.ts b/src/groups.ts index 96e0ff1..0be6f3a 100644 --- a/src/groups.ts +++ b/src/groups.ts @@ -29,10 +29,11 @@ export function groupsCollection(s: ResolvedSharing, opts: SharingOptions): Coll create: async ({ req, data }) => { const user = signedIn(req, s) if (!user || !opts.canCreateGroup) return false - if (!(await exactlyTrue(() => opts.canCreateGroup!({ req, user, data: data as Partial })))) return false + const plain = { ...(data as Record), owner: refOf((data as { owner?: unknown })?.owner) ?? undefined } as Partial + if (!(await exactlyTrue(() => opts.canCreateGroup!({ req, user, data: plain })))) return false // Nobody makes a group that starts with someone else as Owner. try { - const owner = refOf((data as { owner?: unknown })?.owner) ?? { relationTo: s.users, value: user.id } + const owner = plain.owner ?? { relationTo: s.users, value: user.id } return (await identitiesOf(req, s)).some((r) => sameRef(r, owner)) } catch { return false @@ -78,6 +79,12 @@ export function groupsCollection(s: ResolvedSharing, opts: SharingOptions): Coll { name: 'lock', type: 'number', hidden: true, admin: { disabled: true }, access: { create: () => false, update: () => false } }, ], hooks: { + // Groups are never deleted, not even by server code that skips access. + beforeDelete: [ + () => { + throw refuse('Groups are never deleted.') + }, + ], beforeChange: [ async ({ data, originalDoc, operation, req }) => { if (operation === 'create') { diff --git a/src/index.ts b/src/index.ts index 3de94e7..2357e94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,7 +1,7 @@ import type { Config, Plugin } from 'payload' import { groupsCollection } from './groups.js' -import { membersCollection } from './members.js' +import { eventsCollection, membersCollection } from './members.js' import type { ResolvedSharing, Role, SharingOptions } from './types.js' export { @@ -33,6 +33,8 @@ export const sharing = (options: SharingOptions): Plugin => (config: Config): Config => { if (options.enabled === false) return config + if (options.refuseMember === undefined) + throw new Error('payload-plugin-sharing: pass `refuseMember`, a function that vetoes a member, or `refuseMember: false` to say there is none') const users = options.users ?? config.admin?.user ?? 'users' const levels = { ...DEFAULT_LEVELS } for (const role of Object.keys(levels) as Role[]) { @@ -51,6 +53,6 @@ export const sharing = return { ...config, custom: { ...config.custom, sharing: resolved }, - collections: [...(config.collections ?? []), groupsCollection(resolved, options), membersCollection(resolved, options)], + collections: [...(config.collections ?? []), groupsCollection(resolved, options), membersCollection(resolved, options), eventsCollection(resolved, options)], } } diff --git a/src/members.ts b/src/members.ts index b033808..7a4e02f 100644 --- a/src/members.ts +++ b/src/members.ts @@ -3,6 +3,7 @@ import type { CollectionConfig, PayloadRequest, Where } from 'payload' import { exactlyTrue, refuse } from './groups.js' import { idOf, identitiesOf, refOf, roleIn, roleOf, sameRef, signedIn, whereRefs, groupIdsFor } from './helpers.js' import { + EVENTS, GROUPS, MEMBERS, type AuditEvent, @@ -29,6 +30,16 @@ const normalize = (doc: Record): ShareMember => ({ removedBy: idOf(doc.removedBy), }) +/** Ids and member references as plain values, whatever shape the client or server code sent them in. */ +const plain = (data: Record | undefined): Partial => { + const d = { ...(data ?? {}) } as Record + if ('group' in d) d.group = idOf(d.group) + if ('member' in d) d.member = refOf(d.member) + if ('invitedBy' in d) d.invitedBy = idOf(d.invitedBy) + if ('removedBy' in d) d.removedBy = idOf(d.removedBy) + return d as Partial +} + export function membersCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { const levels = Object.values(s.levels) const by = (req: PayloadRequest) => idOf(req.user) @@ -42,14 +53,19 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col } /** The asker's hook, with the group and their own role in it. No signed-in user, no hook, or no exact true is a no. */ - const ask = async (fn: ((a: MemberArgs) => boolean | Promise) | undefined, req: PayloadRequest, member: Partial, to?: string) => { + const ask = async ( + fn: ((a: MemberArgs) => boolean | Promise) | undefined, + req: PayloadRequest, + member: Partial, + extra: { id?: string | number; data?: Partial; to?: string } = {}, + ) => { const user = signedIn(req, s) if (!user || !fn) return false try { const group = await loadGroup(req, member.group) if (!group) return false const actorRole = await roleIn(req, group.id).catch(() => null) - return await exactlyTrue(() => fn({ req, user, group, member, actorRole, to })) + return await exactlyTrue(() => fn({ req, user, group, id: extra.id, member, data: extra.data ?? member, actorRole, to: extra.to })) } catch { return false } @@ -118,21 +134,25 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col description: 'Who is in which group, and at what level. Leave by setting the status to Removed; rows are never deleted, so the record stays.', }, access: { - create: ({ req, data }) => ask(opts.canInvite, req, (data ?? {}) as Partial), + create: ({ req, data }) => { + const d = plain(data as Record) + return ask(opts.canInvite, req, d, { data: d }) + }, update: async ({ req, id, data }) => { try { if (id === undefined || id === null || !signedIn(req, s)) return false const doc = (await req.payload.findByID({ collection: MEMBERS as never, id, depth: 0, overrideAccess: true, req })) as unknown as Record const before = normalize(doc) - const next = (data ?? {}) as Partial + const next = plain(data as Record) + const ctx = { id: before.id, data: next } const asks: Promise[] = [] - if (next.level !== undefined && next.level !== before.level) asks.push(ask(opts.canChangeLevel, req, before, String(next.level))) + if (next.level !== undefined && next.level !== before.level) asks.push(ask(opts.canChangeLevel, req, before, { ...ctx, to: String(next.level) })) if (next.status !== undefined && next.status !== before.status) { - if (next.status === 'active') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canAccept, req, before)) - else if (next.status === 'removed') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canRemove ?? opts.canChangeLevel, req, before)) + if (next.status === 'active') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canAccept, req, before, ctx)) + else if (next.status === 'removed') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canRemove ?? opts.canChangeLevel, req, before, ctx)) else return false } - if (!asks.length) return ask(opts.canChangeLevel, req, before, before.level) + if (!asks.length) return ask(opts.canChangeLevel, req, before, { ...ctx, to: before.level }) return (await Promise.all(asks)).every(Boolean) } catch { return false @@ -148,8 +168,16 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col return answer === true ? true : answer && typeof answer === 'object' ? answer : false } const refs = await identitiesOf(req, s) - const groups = await groupIdsFor(req, 'view') - return { or: [whereRefs(refs), ...(groups.length ? [{ group: { in: groups } }] : [])] } as Where + const staffed = await groupIdsFor(req, 'edit') + const viewed = await groupIdsFor(req, 'view') + // Owners and Managers see every row in their groups. A Viewer sees only the Owners and Managers, and their own row. + return { + or: [ + whereRefs(refs), + ...(staffed.length ? [{ group: { in: staffed } }] : []), + ...(viewed.length ? [{ and: [{ group: { in: viewed } }, { level: { in: [s.levels.owner.value, s.levels.manager.value] } }, { status: { equals: 'active' } }] }] : []), + ], + } as unknown as Where } catch { return false } @@ -194,6 +222,12 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col { name: 'liveKey', type: 'text', unique: true, index: true, hidden: true, admin: { disabled: true } }, ], hooks: { + // Nothing is ever deleted, not even by server code that skips access. + beforeDelete: [ + () => { + throw refuse('Memberships are never deleted. Set the status to Removed.') + }, + ], beforeChange: [ async ({ data, originalDoc, operation, req }) => { const now = new Date().toISOString() @@ -280,18 +314,43 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col async ({ doc, previousDoc, operation, req }) => { const membership = normalize(doc) const asker = by(req) + // The history row is written in the same transaction, so a change without its record is rolled back. + const note = async (event: string, previous?: ShareMember) => { + const ref = membership.member + await req.payload.create({ + collection: EVENTS as never, + data: { + group: membership.group, + membership: doc.id, + memberType: ref.relationTo, + memberId: String(ref.value), + event, + level: membership.level, + previousLevel: previous?.level ?? null, + status: membership.status, + previousStatus: previous?.status ?? null, + by: asker, + } as never, + overrideAccess: true, + req, + }) + } if (operation === 'create') { + await note('invite') await run(opts.audit?.afterInvite, { event: 'invite', phase: 'after', membership, by: asker, req }, false) return doc } if (!previousDoc) return doc const previous = normalize(previousDoc) if (previous.status !== membership.status) { + await note(membership.status === 'removed' ? 'remove' : 'accept', previous) if (membership.status === 'removed') await run(opts.audit?.afterRemove, { event: 'remove', phase: 'after', membership, previous, by: asker, req }, false) else if (membership.status === 'active') await run(opts.audit?.afterAccept, { event: 'accept', phase: 'after', membership, previous, by: asker, req }, false) } - if (previous.level !== membership.level && membership.status !== 'removed') + if (previous.level !== membership.level && membership.status !== 'removed') { + if (previous.status === membership.status) await note('change-level', previous) await run(opts.audit?.afterChangeLevel, { event: 'change-level', phase: 'after', membership, previous, by: asker, req }, false) + } return doc }, ], @@ -300,3 +359,42 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col } export type { Role } + +/** The append-only history: one row per invitation, acceptance, level change and removal. Never edited, never deleted. */ +export function eventsCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { + const stop = (what: string) => () => { + throw refuse(`The history can’t be ${what}.`) + } + return { + slug: EVENTS, + labels: { singular: 'Share member event', plural: 'Share member events' }, + admin: { group: opts.adminGroup ?? 'Sharing', defaultColumns: ['group', 'event', 'memberType', 'memberId', 'createdAt'], description: 'What changed in each group’s membership, and who changed it. Append-only.' }, + access: { + create: () => false, + update: () => false, + delete: () => false, + read: async ({ req }) => { + try { + if (!signedIn(req, s)) return false + const owned = await groupIdsFor(req, 'own') + return owned.length ? { group: { in: owned } } : false + } catch { + return false + } + }, + }, + fields: [ + { name: 'group', type: 'relationship', relationTo: GROUPS, required: true, index: true }, + { name: 'membership', type: 'relationship', relationTo: MEMBERS, required: true, index: true }, + { name: 'memberType', type: 'text', required: true }, + { name: 'memberId', type: 'text', required: true }, + { name: 'event', type: 'select', required: true, options: ['invite', 'accept', 'change-level', 'remove'] }, + { name: 'level', type: 'text' }, + { name: 'previousLevel', type: 'text' }, + { name: 'status', type: 'text' }, + { name: 'previousStatus', type: 'text' }, + { name: 'by', type: 'relationship', relationTo: s.users }, + ], + hooks: { beforeDelete: [stop('deleted')], beforeChange: [({ operation, data }) => { if (operation !== 'create') throw refuse('The history can’t be edited.'); return data }] }, + } +} diff --git a/src/types.ts b/src/types.ts index 71692c0..886c1ab 100644 --- a/src/types.ts +++ b/src/types.ts @@ -2,6 +2,7 @@ import type { Payload, PayloadRequest, Where } from 'payload' export const GROUPS = 'share-groups' export const MEMBERS = 'share-members' +export const EVENTS = 'share-member-events' export type Role = 'owner' | 'manager' | 'viewer' export type MemberStatus = 'invited' | 'active' | 'removed' @@ -54,8 +55,12 @@ export type MemberArgs = { req: PayloadRequest user: User group: ShareGroup & { id: string | number } - /** The membership being created, or (for a change) the membership as it is now. */ + /** The id of the membership being changed. Absent when one is being created. */ + id?: string | number + /** The membership as it is now, or for an invitation what is being created. Ids are plain, never `{ id }` objects. */ member: Partial + /** The fields being sent: the whole invitation, or only what a change touches. Normalized the same way. */ + data: Partial /** The role the asker holds in this group (through themselves or an identity), or null if none. */ actorRole: Role | null /** For `canChangeLevel`: the level it would become. */ @@ -72,6 +77,8 @@ export type RefuseArgs = { action: 'invite' | 'accept' | 'change-level' } +export type RefuseMember = (args: RefuseArgs) => string | null | undefined | Promise + export type AuditEvent = { event: 'invite' | 'accept' | 'change-level' | 'remove' phase: 'before' | 'after' @@ -112,14 +119,18 @@ export type SharingOptions = { canRemove?: Check /** Who may accept an invitation for an organization. A user always accepts their own. Default: nobody. */ canAccept?: Check - /** Who may read memberships. Default: your own, and every membership in groups you are active in. May return a `where`. */ + /** + * Who may read memberships. Default: your own, every row in groups where you are an Owner or Manager, and only the + * Owners and Managers of groups where you are a Viewer. May return a `where` to widen or narrow that. + */ canRead?: (args: { req: PayloadRequest; user: User }) => boolean | Where | Promise /** * A veto the host controls, asked on every invitation, acceptance and level change, even for server code that skips * access. Return `null` or nothing to go ahead, or a reason to refuse. A throw, `false` or anything else refuses with - * a general reason. + * a general reason. The reason is shown to whoever was refused, so never put a reason that reveals something private, + * such as an age. Required: pass `false` to say plainly that the host has no veto. */ - refuseMember?: (args: RefuseArgs) => string | null | undefined | Promise + refuseMember: RefuseMember | false /** Audit hooks. A `before` hook that throws stops the change. An `after` hook that throws is logged and ignored. */ audit?: { beforeInvite?: AuditHook diff --git a/test/plugin.test.ts b/test/plugin.test.ts index c3ce527..339fedb 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -1,6 +1,8 @@ import { mongooseAdapter } from '@payloadcms/db-mongodb' import { MongoMemoryReplSet } from 'mongodb-memory-server' -import { buildConfig, getPayload, type Payload } from 'payload' +import { configToSchema } from '@payloadcms/graphql' +import { graphql } from 'graphql' +import { buildConfig, createLocalReq, getPayload, handleEndpoints, type Payload } from 'payload' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' import { canEdit, canView, groupIdsFor, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' @@ -13,6 +15,7 @@ const PW = 'correct-horse-battery' let payload: Payload let mongo: MongoMemoryReplSet const log: string[] = [] +const seen: { id?: unknown; data?: unknown; member?: unknown }[] = [] const answers: { refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} type U = { id: string | number } @@ -52,6 +55,10 @@ const join = async (u: U, level: string) => { await change(u, r.id, { status: 'active' }) return r } +/** The plugin's collections can't be deleted through Payload, so the test empties its own database directly. */ +const wipe = async () => { + for (const c of ['share-member-events', 'share-members', 'share-groups']) await (payload.db as unknown as { collections: Record Promise }> }).collections[c]!.deleteMany({}) +} const record = (e: AuditEvent) => { log.push(`${e.phase}:${e.event}`) } @@ -98,12 +105,16 @@ beforeAll(async () => { return org ? [{ relationTo: 'organizations', value: ((org as { id?: unknown }).id ?? org) as string }] : [] }, canCreateGroup: ({ user }) => (user as { staff?: boolean }).staff === true, - canInvite: ({ actorRole, member, group: g }) => { + canInvite: ({ actorRole, member, group: g, data, id }) => { + seen.push({ id, data, member }) if (answers.canInvite) return answers.canInvite() as boolean if (actorRole === 'owner') return true return actorRole === 'manager' && member.level === 'viewer' && g.kind !== 'family' }, - canChangeLevel: ({ actorRole }) => actorRole === 'owner', + canChangeLevel: ({ actorRole, id, data, member }) => { + seen.push({ id, data, member }) + return actorRole === 'owner' + }, refuseMember: ({ subject, group: g }) => { if (answers.refuse) return answers.refuse() as string | null return (subject as { minor?: boolean }).minor && g.kind !== 'family' ? 'Not available for this account.' : null @@ -135,7 +146,8 @@ afterAll(async () => { beforeEach(async () => { for (const key of Object.keys(answers)) delete (answers as Record)[key] log.length = 0 - for (const c of ['notes', 'share-members', 'share-groups', 'users', 'organizations']) + await wipe() + for (const c of ['notes', 'users', 'organizations']) await payload.delete({ collection: c as never, where: { id: { exists: true } }, overrideAccess: true }) org = (await payload.create({ collection: 'organizations', data: { name: 'Made-up Co' } as never })) as unknown as U ann = await make('ann@example.com', { staff: true }) @@ -388,8 +400,7 @@ describe('a group always keeps an Owner', () => { it('keeps one Owner when two Owners demote each other at once', async () => { for (let i = 0; i < 4; i++) { - await payload.delete({ collection: 'share-members' as never, where: { id: { exists: true } }, overrideAccess: true }) - await payload.delete({ collection: 'share-groups' as never, where: { id: { exists: true } }, overrideAccess: true }) + await wipe() group = await newGroup(ann) await join(ben, 'owner') const a = (await rowOf(ann)).id @@ -508,9 +519,209 @@ describe('records in a group', () => { }) }) +describe('a closed door for every route', () => { + const token = async (u: string) => (await payload.login({ collection: 'users', data: { email: u, password: PW } })).token as string + const call = async (path: string, init: { method: string; token?: string; body?: unknown }) => { + const res = await handleEndpoints({ + config: payload.config, + request: new Request(`http://localhost/api${path}`, { + method: init.method, + headers: { 'content-type': 'application/json', ...(init.token ? { Authorization: `JWT ${init.token}` } : {}) }, + body: init.body ? JSON.stringify(init.body) : undefined, + }), + }) + return { status: res.status, json: (await res.json().catch(() => ({}))) as Record } + } + const count = async () => (await rows()).totalDocs + + it('refuses REST: signed out, a stranger, a viewer, and a delete by the Owner', async () => { + const before = await count() + const body = { group: group.id, member: ref(dan), level: 'viewer' } + expect((await call('/share-members', { method: 'POST', body })).status).toBeGreaterThanOrEqual(400) + expect((await call('/share-members', { method: 'POST', body, token: await token('ben@example.com') })).status).toBeGreaterThanOrEqual(400) + await join(ben, 'viewer') + const mid = await count() + expect((await call('/share-members', { method: 'POST', body, token: await token('ben@example.com') })).status).toBeGreaterThanOrEqual(400) + const r = await rowOf(ben) + expect((await call(`/share-members/${r.id}`, { method: 'PATCH', body: { level: 'owner' }, token: await token('ben@example.com') })).status).toBeGreaterThanOrEqual(400) + expect((await call(`/share-members/${r.id}`, { method: 'DELETE', token: await token('ann@example.com') })).status).toBeGreaterThanOrEqual(400) + expect((await call(`/share-groups/${group.id}`, { method: 'DELETE', token: await token('ann@example.com') })).status).toBeGreaterThanOrEqual(400) + expect(await count()).toBe(mid) + expect(before).toBe(1) + expect((await rowOf(ben)).level).toBe('viewer') + }) + + it('refuses GraphQL: a stranger inviting and a viewer raising their own level', async () => { + await join(ben, 'viewer') + const r = await rowOf(ben) + const { schema } = configToSchema(payload.config) + const gql = async (query: string, who?: U) => { + const req = await createLocalReq({ user: who ? as(who) : undefined }, payload) + req.payloadAPI = 'GraphQL' + return (await graphql({ schema, source: query, contextValue: { req } })) as { errors?: unknown[] } + } + const invite = `mutation { createShareMember(data: { group: "${group.id}", level: viewer, status: invited, member: { relationTo: users, value: "${dan.id}" } }) { id } }` + expect((await gql(invite, cat)).errors?.length).toBeGreaterThan(0) + const raise = `mutation { updateShareMember(id: "${r.id}", data: { level: owner }) { id } }` + expect((await gql(raise, ben)).errors?.length).toBeGreaterThan(0) + expect((await gql(raise)).errors?.length).toBeGreaterThan(0) + expect((await rowOf(ben)).level).toBe('viewer') + expect((await rowOf(dan).catch(() => undefined)) ?? null).toBeNull() + // The same mutation works for an Owner, so the refusals above came from the rules and not from a typo. + const ok = await gql(invite, ann) + expect(ok.errors).toBeUndefined() + expect((await rowOf(dan)).status).toBe('invited') + }) + + it('refuses a bulk update, from a viewer and from an Owner', async () => { + await join(ben, 'viewer') + await join(dan, 'viewer') + for (const u of [ben, ann]) { + await refused(payload.update({ collection: 'share-members' as never, where: { level: { equals: 'viewer' } } as never, data: { level: 'manager' } as never, user: as(u), overrideAccess: false })) + } + expect((await rows({ level: { equals: 'manager' } })).totalDocs).toBe(0) + const res = await call('/share-members?where[level][equals]=viewer', { method: 'PATCH', body: { level: 'manager' }, token: await token('ann@example.com') }) + expect(res.status).toBeGreaterThanOrEqual(400) + expect((await rows({ level: { equals: 'manager' } })).totalDocs).toBe(0) + }) +}) + +describe('no way round the gate, even for server code', () => { + const server = (id: unknown, data: Record) => + payload.update({ collection: 'share-members' as never, id: id as never, data: data as never, overrideAccess: true }) as unknown as Promise + + it('never brings a removed member back, by status, level or notes', async () => { + const r = await join(ben, 'viewer') + await change(ann, r.id, { status: 'removed' }) + expect(await refused(server(r.id, { status: 'active' }))).toMatch(/final/) + expect(await refused(server(r.id, { status: 'invited' }))).toMatch(/final/) + expect(await refused(server(r.id, { level: 'owner' }))).toMatch(/final/) + expect((await rowOf(ben)).status).toBe('removed') + expect(await roleIn(reqFor(ben), group.id)).toBeNull() + }) + + it('never turns an active member back into an invitation or revives an invite', async () => { + const r = await join(ben, 'viewer') + expect(await refused(server(r.id, { status: 'invited' }))).toMatch(/isn’t allowed/) + await invite(ann, { member: ref(dan), level: 'viewer' }) + const d = await rowOf(dan) + await change(ann, d.id, { status: 'removed' }) + expect(await refused(server(d.id, { status: 'invited' }))).toMatch(/final/) + }) + + it('asks the veto again for a raise from server code, and for a self-accept with a raised level', async () => { + const r = await join(ben, 'viewer') + answers.refuse = () => 'No.' + expect(await refused(server(r.id, { level: 'manager' }))).toBe('No.') + delete answers.refuse + await invite(ann, { member: ref(dan), level: 'viewer' }) + const d = await rowOf(dan) + expect(await refused(change(dan, d.id, { status: 'active', level: 'owner' }))).toBeTruthy() + expect((await rowOf(dan)).status).toBe('invited') + }) + + it('never deletes, even with overrideAccess', async () => { + const r = await rowOf(ann) + for (const [collection, id] of [['share-groups', group.id], ['share-members', r.id]] as const) { + expect(await refused(payload.delete({ collection: collection as never, id: id as never, overrideAccess: true }))).toMatch(/never deleted/) + await refused(payload.delete({ collection: collection as never, where: { id: { exists: true } } as never, overrideAccess: true })) + } + expect((await rows()).totalDocs).toBe(1) + expect((await payload.find({ collection: 'share-groups' as never, overrideAccess: true })).totalDocs).toBe(1) + }) +}) + +describe('what the hooks are given', () => { + it('passes plain ids and member references, and the id and data of a change', async () => { + seen.length = 0 + await invite(ann, { group: { id: group.id }, member: { relationTo: 'users', value: { id: ben.id } }, level: 'viewer' }) + const first = seen[0]! as { data: { group: unknown; member: unknown }; member: { group: unknown; member: unknown } } + expect(first.data.group).toBe(group.id) + expect(first.data.member).toEqual({ relationTo: 'users', value: ben.id }) + expect(first.member.member).toEqual({ relationTo: 'users', value: ben.id }) + seen.length = 0 + const r = await rowOf(ben) + await change(ann, r.id, { level: 'manager' }) + const second = seen[0]! as { id: unknown; data: { level: string } } + expect(String(second.id)).toBe(String(r.id)) + expect(second.data.level).toBe('manager') + }) + + it('gives the audit hooks plain ids too', async () => { + const events: AuditEvent[] = [] + answers.beforeInvite = () => undefined + await invite(ann, { member: ref(ben), level: 'viewer' }) + void events + const r = await rowOf(ben) + expect(typeof r.id).not.toBe('object') + }) +}) + +describe('members are keyed by their collection', () => { + it('does not give a user the membership of an organization with the same id, or the other way round', async () => { + await invite(ann, { member: ref(dan), level: 'manager' }) + await change(dan, (await rowOf(dan)).id, { status: 'active' }) + // someone who acts as an organization that happens to share dan's id + answers.identities = () => [{ relationTo: 'organizations', value: dan.id }] + expect(await roleIn(reqFor(ben), group.id)).toBeNull() + delete answers.identities + await invite(ann, { member: ref(org, 'organizations'), level: 'manager' }) + await payload.update({ collection: 'share-members' as never, id: (await rowOf(org, 'organizations')).id as never, data: { status: 'active' } as never, overrideAccess: true }) + answers.identities = () => [{ relationTo: 'users', value: org.id }] + expect(await roleIn(reqFor(ben), group.id)).toBeNull() + }) +}) + +describe('the history', () => { + const events = async () => + (await payload.find({ collection: 'share-member-events' as never, sort: 'createdAt', pagination: false, overrideAccess: true })).docs as unknown as { event: string; level: string; previousLevel?: string; previousStatus?: string; memberId: string; memberType: string }[] + + it('records every invitation, acceptance, level change and removal', async () => { + const r = await join(ben, 'viewer') + await change(ann, r.id, { level: 'manager' }) + await change(ben, r.id, { status: 'removed' }) + const list = await events() + expect(list.map((e) => e.event)).toEqual(['invite', 'invite', 'accept', 'change-level', 'remove']) + expect(list[3]).toMatchObject({ level: 'manager', previousLevel: 'viewer', memberType: 'users', memberId: String(ben.id) }) + }) + + it('records nothing for a change that was refused', async () => { + const before = (await events()).length + await refused(invite(dan, { member: ref(ben), level: 'viewer' })) + expect((await events()).length).toBe(before) + }) + + it('can’t be written, edited or deleted, by clients or by server code', async () => { + const e = (await payload.find({ collection: 'share-member-events' as never, overrideAccess: true })).docs[0] as { id: string } + expect(await refused(payload.create({ collection: 'share-member-events' as never, data: { group: group.id, membership: (await rowOf(ann)).id, memberType: 'users', memberId: 'x', event: 'invite' } as never, user: as(ann), overrideAccess: false }))).toBeTruthy() + expect(await refused(payload.update({ collection: 'share-member-events' as never, id: e.id as never, data: { level: 'x' } as never, overrideAccess: true }))).toMatch(/edited/) + expect(await refused(payload.delete({ collection: 'share-member-events' as never, id: e.id as never, overrideAccess: true }))).toMatch(/deleted/) + }) + + it('is read by a group’s Owners only', async () => { + await join(ben, 'manager') + const read = (u: U) => payload.find({ collection: 'share-member-events' as never, user: as(u), overrideAccess: false }) + expect((await read(ann)).totalDocs).toBeGreaterThan(0) + expect(await refused(read(ben))).toBeTruthy() + }) +}) + +describe('what a Viewer can see of the other members', () => { + it('shows a Viewer only the Owners and Managers, and their own row; a Manager sees everyone', async () => { + await join(ben, 'viewer') + await join(dan, 'viewer') + await join(cat, 'manager') + const names = async (u: U) => + (await payload.find({ collection: 'share-members' as never, user: as(u), overrideAccess: false, pagination: false })).docs.map((d) => String(((d as unknown as { member: { value: { id?: unknown } | string } }).member.value as { id?: unknown })?.id ?? (d as unknown as { member: { value: unknown } }).member.value)) + const sorted = (a: string[]) => [...a].sort() + expect(sorted(await names(ben))).toEqual(sorted([String(ann.id), String(cat.id), String(ben.id)])) + expect((await names(cat)).length).toBe(4) + }) +}) + describe('configuration', () => { it('stores the levels under the names the host gave them', () => { - const cfg = sharing({ kinds: [{ value: 'hobby' }], levels: { owner: { value: 'steward', label: 'Steward' }, viewer: { label: 'Reader' } } })({ collections: [] } as never) as unknown as { + const cfg = sharing({ kinds: [{ value: 'hobby' }], refuseMember: false, levels: { owner: { value: 'steward', label: 'Steward' }, viewer: { label: 'Reader' } } })({ collections: [] } as never) as unknown as { collections: { slug: string; fields: { name: string; options?: { value: string; label: string }[] }[] }[] custom: { sharing: { levels: Record } } } @@ -523,12 +734,17 @@ describe('configuration', () => { expect(cfg.custom.sharing.levels.owner?.value).toBe('steward') }) + it('requires refuseMember, or an explicit false', () => { + expect(() => sharing({ kinds: [] } as never)({ collections: [] } as never)).toThrow(/refuseMember/) + expect(() => sharing({ kinds: [], refuseMember: false })({ collections: [] } as never)).not.toThrow() + }) + it('is off when disabled', () => { - const cfg = sharing({ enabled: false, kinds: [] })({ collections: [] } as never) as { collections: unknown[] } + const cfg = sharing({ enabled: false, kinds: [], refuseMember: false })({ collections: [] } as never) as { collections: unknown[] } expect(cfg.collections).toHaveLength(0) }) it('refuses two levels with the same stored value', () => { - expect(() => sharing({ kinds: [], levels: { viewer: { value: 'owner' } } })({ collections: [] } as never)).toThrow(/different values/) + expect(() => sharing({ kinds: [], refuseMember: false, levels: { viewer: { value: 'owner' } } })({ collections: [] } as never)).toThrow(/different values/) }) }) diff --git a/vitest.config.ts b/vitest.config.ts index 01d526e..c879b94 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,3 +1,11 @@ import { defineConfig } from 'vitest/config' -export default defineConfig({ test: { testTimeout: 60_000, hookTimeout: 120_000, fileParallelism: false } }) +export default defineConfig({ + test: { + testTimeout: 60_000, + hookTimeout: 120_000, + fileParallelism: false, + // One copy of graphql for the GraphQL refusal tests: Payload's schema and the test must share it. + server: { deps: { inline: ['graphql', '@payloadcms/graphql'] } }, + }, +}) From 8687688d2452855f2c6f03612abfc96e5baf1b33 Mon Sep 17 00:00:00 2001 From: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:54:05 -0700 Subject: [PATCH 3/7] Fix the second review: private fields, accept rules, per-person veto, transactions Notes, invitedBy and removedBy are now readable by Owners and Managers only, and notes are capped. A user accepts only their own invitation and canAccept applies to organization members only. A throwing identities hook refuses before any host hook runs. The veto runs for each person behind an organization (peopleOf, required with organizations) and is shown who is acting. The plugin refuses to start without transactions, and bulk member updates are refused so a change and its history row stay together. Tested: 72 tests against real Payload with in-memory MongoDB. Not tested: a live site, the admin screens, a real database without transactions (checked with stand-ins only). Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +- README.md | 7 ++- docs/decisions.md | 1 + docs/test-audit.md | 2 +- src/index.ts | 22 ++++++++ src/members.ts | 74 +++++++++++++++++++------ src/types.ts | 17 +++++- test/plugin.test.ts | 129 ++++++++++++++++++++++++++++++++++++++++++-- 8 files changed, 232 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d48d313..32e4bb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,9 +9,10 @@ - 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. -- Tested: 61 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, and clean-up of the database and server at the end. +- Tested: 72 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, and clean-up of the database and server at the end. - Not tested: a database without transactions (the last-Owner guard needs a replica set), a live site, the admin screens in a browser, and a very large number of members. diff --git a/README.md b/README.md index 0a49085..f77b835 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Sharing for Payload: people share records with other users and organizations, under access rules the host passes in. -**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 (61 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 relies on one. +**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 @@ -59,7 +59,8 @@ export default buildConfig({ - `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. -- `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 organizations) work the same way. Each gets the group, the membership and `actorRole`, the asker's own role in the group. +- `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. **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.` - `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. Return a `where` to widen it. @@ -76,6 +77,8 @@ export default buildConfig({ - 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. +- 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 diff --git a/docs/decisions.md b/docs/decisions.md index d7c9597..e01d767 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,3 +8,4 @@ Dated decisions for this repo, newest last. - 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 (bottle #119): 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. diff --git a/docs/test-audit.md b/docs/test-audit.md index 5e7d1ba..6bcaacb 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -5,7 +5,7 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". ## 2026-11-22: first version (K5228) - 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` (61 tests, 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. +- Covered: each of those, in `test/plugin.test.ts` (72 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) diff --git a/src/index.ts b/src/index.ts index 2357e94..b235a69 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,20 @@ export { } from './helpers.js' export * from './types.js' +/** Throws unless the database can run transactions. The last-Owner rule and the history rows depend on them. */ +export async function assertTransactions(payload: unknown): Promise { + const db = (payload as { db?: Record }).db + const fail = () => { + throw new Error('payload-plugin-sharing needs a database with transactions (for MongoDB, a replica set). Without them the last-Owner rule and the history can’t be kept safe, so it refuses to start.') + } + if (!db || typeof db.beginTransaction !== 'function' || db.transactionOptions === false) return fail() + const raw = db.connection?.db + if (raw) { + const hello = await raw.admin().command({ hello: 1 }).catch(() => null) + if (!hello || (!hello.setName && hello.msg !== 'isdbgrid')) return fail() + } +} + const DEFAULT_LEVELS: Record = { owner: { value: 'owner', label: 'Owner' }, manager: { value: 'manager', label: 'Manager' }, @@ -35,6 +49,9 @@ export const sharing = if (options.enabled === false) return config if (options.refuseMember === undefined) throw new Error('payload-plugin-sharing: pass `refuseMember`, a function that vetoes a member, or `refuseMember: false` to say there is none') + const extra = [...new Set(options.memberTypes ?? [])].filter((m) => m !== (options.users ?? config.admin?.user ?? 'users')) + if (extra.length && options.refuseMember !== false && options.peopleOf === undefined) + throw new Error('payload-plugin-sharing: with organizations as members, pass `peopleOf` so the veto runs for each person behind them, or `peopleOf: false` to say it does not') const users = options.users ?? config.admin?.user ?? 'users' const levels = { ...DEFAULT_LEVELS } for (const role of Object.keys(levels) as Role[]) { @@ -50,9 +67,14 @@ export const sharing = kinds: options.kinds ?? [], identities: options.identities, } + const before = config.onInit return { ...config, custom: { ...config.custom, sharing: resolved }, + onInit: async (payload) => { + await before?.(payload) + await assertTransactions(payload) + }, collections: [...(config.collections ?? []), groupsCollection(resolved, options), membersCollection(resolved, options), eventsCollection(resolved, options)], } } diff --git a/src/members.ts b/src/members.ts index 7a4e02f..3897dae 100644 --- a/src/members.ts +++ b/src/members.ts @@ -8,6 +8,7 @@ import { MEMBERS, type AuditEvent, type AuditHook, + type RefuseArgs, type MemberArgs, type MemberRef, type MemberStatus, @@ -64,13 +65,25 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col try { const group = await loadGroup(req, member.group) if (!group) return false - const actorRole = await roleIn(req, group.id).catch(() => null) + const actorRole = await roleIn(req, group.id) // a throw (the identities hook, say) is a no, below return await exactlyTrue(() => fn({ req, user, group, id: extra.id, member, data: extra.data ?? member, actorRole, to: extra.to })) } catch { return false } } + /** Notes and who invited or removed someone are for the group's Owners and Managers. Everyone else, a child included, doesn't get them. */ + const staffOnly = async ({ req, doc }: { req: PayloadRequest; doc?: Record }) => { + try { + const gid = idOf(doc?.group) + if (gid === null || !signedIn(req, s)) return false + const role = await roleIn(req, gid) + return role === 'owner' || role === 'manager' + } catch { + return false + } + } + const isSelf = (req: PayloadRequest, ref: MemberRef) => { const user = signedIn(req, s) return !!user && ref.relationTo === s.users && String(ref.value) === String(user.id) @@ -88,17 +101,37 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col /** The host's veto. Only `null` or nothing goes ahead. */ async function vetoed(req: PayloadRequest, group: GroupDoc, ref: MemberRef, level: string, action: 'invite' | 'accept' | 'change-level') { - if (!opts.refuseMember) return - const subject = await req.payload.findByID({ collection: ref.relationTo as never, id: ref.value, depth: 0, overrideAccess: true, req }).catch(() => null) - if (!subject) throw refuse(GENERAL) - let why: unknown - try { - why = await opts.refuseMember({ req, group, subject: subject as never, ref, level, action }) - } catch { - throw refuse(GENERAL) + const veto = opts.refuseMember + if (!veto) return + const actor = signedIn(req, s) as RefuseArgs['actor'] + const ask1 = async (target: MemberRef, via?: MemberRef) => { + const subject = await req.payload.findByID({ collection: target.relationTo as never, id: target.value, depth: 0, overrideAccess: true, req }).catch(() => null) + if (!subject) throw refuse(GENERAL) + let why: unknown + try { + why = await veto({ req, group, subject: subject as never, ref: target, level, action, actor, via }) + } catch { + throw refuse(GENERAL) + } + if (why === null || why === undefined) return + throw refuse(typeof why === 'string' && why.trim() ? why : GENERAL) + } + await ask1(ref) + // An organization isn't one person: ask for each person behind it too, so the veto can't be walked around. + if (ref.relationTo !== s.users && opts.peopleOf) { + let people: unknown + try { + people = await opts.peopleOf({ req, organization: ref }) + } catch { + throw refuse(GENERAL) + } + if (!Array.isArray(people)) throw refuse(GENERAL) + for (const raw of people) { + const person = refOf(raw) + if (!person || person.relationTo !== s.users) throw refuse(GENERAL) + await ask1(person, ref) + } } - if (why === null || why === undefined) return - throw refuse(typeof why === 'string' && why.trim() ? why : GENERAL) } /** @@ -148,7 +181,11 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col const asks: Promise[] = [] if (next.level !== undefined && next.level !== before.level) asks.push(ask(opts.canChangeLevel, req, before, { ...ctx, to: String(next.level) })) if (next.status !== undefined && next.status !== before.status) { - if (next.status === 'active') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canAccept, req, before, ctx)) + if (next.status === 'active') { + // A user accepts only their own invitation, never on their behalf. canAccept is for organization members only. + if (before.member.relationTo === s.users) asks.push(Promise.resolve(isSelf(req, before.member))) + else asks.push(ask(opts.canAccept, req, before, ctx)) + } else if (next.status === 'removed') asks.push(isSelf(req, before.member) ? Promise.resolve(true) : ask(opts.canRemove ?? opts.canChangeLevel, req, before, ctx)) else return false } @@ -213,15 +250,22 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col ], admin: { description: 'An invited member gets nothing until they accept. Removed is final: invite again to bring them back.' }, }, - { name: 'invitedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true } }, + { name: 'invitedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true }, access: { read: staffOnly } }, { name: 'acceptedAt', type: 'date', admin: { readOnly: true } }, { name: 'removedAt', type: 'date', admin: { readOnly: true } }, - { name: 'removedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true } }, - { name: 'notes', type: 'textarea' }, + { name: 'removedBy', type: 'relationship', relationTo: s.users, admin: { readOnly: true }, access: { read: staffOnly } }, + { name: 'notes', type: 'textarea', maxLength: 500, access: { read: staffOnly }, admin: { description: 'Seen by the group’s Owners and Managers only.' } }, // Makes a second live membership for the same group and member fail in the database, not just in a check. { name: 'liveKey', type: 'text', unique: true, index: true, hidden: true, admin: { disabled: true } }, ], hooks: { + // A bulk update can run each row in its own transaction, which would split a change from its history row. + beforeOperation: [ + ({ args, operation }) => { + if (operation === 'update' && (args as { id?: unknown }).id === undefined) throw refuse('Memberships are changed one at a time.') + return args + }, + ], // Nothing is ever deleted, not even by server code that skips access. beforeDelete: [ () => { diff --git a/src/types.ts b/src/types.ts index 886c1ab..7be331a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -75,6 +75,13 @@ export type RefuseArgs = { ref: MemberRef level: string action: 'invite' | 'accept' | 'change-level' + /** The signed-in user making the change, or null for server code. */ + actor: ({ id: string | number } & Record) | null + /** + * Set when the member is an organization: the veto is asked once for the organization itself, and once for each person + * `peopleOf` lists behind it, with `subject` the person and `via` the organization. + */ + via?: MemberRef } export type RefuseMember = (args: RefuseArgs) => string | null | undefined | Promise @@ -109,6 +116,14 @@ export type SharingOptions = { * them counts for the user. A throw means access is refused. Default: only the user. */ identities?: (args: { req: PayloadRequest; user: User }) => MemberRef[] | Promise + /** + * The people behind an organization, asked whenever an organization is invited, accepts or changes level, so that + * `refuseMember` runs for each of them. Required when `memberTypes` adds anything beyond users and there is a veto; + * pass `false` to say plainly that organizations are not checked person by person. Only the people listed at that + * moment are checked: someone who joins the organization later is not, so the host must ask its veto again when people + * join, or keep organizations out of groups where a veto matters. + */ + peopleOf?: ((args: { req: PayloadRequest; organization: MemberRef }) => MemberRef[] | Promise) | false /** Who may make a group. Only an exact `true` counts. The group's owner must also be the asker or one of their identities. */ canCreateGroup?: Check /** Who may invite someone to a group. Only an exact `true` counts; a throw, a truthy value or no hook is a no. */ @@ -117,7 +132,7 @@ export type SharingOptions = { canChangeLevel?: Check /** Who may remove someone else. Default: whoever `canChangeLevel` allows. Anyone may always leave or decline for themselves. */ canRemove?: Check - /** Who may accept an invitation for an organization. A user always accepts their own. Default: nobody. */ + /** Who may accept an invitation for an organization member. A user member can only be accepted by that user, never on their behalf. Default: nobody. */ canAccept?: Check /** * Who may read memberships. Default: your own, every row in groups where you are an Owner or Manager, and only the diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 339fedb..534bb95 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -5,7 +5,7 @@ import { graphql } from 'graphql' import { buildConfig, createLocalReq, getPayload, handleEndpoints, type Payload } from 'payload' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' -import { canEdit, canView, groupIdsFor, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' +import { assertTransactions, canEdit, canView, groupIdsFor, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' /** * A made-up site: users (staff may make groups, some belong to organizations, one is flagged `minor`), organizations, @@ -16,7 +16,8 @@ let payload: Payload let mongo: MongoMemoryReplSet const log: string[] = [] const seen: { id?: unknown; data?: unknown; member?: unknown }[] = [] -const answers: { refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} +const vetoSaw: { subject: unknown; via: unknown; actor: unknown; action: string }[] = [] +const answers: { canAccept?: () => unknown; refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} type U = { id: string | number } let ann: U, ben: U, cat: U, dan: U, kid: U, org: U @@ -115,7 +116,13 @@ beforeAll(async () => { seen.push({ id, data, member }) return actorRole === 'owner' }, - refuseMember: ({ subject, group: g }) => { + peopleOf: async ({ organization }) => { + const found = await payload.find({ collection: 'users', where: { org: { equals: organization.value } }, pagination: false, overrideAccess: true }) + return found.docs.map((d) => ({ relationTo: 'users', value: d.id })) + }, + canAccept: () => (answers.canAccept ? (answers.canAccept() as boolean) : false), + refuseMember: ({ subject, group: g, via, actor, action }) => { + vetoSaw.push({ subject: (subject as { email?: string }).email ?? 'org', via, actor, action }) if (answers.refuse) return answers.refuse() as string | null return (subject as { minor?: boolean }).minor && g.kind !== 'family' ? 'Not available for this account.' : null }, @@ -719,6 +726,122 @@ describe('what a Viewer can see of the other members', () => { }) }) +describe('the second review', () => { + const readRow = async (u: U, id: unknown) => + (await payload.findByID({ collection: 'share-members' as never, id: id as never, user: as(u), overrideAccess: false, depth: 0 })) as unknown as Record + + it('keeps notes and who invited or removed someone from Viewers, a child included, and caps notes', async () => { + const fam = await newGroup(ann, { kind: 'family', name: 'Family' }) + await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(kid), level: 'viewer', notes: 'about the child' } as never, user: as(ann), overrideAccess: false }) + await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(ben), level: 'manager', notes: 'about ben' } as never, user: as(ann), overrideAccess: false }) + const kidRow = (await rows({ and: [{ group: { equals: fam.id } }, { 'member.value': { equals: kid.id } }] })).docs[0] as unknown as { id: string } + await change(kid, kidRow.id, { status: 'active' }) + const ownRow = await readRow(kid, kidRow.id) + expect(ownRow.level).toBe('viewer') + for (const f of ['notes', 'invitedBy', 'removedBy']) expect(ownRow[f]).toBeUndefined() + const benRow = (await rows({ and: [{ group: { equals: fam.id } }, { 'member.value': { equals: ben.id } }] })).docs[0] as unknown as { id: string } + await change(ben, benRow.id, { status: 'active' }) + const asManager = await readRow(ben, benRow.id) + expect(asManager.notes).toBe('about ben') + expect(asManager.invitedBy).toBeTruthy() + const asOwner = await readRow(ann, benRow.id) + expect(asOwner.notes).toBe('about ben') + }) + + it('hides notes from a Viewer who lists the group, and refuses notes over the cap', async () => { + await join(ben, 'viewer') + await join(dan, 'viewer') + await payload.update({ collection: 'share-members' as never, id: (await rowOf(dan)).id as never, data: { notes: 'for owners' } as never, overrideAccess: true }) + const listed = (await payload.find({ collection: 'share-members' as never, user: as(ben), overrideAccess: false, pagination: false, depth: 0 })).docs as unknown as Record[] + expect(listed.length).toBeGreaterThan(0) + expect(listed.every((d) => d.notes === undefined && d.invitedBy === undefined && d.removedBy === undefined)).toBe(true) + expect(await refused(invite(ann, { member: ref(cat), level: 'viewer', notes: 'x'.repeat(501) }))).toBeTruthy() + }) + + it('lets a user accept only their own invitation, even when canAccept says yes', async () => { + answers.canAccept = () => true + await invite(ann, { member: ref(ben), level: 'viewer' }) + const r = await rowOf(ben) + expect(await refused(change(ann, r.id, { status: 'active' }))).toBeTruthy() + expect(await refused(change(dan, r.id, { status: 'active' }))).toBeTruthy() + expect((await rowOf(ben)).status).toBe('invited') + await change(ben, r.id, { status: 'active' }) + }) + + it('applies canAccept to organization members only', async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) + const r = await rowOf(org, 'organizations') + expect(await refused(change(cat, r.id, { status: 'active' }))).toBeTruthy() + answers.canAccept = () => true + await change(cat, r.id, { status: 'active' }) + expect((await rowOf(org, 'organizations')).status).toBe('active') + }) + + it('refuses without calling the host hook when the identities hook throws', async () => { + let called = 0 + answers.canInvite = () => { + called++ + return true + } + answers.identities = () => { + throw new Error('boom') + } + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toBeTruthy() + expect(called).toBe(0) + expect((await rows({ status: { equals: 'invited' } })).totalDocs).toBe(0) + }) + + it('runs the veto for each person behind an organization, and shows who is acting', async () => { + const minor = await make('orgkid@example.com', { minor: true, org: org.id }) + void minor + vetoSaw.length = 0 + expect(await refused(invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }))).toBe('Not available for this account.') + const person = vetoSaw.find((v) => v.subject === 'orgkid@example.com') + expect(person).toBeTruthy() + expect(person!.via).toEqual({ relationTo: 'organizations', value: org.id }) + expect(String((person!.actor as { id: unknown }).id)).toBe(String(ann.id)) + expect((await rows({ 'member.relationTo': { equals: 'organizations' } })).totalDocs).toBe(0) + }) + + it('asks the per-person veto again on accept, and lets an organization of adults in', async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) + await make('late@example.com', { minor: true, org: org.id }) // joins after the invitation + answers.canAccept = () => true + expect(await refused(change(cat, (await rowOf(org, 'organizations')).id, { status: 'active' }))).toBe('Not available for this account.') + }) + + it('lets a minors-only veto pass a family group even for organization members', async () => { + await make('orgkid2@example.com', { minor: true, org: org.id }) + const fam = await newGroup(ann, { kind: 'family', name: 'Family' }) + await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(org, 'organizations'), level: 'viewer' } as never, user: as(ann), overrideAccess: false }) + }) + + it('refuses organizations as members without peopleOf or an explicit false', () => { + const base = { kinds: [], memberTypes: ['organizations'], refuseMember: () => null } + expect(() => sharing(base)({ collections: [] } as never)).toThrow(/peopleOf/) + expect(() => sharing({ ...base, peopleOf: false })({ collections: [] } as never)).not.toThrow() + expect(() => sharing({ ...base, peopleOf: () => [] })({ collections: [] } as never)).not.toThrow() + expect(() => sharing({ kinds: [], memberTypes: ['organizations'], refuseMember: false })({ collections: [] } as never)).not.toThrow() + }) + + it('refuses to run without transactions, and runs with them', async () => { + const real = { db: { beginTransaction: async () => null, connection: { db: { admin: () => ({ command: async () => ({ setName: 'rs0' }) }) } } } } + await expect(assertTransactions(real)).resolves.toBeUndefined() + await expect(assertTransactions(payload)).resolves.toBeUndefined() + const standalone = { db: { beginTransaction: async () => null, connection: { db: { admin: () => ({ command: async () => ({ isWritablePrimary: true }) }) } } } } + await expect(assertTransactions(standalone)).rejects.toThrow(/transactions/) + await expect(assertTransactions({ db: { beginTransaction: async () => null, transactionOptions: false } })).rejects.toThrow(/transactions/) + await expect(assertTransactions({ db: {} })).rejects.toThrow(/transactions/) + }) + + it('refuses a bulk member update, even for server code, so a change and its history row stay together', async () => { + await join(ben, 'viewer') + await join(dan, 'viewer') + expect(await refused(payload.update({ collection: 'share-members' as never, where: { level: { equals: 'viewer' } } as never, data: { notes: 'bulk' } as never, overrideAccess: true }))).toMatch(/one at a time/) + expect((await rows({ notes: { equals: 'bulk' } })).totalDocs).toBe(0) + }) +}) + describe('configuration', () => { it('stores the levels under the names the host gave them', () => { const cfg = sharing({ kinds: [{ value: 'hobby' }], refuseMember: false, levels: { owner: { value: 'steward', label: 'Steward' }, viewer: { label: 'Reader' } } })({ collections: [] } as never) as unknown as { From 281923d4e525beb12caeee213fd0a8626dafdd5c Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:11:16 -0700 Subject: [PATCH 4/7] Make canRead widen, check transactions for real, and close the third review's gaps canRead is now ORed with the default rules and can only add rows, so true, an empty where or a throw no longer opens every membership. The transactions check opens and rolls back a real transaction, so an adapter set up with transactionOptions: false is refused (allowWithoutTransactions opts out). Self-accept and self-leave can't overwrite staff notes. A removal can't carry a level change, and accept with a level change records both events. The veto runs before the already-a-member check, and invitedBy ignores users from other auth collections. @payloadcms/graphql is pinned. Documented: peopleOf must cover everyone identities maps, the veto is not given current members, and a group's founding owner stays visible. Ids and names are out of the docs. Tested: 83 tests against real Payload with in-memory MongoDB, including a real adapter with transactionOptions: false. Not tested: a live site, the admin screens, a standalone database beyond that adapter case. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- README.md | 10 +- docs/decisions.md | 7 +- docs/first-public-push-audit.md | 2 +- docs/test-audit.md | 10 +- package-lock.json | 2 +- package.json | 2 +- src/index.ts | 27 ++- src/members.ts | 37 ++++- src/types.ts | 8 +- test/plugin.test.ts | 281 +++++++++++++++++++++++--------- 11 files changed, 289 insertions(+), 102 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32e4bb1..82b879e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ ## Unreleased - The repo, with the standard Payload plugin kit. Public since 2026-11-22. -- The first version of the plugin (Captive Origins K5228, account model T5; follows D5228, D5234 and D5239): +- 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`. @@ -14,5 +14,6 @@ - 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. -- Tested: 72 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, and clean-up of the database and server at the end. + - 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. Documented: `peopleOf` must cover everyone `identities` maps, the veto isn't given current members, and a group's founding owner stays visible. +- Tested: 83 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, and clean-up of the database and server at the end. - Not tested: a database without transactions (the last-Owner guard needs a replica set), a live site, the admin screens in a browser, and a very large number of members. diff --git a/README.md b/README.md index f77b835..976fa23 100644 --- a/README.md +++ b/README.md @@ -59,11 +59,12 @@ export default buildConfig({ - `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. **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. +- `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. **`peopleOf` must list everyone your `identities` hook can map to that organization.** The veto runs on invitation, acceptance and level change, not when `identities` is resolved, so someone `identities` maps but `peopleOf` leaves out gets the group's access with no veto, and 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.` -- `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. Return a `where` to widen it. + **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 @@ -78,6 +79,9 @@ export default buildConfig({ - 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, unless they are an Owner or Manager of the group. +- 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. diff --git a/docs/decisions.md b/docs/decisions.md index e01d767..bfeb3f4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -3,9 +3,10 @@ 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: first version built for Captive Origins K5228 (account model T5), following Captive Origins D5228 (shared collections with Owner, Manager and Viewer, at least one Owner), D5234 (business accounts and brands) and D5239 (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: 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 (bottle #119): 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-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. diff --git a/docs/first-public-push-audit.md b/docs/first-public-push-audit.md index e1ab23b..229a9ac 100644 --- a/docs/first-public-push-audit.md +++ b/docs/first-public-push-audit.md @@ -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. diff --git a/docs/test-audit.md b/docs/test-audit.md index 6bcaacb..42530fb 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -2,10 +2,16 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". Newest first. -## 2026-11-22: first version (K5228) +## 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` (83 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. +- Gaps skipped (and why): the veto isn't run when `identities` resolves (no group or level to judge; documented that `peopleOf` must cover everyone `identities` maps). + +## 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` (72 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. +- Covered: each of those, in `test/plugin.test.ts` (83 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) diff --git a/package-lock.json b/package-lock.json index 480d6e7..462ea9e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,7 +10,7 @@ "license": "MIT", "devDependencies": { "@payloadcms/db-mongodb": "3.92.1", - "@payloadcms/graphql": "^3.92.1", + "@payloadcms/graphql": "3.92.1", "@types/node": "^24.0.0", "graphql": "^16.14.2", "mongodb-memory-server": "^11.3.0", diff --git a/package.json b/package.json index 9612b4d..b405f9b 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ }, "devDependencies": { "@payloadcms/db-mongodb": "3.92.1", - "@payloadcms/graphql": "^3.92.1", + "@payloadcms/graphql": "3.92.1", "@types/node": "^24.0.0", "graphql": "^16.14.2", "mongodb-memory-server": "^11.3.0", diff --git a/src/index.ts b/src/index.ts index b235a69..0933daf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,13 +18,30 @@ export { } from './helpers.js' export * from './types.js' -/** Throws unless the database can run transactions. The last-Owner rule and the history rows depend on them. */ -export async function assertTransactions(payload: unknown): Promise { +/** + * Throws unless the database can run transactions. The last-Owner rule and the history rows depend on them. It opens a + * transaction and rolls it straight back: an adapter set up without transactions (`transactionOptions: false` on the + * MongoDB adapter) swaps `beginTransaction` for a function that returns nothing, which is how this notices. + */ +export async function assertTransactions(payload: unknown, options: { allowWithoutTransactions?: boolean } = {}): Promise { + if (options.allowWithoutTransactions === true) return const db = (payload as { db?: Record }).db const fail = () => { - throw new Error('payload-plugin-sharing needs a database with transactions (for MongoDB, a replica set). Without them the last-Owner rule and the history can’t be kept safe, so it refuses to start.') + throw new Error('payload-plugin-sharing needs a database with transactions (for MongoDB, a replica set). Without them the last-Owner rule and the history can’t be kept safe, so it refuses to start. Pass `allowWithoutTransactions: true` only if you accept that.') + } + if (!db || typeof db.beginTransaction !== 'function') return fail() + let id: unknown + try { + id = await db.beginTransaction() + } catch { + return fail() + } + if (id === null || id === undefined || id === false) return fail() + try { + await db.rollbackTransaction?.(id) + } catch { + // The check already passed. A failed rollback of an empty transaction changes nothing. } - if (!db || typeof db.beginTransaction !== 'function' || db.transactionOptions === false) return fail() const raw = db.connection?.db if (raw) { const hello = await raw.admin().command({ hello: 1 }).catch(() => null) @@ -73,7 +90,7 @@ export const sharing = custom: { ...config.custom, sharing: resolved }, onInit: async (payload) => { await before?.(payload) - await assertTransactions(payload) + await assertTransactions(payload, { allowWithoutTransactions: options.allowWithoutTransactions }) }, collections: [...(config.collections ?? []), groupsCollection(resolved, options), membersCollection(resolved, options), eventsCollection(resolved, options)], } diff --git a/src/members.ts b/src/members.ts index 3897dae..e366e30 100644 --- a/src/members.ts +++ b/src/members.ts @@ -43,7 +43,8 @@ const plain = (data: Record | undefined): Partial export function membersCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { const levels = Object.values(s.levels) - const by = (req: PayloadRequest) => idOf(req.user) + // Only a user from the users collection counts as the actor; a user from another auth collection is recorded as no one. + const by = (req: PayloadRequest) => signedIn(req, s)?.id ?? null const loadGroup = async (req: PayloadRequest, id: unknown): Promise => { const gid = idOf(id) @@ -200,21 +201,28 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col const user = signedIn(req, s) if (!user) return false try { - if (opts.canRead) { - const answer = await opts.canRead({ req, user }) - return answer === true ? true : answer && typeof answer === 'object' ? answer : false - } const refs = await identitiesOf(req, s) const staffed = await groupIdsFor(req, 'edit') const viewed = await groupIdsFor(req, 'view') // Owners and Managers see every row in their groups. A Viewer sees only the Owners and Managers, and their own row. - return { + const base = { or: [ whereRefs(refs), ...(staffed.length ? [{ group: { in: staffed } }] : []), ...(viewed.length ? [{ and: [{ group: { in: viewed } }, { level: { in: [s.levels.owner.value, s.levels.manager.value] } }, { status: { equals: 'active' } }] }] : []), ], } as unknown as Where + if (!opts.canRead) return base + // The host can only add rows. Its `where` is ORed with the default rules, which always apply. `true`, `false`, an + // empty `where` and a throw add nothing, so no answer can hand out every row, a child's included. + let extra: unknown = null + try { + extra = await opts.canRead({ req, user }) + } catch { + extra = null + } + if (extra && typeof extra === 'object' && !Array.isArray(extra) && Object.keys(extra).length) return { or: [base, extra as Where] } as unknown as Where + return base } catch { return false } @@ -293,6 +301,8 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col data.removedAt = null data.removedBy = null if (asker !== null) data.invitedBy = asker + // The veto runs before the duplicate check, so a vetoed person gets the same answer whether or not they are already in. + await vetoed(req, group, ref, data.level, 'invite') const dup = await req.payload.find({ collection: MEMBERS as never, where: { and: [{ group: { equals: group.id } }, { 'member.relationTo': { equals: ref.relationTo } }, { 'member.value': { equals: ref.value } }, { status: { in: LIVE } }] }, @@ -302,7 +312,6 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col req, }) if (dup.docs.length) throw refuse('That member is already in this group.') - await vetoed(req, group, ref, data.level, 'invite') // The database's unique index on this key is what stops two requests at once. data.liveKey = JSON.stringify([group.id, ref.relationTo, ref.value]) await run(opts.audit?.beforeInvite, { event: 'invite', phase: 'before', membership: normalize(data), by: asker, req }, true) @@ -319,6 +328,17 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col if (!same) throw refuse('Only the level, status and notes can be changed.') } for (const f of ['liveKey', 'acceptedAt', 'removedAt', 'removedBy']) delete data[f] + // Someone changing their own row (accepting or leaving) can't write the staff notes on it, unless they are staff in the group. + if ('notes' in data && isSelf(req, before.member)) { + let staff = false + try { + const r = await roleIn(req, before.group) + staff = r === 'owner' || r === 'manager' + } catch { + staff = false + } + if (!staff) delete data.notes + } const level: string = data.level ?? before.level const status = (data.status ?? before.status) as MemberStatus if (!roleOf(s, level)) throw refuse('Unknown level.') @@ -327,6 +347,7 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col const statusChanged = status !== before.status if (!levelChanged && !statusChanged) return data if (before.status === 'removed') throw refuse('A removed member is final. Invite them again.') + if (status === 'removed' && levelChanged) throw refuse('Change the level and remove in separate steps.') if (statusChanged && !(before.status === 'invited' && (status === 'active' || status === 'removed')) && !(before.status === 'active' && status === 'removed')) throw refuse('That status change isn’t allowed.') const group = await loadGroup(req, before.group) @@ -392,7 +413,7 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col else if (membership.status === 'active') await run(opts.audit?.afterAccept, { event: 'accept', phase: 'after', membership, previous, by: asker, req }, false) } if (previous.level !== membership.level && membership.status !== 'removed') { - if (previous.status === membership.status) await note('change-level', previous) + await note('change-level', previous) await run(opts.audit?.afterChangeLevel, { event: 'change-level', phase: 'after', membership, previous, by: asker, req }, false) } return doc diff --git a/src/types.ts b/src/types.ts index 7be331a..276a6f2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -136,7 +136,8 @@ export type SharingOptions = { canAccept?: Check /** * Who may read memberships. Default: your own, every row in groups where you are an Owner or Manager, and only the - * Owners and Managers of groups where you are a Viewer. May return a `where` to widen or narrow that. + * 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` or a throw add nothing, so they can't open every row. */ canRead?: (args: { req: PayloadRequest; user: User }) => boolean | Where | Promise /** @@ -157,6 +158,11 @@ export type SharingOptions = { beforeRemove?: AuditHook afterRemove?: AuditHook } + /** + * Start even when the database can't run transactions. Not safe: two Owners leaving at once can both pass the + * last-Owner check, and a change can be saved without its history row. Default false. + */ + allowWithoutTransactions?: boolean /** The admin group the collections sit in. Default `Sharing`. */ adminGroup?: string } diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 534bb95..5f164c3 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -17,7 +17,7 @@ let mongo: MongoMemoryReplSet const log: string[] = [] const seen: { id?: unknown; data?: unknown; member?: unknown }[] = [] const vetoSaw: { subject: unknown; via: unknown; actor: unknown; action: string }[] = [] -const answers: { canAccept?: () => unknown; refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} +const answers: { captureAudit?: (e: AuditEvent) => void; afterInvite?: () => void; canRead?: () => unknown; canAccept?: () => unknown; refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} type U = { id: string | number } let ann: U, ben: U, cat: U, dan: U, kid: U, org: U @@ -120,6 +120,7 @@ beforeAll(async () => { const found = await payload.find({ collection: 'users', where: { org: { equals: organization.value } }, pagination: false, overrideAccess: true }) return found.docs.map((d) => ({ relationTo: 'users', value: d.id })) }, + canRead: ({ req }) => (answers.canRead ? (answers.canRead() as never) : (undefined as never)), canAccept: () => (answers.canAccept ? (answers.canAccept() as boolean) : false), refuseMember: ({ subject, group: g, via, actor, action }) => { vetoSaw.push({ subject: (subject as { email?: string }).email ?? 'org', via, actor, action }) @@ -131,11 +132,17 @@ beforeAll(async () => { if (answers.beforeInvite) answers.beforeInvite() record(e) }, - afterInvite: record, + afterInvite: (e) => { + if (answers.afterInvite) answers.afterInvite() + record(e) + }, beforeAccept: record, afterAccept: record, beforeChangeLevel: record, - afterChangeLevel: record, + afterChangeLevel: (e) => { + answers.captureAudit?.(e) + record(e) + }, beforeRemove: record, afterRemove: record, }, @@ -312,13 +319,28 @@ describe('the host veto', () => { expect(await refused(change(ann, (await rowOf(ben)).id, { level: 'manager' }))).toBe('Paused.') }) - it('stops the change when a before audit hook throws, and logs an after hook that throws', async () => { + it('stops the change when a before audit hook throws', async () => { answers.beforeInvite = () => { throw new Error('audit down') } expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toMatch(/can’t be recorded/) expect((await rows({ status: { equals: 'invited' } })).totalDocs).toBe(0) }) + + it('keeps the change when an after audit hook throws', async () => { + answers.afterInvite = () => { + throw new Error('audit down') + } + await invite(ann, { member: ref(ben), level: 'viewer' }) + expect((await rowOf(ben)).status).toBe('invited') + }) + + it('gives the same answer to a vetoed person whether or not they are already in the group', async () => { + await invite(ann, { member: ref(ben), level: 'viewer' }) // live in the group + answers.refuse = () => 'Paused.' + expect(await refused(invite(ann, { member: ref(ben), level: 'viewer' }))).toBe('Paused.') + expect(await refused(invite(ann, { member: ref(dan), level: 'viewer' }))).toBe('Paused.') + }) }) describe('accepting, changing levels and leaving', () => { @@ -655,74 +677,15 @@ describe('what the hooks are given', () => { }) it('gives the audit hooks plain ids too', async () => { - const events: AuditEvent[] = [] - answers.beforeInvite = () => undefined - await invite(ann, { member: ref(ben), level: 'viewer' }) - void events - const r = await rowOf(ben) - expect(typeof r.id).not.toBe('object') - }) -}) - -describe('members are keyed by their collection', () => { - it('does not give a user the membership of an organization with the same id, or the other way round', async () => { - await invite(ann, { member: ref(dan), level: 'manager' }) - await change(dan, (await rowOf(dan)).id, { status: 'active' }) - // someone who acts as an organization that happens to share dan's id - answers.identities = () => [{ relationTo: 'organizations', value: dan.id }] - expect(await roleIn(reqFor(ben), group.id)).toBeNull() - delete answers.identities - await invite(ann, { member: ref(org, 'organizations'), level: 'manager' }) - await payload.update({ collection: 'share-members' as never, id: (await rowOf(org, 'organizations')).id as never, data: { status: 'active' } as never, overrideAccess: true }) - answers.identities = () => [{ relationTo: 'users', value: org.id }] - expect(await roleIn(reqFor(ben), group.id)).toBeNull() - }) -}) - -describe('the history', () => { - const events = async () => - (await payload.find({ collection: 'share-member-events' as never, sort: 'createdAt', pagination: false, overrideAccess: true })).docs as unknown as { event: string; level: string; previousLevel?: string; previousStatus?: string; memberId: string; memberType: string }[] - - it('records every invitation, acceptance, level change and removal', async () => { const r = await join(ben, 'viewer') await change(ann, r.id, { level: 'manager' }) - await change(ben, r.id, { status: 'removed' }) - const list = await events() - expect(list.map((e) => e.event)).toEqual(['invite', 'invite', 'accept', 'change-level', 'remove']) - expect(list[3]).toMatchObject({ level: 'manager', previousLevel: 'viewer', memberType: 'users', memberId: String(ben.id) }) - }) - - it('records nothing for a change that was refused', async () => { - const before = (await events()).length - await refused(invite(dan, { member: ref(ben), level: 'viewer' })) - expect((await events()).length).toBe(before) - }) - - it('can’t be written, edited or deleted, by clients or by server code', async () => { - const e = (await payload.find({ collection: 'share-member-events' as never, overrideAccess: true })).docs[0] as { id: string } - expect(await refused(payload.create({ collection: 'share-member-events' as never, data: { group: group.id, membership: (await rowOf(ann)).id, memberType: 'users', memberId: 'x', event: 'invite' } as never, user: as(ann), overrideAccess: false }))).toBeTruthy() - expect(await refused(payload.update({ collection: 'share-member-events' as never, id: e.id as never, data: { level: 'x' } as never, overrideAccess: true }))).toMatch(/edited/) - expect(await refused(payload.delete({ collection: 'share-member-events' as never, id: e.id as never, overrideAccess: true }))).toMatch(/deleted/) - }) - - it('is read by a group’s Owners only', async () => { - await join(ben, 'manager') - const read = (u: U) => payload.find({ collection: 'share-member-events' as never, user: as(u), overrideAccess: false }) - expect((await read(ann)).totalDocs).toBeGreaterThan(0) - expect(await refused(read(ben))).toBeTruthy() - }) -}) - -describe('what a Viewer can see of the other members', () => { - it('shows a Viewer only the Owners and Managers, and their own row; a Manager sees everyone', async () => { - await join(ben, 'viewer') - await join(dan, 'viewer') - await join(cat, 'manager') - const names = async (u: U) => - (await payload.find({ collection: 'share-members' as never, user: as(u), overrideAccess: false, pagination: false })).docs.map((d) => String(((d as unknown as { member: { value: { id?: unknown } | string } }).member.value as { id?: unknown })?.id ?? (d as unknown as { member: { value: unknown } }).member.value)) - const sorted = (a: string[]) => [...a].sort() - expect(sorted(await names(ben))).toEqual(sorted([String(ann.id), String(cat.id), String(ben.id)])) - expect((await names(cat)).length).toBe(4) + const seenIds: unknown[] = [] + answers.captureAudit = (e: AuditEvent) => seenIds.push(e.membership.group, e.membership.member.value, e.membership.id, e.by) + await change(ann, r.id, { level: 'viewer' }) + expect(seenIds.length).toBeGreaterThan(0) + for (const v of seenIds) expect(typeof v).not.toBe('object') + expect(seenIds).toContain(group.id) + expect(seenIds).toContain(ben.id) }) }) @@ -803,17 +766,30 @@ describe('the second review', () => { expect((await rows({ 'member.relationTo': { equals: 'organizations' } })).totalDocs).toBe(0) }) - it('asks the per-person veto again on accept, and lets an organization of adults in', async () => { + it('asks the per-person veto again on accept, so someone who joined the organization later is stopped', async () => { await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) await make('late@example.com', { minor: true, org: org.id }) // joins after the invitation answers.canAccept = () => true expect(await refused(change(cat, (await rowOf(org, 'organizations')).id, { status: 'active' }))).toBe('Not available for this account.') + expect((await rowOf(org, 'organizations')).status).toBe('invited') + }) + + it('lets an organization of adults in, and asks the veto for each of them', async () => { + vetoSaw.length = 0 + await invite(ann, { member: ref(org, 'organizations'), level: 'viewer' }) + answers.canAccept = () => true + await change(cat, (await rowOf(org, 'organizations')).id, { status: 'active' }) + expect((await rowOf(org, 'organizations')).status).toBe('active') + expect(vetoSaw.some((v) => v.subject === 'cat@example.com' && v.action === 'accept')).toBe(true) }) it('lets a minors-only veto pass a family group even for organization members', async () => { await make('orgkid2@example.com', { minor: true, org: org.id }) const fam = await newGroup(ann, { kind: 'family', name: 'Family' }) await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(org, 'organizations'), level: 'viewer' } as never, user: as(ann), overrideAccess: false }) + const made = await rows({ and: [{ group: { equals: fam.id } }, { 'member.relationTo': { equals: 'organizations' } }] }) + expect(made.totalDocs).toBe(1) + expect((made.docs[0] as unknown as { status: string }).status).toBe('invited') }) it('refuses organizations as members without peopleOf or an explicit false', () => { @@ -825,13 +801,42 @@ describe('the second review', () => { }) it('refuses to run without transactions, and runs with them', async () => { - const real = { db: { beginTransaction: async () => null, connection: { db: { admin: () => ({ command: async () => ({ setName: 'rs0' }) }) } } } } - await expect(assertTransactions(real)).resolves.toBeUndefined() + const replSet = { connection: { db: { admin: () => ({ command: async () => ({ setName: 'rs0' }) }) } } } + const withTx = { db: { ...replSet, beginTransaction: async () => 'tx1', rollbackTransaction: async () => undefined } } + await expect(assertTransactions(withTx)).resolves.toBeUndefined() await expect(assertTransactions(payload)).resolves.toBeUndefined() - const standalone = { db: { beginTransaction: async () => null, connection: { db: { admin: () => ({ command: async () => ({ isWritablePrimary: true }) }) } } } } + // Shaped like @payloadcms/db-mongodb with `transactionOptions: false`: beginTransaction is a no-op that returns null. + const noTx = { db: { ...replSet, transactionOptions: undefined, beginTransaction: async () => null } } + await expect(assertTransactions(noTx)).rejects.toThrow(/transactions/) + await expect(assertTransactions({ db: { ...replSet, beginTransaction: async () => undefined } })).rejects.toThrow(/transactions/) + await expect(assertTransactions({ db: { ...replSet, beginTransaction: async () => { throw new Error('no') } } })).rejects.toThrow(/transactions/) + const standalone = { db: { beginTransaction: async () => 'tx1', rollbackTransaction: async () => undefined, connection: { db: { admin: () => ({ command: async () => ({ isWritablePrimary: true }) }) } } } } await expect(assertTransactions(standalone)).rejects.toThrow(/transactions/) - await expect(assertTransactions({ db: { beginTransaction: async () => null, transactionOptions: false } })).rejects.toThrow(/transactions/) await expect(assertTransactions({ db: {} })).rejects.toThrow(/transactions/) + await expect(assertTransactions(noTx, { allowWithoutTransactions: true })).resolves.toBeUndefined() + }) + + it('rolls the check’s transaction back at once', async () => { + const calls: unknown[] = [] + await assertTransactions({ db: { beginTransaction: async () => 'tx9', rollbackTransaction: async (id: unknown) => void calls.push(id) } }) + expect(calls).toEqual(['tx9']) + }) + + it('refuses to start on a real adapter set up with transactionOptions: false', async () => { + const config = await buildConfig({ + secret: 'test-secret-not-for-production', + telemetry: false, + typescript: { autoGenerate: false }, + db: mongooseAdapter({ url: mongo.getUri('sharing_notx'), transactionOptions: false }), + collections: [{ slug: 'users', auth: true, fields: [] }], + plugins: [sharing({ kinds: [{ value: 'hobby' }], refuseMember: false })], + }) + const second = await getPayload({ config, key: 'no-transactions' }).then( + (p) => ({ p, error: null as string | null }), + (e: Error) => ({ p: null as Payload | null, error: e.message }), + ) + await second.p?.db?.destroy?.() + expect(second.error).toMatch(/transactions/) }) it('refuses a bulk member update, even for server code, so a change and its history row stay together', async () => { @@ -842,6 +847,132 @@ describe('the second review', () => { }) }) +describe('the third review', () => { + const names = async (u: U) => + ((await payload.find({ collection: 'share-members' as never, user: as(u), overrideAccess: false, pagination: false, depth: 0 })).docs as unknown as { member: { value: unknown } }[]).map((d) => String(d.member.value)).sort() + const ids = (...u: U[]) => u.map((x) => String(x.id)).sort() + + describe('canRead only adds rows to the defaults', () => { + beforeEach(async () => { + await join(ben, 'viewer') + await invite(ann, { member: ref(dan), level: 'viewer' }) // invited: a Viewer shouldn't see this row by default + await invite(ann, { member: ref(cat), level: 'viewer' }) + }) + + it('keeps the default for a Viewer when the host says nothing, true, false or {}', async () => { + for (const answer of [undefined, true, false, {}]) { + answers.canRead = () => answer + expect(await names(ben)).toEqual(ids(ann, ben)) + } + }) + + it('keeps the default when the host hook throws', async () => { + answers.canRead = () => { + throw new Error('boom') + } + expect(await names(ben)).toEqual(ids(ann, ben)) + }) + + it('adds rows for a narrow where without dropping the Viewer’s own row or the Owners', async () => { + answers.canRead = () => ({ 'member.value': { equals: cat.id } }) + expect(await names(ben)).toEqual(ids(ann, ben, cat)) + }) + + it('never shows a signed-out user anything, whatever the host answers', async () => { + answers.canRead = () => true + expect((await rows()).totalDocs).toBeGreaterThan(0) + expect(await refused(payload.find({ collection: 'share-members' as never, overrideAccess: false }))).toBeTruthy() + }) + + it('doesn’t show a stranger the rows of other groups when the host answers true', async () => { + answers.canRead = () => true + expect(await names(kid)).toEqual([]) + }) + }) + + describe('notes on someone’s own row', () => { + it('can’t be written during self-accept', async () => { + await payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(ben), level: 'viewer', notes: 'staff note' } as never, user: as(ann), overrideAccess: false }) + const r = await rowOf(ben) + await change(ben, r.id, { status: 'active', notes: 'overwritten' }) + const after = (await rows({ id: { equals: r.id } })).docs[0] as unknown as { status: string; notes: string } + expect(after.status).toBe('active') + expect(after.notes).toBe('staff note') + }) + + it('can’t be written during self-leave, for a child either', async () => { + const fam = await newGroup(ann, { kind: 'family', name: 'Family' }) + await payload.create({ collection: 'share-members' as never, data: { group: fam.id, member: ref(kid), level: 'viewer', notes: 'about the child' } as never, user: as(ann), overrideAccess: false }) + const r = (await rows({ and: [{ group: { equals: fam.id } }, { 'member.value': { equals: kid.id } }] })).docs[0] as unknown as { id: string } + await change(kid, r.id, { status: 'active' }) + await change(kid, r.id, { status: 'removed', notes: 'wiped' }) + expect(((await rows({ id: { equals: r.id } })).docs[0] as unknown as { notes: string }).notes).toBe('about the child') + }) + + it('stay writable by an Owner on their own row and on others’', async () => { + const r = await rowOf(ann) + await change(ann, r.id, { notes: 'mine' }) + expect(((await rows({ id: { equals: r.id } })).docs[0] as unknown as { notes: string }).notes).toBe('mine') + await join(ben, 'viewer') + await change(ann, (await rowOf(ben)).id, { notes: 'about ben' }) + expect(((await rows({ id: { equals: (await rowOf(ben)).id } })).docs[0] as unknown as { notes: string }).notes).toBe('about ben') + }) + + it('can’t be used by a Viewer to search or sort what they can’t read', async () => { + await join(ben, 'viewer') + await payload.update({ collection: 'share-members' as never, id: (await rowOf(ann)).id as never, data: { notes: 'secret-word' } as never, overrideAccess: true }) + const probe = async (query: Record) => { + try { + return { docs: (await payload.find({ collection: 'share-members' as never, user: as(ben), overrideAccess: false, pagination: false, depth: 0, ...query } as never)).docs as unknown as Record[] } + } catch (e) { + return { error: (e as Error).message } + } + } + const hit = await probe({ where: { notes: { contains: 'secret-word' } } }) + const miss = await probe({ where: { notes: { contains: 'nothing-like-it' } } }) + // Either the query is refused outright, or it answers the same whether or not the hidden text matches. + expect(JSON.stringify(hit)).toBe(JSON.stringify(miss)) + const sorted = await probe({ sort: 'notes' }) + const unsorted = await probe({ sort: '-notes' }) + expect(sorted.error !== undefined || unsorted.error !== undefined || JSON.stringify((sorted.docs ?? []).map((d) => d.id)) === JSON.stringify((unsorted.docs ?? []).map((d) => d.id).reverse())).toBe(true) + for (const r of [hit, miss, sorted, unsorted]) for (const d of r.docs ?? []) expect(d.notes).toBeUndefined() + }) + }) + + describe('level changes with other changes', () => { + it('refuses a removal that carries a level change, and changes nothing', async () => { + const r = await join(ben, 'viewer') + expect(await refused(change(ann, r.id, { status: 'removed', level: 'manager' }))).toMatch(/separate steps/) + const after = await rowOf(ben) + expect([after.status, after.level]).toEqual(['active', 'viewer']) + }) + + it('records both the accept and the level change when an invitation is accepted at a new level', async () => { + answers.canInvite = () => true + await invite(ann, { member: ref(ben), level: 'viewer' }) + log.length = 0 + const evs = async () => (await payload.find({ collection: 'share-member-events' as never, sort: 'createdAt', pagination: false, overrideAccess: true })).docs as unknown as { event: string; level: string; previousLevel?: string }[] + const before = (await evs()).length + await payload.update({ collection: 'share-members' as never, id: (await rowOf(ben)).id as never, data: { status: 'active', level: 'manager' } as never, overrideAccess: true }) + const added = (await evs()).slice(before) + expect(added.map((e) => e.event).sort()).toEqual(['accept', 'change-level']) + expect(added.find((e) => e.event === 'change-level')).toMatchObject({ level: 'manager', previousLevel: 'viewer' }) + }) + }) + + it('records no inviter when the acting user is from another collection', async () => { + await payload.create({ + collection: 'share-members' as never, + data: { group: group.id, member: ref(ben), level: 'viewer' } as never, + user: { id: ann.id, collection: 'organizations' } as never, + overrideAccess: true, + }) + expect((await rows({ id: { exists: true }, 'member.value': { equals: ben.id } })).docs[0]).not.toHaveProperty('invitedBy', ann.id) + const row = (await rows({ 'member.value': { equals: ben.id } })).docs[0] as unknown as { invitedBy?: unknown } + expect(row.invitedBy ?? null).toBeNull() + }) +}) + describe('configuration', () => { it('stores the levels under the names the host gave them', () => { const cfg = sharing({ kinds: [{ value: 'hobby' }], refuseMember: false, levels: { owner: { value: 'steward', label: 'Steward' }, viewer: { label: 'Reader' } } })({ collections: [] } as never) as unknown as { From cec5fea76a3ce8dd37a35cd9a45d315e775eb686 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:58:33 -0700 Subject: [PATCH 5/7] Restore the dropped history tests and close the re-review's gaps Three describe blocks (members keyed by collection, the history, what a Viewer sees of other members) were lost in the last rewrite of a test; they are back, six tests. identities now keeps an organization only when peopleOf lists the user, asked once per request and dropped on a throw. invitedBy is always the acting user or none. Member changes refuse without a request transaction, so disableTransaction can't skip the lock or the history row. Non-staff can't write notes on an organization's row they act for. The server-code level-change test now exercises the veto itself. Tested: 95 tests against real Payload with in-memory MongoDB. Not tested: a live site, the admin screens. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- README.md | 5 +- docs/decisions.md | 3 +- docs/test-audit.md | 5 +- src/helpers.ts | 29 ++++++++- src/index.ts | 2 + src/members.ts | 14 ++++- src/types.ts | 5 +- test/plugin.test.ts | 140 +++++++++++++++++++++++++++++++++++++++++++- 9 files changed, 194 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82b879e..2561499 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,6 @@ - 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. Documented: `peopleOf` must cover everyone `identities` maps, the veto isn't given current members, and a group's founding owner stays visible. -- Tested: 83 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, and clean-up of the database and server at the end. -- Not tested: a database without transactions (the last-Owner guard needs a replica set), a live site, the admin screens in a browser, and a very large number of members. + - 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. Documented: `peopleOf` must cover everyone `identities` maps, the veto isn't given current members, and a group's founding owner stays visible. +- Tested: 95 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 standalone MongoDB or another database with transactions off beyond the adapter case below, a live site, the admin screens in a browser, and a very large number of members. diff --git a/README.md b/README.md index 976fa23..c28a2e9 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ export default buildConfig({ - `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. **`peopleOf` must list everyone your `identities` hook can map to that organization.** The veto runs on invitation, acceptance and level change, not when `identities` is resolved, so someone `identities` maps but `peopleOf` leaves out gets the group's access with no veto, and 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. +- `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. **`identities` keeps an organization only when `peopleOf` 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. 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. @@ -79,7 +79,8 @@ export default buildConfig({ - 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, unless they are an Owner or Manager of the group. +- Someone changing their own row (accepting or leaving) can't write its notes, 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. diff --git a/docs/decisions.md b/docs/decisions.md index bfeb3f4..3b99ce7 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -8,5 +8,6 @@ Dated decisions for this repo, newest last. - 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-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. diff --git a/docs/test-audit.md b/docs/test-audit.md index 42530fb..45a57a0 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -5,8 +5,9 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". ## 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` (83 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. -- Gaps skipped (and why): the veto isn't run when `identities` resolves (no group or level to judge; documented that `peopleOf` must cover everyone `identities` maps). +- Covered: each of those in `test/plugin.test.ts` (95 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 diff --git a/src/helpers.ts b/src/helpers.ts index ae010bd..f841c1a 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -34,6 +34,30 @@ export const signedIn = (req: PayloadRequest, s: ResolvedSharing) => { return user && user.collection === s.users && idOf(user) !== null ? user : null } +/** Whether `peopleOf` lists the user for the organization. Asked once per organization per request. A throw is a no. */ +async function listsUser(req: PayloadRequest, s: ResolvedSharing, org: MemberRef, userId: string | number): Promise { + const context = (req.context ??= {}) as Record + const cache = (context.sharingPeople ??= new Map>()) as Map> + const key = JSON.stringify([org.relationTo, String(org.value)]) + if (!cache.has(key)) { + cache.set( + key, + (async () => { + try { + const ask = s.peopleOf + if (typeof ask !== 'function') return null + const people = await ask({ req, organization: org }) + return Array.isArray(people) ? people.map((p) => refOf(p)).filter((p): p is MemberRef => !!p) : null + } catch { + return null + } + })(), + ) + } + const people = await cache.get(key)! + return !!people && people.some((p) => p.relationTo === s.users && String(p.value) === String(userId)) +} + /** The user plus whatever the host's `identities` hook adds. Throws if the hook throws; callers fail closed. */ export async function identitiesOf(req: PayloadRequest, s = settings(req)): Promise { const user = signedIn(req, s) @@ -42,7 +66,10 @@ export async function identitiesOf(req: PayloadRequest, s = settings(req)): Prom if (s.identities) { for (const raw of await s.identities({ req, user })) { const ref = refOf(raw) - if (ref && s.memberTypes.includes(ref.relationTo) && !refs.some((r) => sameRef(r, ref))) refs.push(ref) + if (!ref || !s.memberTypes.includes(ref.relationTo) || refs.some((r) => sameRef(r, ref))) continue + // An organization counts only while the host's `peopleOf` lists this user for it. If that throws, the identity is dropped. + if (ref.relationTo !== s.users && typeof s.peopleOf === 'function' && !(await listsUser(req, s, ref, user.id))) continue + refs.push(ref) } } return refs diff --git a/src/index.ts b/src/index.ts index 0933daf..fec90aa 100644 --- a/src/index.ts +++ b/src/index.ts @@ -83,6 +83,8 @@ export const sharing = levels, kinds: options.kinds ?? [], identities: options.identities, + peopleOf: options.peopleOf, + needsTransactions: options.allowWithoutTransactions !== true, } const before = config.onInit return { diff --git a/src/members.ts b/src/members.ts index e366e30..54960dc 100644 --- a/src/members.ts +++ b/src/members.ts @@ -135,11 +135,17 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col } } + /** Server code can pass `disableTransaction`, which would split a change from its history row and skip the lock. */ + const needTransaction = (req: PayloadRequest) => { + if (s.needsTransactions && !req.transactionID) throw refuse('This change needs a transaction, so it wasn’t made.') + } + /** * Takes the group's lock and checks that an Owner is left once this one goes. Writing the group first means two * Owners leaving or demoting each other at once collide, and one of them is turned back. */ async function keepAnOwner(req: PayloadRequest, group: GroupDoc, leaving: string | number) { + needTransaction(req) try { const fresh = (await req.payload.findByID({ collection: GROUPS as never, id: group.id, depth: 0, overrideAccess: true, req })) as unknown as { lock?: number } await req.payload.update({ collection: GROUPS as never, id: group.id, data: { lock: (fresh.lock ?? 0) + 1 } as never, overrideAccess: true, req }) @@ -282,6 +288,7 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col ], beforeChange: [ async ({ data, originalDoc, operation, req }) => { + needTransaction(req) const now = new Date().toISOString() if (operation === 'create') { const group = await loadGroup(req, data.group) @@ -300,7 +307,7 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col data.acceptedAt = founding ? now : null data.removedAt = null data.removedBy = null - if (asker !== null) data.invitedBy = asker + data.invitedBy = asker // The veto runs before the duplicate check, so a vetoed person gets the same answer whether or not they are already in. await vetoed(req, group, ref, data.level, 'invite') const dup = await req.payload.find({ @@ -328,8 +335,9 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col if (!same) throw refuse('Only the level, status and notes can be changed.') } for (const f of ['liveKey', 'acceptedAt', 'removedAt', 'removedBy']) delete data[f] - // Someone changing their own row (accepting or leaving) can't write the staff notes on it, unless they are staff in the group. - if ('notes' in data && isSelf(req, before.member)) { + // A signed-in person who isn't an Owner or Manager of the group can't write notes: not on their own row when they accept + // or leave, and not on an organization's row they act for. Server code can. + if ('notes' in data && signedIn(req, s)) { let staff = false try { const r = await roleIn(req, before.group) diff --git a/src/types.ts b/src/types.ts index 276a6f2..22ddec8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -19,6 +19,9 @@ export type ResolvedSharing = { levels: Record kinds: { value: string; label?: string }[] identities?: SharingOptions['identities'] + peopleOf?: SharingOptions['peopleOf'] + /** False only when the host passed `allowWithoutTransactions`. */ + needsTransactions: boolean } export type ShareGroup = { @@ -113,7 +116,7 @@ export type SharingOptions = { levels?: Partial> /** * Other identities the signed-in user acts as, such as the organizations they work for. A membership held by any of - * them counts for the user. A throw means access is refused. Default: only the user. + * them counts for the user. An organization counts only if `peopleOf` lists the user for it; if `peopleOf` throws, it is dropped. A throw means access is refused. Default: only the user. */ identities?: (args: { req: PayloadRequest; user: User }) => MemberRef[] | Promise /** diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 5f164c3..551b014 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -17,7 +17,7 @@ let mongo: MongoMemoryReplSet const log: string[] = [] const seen: { id?: unknown; data?: unknown; member?: unknown }[] = [] const vetoSaw: { subject: unknown; via: unknown; actor: unknown; action: string }[] = [] -const answers: { captureAudit?: (e: AuditEvent) => void; afterInvite?: () => void; canRead?: () => unknown; canAccept?: () => unknown; refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} +const answers: { peopleOf?: () => unknown; captureAudit?: (e: AuditEvent) => void; afterInvite?: () => void; canRead?: () => unknown; canAccept?: () => unknown; refuse?: () => unknown; beforeInvite?: () => void; canInvite?: () => unknown; identities?: () => unknown } = {} type U = { id: string | number } let ann: U, ben: U, cat: U, dan: U, kid: U, org: U @@ -117,6 +117,7 @@ beforeAll(async () => { return actorRole === 'owner' }, peopleOf: async ({ organization }) => { + if (answers.peopleOf) return answers.peopleOf() as never const found = await payload.find({ collection: 'users', where: { org: { equals: organization.value } }, pagination: false, overrideAccess: true }) return found.docs.map((d) => ({ relationTo: 'users', value: d.id })) }, @@ -645,8 +646,19 @@ describe('no way round the gate, even for server code', () => { delete answers.refuse await invite(ann, { member: ref(dan), level: 'viewer' }) const d = await rowOf(dan) - expect(await refused(change(dan, d.id, { status: 'active', level: 'owner' }))).toBeTruthy() + expect(await refused(change(dan, d.id, { status: 'active', level: 'owner' }))).toBeTruthy() // the user can't raise their own level expect((await rowOf(dan)).status).toBe('invited') + // Server code accepting at a raised level: the veto is asked for the level change itself, and can stop it. + vetoSaw.length = 0 + answers.refuse = () => null + await server(d.id, { status: 'active', level: 'manager' }) + expect(vetoSaw.map((v) => v.action).sort()).toEqual(['accept', 'change-level']) + const e = await rowOf(ben) + vetoSaw.length = 0 + answers.refuse = () => 'No.' + expect(await refused(server(e.id, { level: 'owner' }))).toBe('No.') + expect(vetoSaw.map((v) => v.action)).toEqual(['change-level']) + expect((await rowOf(ben)).level).toBe('viewer') }) it('never deletes, even with overrideAccess', async () => { @@ -689,6 +701,68 @@ describe('what the hooks are given', () => { }) }) +describe('members are keyed by their collection', () => { + it('does not give a user the membership of an organization with the same id, or the other way round', async () => { + await invite(ann, { member: ref(dan), level: 'manager' }) + await change(dan, (await rowOf(dan)).id, { status: 'active' }) + // someone who acts as an organization that happens to share dan's id + answers.identities = () => [{ relationTo: 'organizations', value: dan.id }] + expect(await roleIn(reqFor(ben), group.id)).toBeNull() + delete answers.identities + await invite(ann, { member: ref(org, 'organizations'), level: 'manager' }) + await payload.update({ collection: 'share-members' as never, id: (await rowOf(org, 'organizations')).id as never, data: { status: 'active' } as never, overrideAccess: true }) + answers.identities = () => [{ relationTo: 'users', value: org.id }] + expect(await roleIn(reqFor(ben), group.id)).toBeNull() + }) +}) + +describe('the history', () => { + const events = async () => + (await payload.find({ collection: 'share-member-events' as never, sort: 'createdAt', pagination: false, overrideAccess: true })).docs as unknown as { event: string; level: string; previousLevel?: string; previousStatus?: string; memberId: string; memberType: string }[] + + it('records every invitation, acceptance, level change and removal', async () => { + const r = await join(ben, 'viewer') + await change(ann, r.id, { level: 'manager' }) + await change(ben, r.id, { status: 'removed' }) + const list = await events() + expect(list.map((e) => e.event)).toEqual(['invite', 'invite', 'accept', 'change-level', 'remove']) + expect(list[3]).toMatchObject({ level: 'manager', previousLevel: 'viewer', memberType: 'users', memberId: String(ben.id) }) + }) + + it('records nothing for a change that was refused', async () => { + const before = (await events()).length + await refused(invite(dan, { member: ref(ben), level: 'viewer' })) + expect((await events()).length).toBe(before) + }) + + it('can’t be written, edited or deleted, by clients or by server code', async () => { + const e = (await payload.find({ collection: 'share-member-events' as never, overrideAccess: true })).docs[0] as { id: string } + expect(await refused(payload.create({ collection: 'share-member-events' as never, data: { group: group.id, membership: (await rowOf(ann)).id, memberType: 'users', memberId: 'x', event: 'invite' } as never, user: as(ann), overrideAccess: false }))).toBeTruthy() + expect(await refused(payload.update({ collection: 'share-member-events' as never, id: e.id as never, data: { level: 'x' } as never, overrideAccess: true }))).toMatch(/edited/) + expect(await refused(payload.delete({ collection: 'share-member-events' as never, id: e.id as never, overrideAccess: true }))).toMatch(/deleted/) + }) + + it('is read by a group’s Owners only', async () => { + await join(ben, 'manager') + const read = (u: U) => payload.find({ collection: 'share-member-events' as never, user: as(u), overrideAccess: false }) + expect((await read(ann)).totalDocs).toBeGreaterThan(0) + expect(await refused(read(ben))).toBeTruthy() + }) +}) + +describe('what a Viewer can see of the other members', () => { + it('shows a Viewer only the Owners and Managers, and their own row; a Manager sees everyone', async () => { + await join(ben, 'viewer') + await join(dan, 'viewer') + await join(cat, 'manager') + const names = async (u: U) => + (await payload.find({ collection: 'share-members' as never, user: as(u), overrideAccess: false, pagination: false })).docs.map((d) => String(((d as unknown as { member: { value: { id?: unknown } | string } }).member.value as { id?: unknown })?.id ?? (d as unknown as { member: { value: unknown } }).member.value)) + const sorted = (a: string[]) => [...a].sort() + expect(sorted(await names(ben))).toEqual(sorted([String(ann.id), String(cat.id), String(ben.id)])) + expect((await names(cat)).length).toBe(4) + }) +}) + describe('the second review', () => { const readRow = async (u: U, id: unknown) => (await payload.findByID({ collection: 'share-members' as never, id: id as never, user: as(u), overrideAccess: false, depth: 0 })) as unknown as Record @@ -939,6 +1013,68 @@ describe('the third review', () => { }) }) + describe('organizations the identities hook maps', () => { + const activeOrg = async () => { + await invite(ann, { member: ref(org, 'organizations'), level: 'manager' }) + await payload.update({ collection: 'share-members' as never, id: (await rowOf(org, 'organizations')).id as never, data: { status: 'active' } as never, overrideAccess: true }) + } + + it('gives access through an organization only to people peopleOf lists for it', async () => { + await activeOrg() + expect(await roleIn(reqFor(cat), group.id)).toBe('manager') // listed: cat works for the organization + answers.identities = () => [{ relationTo: 'organizations', value: org.id }] + expect(await roleIn(reqFor(ben), group.id)).toBeNull() // mapped by identities, missing from peopleOf + expect(await names(ben)).toEqual([]) + }) + + it('drops the organization when peopleOf throws', async () => { + await activeOrg() + answers.peopleOf = () => { + throw new Error('boom') + } + expect(await roleIn(reqFor(cat), group.id)).toBeNull() + }) + + it('asks peopleOf once per organization per request', async () => { + await activeOrg() + let calls = 0 + answers.peopleOf = () => { + calls++ + return [{ relationTo: 'users', value: cat.id }] + } + const req = reqFor(cat) + await roleIn(req, group.id) + await roleIn(req, group.id) + expect(calls).toBe(1) + }) + + it('can’t be used by someone acting for an organization to write notes on its row', async () => { + await payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(org, 'organizations'), level: 'viewer', notes: 'staff note' } as never, user: as(ann), overrideAccess: false }) + answers.canAccept = () => true + const r = await rowOf(org, 'organizations') + await change(cat, r.id, { status: 'active', notes: 'overwritten' }) + const after = (await rows({ id: { equals: r.id } })).docs[0] as unknown as { status: string; notes: string } + expect([after.status, after.notes]).toEqual(['active', 'staff note']) + }) + }) + + describe('server code', () => { + it('can’t forge who invited someone', async () => { + await payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(ben), level: 'viewer', invitedBy: ann.id } as never, overrideAccess: true }) + const row = (await rows({ 'member.value': { equals: ben.id } })).docs[0] as unknown as { invitedBy?: unknown } + expect(row.invitedBy ?? null).toBeNull() + }) + + it('can’t skip the transaction, which would skip the lock and the history row', async () => { + const before = (await rows()).totalDocs + expect(await refused(payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(ben), level: 'viewer' } as never, overrideAccess: true, disableTransaction: true }))).toMatch(/transaction/) + expect((await rows()).totalDocs).toBe(before) + const r = await rowOf(ann) + expect(await refused(payload.update({ collection: 'share-members' as never, id: r.id as never, data: { status: 'removed' } as never, overrideAccess: true, disableTransaction: true }))).toMatch(/transaction/) + expect((await rowOf(ann)).status).toBe('active') + }) + }) + describe('level changes with other changes', () => { it('refuses a removal that carries a level change, and changes nothing', async () => { const r = await join(ben, 'viewer') From e2745e6cfbb375461db023791cf6adc5979c82e1 Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:58:38 -0700 Subject: [PATCH 6/7] Fix the test count in the first-version audit entry Tested: no code changed. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- docs/test-audit.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/test-audit.md b/docs/test-audit.md index 45a57a0..4c51544 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -12,7 +12,7 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". ## 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` (83 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. +- Covered: each of those, in `test/plugin.test.ts` (95 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) From d6b12c2ae931e4c3599ac26541b89adf8bf3e32e Mon Sep 17 00:00:00 2001 From: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Date: Mon, 23 Nov 2026 06:42:48 -0700 Subject: [PATCH 7/7] Await the transaction check, cover group creation and keep notes off new invitations The check now awaits req.transactionID, which is a promise that can resolve to null when the adapter has no transaction. Creating a group is checked too, so a refused founding Owner can't leave an ownerless group. Notes are dropped on a new invitation unless an Owner or Manager sends it. The README and types say the organization check applies only when peopleOf is a function. New tests: a non-array peopleOf, peopleOf: false, a new request asking again, and a user switched on the same request. Tested: 100 tests against real Payload with in-memory MongoDB. Not tested: a hosted production database, the admin screens, a live site. Co-Authored-By: Michael Gilardi <11632652+mgilardi@users.noreply.github.com> Co-Authored-By: Garfunkel Botsworth <357926774+garfunkelbot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++--- README.md | 4 +-- docs/test-audit.md | 4 +-- src/groups.ts | 6 +++++ src/members.ts | 22 +++++++++++------ src/types.ts | 2 +- test/plugin.test.ts | 59 ++++++++++++++++++++++++++++++++++++++++++++- 7 files changed, 86 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2561499..3eadeb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,6 @@ - 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. Documented: `peopleOf` must cover everyone `identities` maps, the veto isn't given current members, and a group's founding owner stays visible. -- Tested: 95 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 standalone MongoDB or another database with transactions off beyond the adapter case below, a live site, the admin screens in a browser, and a very large number of members. + - 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. diff --git a/README.md b/README.md index c28a2e9..9c82dca 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,7 @@ export default buildConfig({ - `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. **`identities` keeps an organization only when `peopleOf` 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. 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. +- `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. @@ -79,7 +79,7 @@ export default buildConfig({ - 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, and neither can someone acting for an organization on its row, unless they are an Owner or Manager of the group. Server code can. +- 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. diff --git a/docs/test-audit.md b/docs/test-audit.md index 4c51544..668637b 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -5,14 +5,14 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". ## 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` (95 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. +- 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` (95 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. +- 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) diff --git a/src/groups.ts b/src/groups.ts index 0be6f3a..0f20da8 100644 --- a/src/groups.ts +++ b/src/groups.ts @@ -14,6 +14,11 @@ export async function exactlyTrue(check: () => unknown): Promise { } } +/** Server code can pass `disableTransaction`. The adapter can also hand back no transaction. Either way the change is refused, because it must be atomic with its lock and history rows. */ +export async function needTransaction(req: PayloadRequest, s: ResolvedSharing) { + if (s.needsTransactions && !(await req.transactionID)) throw refuse('This change needs a transaction, so it wasn’t made.') +} + export function groupsCollection(s: ResolvedSharing, opts: SharingOptions): CollectionConfig { const memberTypes = s.memberTypes return { @@ -87,6 +92,7 @@ export function groupsCollection(s: ResolvedSharing, opts: SharingOptions): Coll ], beforeChange: [ async ({ data, originalDoc, operation, req }) => { + await needTransaction(req, s) if (operation === 'create') { if (typeof data.name !== 'string' || !data.name.trim()) throw refuse('A group needs a name.') data.name = data.name.trim() diff --git a/src/members.ts b/src/members.ts index 54960dc..aabf669 100644 --- a/src/members.ts +++ b/src/members.ts @@ -1,6 +1,6 @@ import type { CollectionConfig, PayloadRequest, Where } from 'payload' -import { exactlyTrue, refuse } from './groups.js' +import { exactlyTrue, needTransaction, refuse } from './groups.js' import { idOf, identitiesOf, refOf, roleIn, roleOf, sameRef, signedIn, whereRefs, groupIdsFor } from './helpers.js' import { EVENTS, @@ -135,17 +135,12 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col } } - /** Server code can pass `disableTransaction`, which would split a change from its history row and skip the lock. */ - const needTransaction = (req: PayloadRequest) => { - if (s.needsTransactions && !req.transactionID) throw refuse('This change needs a transaction, so it wasn’t made.') - } - /** * Takes the group's lock and checks that an Owner is left once this one goes. Writing the group first means two * Owners leaving or demoting each other at once collide, and one of them is turned back. */ async function keepAnOwner(req: PayloadRequest, group: GroupDoc, leaving: string | number) { - needTransaction(req) + await needTransaction(req, s) try { const fresh = (await req.payload.findByID({ collection: GROUPS as never, id: group.id, depth: 0, overrideAccess: true, req })) as unknown as { lock?: number } await req.payload.update({ collection: GROUPS as never, id: group.id, data: { lock: (fresh.lock ?? 0) + 1 } as never, overrideAccess: true, req }) @@ -288,7 +283,7 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col ], beforeChange: [ async ({ data, originalDoc, operation, req }) => { - needTransaction(req) + await needTransaction(req, s) const now = new Date().toISOString() if (operation === 'create') { const group = await loadGroup(req, data.group) @@ -301,6 +296,17 @@ export function membersCollection(s: ResolvedSharing, opts: SharingOptions): Col const empty = !(await req.payload.count({ collection: MEMBERS as never, where: { group: { equals: group.id } }, overrideAccess: true, req })).totalDocs // The founding Owner is the only member who starts active: the first row of a new group, for its owner. const founding = empty && !!owner && sameRef(owner, ref) && data.level === s.levels.owner.value + // Notes are for staff. Someone who isn't an Owner or Manager of the group can't set them, even if the host lets them invite. + if ('notes' in data && signedIn(req, s)) { + let staff = false + try { + const r = await roleIn(req, group.id) + staff = r === 'owner' || r === 'manager' + } catch { + staff = false + } + if (!staff) delete data.notes + } data.group = group.id data.member = ref data.status = founding ? 'active' : 'invited' diff --git a/src/types.ts b/src/types.ts index 22ddec8..8d38f58 100644 --- a/src/types.ts +++ b/src/types.ts @@ -116,7 +116,7 @@ export type SharingOptions = { levels?: Partial> /** * Other identities the signed-in user acts as, such as the organizations they work for. A membership held by any of - * them counts for the user. An organization counts only if `peopleOf` lists the user for it; if `peopleOf` throws, it is dropped. A throw means access is refused. Default: only the user. + * them counts for the user. When `peopleOf` is a function, an organization counts only if it lists the user; if it throws or returns no list, the organization is dropped. With `peopleOf: false` or none, organizations count as given. A throw means access is refused. Default: only the user. */ identities?: (args: { req: PayloadRequest; user: User }) => MemberRef[] | Promise /** diff --git a/test/plugin.test.ts b/test/plugin.test.ts index 551b014..e68ffb4 100644 --- a/test/plugin.test.ts +++ b/test/plugin.test.ts @@ -5,7 +5,7 @@ import { graphql } from 'graphql' import { buildConfig, createLocalReq, getPayload, handleEndpoints, type Payload } from 'payload' import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest' -import { assertTransactions, canEdit, canView, groupIdsFor, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' +import { assertTransactions, canEdit, canView, groupIdsFor, identitiesOf, roleIn, sharedWhere, sharing, shareGroupField, type AuditEvent } from '../src/index.js' /** * A made-up site: users (staff may make groups, some belong to organizations, one is flagged `minor`), organizations, @@ -1048,6 +1048,38 @@ describe('the third review', () => { expect(calls).toBe(1) }) + it('drops the organization when peopleOf returns no list, and counts it as given with peopleOf: false', async () => { + await activeOrg() + answers.peopleOf = () => 'cat' + expect(await roleIn(reqFor(cat), group.id)).toBeNull() + delete answers.peopleOf + const custom = payload.config.custom as { sharing: Record } + const open = { ...custom.sharing, peopleOf: false } as never + answers.identities = () => [{ relationTo: 'organizations', value: org.id }] + const refs = await identitiesOf(reqFor(ben), open) + expect(refs.some((r) => r.relationTo === 'organizations')).toBe(true) + expect((await identitiesOf(reqFor(ben))).some((r) => r.relationTo === 'organizations')).toBe(false) + }) + + it('asks peopleOf again on a new request, and doesn’t reuse a list that matched someone else on the same request', async () => { + await activeOrg() + let calls = 0 + answers.peopleOf = () => { + calls++ + return [{ relationTo: 'users', value: cat.id }] + } + expect(await roleIn(reqFor(cat), group.id)).toBe('manager') + expect(await roleIn(reqFor(cat), group.id)).toBe('manager') + expect(calls).toBe(2) + // the same request, the signed-in user switched to someone the list doesn't name + answers.identities = () => [{ relationTo: 'organizations', value: org.id }] + const req = reqFor(cat) as unknown as { user: unknown } + expect(await roleIn(req as never, group.id)).toBe('manager') + req.user = as(ben) + expect(await roleIn(req as never, group.id)).toBeNull() + expect(calls).toBe(3) + }) + it('can’t be used by someone acting for an organization to write notes on its row', async () => { await payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(org, 'organizations'), level: 'viewer', notes: 'staff note' } as never, user: as(ann), overrideAccess: false }) answers.canAccept = () => true @@ -1065,6 +1097,31 @@ describe('the third review', () => { expect(row.invitedBy ?? null).toBeNull() }) + it('refuses when the adapter hands back no transaction, even though the id is a promise', async () => { + const before = (await rows()).totalDocs + const req = await createLocalReq({ user: as(ann) }, payload) + ;(req as unknown as { transactionID: unknown }).transactionID = Promise.resolve(null) + expect(await refused(payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(ben), level: 'viewer' } as never, overrideAccess: true, req }))).toMatch(/transaction/) + expect((await rows()).totalDocs).toBe(before) + }) + + it('can’t make a group without a transaction, and leaves no ownerless group behind', async () => { + const count = async () => (await payload.count({ collection: 'share-groups' as never, overrideAccess: true })).totalDocs + const before = await count() + expect(await refused(payload.create({ collection: 'share-groups' as never, data: { name: 'Loose', kind: 'hobby', owner: ref(kid) } as never, overrideAccess: true, disableTransaction: true }))).toMatch(/transaction/) + expect(await count()).toBe(before) + }) + + it('keeps notes off a new invitation unless an Owner or Manager sent it', async () => { + answers.canInvite = () => true + await invite(dan, { member: ref(ben), level: 'viewer', notes: 'sneaky' }) + expect(((await rows({ 'member.value': { equals: ben.id } })).docs[0] as unknown as { notes?: string }).notes ?? null).toBeNull() + await invite(ann, { member: ref(cat), level: 'viewer', notes: 'staff note' }) + expect(((await rows({ 'member.value': { equals: cat.id } })).docs[0] as unknown as { notes?: string }).notes).toBe('staff note') + await payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(dan), level: 'viewer', notes: 'server note' } as never, overrideAccess: true }) + expect(((await rows({ 'member.value': { equals: dan.id } })).docs[0] as unknown as { notes?: string }).notes).toBe('server note') + }) + it('can’t skip the transaction, which would skip the lock and the history row', async () => { const before = (await rows()).totalDocs expect(await refused(payload.create({ collection: 'share-members' as never, data: { group: group.id, member: ref(ben), level: 'viewer' } as never, overrideAccess: true, disableTransaction: true }))).toMatch(/transaction/)