@extantape/payload-plugin-membership 0.1.3 → 0.3.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
@@ -20,7 +20,7 @@ Patreon, or let members support **categories** with **their own amount** — or
20
20
 
21
21
  ## On its own, and with others
22
22
 
23
- **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 Captive Origins plugin. Perks, votes and credits are whatever your own `onPayment` and `onStatusChange` do.
23
+ **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.
24
24
 
25
25
  **Works with:**
26
26
 
@@ -32,6 +32,8 @@ Patreon, or let members support **categories** with **their own amount** — or
32
32
 
33
33
  ## Install
34
34
 
35
+ Requires Payload 3.94.2 or later.
36
+
35
37
  ```bash
36
38
  npm install @extantape/payload-plugin-membership
37
39
  ```
@@ -65,7 +67,7 @@ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-we
65
67
  | `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
66
68
  | `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
67
69
  | `POST /api/memberships/:id/portal` | `{ returnPath? }` | `{ url }` of Stripe's customer portal |
68
- | `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice |
70
+ | `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice. A manager may only send `show: false` |
69
71
 
70
72
  Amounts are in cents. Server code can call `startCheckout`, `changeMembership`, `cancelMembership`,
71
73
  `portalLink`, `myMembership` and `getBackers` directly.
@@ -76,7 +78,7 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
76
78
  |---|---|---|
77
79
  | `slugs` | `membership-tiers`, `membership-categories`, `memberships`, `membership-payments` | |
78
80
  | `users` | `admin.user` | The members' auth collection |
