@extantape/payload-plugin-membership 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,12 +29,16 @@ Patreon, or let members support **categories** with **their own amount** — or
29
29
 
30
30
  **On its own.** Membership needs a Stripe account (a secret key and a webhook) and an auth collection for members. It doesn't import any other plugin. Perks, votes and credits are whatever your own `onPayment` and `onStatusChange` do.
31
31
 
32
+ **Needs.** Payload `^3.94.2` as a peer dependency. No other EXTANT APE plugin is required.
33
+
32
34
  **Works with:**
33
35
 
34
36
  - **Sponsors** (`@extantape/payload-plugin-sponsors`): tick "Members are listed as sponsors" on a tier, and call Sponsors' `upsertListing()` and `retireListing()` from `onStatusChange`. Your site makes the call; neither plugin imports the other.
35
37
  - **Roadmap** (`@extantape/payload-plugin-roadmap`): Roadmap's extra votes come from a number your site works out (`allocation.earned`), and a membership can be where they come from. There's no adapter for this. It's a few lines of your own code.
36
38
  - **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them. See [Sites](#sites) for what `scopeOf` returns and how `getBackers` and `myMembership` take a site.
37
39
 
40
+ **Color Theory.** None needed. It has no screens of its own, and its collections use Payload's standard admin, which takes Color Theory's admin colors when its `applyToAdmin` option is on.
41
+
38
42
  **Family.** Membership is in the Patronage family, with Sponsors, Backing, Credits, Printify and Roadmap. Backing and Credits are named but not built yet, and the families are a working draft that may change.
39
43
 
40
44
  ## Install
@@ -124,8 +128,9 @@ refuses to build with only one of them.
124
128
  plugin applies it through each payment's `membership`.
125
129
  - Anything else is no: `false`, `null`, `0`, `''`, `1`, `'yes'`, an array, an empty `{}` or `{ and: [] }`,
126
130
  a field with no operator, an operator Payload doesn't have or the plugin doesn't take (a typo such as
127
- `equal` included), a value that would match every row (`like: ''`, `contains: ''`, `not_in: []`,
128
- `all: []`), a query that doesn't run against the memberships collection (an unknown field), or an
131
+ `equal` included), a value that would match every row (`like` or `contains` with nothing or only whitespace, `not_in: []`,
132
+ `all: []`), a query that doesn't run against the memberships collection or against the tiers,
133
+ categories or payments it is used on (an unknown field), or an
129
134
  error thrown or rejected. The request is refused cleanly, never a 500. An empty `{}` would match
130
135
  every row, so it is a no. Return `true` to mean all. The accepted operators are `equals`,
131
136
  `not_equals`, `in`, `not_in`, `all`, `exists`, `greater_than`, `greater_than_equal`, `less_than`,
@@ -173,7 +178,9 @@ request). Managers keep `cancel`. (Decided 2026-11-23.)
173
178
  This is enforced in field access too, not just in the endpoints, so editing a membership through
174
179
  Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
