@extantape/payload-plugin-membership 0.2.0 → 0.3.1

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
@@ -3,6 +3,13 @@
3
3
  Memberships for [Payload](https://payloadcms.com), billed as Stripe subscriptions. Run it like
4
4
  Patreon, or let members support **categories** with **their own amount** — or both.
5
5
 
6
+ > **Status: 0.x, so a new version can include breaking changes. The [CHANGELOG](https://github.com/ExtantApe/payload-plugin-membership/blob/main/CHANGELOG.md) marks them.**
7
+ > The automated tests run on Payload 3.94.2 with an in-memory MongoDB and a fake Stripe. CI runs them on
8
+ > Node 24. They call REST and GraphQL in-process, and include `@payloadcms/plugin-multi-tenant` 3.94.2.
9
+ > Not tested: real Stripe, the admin UI in a browser, REST or GraphQL through a running web server,
10
+ > databases other than MongoDB, Payload versions after 3.94.2, Node 22, Node 26.13.1 or newer, and upgrading a real 0.2.0
11
+ > database. You need Payload 3.94.2 or later, and Node ^22.23.5, ^24.22.3, or 26.13.1 or newer.
12
+
6
13
  - **Tiers** (Patreon-style): fixed monthly and/or yearly prices, perks, colors. Drag-and-drop order.
7
14
  - **Categories**: things members can choose to support (e.g. "Turtles", "North American turtles"),
8
15
  nestable, with a minimum amount and an optional **earmarked** flag (otherwise the category is the
@@ -32,6 +39,8 @@ Patreon, or let members support **categories** with **their own amount** — or
32
39
 
33
40
  ## Install
34
41
 
42
+ Requires Payload 3.94.2 or later, and Node ^22.23.5, ^24.22.3, or 26.13.1 or newer (`^22.23.5 || ^24.22.3 || >=26.13.1`, the same range as Payload 3.94.2).
43
+
35
44
  ```bash
36
45
  npm install @extantape/payload-plugin-membership
37
46
  ```
@@ -130,7 +139,7 @@ example a membership they hold as a member there).
130
139
  | Where | A manager | A signed-in member | Signed out |
131
140
  |---|---|---|---|
132
141
  | Tiers, categories | Reads; creates, edits, deletes within their scope | Reads | Reads |
133
- | Their `stripeProduct` (field) | Reads and writes within their scope | Never sees it | Never sees it |
142
+ | Their `stripeProduct` (field) | Reads within their scope; never writes | Never sees it | Never sees it |
134
143
  | Memberships | Reads and edits within their scope, deletes within their scope | Reads their own | Nothing |
135
144
  | A membership's `stripe` and `notes` (fields) | Reads and writes within their scope | Never sees them | Nothing |
136
145
  | Payments | Reads and deletes within their scope | Reads their own | Nothing |
@@ -148,7 +157,48 @@ Payload's own REST, GraphQL or admin can't get around it. A manager can't write
148
157
  `kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
149
158
  `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
150
159
  Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
151
- set a category's `parent` only to a category in their scope.
160
+ set a category's `parent` only to a category in their scope. That is judged on the parent the row
161
+ ends up with, whether the save is a create, an update, a duplicate (which keeps the original's parent
162
+ unless the data changes it) or a restore. A save whose final parent is outside their scope is refused
163
+ with a message saying so; clear the parent or choose one they manage. If you localize `parent` through
164
+ `overrides`, every locale's parent counts: a save in one locale is refused while another locale's
165
+ parent is outside their scope, until that locale's parent is cleared or moved.
166
+
167
+ Saves to the plugin's collections send each field by its plain name, with nested fields as nested
168
+ objects. A field name that starts with a dollar sign or contains a dot is refused (400) on every save,
169
+ through any API, bulk updates, drafts and duplicates included, and from your server code with
170
+ `overrideAccess` too, since the Local API overrides access by default. The values of JSON and rich
171
+ text fields are left alone. The plugin puts this check at the front of each collection's
172
+ `beforeOperation` hooks, after your `overrides`. A plugin that runs after this one can still add its
173
+ own hook in front of it, so that hook sees the data before the check does.
174
+
175
+ A manager limited by a `Where` may restore a version of a tier, category or membership only when the
176
+ version itself matches their `Where`. A version that can't be read is refused. (Restoring a
177
+ membership by anyone other than server code fails validation, as it did before, because the fields
178
+ managers can't write aren't refilled on restore.)
179
+
180
+ If you turn on drafts for tiers or categories through `overrides`, people who aren't managers read
181
+ only published rows (and rows saved before drafts were on). A limited manager also reads drafts in
182
+ their scope, and a manager of every row reads all of them.
183
+
184
+ Saved versions are for managers only: the `versions` routes in REST, the version queries in GraphQL,
185
+ and `findVersions` and `findVersionByID` in the Local API with access on. Members and signed-out
186
+ visitors get none, and a limited manager gets only the versions that match their `Where`. This covers
187
+ all four collections, versions you turn on through `overrides` included. If your `overrides` set
188
+ `access.readVersions`, your rule is used. If they replace `access` without one, the plugin's rule is
189
+ put back, so these collections always have a rule for versions.
190
+
191
+ A server-side duplicate of a membership starts as `pending`, without Stripe ids, period dates,
192
+ `canceledAt` or `cancelAtPeriodEnd`. It also starts without the staff `notes` and off the backers
193
+ wall (`wall.show` false, no `wall.name`). Server code that wants any of these on the copy passes them
194
+ in `data`.
195
+
196
+ `stripeProduct` on tiers and categories is set only by server code (`overrideAccess`): the plugin
197
+ stores it at a row's first checkout, and your own server code (a seed or an import) may set it on
198
+ create or update. A create or update that doesn't override access ignores it. It belongs to one row,
199
+ so a duplicate starts without it, in every locale, and gets its own at its first checkout. That
200
+ includes a duplicate made by your server code. To give a copy a particular value, pass `stripeProduct`
201
+ in the `data` of a duplicate that overrides access.
152
202
 
153
203
  Nobody creates memberships or payments directly: checkout and Stripe do. The member endpoints answer
154
204
  404, not 403, to anyone who may not use them, so they don't say whether a membership exists.
@@ -161,7 +211,35 @@ an error included, refuses it with "Memberships are not available here yet." (50
161
211
  Upgrading: a `canManage` that returned `true` or `false` works as before. One that returned an object
162
212
  (it was a no) now has that object used as a query, so return `false` if you meant no.
163
213
 
164
- `overrides` can change a collection's `access`; if you do, your rules replace these.
214
+ Upgrading, `stripeProduct`: if anything other than server code writes it (the REST or GraphQL API, or
215
+ the Local API with `overrideAccess: false`), move that write to server code with `overrideAccess`,
216
+ after your own permission check. If your server code duplicates a tier or category and expects the
217
+ copy to keep the value, pass it in `data`. Rows saved earlier keep what they hold, and checkout uses
218
+ it, so check them: each value should be used by one row only, and a product the plugin created names
219
+ its row in its Stripe metadata (`payloadCollection`, `payloadId`). Where a value belongs to another
220
+ row, set it to `null` from server code (in each locale, if you localize the field). The next checkout
221
+ creates the row's own product.
222
+
223
+ Upgrading from 0.2.0, checks to run once from server code:
224
+
225
+ 1. Stored products. For each tier and category with a `stripeProduct`, clear it (set `null` with
226
+ `overrideAccess`, in each locale if you localize the field) when more than one row holds the same
227
+ value, or when the product's Stripe metadata `payloadCollection` and `payloadId` don't name this
228
+ collection and this row's id. Clear every row that shares a value, the first one too. The next
229
+ checkout makes each row its own product. Running it again should find nothing.
230
+ 2. Parent categories. If you use a `Where` for managers, list categories whose `parent` is outside the
231
+ category's own scope (on another site). If you localize `parent`, check it in each locale. A limited
232
+ manager can't save such a category until its parent is cleared or moved into their scope, so fix
233
+ these from server code or as a manager of every row.
234
+
235
+ This version requires Payload 3.94.2 or later (peer range `^3.94.2`). Upgrade Payload before you
236
+ install it.
237
+
238
+ Saves to these collections, from your front end, scripts and server code alike, must use plain field
239
+ names (no leading dollar sign, no dots). Nested fields go as nested objects.
240
+
241
+ `overrides` can change a collection's `access`; if you do, your rules replace these, except that a
242
+ collection whose `access` has no `readVersions` keeps the plugin's.
165
243
 
166
244
  ## License
167
245
 
package/dist/access.d.ts CHANGED
@@ -20,6 +20,11 @@ export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | '
20
20
  export declare function isManager(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<boolean>;
21
21
  /** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
22
22
  export declare function viaMembership(where: Where): Where;
23
+ /**
24
+ * The query as it applies to a collection's saved versions, where every field sits under `version`
25
+ * and the row's own id is `parent`.
26
+ */
27
+ export declare function inVersions(where: Where): Where;
23
28
  /**
24
29
  * Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
25
30
  * `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
package/dist/access.js CHANGED
@@ -100,6 +100,20 @@ export function viaMembership(where) {
100
100
  }
101
101
  return out;
102
102
  }
103
+ /**
104
+ * The query as it applies to a collection's saved versions, where every field sits under `version`
105
+ * and the row's own id is `parent`.
106
+ */
107
+ export function inVersions(where) {
108
+ const out = {};
109
+ for (const [k, v] of Object.entries(where)) {
110
+ if (k === 'and' || k === 'or')
111
+ out[k] = v.map(inVersions);
112
+ else
113
+ out[k === 'id' ? 'parent' : `version.${k}`] = v;
114
+ }
115
+ return out;
116
+ }
103
117
  const idOf = (v) => (v && typeof v === 'object' && 'id' in v ? v.id : v);
104
118
  const same = (a, b) => a != null && b != null && String(idOf(a)) === String(idOf(b));
105
119
  /**
@@ -1,6 +1,15 @@
1
- import type { CollectionConfig } from 'payload';
1
+ import type { Access, CollectionConfig, Where } from 'payload';
2
2
  import type { ResolvedMembership } from './types.js';
3
+ type Via = (w: Where) => Where;
4
+ /**
5
+ * Who reads saved versions (REST, GraphQL and the Local API's `findVersions`): managers only, a
6
+ * limited manager only versions inside their scope. Members and signed-out callers get none. Payload
7
+ * applies this to the versions collection as is, so the scope is rewritten for it (`version.<field>`, `parent` for the id) and run once; a
8
+ * scope that doesn't run there is no.
9
+ */
10
+ export declare function managersReadVersions(o: ResolvedMembership, collection: string, via?: Via): Access;
3
11
  export declare function tiersCollection(o: ResolvedMembership): CollectionConfig;
4
12
  export declare function categoriesCollection(o: ResolvedMembership): CollectionConfig;
5
13
  export declare function membershipsCollection(o: ResolvedMembership): CollectionConfig;
6
14
  export declare function paymentsCollection(o: ResolvedMembership): CollectionConfig;
15
+ export {};
@@ -1,5 +1,6 @@
1
+ import { APIError } from 'payload';
1
2
  import { generateKeyBetween } from 'payload/shared';
2
- import { managerReaches, managerScope, matchesWhere, viaMembership } from './access.js';
3
+ import { inVersions, managerReaches, managerScope, matchesWhere, viaMembership } from './access.js';
3
4
  const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
5
  /** Drag-and-drop ordered (Payload `orderable`); a new record goes between its alphabetical neighbours. */
5
6
  const placeAlphabetically = (o, slug, field) => async ({ data, operation, req }) => {
@@ -30,6 +31,20 @@ const placeAlphabetically = (o, slug, field) => async ({ data, operation, req })
30
31
  };
31
32
  /** No write through the API for anyone: only the plugin's own server code (with overrideAccess) changes these. */
32
33
  const LOCKED = { update: () => false };
34
+ /**
35
+ * The Stripe product of a tier or category, created at its first checkout (prices are set per member).
36
+ * Only server code (`overrideAccess`) writes it. It belongs to one row, so a duplicate starts without
37
+ * it, whoever makes the copy. `null` is deliberate: Payload ignores `undefined` from this hook.
38
+ */
39
+ const stripeProductField = (read) => ({
40
+ name: 'stripeProduct',
41
+ type: 'text',
42
+ access: { read, create: () => false, update: () => false },
43
+ hooks: { beforeDuplicate: [() => null] },
44
+ admin: { position: 'sidebar', readOnly: true },
45
+ });
46
+ /** A copy of a membership is a new, unpaid row: these start empty, whoever makes the copy (`null`: Payload ignores `undefined`). The staff notes and the member's wall choice start empty too. */
47
+ const fresh = (value = null) => ({ beforeDuplicate: [() => value] });
33
48
  /** Only the member whose row it is. */
34
49
  const memberOnly = ({ req, doc }) => Boolean(req.user) && String(idOf(doc?.user)) === String(req.user.id);
35
50
  /** Only the member sets `wall.show` to true; a manager may only hide (`false`), e.g. for an offensive name or a takedown request. */
@@ -99,13 +114,125 @@ function ownOrScoped(o, via = (w) => w) {
99
114
  return scope ? { or: [via(scope), own] } : own;
100
115
  };
101
116
  }
117
+ /**
118
+ * Who reads saved versions (REST, GraphQL and the Local API's `findVersions`): managers only, a
119
+ * limited manager only versions inside their scope. Members and signed-out callers get none. Payload
120
+ * applies this to the versions collection as is, so the scope is rewritten for it (`version.<field>`, `parent` for the id) and run once; a
121
+ * scope that doesn't run there is no.
122
+ */
123
+ export function managersReadVersions(o, collection, via = (w) => w) {
124
+ return async ({ req }) => {
125
+ const scope = await managerScope(o, req);
126
+ if (scope === true)
127
+ return true;
128
+ if (!scope)
129
+ return false;
130
+ const where = inVersions(via(scope));
131
+ const checked = (req.context.membershipVersionWhereChecked ??= new Map());
132
+ const key = `${collection}:${JSON.stringify(where)}`;
133
+ let ok = checked.get(key);
134
+ if (ok === undefined) {
135
+ try {
136
+ await req.payload.countVersions({ collection: collection, where, overrideAccess: true, req });
137
+ ok = true;
138
+ }
139
+ catch {
140
+ ok = false;
141
+ }
142
+ checked.set(key, ok);
143
+ }
144
+ return ok ? where : false;
145
+ };
146
+ }
147
+ const localeCodes = (req) => (req.payload.config.localization ? req.payload.config.localization.localeCodes : []);
148
+ /** A value sent with every locale at once (`locale: 'all'`): one value per locale code. */
149
+ const perLocale = (value, req) => req.locale === 'all' && localeCodes(req).length && value && typeof value === 'object' && !Array.isArray(value) && !('id' in value) ? value : null;
150
+ /** The parent ids in a value, each locale's when it holds one per locale. Anything that isn't a locale code counts as an id too. */
151
+ function parentIds(value, req) {
152
+ const each = perLocale(value, req);
153
+ const values = each ? Object.values(each) : [value];
154
+ return values.filter((v) => v != null && v !== '').map((v) => String(idOf(v)));
155
+ }
102
156
  /** A relationship may only be set to a row the manager reaches (nothing to check when it isn't being set). */
103
157
  function inScope(o, target) {
104
158
  return async ({ req, siblingData, data }) => {
105
159
  const sent = siblingData?.parent ?? data?.parent;
106
- if (sent == null || sent === '')
160
+ for (const id of parentIds(sent, req))
161
+ if (!(await managerReaches(o, req, target, id)))
162
+ return false;
163
+ return true;
164
+ };
165
+ }
166
+ const PARENT_REFUSED = 'The parent category is outside what you manage. Choose a category you manage, or clear the parent.';
167
+ /**
168
+ * Saves made by server code (`overrideAccess`), marked in `beforeValidate`, the only field hook
169
+ * Payload tells. The mark is the document both phases share; a missing mark only means the save is
170
+ * checked as though it came from a manager.
171
+ */
172
+ const unchecked = new WeakSet();
173
+ /**
174
+ * The parent a category ends up with must be one the manager reaches, whether it was sent, kept
175
+ * from the existing row, copied by a duplicate or brought back by restoring a version. Runs as a
176
+ * field `beforeValidate` hook, where Payload has already merged those in, and refuses rather than
177
+ * dropping the value so the manager knows why. Server code (`overrideAccess`) isn't checked.
178
+ */
179
+ function parentInScope(o, target) {
180
+ return async ({ originalDoc, overrideAccess, req, value }) => {
181
+ if (overrideAccess) {
182
+ if (originalDoc && typeof originalDoc === 'object')
183
+ unchecked.add(originalDoc);
184
+ return value;
185
+ }
186
+ for (const id of parentIds(value, req))
187
+ if (!(await managerReaches(o, req, target, id)))
188
+ throw new APIError(PARENT_REFUSED, 403, undefined, true);
189
+ return value;
190
+ };
191
+ }
192
+ /**
193
+ * When a host localizes the parent, a save in one locale keeps the other locales' parents, and a
194
+ * duplicate or restore carries them all. Each locale's final parent is worked out the way Payload
195
+ * merges locales (the value sent for the current locale, or for each locale sent with `all`, and the
196
+ * stored value for every other locale), and every one must be reachable.
197
+ */
198
+ function everyLocaleInScope(o, target) {
199
+ return async ({ field, originalDoc, req, siblingDocWithLocales, value }) => {
200
+ if (originalDoc && typeof originalDoc === 'object' && unchecked.has(originalDoc))
201
+ return value;
202
+ const codes = localeCodes(req);
203
+ if (!('localized' in field && field.localized) || !codes.length)
204
+ return value;
205
+ const scope = await managerScope(o, req);
206
+ if (scope === true || !scope)
207
+ return value; // no scope at all is refused by access
208
+ const existing = (siblingDocWithLocales?.[field.name] ?? {});
209
+ const sentAll = perLocale(value, req);
210
+ for (const code of codes) {
211
+ const sent = sentAll ? sentAll[code] : code === req.locale ? value : undefined;
212
+ const final = sent === undefined ? existing[code] : sent;
213
+ if (final == null || final === '')
214
+ continue;
215
+ if (!(await managerReaches(o, req, target, idOf(final))))
216
+ throw new APIError(PARENT_REFUSED, 403, undefined, true);
217
+ }
218
+ return value;
219
+ };
220
+ }
221
+ /**
222
+ * Who reads tiers and categories. Everyone, as the plugin ships. If a host turns on drafts through
223
+ * `overrides`, only managers see unpublished rows (a limited manager only in their scope); anyone
224
+ * else sees published rows.
225
+ */
226
+ function publicRead(o, slug) {
227
+ return async ({ req }) => {
228
+ const versions = req.payload.collections[slug]?.config.versions;
229
+ if (!(versions && typeof versions === 'object' && versions.drafts))
230
+ return true;
231
+ const published = { or: [{ _status: { equals: 'published' } }, { _status: { exists: false } }] };
232
+ const scope = await managerScope(o, req);
233
+ if (scope === true)
107
234
  return true;
108
- return managerReaches(o, req, target, idOf(sent));
235
+ return scope ? { or: [published, scope] } : published;
109
236
  };
110
237
  }
111
238
  /** Field access for managers: judged on the particular row, never on a bare yes. */
@@ -132,7 +259,7 @@ export function tiersCollection(o) {
132
259
  defaultColumns: ['name', 'monthly', 'yearly', 'active'],
133
260
  description: 'Fixed-price levels (Patreon-style). Shown in this order: drag rows to change it.',
134
261
  },
135
- access: { read: () => true, create, update, delete: remove },
262
+ access: { read: publicRead(o, o.tiers), readVersions: managersReadVersions(o, o.tiers), create, update, delete: remove },
136
263
  orderable: true,
137
264
  defaultSort: '_order',
138
265
  hooks: { beforeChange: [placeAlphabetically(o, o.tiers, 'name')] },
@@ -149,8 +276,7 @@ export function tiersCollection(o) {
149
276
  type: 'checkbox',
150
277
  admin: { position: 'sidebar', description: 'A perk your site can act on in onStatusChange (e.g. with payload-plugin-sponsors).' },
151
278
  },
152
- // Stripe product for this tier/category (created on first checkout; prices are set per member).
153
- { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
279
+ stripeProductField(managerField),
154
280
  ],
155
281
  timestamps: true,
156
282
  };
@@ -166,14 +292,14 @@ export function categoriesCollection(o) {
166
292
  defaultColumns: ['name', 'parent', 'minimum', 'active'],
167
293
  description: 'What members can choose to support, setting their own amount (A–Z for new ones; drag to reorder). Add your own fields to tie categories to anything.',
168
294
  },
169
- access: { read: () => true, create, update, delete: remove },
295
+ access: { read: publicRead(o, o.categories), readVersions: managersReadVersions(o, o.categories), create, update, delete: remove },
170
296
  orderable: true,
171
297
  defaultSort: '_order',
172
298
  hooks: { beforeChange: [placeAlphabetically(o, o.categories, 'name')] },
173
299
  fields: [
174
300
  { name: 'name', type: 'text', required: true },
175
301
  { name: 'active', label: 'Open to new pledges', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
176
- { name: 'parent', type: 'relationship', relationTo: o.categories, access: { create: inScope(o, o.categories), update: inScope(o, o.categories) }, admin: { position: 'sidebar', description: 'Optional: nest under a broader category.' } },
302
+ { name: 'parent', type: 'relationship', relationTo: o.categories, access: { create: inScope(o, o.categories), update: inScope(o, o.categories) }, hooks: { beforeValidate: [parentInScope(o, o.categories)], beforeChange: [everyLocaleInScope(o, o.categories)] }, admin: { position: 'sidebar', description: 'Optional: nest under a broader category.' } },
177
303
  { name: 'description', type: 'textarea' },
178
304
  money('minimum', 'Minimum per month', 'Smallest monthly amount for this category (yearly: 12×).'),
179
305
  {
@@ -182,8 +308,7 @@ export function categoriesCollection(o) {
182
308
  admin: { description: 'Off: the category is the member’s preference. On: pledges are reserved for work in this category (say so on your page).' },
183
309
  },
184
310
  { name: 'color', type: 'text', admin: { position: 'sidebar' } },
185
- // Stripe product for this tier/category (created on first checkout; prices are set per member).
186
- { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
311
+ stripeProductField(managerField),
187
312
  ],
188
313
  timestamps: true,
189
314
  };
@@ -203,7 +328,7 @@ export function membershipsCollection(o) {
203
328
  description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
204
329
  },
205
330
  // Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
206
- access: { read: ownOrManager, create: nobody, update, delete: remove },
331
+ access: { read: ownOrManager, readVersions: managersReadVersions(o, o.memberships), create: nobody, update, delete: remove },
207
332
  fields: [
208
333
  { name: 'label', type: 'text', access: LOCKED, admin: { readOnly: true } },
209
334
  { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, access: LOCKED, admin: { readOnly: true } },
@@ -218,6 +343,7 @@ export function membershipsCollection(o) {
218
343
  defaultValue: 'pending',
219
344
  index: true,
220
345
  access: LOCKED,
346
+ hooks: fresh('pending'),
221
347
  options: ['pending', 'incomplete', 'active', 'past_due', 'canceled'].map((v) => ({ label: v.replace('_', ' '), value: v })),
222
348
  admin: { width: '33%', readOnly: true },
223
349
  },
@@ -265,10 +391,10 @@ export function membershipsCollection(o) {
265
391
  {
266
392
  type: 'row',
267
393
  fields: [
268
- { name: 'startedAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
269
- { name: 'currentPeriodEnd', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
270
- { name: 'cancelAtPeriodEnd', type: 'checkbox', access: LOCKED, admin: { width: '25%', readOnly: true } },
271
- { name: 'canceledAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
394
+ { name: 'startedAt', type: 'date', access: LOCKED, hooks: fresh(), admin: { width: '25%', readOnly: true } },
395
+ { name: 'currentPeriodEnd', type: 'date', access: LOCKED, hooks: fresh(), admin: { width: '25%', readOnly: true } },
396
+ { name: 'cancelAtPeriodEnd', type: 'checkbox', access: LOCKED, hooks: fresh(false), admin: { width: '25%', readOnly: true } },
397
+ { name: 'canceledAt', type: 'date', access: LOCKED, hooks: fresh(), admin: { width: '25%', readOnly: true } },
272
398
  ],
273
399
  },
274
400
  {
@@ -277,8 +403,8 @@ export function membershipsCollection(o) {
277
403
  type: 'group',
278
404
  admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
279
405
  fields: [
280
- { name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false, access: { update: wallShow(o) } },
281
- { name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80, access: { update: memberOnly } },
406
+ { name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false, access: { update: wallShow(o) }, hooks: fresh(false) },
407
+ { name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80, access: { update: memberOnly }, hooks: fresh() },
282
408
  ],
283
409
  },
284
410
  // Stripe references: managers only, never in public responses.
@@ -288,12 +414,12 @@ export function membershipsCollection(o) {
288
414
  access: { read: managerField, create: LOCKED.update, update: LOCKED.update },
289
415
  admin: { position: 'sidebar', readOnly: true },
290
416
  fields: [
291
- { name: 'customer', type: 'text', index: true },
292
- { name: 'subscription', type: 'text', index: true },
293
- { name: 'checkoutSession', type: 'text', index: true },
417
+ { name: 'customer', type: 'text', index: true, hooks: fresh() },
418
+ { name: 'subscription', type: 'text', index: true, hooks: fresh() },
419
+ { name: 'checkoutSession', type: 'text', index: true, hooks: fresh() },
294
420
  ],
295
421
  },
296
- { name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, admin: { position: 'sidebar' } },
422
+ { name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, hooks: fresh(), admin: { position: 'sidebar' } },
297
423
  ],
298
424
  timestamps: true,
299
425
  };
@@ -305,7 +431,7 @@ export function paymentsCollection(o) {
305
431
  slug: o.payments,
306
432
  labels: { singular: 'Membership payment', plural: 'Membership payments' },
307
433
  admin: { useAsTitle: 'invoiceId', defaultColumns: ['membership', 'amount', 'currency', 'paidAt'], description: 'Every paid invoice, recorded once from Stripe.' },
308
- access: { read: ownOrManager, create: () => false, update: () => false, delete: remove },
434
+ access: { read: ownOrManager, readVersions: managersReadVersions(o, o.payments, viaMembership), create: () => false, update: () => false, delete: remove },
309
435
  fields: [
310
436
  { name: 'membership', type: 'relationship', relationTo: o.memberships, required: true, index: true },
311
437
  { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true },
@@ -0,0 +1,21 @@
1
+ import type { CollectionBeforeOperationHook, CollectionConfig, Field, PayloadRequest } from 'payload';
2
+ import type { ResolvedMembership } from './types.js';
3
+ export declare const BAD_KEY_MESSAGE = "Field names in a save can\u2019t start with a dollar sign or contain a dot. Send each field by its plain name.";
4
+ /**
5
+ * Throws when any key in a save's data isn't a plain field name. Values of rich text and JSON fields are their own documents and are left alone; anything
6
+ * the plugin can't place against the field config is checked all the way down.
7
+ */
8
+ export declare function refuseBadKeys(data: unknown, fields: Field[] | null | undefined, req: PayloadRequest, depth?: number): void;
9
+ /**
10
+ * Added at the front of the collection's `beforeOperation` hooks after the host's overrides, so it
11
+ * sees the data as the request sent it, ahead of the collection's other hooks. A plugin that runs
12
+ * after this one can still add a hook in front of it.
13
+ *
14
+ * - Create, update and duplicate, for every caller (server code with `overrideAccess` too): refuses
15
+ * keys that aren't plain field names.
16
+ * - Restoring a version, for callers held to access rules: a manager limited to a scope may only
17
+ * restore a version that is itself inside their scope. A version that can't be read is refused.
18
+ */
19
+ export declare function writeGuard(o: ResolvedMembership): CollectionBeforeOperationHook;
20
+ /** Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's overrides. */
21
+ export declare function guarded(o: ResolvedMembership, c: CollectionConfig): CollectionConfig;
package/dist/guard.js ADDED
@@ -0,0 +1,121 @@
1
+ import { APIError } from 'payload';
2
+ import { managerScope, matchesWhere } from './access.js';
3
+ /** How deep a write's data may nest before it is refused outright (fail closed). */
4
+ const MAX_DEPTH = 32;
5
+ export const BAD_KEY_MESSAGE = 'Field names in a save can’t start with a dollar sign or contain a dot. Send each field by its plain name.';
6
+ /** A key that isn't a plain field name: a leading dollar sign, a dot or a NUL. */
7
+ const badKey = (k) => k.startsWith('$') || k.includes('.') || k.includes('\u0000');
8
+ /** The fields that store data at this level, looking through rows, collapsibles and unnamed tabs. */
9
+ function named(fields) {
10
+ const out = new Map();
11
+ const walk = (list) => {
12
+ for (const f of (list ?? [])) {
13
+ if (f.type === 'tabs') {
14
+ for (const t of f.tabs ?? []) {
15
+ if (t.name)
16
+ out.set(t.name, { ...t, type: 'group' });
17
+ else
18
+ walk(t.fields);
19
+ }
20
+ }
21
+ else if ((f.type === 'row' || f.type === 'collapsible' || (f.type === 'group' && !f.name)) && f.fields)
22
+ walk(f.fields);
23
+ else if (f.name)
24
+ out.set(f.name, f);
25
+ }
26
+ };
27
+ walk(fields);
28
+ return out;
29
+ }
30
+ /**
31
+ * Throws when any key in a save's data isn't a plain field name. Values of rich text and JSON fields are their own documents and are left alone; anything
32
+ * the plugin can't place against the field config is checked all the way down.
33
+ */
34
+ export function refuseBadKeys(data, fields, req, depth = 0) {
35
+ if (depth > MAX_DEPTH)
36
+ throw new APIError(BAD_KEY_MESSAGE, 400, undefined, true);
37
+ if (Array.isArray(data)) {
38
+ for (const item of data)
39
+ refuseBadKeys(item, fields, req, depth + 1);
40
+ return;
41
+ }
42
+ if (!data || typeof data !== 'object')
43
+ return;
44
+ const known = fields ? named(fields) : null;
45
+ const locales = req.payload.config.localization ? req.payload.config.localization.localeCodes : [];
46
+ for (const [k, v] of Object.entries(data)) {
47
+ if (badKey(k))
48
+ throw new APIError(BAD_KEY_MESSAGE, 400, undefined, true);
49
+ const field = known?.get(k);
50
+ if (!field) {
51
+ refuseBadKeys(v, null, req, depth + 1);
52
+ continue;
53
+ }
54
+ checkFieldValue(field, v, req, depth + 1, locales);
55
+ }
56
+ }
57
+ function checkFieldValue(field, v, req, depth, locales) {
58
+ if (field.type === 'json' || field.type === 'richText')
59
+ return;
60
+ // With every locale at once, a localized field holds one value per locale code.
61
+ if (field.localized && v && typeof v === 'object' && !Array.isArray(v) && locales.length && Object.keys(v).length && Object.keys(v).every((k) => locales.includes(k))) {
62
+ for (const each of Object.values(v))
63
+ checkFieldValue({ ...field, localized: false }, each, req, depth + 1, locales);
64
+ return;
65
+ }
66
+ if (field.type === 'group')
67
+ return refuseBadKeys(v, field.fields, req, depth);
68
+ if (field.type === 'array')
69
+ return refuseBadKeys(v, field.fields, req, depth);
70
+ if (field.type === 'blocks' && Array.isArray(v)) {
71
+ for (const row of v) {
72
+ const type = row && typeof row === 'object' ? row.blockType : undefined;
73
+ const blocks = [...(field.blocks ?? []), ...(field.blockReferences ?? []).map((b) => (typeof b === 'string' ? req.payload.config.blocks?.find((x) => x.slug === b) : b))];
74
+ const block = blocks.find((b) => b && b.slug === type);
75
+ refuseBadKeys(row, block ? block.fields : null, req, depth + 1);
76
+ }
77
+ return;
78
+ }
79
+ refuseBadKeys(v, null, req, depth);
80
+ }
81
+ /**
82
+ * Added at the front of the collection's `beforeOperation` hooks after the host's overrides, so it
83
+ * sees the data as the request sent it, ahead of the collection's other hooks. A plugin that runs
84
+ * after this one can still add a hook in front of it.
85
+ *
86
+ * - Create, update and duplicate, for every caller (server code with `overrideAccess` too): refuses
87
+ * keys that aren't plain field names.
88
+ * - Restoring a version, for callers held to access rules: a manager limited to a scope may only
89
+ * restore a version that is itself inside their scope. A version that can't be read is refused.
90
+ */
91
+ export function writeGuard(o) {
92
+ return async ({ args, collection, operation, overrideAccess, req }) => {
93
+ const a = args;
94
+ // Every caller, server code included: the Local API overrides access by default, so a host that
95
+ // passes a request body straight to it gets the same check.
96
+ if (operation === 'create' || operation === 'update') {
97
+ refuseBadKeys(a.data, collection.fields, req);
98
+ return args;
99
+ }
100
+ if (operation === 'restoreVersion' && !overrideAccess) {
101
+ const scope = await managerScope(o, req);
102
+ if (scope === true || !scope)
103
+ return args; // no scope at all is refused by update access
104
+ let version;
105
+ try {
106
+ const { docs } = await req.payload.db.findVersions({ collection: collection.slug, limit: 1, locale: 'all', pagination: false, req, where: { id: { equals: a.id } } });
107
+ version = docs[0]?.version;
108
+ }
109
+ catch {
110
+ version = undefined;
111
+ }
112
+ if (!version || !matchesWhere(scope, version))
113
+ throw new APIError('This version belongs outside what you manage, so it can’t be restored here.', 403, undefined, true);
114
+ }
115
+ return args;
116
+ };
117
+ }
118
+ /** Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's overrides. */
119
+ export function guarded(o, c) {
120
+ return { ...c, hooks: { ...c.hooks, beforeOperation: [writeGuard(o), ...(c.hooks?.beforeOperation ?? [])] } };
121
+ }
package/dist/plugin.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import Stripe from 'stripe';
2
2
  import { categoriesCollection, membershipsCollection, paymentsCollection, tiersCollection } from './collections.js';
3
+ import { guarded } from './guard.js';
3
4
  import { cancelEndpoint, changeEndpoint, checkoutEndpoint, portalEndpoint, wallEndpoint, webhookEndpoint } from './endpoints.js';
4
5
  /**
5
6
  * Memberships: fixed tiers (Patreon-style) and/or pledges where members pick
@@ -26,7 +27,14 @@ export const membershipPlugin = (options = {}) => (config) => {
26
27
  onPayment: options.onPayment,
27
28
  onStatusChange: options.onStatusChange,
28
29
  };
29
- const apply = (c, f) => (f ? f(c) : c);
30
+ // The write guard goes on after the host's overrides, whatever they change. So does the rule for
31
+ // reading saved versions, since overrides can turn versions on or rebuild `access`. A host that
32
+ // sets `readVersions` itself keeps it.
33
+ const apply = (c, f) => {
34
+ const out = f ? f(c) : c;
35
+ const readVersions = out.access?.readVersions ?? c.access.readVersions;
36
+ return guarded(o, { ...out, access: { ...out.access, readVersions } });
37
+ };
30
38
  const memberships = membershipsCollection(o);
31
39
  memberships.endpoints = [checkoutEndpoint, webhookEndpoint, changeEndpoint, cancelEndpoint, portalEndpoint, wallEndpoint];
32
40
  return {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
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": {
@@ -38,7 +38,7 @@
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
41
- "node": ">=20.9"
41
+ "node": "^22.23.5 || ^24.22.3 || >=26.13.1"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "rm -rf dist && tsc -p tsconfig.build.json",
@@ -51,15 +51,16 @@
51
51
  "stripe": "^23.1.0"
52
52
  },
53
53
  "peerDependencies": {
54
- "payload": "^3.80.0"
54
+ "payload": "^3.94.2"
55
55
  },
56
56
  "devDependencies": {
57
- "@payloadcms/db-mongodb": "3.92.1",
58
- "@payloadcms/plugin-multi-tenant": "3.92.1",
57
+ "@payloadcms/db-mongodb": "3.94.2",
58
+ "@payloadcms/graphql": "3.94.2",
59
+ "@payloadcms/plugin-multi-tenant": "3.94.2",
59
60
  "@types/node": "^24.0.0",
60
61
  "graphql": "^16.14.2",
61
62
  "mongodb-memory-server": "^11.3.0",
62
- "payload": "3.92.1",
63
+ "payload": "3.94.2",
63
64
  "typescript": "^5.9.0",
64
65
  "vitest": "^5.1.0"
65
66
  }