79
- | `canManage` | nobody | Who manages tiers, categories and memberships in the admin. Only `true` counts: see [Access](#access) |
81
+ | `canManage` | nobody | Who manages tiers, categories and memberships in the admin: `true`, or a `Where` for one site's rows. See [Access](#access) |
80
82
  | `canCheckout` | always | E.g. off in development. Only `true` allows a checkout |
81
83
  | `stripeSecretKey` / `stripe` | | Key, or a ready client (tests) |
82
84
  | `webhookSecret` | | Signing secret of the webhook endpoint |
@@ -89,30 +91,148 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
89
91
 
90
92
  ## Access
91
93
 
92
- `canManage` decides everything a manager can do, and only an answer of exactly `true` counts.
93
- Anything else is a no: `false`, `1`, `'yes'`, an object, or an error thrown or rejected. An error
94
- doesn't escape as a 500; the request is refused. Nobody who isn't signed in is a manager, whatever
95
- `canManage` says.
94
+ `canManage` decides everything a manager can do. It gets `{ req }` and answers one of three things:
95
+
96
+ - `true`: a manager of every row.
97
+ - A `Where`, such as `{ tenant: { equals: siteId } }`: a manager of only the rows it matches. Write it
98
+ against the memberships collection and the `scopeField` of tiers and categories. For payments the
99
+ plugin applies it through each payment's `membership`.
100
+ - Anything else is no: `false`, `null`, `0`, `''`, `1`, `'yes'`, an array, an empty `{}` or `{ and: [] }`,
101
+ a field with no operator, an operator Payload doesn't have or the plugin doesn't take (a typo such as
102
+ `equal` included), a value that would match every row (`like: ''`, `contains: ''`, `not_in: []`,
103
+ `all: []`), a query that doesn't run against the memberships collection (an unknown field), or an
104
+ error thrown or rejected. The request is refused cleanly, never a 500. An empty `{}` would match
105
+ every row, so it is a no. Return `true` to mean all. The accepted operators are `equals`,
106
+ `not_equals`, `in`, `not_in`, `all`, `exists`, `greater_than`, `greater_than_equal`, `less_than`,
107
+ `less_than_equal`, `like` and `contains`. `in: []` is accepted and matches nothing.
108
+
109
+ Nobody who isn't signed in is a manager, whatever `canManage` says.
110
+
111
+ ```ts
112
+ canManage: ({ req }) => {
113
+ const user = req.user as { role?: string; site?: string } | null
114
+ if (user?.role === 'admin') return true
115
+ if (user?.role === 'manager' && user.site) return { site: { equals: user.site } }
116
+ return false
117
+ }
118
+ ```
119
+
120
+ A manager limited by a `Where` reaches only the matching memberships, payments, tiers and categories:
121
+ list, read, edit, delete, REST and GraphQL alike, and the endpoints below. A new tier or category
122
+ must match the `Where` in its own data. The plugin checks `equals`, `not_equals`, `in`, `not_in`,
123
+ `exists`, `and` and `or` there; any other operator is a no for a create. An update that names a
124
+ field your `Where` uses is checked the same way, on the stored row with the new data merged over it, so
125
+ a limited manager can't move a row out of their scope or into another one. An update that leaves those
126
+ fields alone isn't checked again.
127
+
128
+ `notes`, `stripe` and `stripeProduct` are judged row by row with the same answer, so a manager of
129
+ site A never reads site B's notes or Stripe ids, even in a list that includes site B's rows (for
130
+ example a membership they hold as a member there).
96
131
 
97
132
  | Where | A manager | A signed-in member | Signed out |
98
133
  |---|---|---|---|
99
- | Tiers, categories | Reads, creates, edits, deletes | Reads | Reads |
100
- | Their `stripeProduct` (field) | Reads and writes | Never sees it | Never sees it |
101
- | Memberships | Reads all, edits, deletes | Reads their own | Nothing |
102
- | A membership's `stripe` and `notes` (fields) | Reads and writes | Never sees them | Nothing |
103
- | Payments | Reads all, deletes | Reads their own | Nothing |
104
- | `change`, `cancel`, `portal`, `wall` endpoints | Any membership on their site | Their own | 404 |
134
+ | Tiers, categories | Reads; creates, edits, deletes within their scope | Reads | Reads |
135
+ | Their `stripeProduct` (field) | Reads within their scope; never writes | Never sees it | Never sees it |
136
+ | Memberships | Reads and edits within their scope, deletes within their scope | Reads their own | Nothing |
137
+ | A membership's `stripe` and `notes` (fields) | Reads and writes within their scope | Never sees them | Nothing |
138
+ | Payments | Reads and deletes within their scope | Reads their own | Nothing |
139
+ | `cancel` endpoint | A membership within their scope, on this request's site | Their own | 404 |
140
+ | `wall` endpoint | Only to hide (`show: false`), within their scope | Their own, show and name | 404 |
141
+ | `change`, `portal` endpoints | Never | Their own | 404 |
142
+
143
+ Only the member changes their own plan, opens their own Stripe billing portal, shows themselves on the
144
+ backers wall or sets the wall name. A manager, even one who manages everything, gets a 404 on `change`
145
+ and `portal`, and may only hide a wall entry (`show: false`, for an offensive name or a takedown
146
+ request). Managers keep `cancel`. (Decided 2026-11-23.)
147
+
148
+ This is enforced in field access too, not just in the endpoints, so editing a membership through
149
+ Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
150
+ `kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
151
+ `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
152
+ Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
153
+ set a category's `parent` only to a category in their scope. That is judged on the parent the row
154
+ ends up with, whether the save is a create, an update, a duplicate (which keeps the original's parent
155
+ unless the data changes it) or a restore. A save whose final parent is outside their scope is refused
156
+ with a message saying so; clear the parent or choose one they manage. If you localize `parent` through
157
+ `overrides`, every locale's parent counts: a save in one locale is refused while another locale's
158
+ parent is outside their scope, until that locale's parent is cleared or moved.
159
+
160
+ Saves to the plugin's collections send each field by its plain name, with nested fields as nested
161
+ objects. A field name that starts with a dollar sign or contains a dot is refused (400) on every save,
162
+ through any API, bulk updates, drafts and duplicates included, and from your server code with
163
+ `overrideAccess` too, since the Local API overrides access by default. The values of JSON and rich
164
+ text fields are left alone. The plugin puts this check at the front of each collection's
165
+ `beforeOperation` hooks, after your `overrides`. A plugin that runs after this one can still add its
166
+ own hook in front of it, so that hook sees the data before the check does.
167
+
168
+ A manager limited by a `Where` may restore a version of a tier, category or membership only when the
169
+ version itself matches their `Where`. A version that can't be read is refused. (Restoring a
170
+ membership by anyone other than server code fails validation, as it did before, because the fields
171
+ managers can't write aren't refilled on restore.)
172
+
173
+ If you turn on drafts for tiers or categories through `overrides`, people who aren't managers read
174
+ only published rows (and rows saved before drafts were on). A limited manager also reads drafts in
175
+ their scope, and a manager of every row reads all of them.
176
+
177
+ Saved versions are for managers only: the `versions` routes in REST, the version queries in GraphQL,
178
+ and `findVersions` and `findVersionByID` in the Local API with access on. Members and signed-out
179
+ visitors get none, and a limited manager gets only the versions that match their `Where`. This covers
180
+ all four collections, versions you turn on through `overrides` included. If your `overrides` set
181
+ `access.readVersions`, your rule is used. If they replace `access` without one, the plugin's rule is
182
+ put back, so these collections always have a rule for versions.
183
+
184
+ A server-side duplicate of a membership starts as `pending`, without Stripe ids, period dates,
185
+ `canceledAt` or `cancelAtPeriodEnd`. It also starts without the staff `notes` and off the backers
186
+ wall (`wall.show` false, no `wall.name`). Server code that wants any of these on the copy passes them
187
+ in `data`.
188
+
189
+ `stripeProduct` on tiers and categories is set only by server code (`overrideAccess`): the plugin
190
+ stores it at a row's first checkout, and your own server code (a seed or an import) may set it on
191
+ create or update. A create or update that doesn't override access ignores it. It belongs to one row,
192
+ so a duplicate starts without it, in every locale, and gets its own at its first checkout. That
193
+ includes a duplicate made by your server code. To give a copy a particular value, pass `stripeProduct`
194
+ in the `data` of a duplicate that overrides access.
105
195
 
106
196
  Nobody creates memberships or payments directly: checkout and Stripe do. The member endpoints answer
107
197
  404, not 403, to anyone who may not use them, so they don't say whether a membership exists.
108
198
 
109
199
  Memberships' and payments' read access returns a query for members: the plugin's own "your rows"