175
180
  `kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
176
- `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
181
+ `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit. In the admin form the `show` box is read-only for a manager, because
182
+ field access can't know at display time that the new value is `false`. A manager hides a wall entry
183
+ through the wall endpoint (`POST /api/memberships/:id/wall` with `show: false`), or through REST or the Local API.
177
184
  Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
178
185
  set a category's `parent` only to a category in their scope. That is judged on the parent the row
179
186
  ends up with, whether the save is a create, an update, a duplicate (which keeps the original's parent
package/dist/access.d.ts CHANGED
@@ -15,7 +15,10 @@ export declare function usableWhere(w: unknown, depth?: number): w is Where;
15
15
  * and anyone not signed in, is `null`.
16
16
  */
17
17
  export type ManagerScope = true | Where | null;
18
- export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<ManagerScope>;
18
+ export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, on?: {
19
+ collection: string;
20
+ via?: (w: Where) => Where;
21
+ }): Promise<ManagerScope>;
19
22
  /** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
20
23
  export declare function isManager(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<boolean>;
21
24
  /** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
package/dist/access.js CHANGED
@@ -15,7 +15,8 @@ const isPlain = (v) => {
15
15
  };
16
16
  const scalar = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v);
17
17
  const scalars = (v, minimum) => Array.isArray(v) && v.length >= minimum && v.every(scalar);
18
- const nonEmptyText = (v) => typeof v === 'string' && v.length > 0;
18
+ // Whitespace and zero-width characters alone would match nearly every row, so they don't count as text.
19
+ const nonEmptyText = (v) => typeof v === 'string' && /[^\s\u200b-\u200d\u2060\ufeff]/.test(v);
19
20
  const number = (v) => typeof v === 'number' || typeof v === 'string';
20
21
  /**
21
22
  * The operators the plugin accepts, each with a check on its value. An unknown operator (a typo
@@ -57,7 +58,7 @@ export function usableWhere(w, depth = 0) {
57
58
  return ops.length > 0 && ops.every(([op, arg]) => Object.hasOwn(OPERATORS, op) && OPERATORS[op](arg));
58
59
  });
59
60
  }
60
- export async function managerScope(o, req) {
61
+ export async function managerScope(o, req, on) {
61
62
  if (!req.user)
62
63
  return null;
63
64
  try {
@@ -66,19 +67,27 @@ export async function managerScope(o, req) {
66
67
  return true;
67
68
  if (!usableWhere(answer))
68
69
  return null;
70
+ // The query must run on the memberships collection and on the collection it is used on (a field
71
+ // that only memberships have can't be queried on tiers or categories), or the answer is no.
69
72
  const checked = (req.context.membershipWhereChecked ??= new Map());
70
- const key = JSON.stringify(answer);
71
- let ok = checked.get(key);
72
- if (ok === undefined) {
73
- try {
74
- await req.payload.count({ collection: o.memberships, where: answer, overrideAccess: true, req });
75
- ok = true;
73
+ const runsOn = async (collection, where) => {
74
+ const key = `${collection}:${JSON.stringify(where)}`;
75
+ let ok = checked.get(key);
76
+ if (ok === undefined) {
77
+ try {
78
+ await req.payload.count({ collection: collection, where, overrideAccess: true, req });
79
+ ok = true;
80
+ }
81
+ catch {
82
+ ok = false;
83
+ }
84
+ checked.set(key, ok);
76
85
  }
77
- catch {
78
- ok = false;
79
- }
80
- checked.set(key, ok);
81
- }
86
+ return ok;
87
+ };
88
+ let ok = await runsOn(o.memberships, answer);
89
+ if (ok && on && on.collection !== o.memberships)
90
+ ok = await runsOn(on.collection, on.via ? on.via(answer) : answer);
82
91
  return ok ? answer : null;
83
92
  }
84
93
  catch {
@@ -152,7 +161,7 @@ export function matchesWhere(where, data) {
152
161
  * (checked against the database), nobody else. The answer is kept for the request.
153
162
  */
154
163
  export async function managerReaches(o, req, collection, id, via = (w) => w) {
155
- const scope = await managerScope(o, req);
164
+ const scope = await managerScope(o, req, { collection, via });
156
165
  if (scope === true)
157
166
  return true;
158
167
  if (!scope || id == null || id === '')
@@ -64,12 +64,12 @@ const wallShow = (o) => async (args) => {
64
64
  * (`via` rewrites it for a collection that holds the rows indirectly), anything else is no. A new
65
65
  * row (`create`) must match the query in its own data.
66
66
  */
67
- function scopedManager(o, via = (w) => w, collection) {
67
+ function scopedManager(o, via = (w) => w, collection, target = collection) {
68
68
  // An update by a limited manager must leave the row inside their query: the existing row with the
69
69
  // incoming data merged over it is matched in memory, so a row can't be moved out of scope or into
70
70
  // another site. Nothing to check unless the data touches a field the query names.
71
71
  const update = async ({ req, id, data }) => {
72
- const scope = await managerScope(o, req);
72
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
73
73
  if (scope === true)
74
74
  return true;
75
75
  if (!scope)
@@ -89,11 +89,11 @@ function scopedManager(o, via = (w) => w, collection) {
89
89
  return where;
90
90
  };
91
91
  const rows = () => async ({ req }) => {
92
- const scope = await managerScope(o, req);
92
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
93
93
  return scope === true ? true : scope ? via(scope) : false;
94
94
  };
95
95
  const create = async ({ req, data }) => {
96
- const scope = await managerScope(o, req);
96
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
97
97
  return scope === true || (scope !== null && matchesWhere(scope, data));
98
98
  };
99
99
  return { create, update: collection ? update : rows(), remove: rows() };
@@ -103,12 +103,12 @@ function referencedFields(where) {
103
103
  return Object.entries(where).flatMap(([k, v]) => (k === 'and' || k === 'or' ? v.flatMap(referencedFields) : [k.split('.')[0]]));
104
104
  }
105
105
  /** Managers read what `canManage` reaches and members their own rows; anyone else gets nothing. */
106
- function ownOrScoped(o, via = (w) => w) {
106
+ function ownOrScoped(o, via = (w) => w, target) {
107
107
  return async ({ req }) => {
108
108
  if (!req.user)
109
109
  return false;
110
110
  const own = { user: { equals: req.user.id } };
111
- const scope = await managerScope(o, req);
111
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
112
112
  if (scope === true)
113
113
  return true;
114
114
  return scope ? { or: [via(scope), own] } : own;
@@ -202,7 +202,7 @@ function everyLocaleInScope(o, target) {
202
202
  const codes = localeCodes(req);
203
203
  if (!('localized' in field && field.localized) || !codes.length)
204
204
  return value;
205
- const scope = await managerScope(o, req);
205
+ const scope = await managerScope(o, req, { collection: target });
206
206
  if (scope === true || !scope)
207
207
  return value; // no scope at all is refused by access
208
208
  const existing = (siblingDocWithLocales?.[field.name] ?? {});
@@ -229,7 +229,7 @@ function publicRead(o, slug) {
229
229
  if (!(versions && typeof versions === 'object' && versions.drafts))
230
230
  return true;
231
231
  const published = { or: [{ _status: { equals: 'published' } }, { _status: { exists: false } }] };
232
- const scope = await managerScope(o, req);
232
+ const scope = await managerScope(o, req, { collection: slug });
233
233
  if (scope === true)
234
234
  return true;
235
235
  return scope ? { or: [published, scope] } : published;
@@ -238,7 +238,7 @@ function publicRead(o, slug) {
238
238
  /** Field access for managers: judged on the particular row, never on a bare yes. */
239
239
  function managerFieldOn(o, collection) {
240
240
  return async ({ req, id, doc, data }) => {
241
- const scope = await managerScope(o, req);
241
+ const scope = await managerScope(o, req, { collection });
242
242
  if (scope === true)
243
243
  return true;
244
244
  if (!scope)
@@ -317,7 +317,7 @@ export function membershipsCollection(o) {
317
317
  const { update, remove } = scopedManager(o, undefined, o.memberships);
318
318
  const managerField = managerFieldOn(o, o.memberships);
319
319
  // A manager reads what `canManage` reaches; members read their own (the plugin's own query, never the site's answer).
320
- const ownOrManager = ownOrScoped(o);
320
+ const ownOrManager = ownOrScoped(o, undefined, o.memberships);
321
321
  const nobody = () => false;
322
322
  return {
323
323
  slug: o.memberships,
@@ -325,7 +325,7 @@ export function membershipsCollection(o) {
325
325
  admin: {
326
326
  useAsTitle: 'label',
327
327
  defaultColumns: ['label', 'kind', 'amount', 'interval', 'status', 'currentPeriodEnd'],
328
- description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
328
+ description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the staff notes here. Managers can hide a wall entry through the wall endpoint.',
329
329
  },
330
330
  // Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
331
331
  access: { read: ownOrManager, readVersions: managersReadVersions(o, o.memberships), create: nobody, update, delete: remove },
@@ -425,8 +425,8 @@ export function membershipsCollection(o) {
425
425
  };
426
426
  }
427
427
  export function paymentsCollection(o) {
428
- const { remove } = scopedManager(o, viaMembership);
429
- const ownOrManager = ownOrScoped(o, viaMembership);
428
+ const { remove } = scopedManager(o, viaMembership, undefined, o.payments);
429
+ const ownOrManager = ownOrScoped(o, viaMembership, o.payments);
430
430
  return {
431
431
  slug: o.payments,
432
432
  labels: { singular: 'Membership payment', plural: 'Membership payments' },
package/dist/guard.js CHANGED
@@ -78,6 +78,39 @@ function checkFieldValue(field, v, req, depth, locales) {
78
78
  }
79
79
  refuseBadKeys(v, null, req, depth);
80
80
  }
81
+ // A group is an object. Payload's field hooks read inside it before any access rule runs, so a null
82
+ // (or any non-object) for a group, `wall: null` on a membership for one, would end as a 500. It is a
83
+ // clean 400 instead, for every caller, and nothing is saved.
84
+ function refuseNullGroups(data, fields, req) {
85
+ if (!data || typeof data !== 'object' || Array.isArray(data))
86
+ return;
87
+ for (const [name, f] of named(fields)) {
88
+ if (!(name in data))
89
+ continue;
90
+ const v = data[name];
91
+ if (v === undefined)
92
+ continue; // undefined means not sent
93
+ if (f.type === 'group') {
94
+ if (v === null || typeof v !== 'object' || Array.isArray(v))
95
+ throw new APIError(`${name} must be an object.`, 400, undefined, true);
96
+ refuseNullGroups(v, f.fields, req);
97
+ }
98
+ else if (f.type === 'array' && Array.isArray(v)) {
99
+ for (const row of v)
100
+ refuseNullGroups(row, f.fields, req);
101
+ }
102
+ else if (f.type === 'blocks' && Array.isArray(v)) {
103
+ // A block row is checked against the block its blockType names, whether the host listed the block here or by reference.
104
+ const blocks = [...(f.blocks ?? []), ...(f.blockReferences ?? []).map((b) => (typeof b === 'string' ? req.payload.config.blocks?.find((x) => x.slug === b) : b))];
105
+ for (const row of v) {
106
+ const type = row && typeof row === 'object' ? row.blockType : undefined;
107
+ const block = blocks.find((b) => b && b.slug === type);
108
+ if (block)
109
+ refuseNullGroups(row, block.fields, req);
110
+ }
111
+ }
112
+ }
113
+ }
81
114
  /**
82
115
  * Added at the front of the collection's `beforeOperation` hooks after the host's overrides, so it
83
116
  * sees the data as the request sent it, ahead of the collection's other hooks. A plugin that runs
@@ -95,6 +128,7 @@ export function writeGuard(o) {
95
128
  // passes a request body straight to it gets the same check.
96
129
  if (operation === 'create' || operation === 'update') {
97
130
  refuseBadKeys(a.data, collection.fields, req);
131
+ refuseNullGroups(a.data, collection.fields, req);
98
132
  return args;
99
133
  }
100
134
  if (operation === 'restoreVersion' && !overrideAccess) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Memberships for Payload: Patreon-style tiers or pick-your-own-amount pledges to categories, billed as Stripe subscriptions, with a backers wall and hooks for perks.",
5
5
  "homepage": "https://github.com/ExtantApe/payload-plugin-membership#readme",
6
6
  "bugs": {