110
- filter. What `canManage` returns is never passed to Payload, so an object that looks like a query
111
- can't widen it to every row. `canCheckout` follows the same rule: only `true` lets a checkout start,
112
- and anything else, an error included, refuses it with "Memberships are not available here yet."
113
- (503).
114
-
115
- `overrides` can change a collection's `access`; if you do, your rules replace these.
200
+ filter. A manager's query comes only from `canManage`, and only when it passes the checks above.
201
+ `canCheckout` follows the exact-`true` rule: only `true` lets a checkout start, and anything else,
202
+ an error included, refuses it with "Memberships are not available here yet." (503).
203
+
204
+ Upgrading: a `canManage` that returned `true` or `false` works as before. One that returned an object
205
+ (it was a no) now has that object used as a query, so return `false` if you meant no.
206
+
207
+ Upgrading, `stripeProduct`: if anything other than server code writes it (the REST or GraphQL API, or
208
+ the Local API with `overrideAccess: false`), move that write to server code with `overrideAccess`,
209
+ after your own permission check. If your server code duplicates a tier or category and expects the
210
+ copy to keep the value, pass it in `data`. Rows saved earlier keep what they hold, and checkout uses
211
+ it, so check them: each value should be used by one row only, and a product the plugin created names
212
+ its row in its Stripe metadata (`payloadCollection`, `payloadId`). Where a value belongs to another
213
+ row, set it to `null` from server code (in each locale, if you localize the field). The next checkout
214
+ creates the row's own product.
215
+
216
+ Upgrading from 0.2.0, checks to run once from server code:
217
+
218
+ 1. Stored products. For each tier and category with a `stripeProduct`, clear it (set `null` with
219
+ `overrideAccess`, in each locale if you localize the field) when more than one row holds the same
220
+ value, or when the product's Stripe metadata `payloadCollection` and `payloadId` don't name this
221
+ collection and this row's id. Clear every row that shares a value, the first one too. The next
222
+ checkout makes each row its own product. Running it again should find nothing.
223
+ 2. Parent categories. If you use a `Where` for managers, list categories whose `parent` is outside the
224
+ category's own scope (on another site). If you localize `parent`, check it in each locale. A limited
225
+ manager can't save such a category until its parent is cleared or moved into their scope, so fix
226
+ these from server code or as a manager of every row.
227
+
228
+ This version requires Payload 3.94.2 or later (peer range `^3.94.2`). Upgrade Payload before you
229
+ install it.
230
+
231
+ Saves to these collections, from your front end, scripts and server code alike, must use plain field
232
+ names (no leading dollar sign, no dots). Nested fields go as nested objects.
233
+
234
+ `overrides` can change a collection's `access`; if you do, your rules replace these, except that a
235
+ collection whose `access` has no `readVersions` keeps the plugin's.
116
236
 
117
237
  ## License
118
238
 
package/dist/access.d.ts CHANGED
@@ -1,8 +1,39 @@
1
- import type { Payload, PayloadRequest } from 'payload';
1
+ import type { Payload, PayloadRequest, Where } from 'payload';
2
2
  import type { ResolvedMembership } from './types.js';
3
3
  /** Only an answer of exactly `true` passes; anything else, a thrown error included, is no. */
4
4
  export declare function exactlyTrue(check: () => unknown): Promise<boolean>;
5
- /** A signed-in manager: `canManage` answered exactly `true` (a truthy value or an error is a no). */
6
- export declare const isManager: (o: Pick<ResolvedMembership, "canManage">, req: PayloadRequest) => Promise<boolean>;
5
+ /**
6
+ * A usable query: a plain object with at least one key, where `and`/`or` hold non-empty lists of
7
+ * usable queries and every field key holds a non-empty plain object of known operators with
8
+ * sensible values. `{}` matches every row, so it is not usable: a host that means "all" returns `true`.
9
+ */
10
+ export declare function usableWhere(w: unknown, depth?: number): w is Where;
11
+ /**
12
+ * What a manager may reach: `true` (everything), a query (only the rows it matches), or `null` (nothing).
13
+ * Only an exact `true` or a usable query counts, and a query must also run against the memberships
14
+ * collection (an unknown field makes it a no). Everything else, a throw or rejection included,
15
+ * and anyone not signed in, is `null`.
16
+ */
17
+ export type ManagerScope = true | Where | null;
18
+ export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<ManagerScope>;
19
+ /** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
20
+ export declare function isManager(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<boolean>;
21
+ /** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
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;
28
+ /**
29
+ * Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
30
+ * `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
31
+ */
32
+ export declare function matchesWhere(where: Where, data: Record<string, unknown> | undefined): boolean;
33
+ /**
34
+ * Whether this manager may reach one row: `true` always, a query only when it matches that row
35
+ * (checked against the database), nobody else. The answer is kept for the request.
36
+ */
37
+ export declare function managerReaches(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, collection: string, id: unknown, via?: (w: Where) => Where): Promise<boolean>;
7
38
  /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
8
39
  export declare const checkoutAllowed: (o: Pick<ResolvedMembership, "canCheckout">, payload: Payload) => Promise<boolean>;
package/dist/access.js CHANGED
@@ -7,7 +7,176 @@ export async function exactlyTrue(check) {
7
7
  return false;
8
8
  }
9
9
  }
10
- /** A signed-in manager: `canManage` answered exactly `true` (a truthy value or an error is a no). */
11
- export const isManager = (o, req) => req.user ? exactlyTrue(() => o.canManage({ req })) : Promise.resolve(false);
10
+ const isPlain = (v) => {
11
+ if (!v || typeof v !== 'object' || Array.isArray(v))
12
+ return false;
13
+ const proto = Object.getPrototypeOf(v);
14
+ return proto === Object.prototype || proto === null;
15
+ };
16
+ const scalar = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v);
17
+ const scalars = (v, minimum) => Array.isArray(v) && v.length >= minimum && v.every(scalar);
18
+ const nonEmptyText = (v) => typeof v === 'string' && v.length > 0;
19
+ const number = (v) => typeof v === 'number' || typeof v === 'string';
20
+ /**
21
+ * The operators the plugin accepts, each with a check on its value. An unknown operator (a typo
22
+ * such as `equal`) is refused rather than ignored, because Payload ignores some unknown operators
23
+ * on writes. Values that would match every row, such as an empty `like` or an empty `not_in`, are refused.
24
+ */
25
+ const OPERATORS = {
26
+ equals: scalar,
27
+ not_equals: scalar,
28
+ in: (v) => scalars(v, 0), // an empty list matches nothing
29
+ not_in: (v) => scalars(v, 1),
30
+ all: (v) => scalars(v, 1),
31
+ exists: (v) => typeof v === 'boolean',
32
+ greater_than: number,
33
+ greater_than_equal: number,
34
+ less_than: number,
35
+ less_than_equal: number,
36
+ like: nonEmptyText,
37
+ contains: nonEmptyText,
38
+ };
39
+ /**
40
+ * A usable query: a plain object with at least one key, where `and`/`or` hold non-empty lists of
41
+ * usable queries and every field key holds a non-empty plain object of known operators with
42
+ * sensible values. `{}` matches every row, so it is not usable: a host that means "all" returns `true`.
43
+ */
44
+ export function usableWhere(w, depth = 0) {
45
+ if (!isPlain(w) || depth > 8)
46
+ return false;
47
+ const keys = Object.keys(w);
48
+ if (!keys.length)
49
+ return false;
50
+ return keys.every((k) => {
51
+ const v = w[k];
52
+ if (k === 'and' || k === 'or')
53
+ return Array.isArray(v) && v.length > 0 && v.every((x) => usableWhere(x, depth + 1));
54
+ if (!isPlain(v))
55
+ return false;
56
+ const ops = Object.entries(v);
57
+ return ops.length > 0 && ops.every(([op, arg]) => Object.hasOwn(OPERATORS, op) && OPERATORS[op](arg));
58
+ });
59
+ }
60
+ export async function managerScope(o, req) {
61
+ if (!req.user)
62
+ return null;
63
+ try {
64
+ const answer = await o.canManage({ req });
65
+ if (answer === true)
66
+ return true;
67
+ if (!usableWhere(answer))
68
+ return null;
69
+ 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;
76
+ }
77
+ catch {
78
+ ok = false;
79
+ }
80
+ checked.set(key, ok);
81
+ }
82
+ return ok ? answer : null;
83
+ }
84
+ catch {
85
+ return null;
86
+ }
87
+ }
88
+ /** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
89
+ export async function isManager(o, req) {
90
+ return (await managerScope(o, req)) !== null;
91
+ }
92
+ /** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
93
+ export function viaMembership(where) {
94
+ const out = {};
95
+ for (const [k, v] of Object.entries(where)) {
96
+ if (k === 'and' || k === 'or')
97
+ out[k] = v.map(viaMembership);
98
+ else
99
+ out[k === 'id' ? 'membership' : `membership.${k}`] = v;
100
+ }
101
+ return out;
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
+ }
117
+ const idOf = (v) => (v && typeof v === 'object' && 'id' in v ? v.id : v);
118
+ const same = (a, b) => a != null && b != null && String(idOf(a)) === String(idOf(b));
119
+ /**
120
+ * Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
121
+ * `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
122
+ */
123
+ export function matchesWhere(where, data) {
124
+ if (!data)
125
+ return false;
126
+ return Object.entries(where).every(([k, v]) => {
127
+ if (k === 'and')
128
+ return v.every((x) => matchesWhere(x, data));
129
+ if (k === 'or')
130
+ return v.some((x) => matchesWhere(x, data));
131
+ const value = data[k];
132
+ return Object.entries(v).every(([op, arg]) => {
133
+ switch (op) {
134
+ case 'equals':
135
+ return same(value, arg);
136
+ case 'not_equals':
137
+ return value != null && !same(value, arg);
138
+ case 'in':
139
+ return Array.isArray(arg) && arg.some((a) => same(value, a));
140
+ case 'not_in':
141
+ return value != null && Array.isArray(arg) && !arg.some((a) => same(value, a));
142
+ case 'exists':
143
+ return (value != null) === Boolean(arg);
144
+ default:
145
+ return false;
146
+ }
147
+ });
148
+ });
149
+ }
150
+ /**
151
+ * Whether this manager may reach one row: `true` always, a query only when it matches that row
152
+ * (checked against the database), nobody else. The answer is kept for the request.
153
+ */
154
+ export async function managerReaches(o, req, collection, id, via = (w) => w) {
155
+ const scope = await managerScope(o, req);
156
+ if (scope === true)
157
+ return true;
158
+ if (!scope || id == null || id === '')
159
+ return false;
160
+ const cache = (req.context.membershipReach ??= new Map());
161
+ const key = `${collection}:${String(id)}:${JSON.stringify(scope)}`;
162
+ const known = cache.get(key);
163
+ if (known !== undefined)
164
+ return known;
165
+ let reached = false;
166
+ try {
167
+ const found = await req.payload.count({
168
+ collection: collection,
169
+ where: { and: [{ id: { equals: id } }, via(scope)] },
170
+ overrideAccess: true,
171
+ req,
172
+ });
173
+ reached = found.totalDocs > 0;
174
+ }
175
+ catch {
176
+ reached = false;
177
+ }
178
+ cache.set(key, reached);
179
+ return reached;
180
+ }
12
181
  /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
13
182
  export const checkoutAllowed = (o, payload) => o.canCheckout ? exactlyTrue(() => o.canCheckout({ payload })) : Promise.resolve(true);
package/dist/api.d.ts CHANGED
@@ -51,7 +51,7 @@ export type BackerGroup<T> = {
51
51
  /**
52
52
  * The backers wall: active members who chose to be shown, under their tier or
53
53
  * under each category they support, A–Z within each (user decision for
54
- * Captive Origins). Groups follow the admin's (drag-and-drop) order.
54
+ * the original site). Groups follow the admin's (drag-and-drop) order.
55
55
  */
56
56
  export declare function getBackers(payload: Payload, opts?: {
57
57
  scope?: string | null;
package/dist/api.js CHANGED
@@ -280,7 +280,7 @@ export async function handleStripeEvent(payload, event) {
280
280
  /**
281
281
  * The backers wall: active members who chose to be shown, under their tier or
282
282
  * under each category they support, A–Z within each (user decision for
283
- * Captive Origins). Groups follow the admin's (drag-and-drop) order.
283
+ * the original site). Groups follow the admin's (drag-and-drop) order.
284
284
  */
285
285
  export async function getBackers(payload, opts = {}) {
286
286
  const o = membershipOf(payload);
@@ -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 { isManager } 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 }) => {
@@ -28,11 +29,228 @@ const placeAlphabetically = (o, slug, field) => async ({ data, operation, req })
28
29
  }
29
30
  return data;
30
31
  };
32
+ /** No write through the API for anyone: only the plugin's own server code (with overrideAccess) changes these. */
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] });
48
+ /** Only the member whose row it is. */
49
+ const memberOnly = ({ req, doc }) => Boolean(req.user) && String(idOf(doc?.user)) === String(req.user.id);
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. */
51
+ const wallShow = (o) => async (args) => {
52
+ if (await memberOnly(args))
53
+ return true;
54
+ if (args.siblingData?.show !== false)
55
+ return false;
56
+ const scope = await managerScope(o, args.req);
57
+ if (scope === true)
58
+ return true;
59
+ const id = args.id ?? args.doc?.id;
60
+ return Boolean(scope) && id != null && managerReaches(o, args.req, o.memberships, id);
61
+ };
62
+ /**
63
+ * Manager access by `canManage`'s answer: `true` is every row, a query is only the rows it matches
64
+ * (`via` rewrites it for a collection that holds the rows indirectly), anything else is no. A new
65
+ * row (`create`) must match the query in its own data.
66
+ */
67
+ function scopedManager(o, via = (w) => w, collection) {
68
+ // An update by a limited manager must leave the row inside their query: the existing row with the
69
+ // incoming data merged over it is matched in memory, so a row can't be moved out of scope or into
70
+ // another site. Nothing to check unless the data touches a field the query names.
71
+ const update = async ({ req, id, data }) => {
72
+ const scope = await managerScope(o, req);
73
+ if (scope === true)
74
+ return true;
75
+ if (!scope)
76
+ return false;
77
+ const where = via(scope);
78
+ if (data && collection && referencedFields(scope).some((k) => k in data)) {
79
+ let merged = data;
80
+ if (id != null) {
81
+ const existing = await req.payload.findByID({ collection: collection, id, depth: 0, overrideAccess: true, disableErrors: true, req });
82
+ if (!existing)
83
+ return false;
84
+ merged = { ...existing, ...data };
85
+ }
86
+ if (!matchesWhere(scope, merged))
87
+ return false;
88
+ }
89
+ return where;
90
+ };
91
+ const rows = () => async ({ req }) => {
92
+ const scope = await managerScope(o, req);
93
+ return scope === true ? true : scope ? via(scope) : false;
94
+ };
95
+ const create = async ({ req, data }) => {
96
+ const scope = await managerScope(o, req);
97
+ return scope === true || (scope !== null && matchesWhere(scope, data));
98
+ };
99
+ return { create, update: collection ? update : rows(), remove: rows() };
100
+ }
101
+ /** Top-level field names a query mentions. */
102
+ function referencedFields(where) {
103
+ return Object.entries(where).flatMap(([k, v]) => (k === 'and' || k === 'or' ? v.flatMap(referencedFields) : [k.split('.')[0]]));
104
+ }
105
+ /** Managers read what `canManage` reaches and members their own rows; anyone else gets nothing. */
106
+ function ownOrScoped(o, via = (w) => w) {
107
+ return async ({ req }) => {
108
+ if (!req.user)
109
+ return false;
110
+ const own = { user: { equals: req.user.id } };
111
+ const scope = await managerScope(o, req);
112
+ if (scope === true)
113
+ return true;
114
+ return scope ? { or: [via(scope), own] } : own;
115
+ };
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
+ }
156
+ /** A relationship may only be set to a row the manager reaches (nothing to check when it isn't being set). */
157
+ function inScope(o, target) {
158
+ return async ({ req, siblingData, data }) => {
159
+ const sent = siblingData?.parent ?? data?.parent;
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)
234
+ return true;
235
+ return scope ? { or: [published, scope] } : published;
236
+ };
237
+ }
238
+ /** Field access for managers: judged on the particular row, never on a bare yes. */
239
+ function managerFieldOn(o, collection) {
240
+ return async ({ req, id, doc, data }) => {
241
+ const scope = await managerScope(o, req);
242
+ if (scope === true)
243
+ return true;
244
+ if (!scope)
245
+ return false;
246
+ const rowId = id ?? doc?.id;
247
+ return rowId != null ? managerReaches(o, req, collection, rowId) : matchesWhere(scope, data);
248
+ };
249
+ }
31
250
  const money = (name, label, description) => ({ name, label, type: 'number', min: 0, admin: { description: `${description} In cents (e.g. 500 = 5.00).` } });
32
251
  export function tiersCollection(o) {
33
- // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
34
- const manager = ({ req }) => isManager(o, req);
35
- const managerField = ({ req }) => isManager(o, req);
252
+ const { create, update, remove } = scopedManager(o, undefined, o.tiers);
253
+ const managerField = managerFieldOn(o, o.tiers);
36
254
  return {
37
255
  slug: o.tiers,
38
256
  labels: { singular: 'Membership tier', plural: 'Membership tiers' },
@@ -41,7 +259,7 @@ export function tiersCollection(o) {
41
259
  defaultColumns: ['name', 'monthly', 'yearly', 'active'],
42
260
  description: 'Fixed-price levels (Patreon-style). Shown in this order: drag rows to change it.',
43
261
  },
44
- access: { read: () => true, create: manager, update: manager, delete: manager },
262
+ access: { read: publicRead(o, o.tiers), readVersions: managersReadVersions(o, o.tiers), create, update, delete: remove },
45
263
  orderable: true,
46
264
  defaultSort: '_order',
47
265
  hooks: { beforeChange: [placeAlphabetically(o, o.tiers, 'name')] },
@@ -58,16 +276,14 @@ export function tiersCollection(o) {
58
276
  type: 'checkbox',
59
277
  admin: { position: 'sidebar', description: 'A perk your site can act on in onStatusChange (e.g. with payload-plugin-sponsors).' },
60
278
  },
61
- // Stripe product for this tier/category (created on first checkout; prices are set per member).
62
- { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
279
+ stripeProductField(managerField),
63
280
  ],
64
281
  timestamps: true,
65
282
  };
66
283
  }
67
284
  export function categoriesCollection(o) {
68
- // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
69
- const manager = ({ req }) => isManager(o, req);
70
- const managerField = ({ req }) => isManager(o, req);
285
+ const { create, update, remove } = scopedManager(o, undefined, o.categories);
286
+ const managerField = managerFieldOn(o, o.categories);
71
287
  return {
72
288
  slug: o.categories,
73
289
  labels: { singular: 'Membership category', plural: 'Membership categories' },
@@ -76,14 +292,14 @@ export function categoriesCollection(o) {
76
292
  defaultColumns: ['name', 'parent', 'minimum', 'active'],
77
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.',
78
294
  },
79
- access: { read: () => true, create: manager, update: manager, delete: manager },
295
+ access: { read: publicRead(o, o.categories), readVersions: managersReadVersions(o, o.categories), create, update, delete: remove },
80
296
  orderable: true,
81
297
  defaultSort: '_order',
82
298
  hooks: { beforeChange: [placeAlphabetically(o, o.categories, 'name')] },
83
299
  fields: [
84
300
  { name: 'name', type: 'text', required: true },
85
301
  { name: 'active', label: 'Open to new pledges', type: 'checkbox', defaultValue: true, admin: { position: 'sidebar' } },
86
- { name: 'parent', type: 'relationship', relationTo: 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.' } },
87
303
  { name: 'description', type: 'textarea' },
88
304
  money('minimum', 'Minimum per month', 'Smallest monthly amount for this category (yearly: 12×).'),
89
305
  {
@@ -92,24 +308,16 @@ export function categoriesCollection(o) {
92
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).' },
93
309
  },
94
310
  { name: 'color', type: 'text', admin: { position: 'sidebar' } },
95
- // Stripe product for this tier/category (created on first checkout; prices are set per member).
96
- { name: 'stripeProduct', type: 'text', access: { read: managerField, create: managerField, update: managerField }, admin: { position: 'sidebar', readOnly: true } },
311
+ stripeProductField(managerField),
97
312
  ],
98
313
  timestamps: true,
99
314
  };
100
315
  }
101
316
  export function membershipsCollection(o) {
102
- // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
103
- const manager = ({ req }) => isManager(o, req);
104
- const managerField = ({ req }) => isManager(o, req);
105
- // Managers read all; members read their own (the plugin's own query, never the site's answer).
106
- const ownOrManager = async ({ req }) => {
107
- if (!req.user)
108
- return false;
109
- if (await isManager(o, req))
110
- return true;
111
- return { user: { equals: req.user.id } };
112
- };
317
+ const { update, remove } = scopedManager(o, undefined, o.memberships);
318
+ const managerField = managerFieldOn(o, o.memberships);
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);
113
321
  const nobody = () => false;
114
322
  return {
115
323
  slug: o.memberships,
@@ -120,30 +328,33 @@ export function membershipsCollection(o) {
120
328
  description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
121
329
  },
122
330
  // Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
123
- access: { read: ownOrManager, create: nobody, update: manager, delete: manager },
331
+ access: { read: ownOrManager, readVersions: managersReadVersions(o, o.memberships), create: nobody, update, delete: remove },
124
332
  fields: [
125
- { name: 'label', type: 'text', admin: { readOnly: true } },
126
- { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, admin: { readOnly: true } },
333
+ { name: 'label', type: 'text', access: LOCKED, admin: { readOnly: true } },
334
+ { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, access: LOCKED, admin: { readOnly: true } },
127
335
  {
128
336
  type: 'row',
129
337
  fields: [
130
- { name: 'kind', type: 'select', required: true, options: [{ label: 'Tier', value: 'tier' }, { label: 'Pledge to categories', value: 'pledge' }], admin: { width: '33%', readOnly: true } },
338
+ { name: 'kind', type: 'select', required: true, options: [{ label: 'Tier', value: 'tier' }, { label: 'Pledge to categories', value: 'pledge' }], access: LOCKED, admin: { width: '33%', readOnly: true } },
131
339
  {
132
340
  name: 'status',
133
341
  type: 'select',
134
342
  required: true,
135
343
  defaultValue: 'pending',
136
344
  index: true,
345
+ access: LOCKED,
346
+ hooks: fresh('pending'),
137
347
  options: ['pending', 'incomplete', 'active', 'past_due', 'canceled'].map((v) => ({ label: v.replace('_', ' '), value: v })),
138
348
  admin: { width: '33%', readOnly: true },
139
349
  },
140
- { name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], admin: { width: '34%', readOnly: true } },
350
+ { name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], access: LOCKED, admin: { width: '34%', readOnly: true } },
141
351
  ],
142
352
  },
143
- { name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
353
+ { name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, access: LOCKED, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
144
354
  {
145
355
  name: 'pledges',
146
356
  type: 'array',
357
+ access: LOCKED,
147
358
  admin: { readOnly: true, condition: (d) => d?.kind === 'pledge' },
148
359
  fields: [
149
360
  { name: 'category', type: 'relationship', relationTo: o.categories, required: true, index: true },
@@ -153,8 +364,8 @@ export function membershipsCollection(o) {
153
364
  {
154
365
  type: 'row',
155
366
  fields: [
156
- { name: 'amount', type: 'number', required: true, min: 0, admin: { width: '33%', readOnly: true, description: 'Per interval, in cents.' } },
157
- { name: 'currency', type: 'text', required: true, admin: { width: '33%', readOnly: true } },
367
+ { name: 'amount', type: 'number', required: true, min: 0, access: LOCKED, admin: { width: '33%', readOnly: true, description: 'Per interval, in cents.' } },
368
+ { name: 'currency', type: 'text', required: true, access: LOCKED, admin: { width: '33%', readOnly: true } },
158
369
  {
159
370
  name: 'totalPaid',
160
371
  type: 'number',
@@ -180,10 +391,10 @@ export function membershipsCollection(o) {
180
391
  {
181
392
  type: 'row',
182
393
  fields: [
183
- { name: 'startedAt', type: 'date', admin: { width: '25%', readOnly: true } },
184
- { name: 'currentPeriodEnd', type: 'date', admin: { width: '25%', readOnly: true } },
185
- { name: 'cancelAtPeriodEnd', type: 'checkbox', admin: { width: '25%', readOnly: true } },
186
- { name: 'canceledAt', type: 'date', 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 } },
187
398
  ],
188
399
  },
189
400
  {
@@ -192,43 +403,35 @@ export function membershipsCollection(o) {
192
403
  type: 'group',
193
404
  admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
194
405
  fields: [
195
- { name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false },
196
- { name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80 },
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() },
197
408
  ],
198
409
  },
199
410
  // Stripe references: managers only, never in public responses.
200
411
  {
201
412
  name: 'stripe',
202
413
  type: 'group',
203
- access: { read: managerField, create: managerField, update: managerField },
414
+ access: { read: managerField, create: LOCKED.update, update: LOCKED.update },
204
415
  admin: { position: 'sidebar', readOnly: true },
205
416
  fields: [
206
- { name: 'customer', type: 'text', index: true },
207
- { name: 'subscription', type: 'text', index: true },
208
- { 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() },
209
420
  ],
210
421
  },
211
- { 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' } },
212
423
  ],
213
424
  timestamps: true,
214
425
  };
215
426
  }
216
427
  export function paymentsCollection(o) {
217
- // Only an exact `true` from `canManage` makes a manager; a truthy value or a thrown error is a no.
218
- const manager = ({ req }) => isManager(o, req);
219
- // Managers read all; members read their own (the plugin's own query, never the site's answer).
220
- const ownOrManager = async ({ req }) => {
221
- if (!req.user)
222
- return false;
223
- if (await isManager(o, req))
224
- return true;
225
- return { user: { equals: req.user.id } };
226
- };
428
+ const { remove } = scopedManager(o, viaMembership);
429
+ const ownOrManager = ownOrScoped(o, viaMembership);
227
430
  return {
228
431
  slug: o.payments,
229
432
  labels: { singular: 'Membership payment', plural: 'Membership payments' },
230
433
  admin: { useAsTitle: 'invoiceId', defaultColumns: ['membership', 'amount', 'currency', 'paidAt'], description: 'Every paid invoice, recorded once from Stripe.' },
231
- access: { read: ownOrManager, create: () => false, update: () => false, delete: manager },
434
+ access: { read: ownOrManager, readVersions: managersReadVersions(o, o.payments, viaMembership), create: () => false, update: () => false, delete: remove },
232
435
  fields: [
233
436
  { name: 'membership', type: 'relationship', relationTo: o.memberships, required: true, index: true },
234
437
  { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true },
@@ -1,13 +1,13 @@
1
1
  import type { Endpoint } from 'payload';
2
2
  /** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
3
3
  export declare const checkoutEndpoint: Endpoint;
4
- /** POST /api/<memberships>/:id/change { tier? | pledges? } */
4
+ /** POST /api/<memberships>/:id/change { tier? | pledges? }: the member's own only. */
5
5
  export declare const changeEndpoint: Endpoint;
6
6
  /** POST /api/<memberships>/:id/cancel: ends at the close of the paid period. */
7
7
  export declare const cancelEndpoint: Endpoint;
8
- /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal). */
8
+ /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal): the member's own only. */
9
9
  export declare const portalEndpoint: Endpoint;
10
- /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. */
10
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. A manager may only send `show: false`. */
11
11
  export declare const wallEndpoint: Endpoint;
12
12
  /** POST /api/<memberships>/stripe-webhook: Stripe events, verified with the endpoint's signing secret. */
13
13
  export declare const webhookEndpoint: Endpoint;
package/dist/endpoints.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isManager } from './access.js';
1
+ import { managerReaches } from './access.js';
2
2
  import { cancelMembership, changeMembership, handleStripeEvent, membershipOf, portalLink, startCheckout } from './api.js';
3
3
  const json = (body, status = 200) => Response.json(body, { status });
4
4
  const fail = (err) => {
@@ -28,12 +28,12 @@ async function siteOf(req) {
28
28
  }
29
29
  const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
30
30
  /**
31
- * The member's own membership, or one a manager may read, on this request's site only.
32
- * Managers go through the collection's read access (so a multi-tenant host's tenant rules
33
- * apply); with `scopeField` and `scopeOf`, a membership from another site, or asked for from
34
- * an unknown site, is not found.
31
+ * The member's own membership, or (unless `memberOnly`) one a manager may reach, on this request's
32
+ * site only. A manager is checked against this very row with `canManage`'s answer: `true` reaches
33
+ * every row, a query only the rows it matches. With `scopeField` and `scopeOf`, a membership from
34
+ * another site, or asked for from an unknown site, is not found.
35
35
  */
36
- async function ownMembership(req) {
36
+ async function ownMembership(req, { memberOnly = false } = {}) {
37
37
  const o = membershipOf(req.payload);
38
38
  if (!req.user)
39
39
  return null;
@@ -49,8 +49,11 @@ async function ownMembership(req) {
49
49
  }
50
50
  if (idOf(m.user) === String(req.user.id))
51
51
  return m;
52
- if (!(await isManager(o, req)))
52
+ if (memberOnly)
53
53
  return null;
54
+ if (!(await managerReaches(o, req, o.memberships, m.id)))
55
+ return null;
56
+ // And the collection's own read access, so rules the host added there (a tenant plugin's, say) apply too.
54
57
  const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
55
58
  return visible.totalDocs > 0 ? m : null;
56
59
  }
@@ -82,12 +85,12 @@ export const checkoutEndpoint = {
82
85
  }
83
86
  },
84
87
  };
85
- /** POST /api/<memberships>/:id/change { tier? | pledges? } */
88
+ /** POST /api/<memberships>/:id/change { tier? | pledges? }: the member's own only. */
86
89
  export const changeEndpoint = {
87
90
  path: '/:id/change',
88
91
  method: 'post',
89
92
  handler: async (req) => {
90
- const m = await ownMembership(req);
93
+ const m = await ownMembership(req, { memberOnly: true });
91
94
  if (!m)
92
95
  return json({ error: 'Not found.' }, 404);
93
96
  try {
@@ -115,12 +118,12 @@ export const cancelEndpoint = {
115
118
  }
116
119
  },
117
120
  };
118
- /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal). */
121
+ /** POST /api/<memberships>/:id/portal { returnPath? } → { url } (Stripe customer portal): the member's own only. */
119
122
  export const portalEndpoint = {
120
123
  path: '/:id/portal',
121
124
  method: 'post',
122
125
  handler: async (req) => {
123
- const m = await ownMembership(req);
126
+ const m = await ownMembership(req, { memberOnly: true });
124
127
  if (!m)
125
128
  return json({ error: 'Not found.' }, 404);
126
129
  try {
@@ -132,7 +135,7 @@ export const portalEndpoint = {
132
135
  }
133
136
  },
134
137
  };
135
- /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. */
138
+ /** POST /api/<memberships>/:id/wall { show, name }: the member's own choice for the backers wall. A manager may only send `show: false`. */
136
139
  export const wallEndpoint = {
137
140
  path: '/:id/wall',
138
141
  method: 'post',
@@ -141,11 +144,15 @@ export const wallEndpoint = {
141
144
  if (!m)
142
145
  return json({ error: 'Not found.' }, 404);
143
146
  const b = await body(req);
144
- const name = typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '';
147
+ const member = idOf(m.user) === String(req.user.id);
148
+ // Only the member shows themselves on the wall or changes the name; a manager may only hide it.
149
+ if (!member && b.show !== false)
150
+ return json({ error: 'Only the member can do that.' }, 403);
151
+ const name = member ? (typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '') : (m.wall?.name ?? '');
145
152
  const updated = await req.payload.update({
146
153
  collection: membershipOf(req.payload).memberships,
147
154
  id: m.id,
148
- data: { wall: { show: Boolean(b.show) && Boolean(name), name: name || null } },
155
+ data: { wall: { show: member ? Boolean(b.show) && Boolean(name) : false, name: name || null } },
149
156
  overrideAccess: true,
150
157
  context: { membershipSync: true },
151
158
  });
@@ -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/dist/types.d.ts CHANGED
@@ -1,8 +1,13 @@
1
- import type { CollectionConfig, Payload, PayloadRequest } from 'payload';
2
- /** Who manages tiers, categories and memberships in the admin (default: nobody but overrideAccess code). */
1
+ import type { CollectionConfig, Payload, PayloadRequest, Where } from 'payload';
2
+ /**
3
+ * Who manages tiers, categories and memberships in the admin (default: nobody but overrideAccess code).
4
+ * `true` is every row, a `Where` is only the rows it matches (e.g. `{ tenant: { equals: siteId } }`,
5
+ * written against the memberships collection and the `scopeField` of tiers and categories), anything
6
+ * else is no. An empty `{}` is no: return `true` for all.
7
+ */
3
8
  export type CanManage = (args: {
4
9
  req: PayloadRequest;
5
- }) => boolean | Promise<boolean>;
10
+ }) => boolean | Where | Promise<boolean | Where>;
6
11
  export type Interval = 'month' | 'year';
7
12
  /** A paid invoice, as recorded in the payments ledger. Amounts in the currency's minor unit (cents). */
8
13
  export type PaymentRecord = {
@@ -98,7 +103,7 @@ export type MembershipPluginOptions = {
98
103
  };
99
104
  /** The auth collection of members. Default: `admin.user` of your config. */
100
105
  users?: string;
101
- /** Who manages tiers, categories and memberships in the admin. Only `true` counts; anything else, or a throw, is a no. */
106
+ /** Who manages tiers, categories and memberships in the admin. `true` (all rows) or a `Where` (those rows only) counts; anything else, `{}` and a throw included, is a no. */
102
107
  canManage?: CanManage;
103
108
  /** May members start memberships here right now (e.g. off in development)? Default: always. Only `true` allows it. */
104
109
  canCheckout?: (args: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.1.3",
3
+ "version": "0.3.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": {
@@ -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
  }