@extantape/payload-plugin-membership 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,8 +7,8 @@ Patreon, or let members support **categories** with **their own amount** — or
7
7
  > The automated tests run on Payload 3.94.2 with an in-memory MongoDB and a fake Stripe. CI runs them on
8
8
  > Node 24. They call REST and GraphQL in-process, and include `@payloadcms/plugin-multi-tenant` 3.94.2.
9
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.
10
+ > databases other than MongoDB, Payload versions after 3.94.2, Node 22, Node 26.13.1 or newer, and upgrading a real
11
+ > database from an earlier version. You need Payload 3.94.2 or later, and Node ^22.23.5, ^24.22.3, or 26.13.1 or newer.
12
12
 
13
13
  - **Tiers** (Patreon-style): fixed monthly and/or yearly prices, perks, colors. Drag-and-drop order.
14
14
  - **Categories**: things members can choose to support (e.g. "Turtles", "North American turtles"),
@@ -29,11 +29,15 @@ Patreon, or let members support **categories** with **their own amount** — or
29
29
 
30
30
  **On its own.** Membership needs a Stripe account (a secret key and a webhook) and an auth collection for members. It doesn't import any other plugin. Perks, votes and credits are whatever your own `onPayment` and `onStatusChange` do.
31
31
 
32
+ **Needs.** Payload `^3.94.2` as a peer dependency. No other EXTANT APE plugin is required.
33
+
32
34
  **Works with:**
33
35
 
34
36
  - **Sponsors** (`@extantape/payload-plugin-sponsors`): tick "Members are listed as sponsors" on a tier, and call Sponsors' `upsertListing()` and `retireListing()` from `onStatusChange`. Your site makes the call; neither plugin imports the other.
35
37
  - **Roadmap** (`@extantape/payload-plugin-roadmap`): Roadmap's extra votes come from a number your site works out (`allocation.earned`), and a membership can be where they come from. There's no adapter for this. It's a few lines of your own code.
36
- - **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them. Pass `scope` to `getBackers`, or it lists every site.
38
+ - **Multi-tenant** (`@payloadcms/plugin-multi-tenant`): set `scopeField` and `scopeOf`, and each site has its own tiers and members. The member endpoints answer only for the site `scopeOf` names: another site's membership, or a request from a site `scopeOf` doesn't know, gets a 404, and so does a request where `scopeOf` throws (only the error's name is logged). Managers also need the collection's read access, so the tenant plugin's rules apply to them. See [Sites](#sites) for what `scopeOf` returns and how `getBackers` and `myMembership` take a site.
39
+
40
+ **Color Theory.** None needed. It has no screens of its own, and its collections use Payload's standard admin, which takes Color Theory's admin colors when its `applyToAdmin` option is on.
37
41
 
38
42
  **Family.** Membership is in the Patronage family, with Sponsors, Backing, Credits, Printify and Roadmap. Backing and Credits are named but not built yet, and the families are a working draft that may change.
39
43
 
@@ -91,11 +95,29 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
91
95
  | `webhookSecret` | | Signing secret of the webhook endpoint |
92
96
  | `currency` | `usd` | |
93
97
  | `publicURL` | `serverURL` | Origin for Stripe return links |
94
- | `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request |
98
+ | `scopeField` / `scopeOf` | | Multi-site: the owner field (e.g. `tenant`) and how to read it from a request. Set both or neither. See [Sites](#sites) |
95
99
  | `onPayment` | | Once per paid invoice |
96
100
  | `onStatusChange` | | When a membership's status changes |
97
101
  | `overrides` | | Adjust the generated collections |
98
102
 
103
+ ## Sites
104
+
105
+ Leave out `scopeField` and `scopeOf` on a single site. For several sites, set both: the plugin
106
+ refuses to build with only one of them.
107
+
108
+ - `scopeOf(req)` returns the request's site id as a non-empty string. Anything else counts as no
109
+ site: `null`, an empty string, a number, or a throw. If your ids are numbers, return `String(id)`.
110
+ - With no site, checkout answers 404 (`Not found.`) before it reads anything or calls Stripe, and so
111
+ do the member endpoints. Server code calling `startCheckout` passes `scope` the same way.
112
+ - Each membership is saved with its site, and only tiers and categories of that site can be chosen,
113
+ at checkout and when the member changes plan. A tier or category with no site is never offered.
114
+ A membership with no site can't be changed (404) until it has one.
115
+ - `getBackers(payload, { scope })` lists one site's wall. `getBackers(payload, { allSites: true })`
116
+ lists every site's. Anything else throws, including both at once.
117
+ - `myMembership(payload, userId, scope)` needs the site too, and throws without it.
118
+ - `onPayment` and `onStatusChange` get the site as `scope` on `membership` and `payment`. It is `null`
119
+ on a single site and for a row with no site, so don't treat `null` as a site.
120
+
99
121
  ## Access
100
122
 
101
123
  `canManage` decides everything a manager can do. It gets `{ req }` and answers one of three things:
@@ -106,8 +128,9 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
106
128
  plugin applies it through each payment's `membership`.
107
129
  - Anything else is no: `false`, `null`, `0`, `''`, `1`, `'yes'`, an array, an empty `{}` or `{ and: [] }`,
108
130
  a field with no operator, an operator Payload doesn't have or the plugin doesn't take (a typo such as
109
- `equal` included), a value that would match every row (`like: ''`, `contains: ''`, `not_in: []`,
110
- `all: []`), a query that doesn't run against the memberships collection (an unknown field), or an
131
+ `equal` included), a value that would match every row (`like` or `contains` with nothing or only whitespace, `not_in: []`,
132
+ `all: []`), a query that doesn't run against the memberships collection or against the tiers,
133
+ categories or payments it is used on (an unknown field), or an
111
134
  error thrown or rejected. The request is refused cleanly, never a 500. An empty `{}` would match
112
135
  every row, so it is a no. Return `true` to mean all. The accepted operators are `equals`,
113
136
  `not_equals`, `in`, `not_in`, `all`, `exists`, `greater_than`, `greater_than_equal`, `less_than`,
@@ -155,7 +178,9 @@ request). Managers keep `cancel`. (Decided 2026-11-23.)
155
178
  This is enforced in field access too, not just in the endpoints, so editing a membership through
156
179
  Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
157
180
  `kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
158
- `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
181
+ `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit. In the admin form the `show` box is read-only for a manager, because
182
+ field access can't know at display time that the new value is `false`. A manager hides a wall entry
183
+ through the wall endpoint (`POST /api/memberships/:id/wall` with `show: false`), or through REST or the Local API.
159
184
  Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
160
185
  set a category's `parent` only to a category in their scope. That is judged on the parent the row
161
186
  ends up with, whether the save is a create, an update, a duplicate (which keeps the original's parent
@@ -232,6 +257,36 @@ Upgrading from 0.2.0, checks to run once from server code:
232
257
  manager can't save such a category until its parent is cleared or moved into their scope, so fix
233
258
  these from server code or as a manager of every row.
234
259
 
260
+ Upgrading, sites (only if you set `scopeField`):
261
+
262
+ 1. Set `scopeOf` too, if you hadn't. Make sure it returns the site id as a string.
263
+ 2. Pass a `scope` to every server call of `startCheckout` and `myMembership`. Pass `scope` or
264
+ `allSites: true` to every `getBackers` call.
265
+ 3. Find memberships that have no site, from server code. With `tenant` as your `scopeField`:
266
+
267
+ ```ts
268
+ const { docs } = await payload.find({
269
+ collection: 'memberships',
270
+ where: { or: [{ tenant: { exists: false } }, { tenant: { equals: null } }] },
271
+ depth: 0,
272
+ pagination: false,
273
+ overrideAccess: true,
274
+ })
275
+ ```
276
+
277
+ For a text field, also look for an empty string. For each row, first try to give it the site its
278
+ tier or categories belong to, with
279
+ `payload.update({ collection: 'memberships', id, data: { tenant: siteId }, overrideAccess: true })`,
280
+ and its payments too if you added the field to them. If you can't, `cancelMembership(payload, id)`
281
+ ends it at the close of the paid period, with no refund. To stop it now or refund, do that in
282
+ Stripe. A member who joins again before then pays for both. A row with no site can't be managed by
283
+ the member from any site, and it isn't on any one site's backers wall (`allSites: true` still lists
284
+ it). A Checkout opened before the upgrade can still finish afterwards and activate a row with no
285
+ site, so run the query again a day later.
286
+ 4. Give a site to any tier or category that has none, or it won't be offered.
287
+ 5. Check: a checkout with no site answers 404 and creates nothing, a checkout on a site works, and the
288
+ query in step 3 finds nothing.
289
+
235
290
  This version requires Payload 3.94.2 or later (peer range `^3.94.2`). Upgrade Payload before you
236
291
  install it.
237
292
 
package/dist/access.d.ts CHANGED
@@ -15,7 +15,10 @@ export declare function usableWhere(w: unknown, depth?: number): w is Where;
15
15
  * and anyone not signed in, is `null`.
16
16
  */
17
17
  export type ManagerScope = true | Where | null;
18
- export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<ManagerScope>;
18
+ export declare function managerScope(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, on?: {
19
+ collection: string;
20
+ via?: (w: Where) => Where;
21
+ }): Promise<ManagerScope>;
19
22
  /** A manager of anything at all (a scope or all): for callers that go on to check a particular row. */
20
23
  export declare function isManager(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest): Promise<boolean>;
21
24
  /** The query as it applies to payments: written against memberships, so every field goes through `membership`. */
package/dist/access.js CHANGED
@@ -15,7 +15,8 @@ const isPlain = (v) => {
15
15
  };
16
16
  const scalar = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v);
17
17
  const scalars = (v, minimum) => Array.isArray(v) && v.length >= minimum && v.every(scalar);
18
- const nonEmptyText = (v) => typeof v === 'string' && v.length > 0;
18
+ // Whitespace and zero-width characters alone would match nearly every row, so they don't count as text.
19
+ const nonEmptyText = (v) => typeof v === 'string' && /[^\s\u200b-\u200d\u2060\ufeff]/.test(v);
19
20
  const number = (v) => typeof v === 'number' || typeof v === 'string';
20
21
  /**
21
22
  * The operators the plugin accepts, each with a check on its value. An unknown operator (a typo
@@ -57,7 +58,7 @@ export function usableWhere(w, depth = 0) {
57
58
  return ops.length > 0 && ops.every(([op, arg]) => Object.hasOwn(OPERATORS, op) && OPERATORS[op](arg));
58
59
  });
59
60
  }
60
- export async function managerScope(o, req) {
61
+ export async function managerScope(o, req, on) {
61
62
  if (!req.user)
62
63
  return null;
63
64
  try {
@@ -66,19 +67,27 @@ export async function managerScope(o, req) {
66
67
  return true;
67
68
  if (!usableWhere(answer))
68
69
  return null;
70
+ // The query must run on the memberships collection and on the collection it is used on (a field
71
+ // that only memberships have can't be queried on tiers or categories), or the answer is no.
69
72
  const checked = (req.context.membershipWhereChecked ??= new Map());
70
- const key = JSON.stringify(answer);
71
- let ok = checked.get(key);
72
- if (ok === undefined) {
73
- try {
74
- await req.payload.count({ collection: o.memberships, where: answer, overrideAccess: true, req });
75
- ok = true;
73
+ const runsOn = async (collection, where) => {
74
+ const key = `${collection}:${JSON.stringify(where)}`;
75
+ let ok = checked.get(key);
76
+ if (ok === undefined) {
77
+ try {
78
+ await req.payload.count({ collection: collection, where, overrideAccess: true, req });
79
+ ok = true;
80
+ }
81
+ catch {
82
+ ok = false;
83
+ }
84
+ checked.set(key, ok);
76
85
  }
77
- catch {
78
- ok = false;
79
- }
80
- checked.set(key, ok);
81
- }
86
+ return ok;
87
+ };
88
+ let ok = await runsOn(o.memberships, answer);
89
+ if (ok && on && on.collection !== o.memberships)
90
+ ok = await runsOn(on.collection, on.via ? on.via(answer) : answer);
82
91
  return ok ? answer : null;
83
92
  }
84
93
  catch {
@@ -152,7 +161,7 @@ export function matchesWhere(where, data) {
152
161
  * (checked against the database), nobody else. The answer is kept for the request.
153
162
  */
154
163
  export async function managerReaches(o, req, collection, id, via = (w) => w) {
155
- const scope = await managerScope(o, req);
164
+ const scope = await managerScope(o, req, { collection, via });
156
165
  if (scope === true)
157
166
  return true;
158
167
  if (!scope || id == null || id === '')
package/dist/api.d.ts CHANGED
@@ -2,6 +2,8 @@ import { type Payload } from 'payload';
2
2
  import type { Interval, ResolvedMembership, StripeEvent } from './types.js';
3
3
  type Doc = Record<string, any>;
4
4
  export declare const membershipOf: (payload: Payload) => ResolvedMembership;
5
+ /** A site id the plugin accepts: a string with something in it. Anything else is no site. */
6
+ export declare const knownScope: (v: unknown) => string | null;
5
7
  /** What a member chooses: a tier, or amounts (cents per interval) for categories. */
6
8
  export type Choice = {
7
9
  tier?: string | null;
@@ -14,7 +16,9 @@ export type Choice = {
14
16
  /**
15
17
  * Starts a membership: validates the choice, records it as pending and opens
16
18
  * Stripe Checkout (a subscription with the member's own amounts). Returns the
17
- * Checkout URL; the webhook activates it once Stripe confirms.
19
+ * Checkout URL; the webhook activates it once Stripe confirms. With `scopeField`,
20
+ * `scope` must be the site's id as a non-empty string, or this answers 404
21
+ * before it reads anything or calls Stripe.
18
22
  */
19
23
  export declare function startCheckout(payload: Payload, args: Choice & {
20
24
  user: Doc;
@@ -29,7 +33,11 @@ export declare function startCheckout(payload: Payload, args: Choice & {
29
33
  url: string;
30
34
  membership: string;
31
35
  }>;
32
- /** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
36
+ /**
37
+ * Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
38
+ * With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
39
+ * site can't be changed (404) until it is given one.
40
+ */
33
41
  export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
34
42
  /** Cancels at the end of the paid period (the member keeps their perks until then). */
35
43
  export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
@@ -52,14 +60,22 @@ export type BackerGroup<T> = {
52
60
  * The backers wall: active members who chose to be shown, under their tier or
53
61
  * under each category they support, A–Z within each (user decision for
54
62
  * the original site). Groups follow the admin's (drag-and-drop) order.
63
+ *
64
+ * With `scopeField`, pass the site's id as `scope` for that site's wall, or `allSites: true` for
65
+ * every site's together. Anything else throws, so a wall never lists more than was asked for.
66
+ * Without `scopeField`, both are ignored.
55
67
  */
56
68
  export declare function getBackers(payload: Payload, opts?: {
57
69
  scope?: string | null;
70
+ allSites?: boolean;
58
71
  locale?: string;
59
72
  }): Promise<{
60
73
  tiers: BackerGroup<Doc>[];
61
74
  categories: BackerGroup<Doc>[];
62
75
  }>;
63
- /** The signed-in member's current membership in a scope (for account pages). */
76
+ /**
77
+ * The signed-in member's current membership in a scope (for account pages). With `scopeField`, `scope`
78
+ * must be the site's id as a non-empty string, or this throws.
79
+ */
64
80
  export declare function myMembership(payload: Payload, userId: string, scope?: string | null): Promise<Doc | null>;
65
81
  export {};
package/dist/api.js CHANGED
@@ -3,6 +3,18 @@ import { checkoutAllowed } from './access.js';
3
3
  const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
4
  const ctx = { membershipSync: true };
5
5
  export const membershipOf = (payload) => payload.config.custom?.membership;
6
+ /** A site id the plugin accepts: a string with something in it. Anything else is no site. */
7
+ export const knownScope = (v) => (typeof v === 'string' && v.trim() !== '' ? v : null);
8
+ /** With `scopeField`, an unknown site is answered as if nothing were there: 404, before any lookup. */
9
+ const notFound = () => new APIError('Not found.', 404, undefined, true);
10
+ function requireScope(o, scope) {
11
+ if (!o.scopeField)
12
+ return null;
13
+ const known = knownScope(scope);
14
+ if (known === null)
15
+ throw notFound();
16
+ return known;
17
+ }
6
18
  const stripeOf = (o) => {
7
19
  const s = o.stripe();
8
20
  if (!s)
@@ -13,7 +25,10 @@ const stripeOf = (o) => {
13
25
  async function linesFor(payload, o, choice, scope) {
14
26
  if (choice.interval !== 'month' && choice.interval !== 'year')
15
27
  throw new APIError('Choose monthly or yearly.', 400, undefined, true);
16
- const inScope = (d) => !o.scopeField || !scope || idOf(d[o.scopeField]) === scope;
28
+ // With `scopeField`, a row counts only when its own site is this exact site; a row with no site never does.
29
+ if (o.scopeField && knownScope(scope) === null)
30
+ throw notFound();
31
+ const inScope = (d) => !o.scopeField || (scope !== null && idOf(d[o.scopeField]) === scope);
17
32
  if (choice.tier) {
18
33
  const tier = (await payload.findByID({ collection: o.tiers, id: choice.tier, depth: 0, overrideAccess: true, disableErrors: true }));
19
34
  const price = tier?.[choice.interval === 'month' ? 'monthly' : 'yearly'];
@@ -56,20 +71,22 @@ const priceData = (o, line, interval) => ({
56
71
  const labelOf = (user, kind, tier, lines) => `${user.name || user.email || 'Member'} · ${kind === 'tier' ? tier.name : lines.map((l) => l.name).join(', ')}`.slice(0, 200);
57
72
  /** Members in good standing (or still paying) block a second membership in the same scope. */
58
73
  async function currentMembership(payload, o, userId, scope) {
59
- const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
74
+ const where = { and: [{ user: { equals: userId } }, { status: { in: ['active', 'past_due', 'incomplete'] } }, ...(o.scopeField ? [{ [o.scopeField]: { equals: scope } }] : [])] };
60
75
  return (await payload.find({ collection: o.memberships, where, limit: 1, depth: 0, overrideAccess: true })).docs[0];
61
76
  }
62
77
  /**
63
78
  * Starts a membership: validates the choice, records it as pending and opens
64
79
  * Stripe Checkout (a subscription with the member's own amounts). Returns the
65
- * Checkout URL; the webhook activates it once Stripe confirms.
80
+ * Checkout URL; the webhook activates it once Stripe confirms. With `scopeField`,
81
+ * `scope` must be the site's id as a non-empty string, or this answers 404
82
+ * before it reads anything or calls Stripe.
66
83
  */
67
84
  export async function startCheckout(payload, args) {
68
85
  const o = membershipOf(payload);
86
+ const scope = requireScope(o, args.scope);
69
87
  if (!(await checkoutAllowed(o, payload)))
70
88
  throw new APIError('Memberships are not available here yet.', 503, undefined, true);
71
89
  const stripe = stripeOf(o);
72
- const scope = args.scope ?? null;
73
90
  if (await currentMembership(payload, o, String(args.user.id), scope))
74
91
  throw new APIError('You already have a membership: change it instead.', 409, undefined, true);
75
92
  const { kind, lines, tier, pledges } = await linesFor(payload, o, args, scope);
@@ -87,7 +104,7 @@ export async function startCheckout(payload, args) {
87
104
  currency: o.currency,
88
105
  status: 'pending',
89
106
  wall: { show: Boolean(args.wall?.show), name: args.wall?.name?.trim().slice(0, 80) || null },
90
- ...(o.scopeField && scope ? { [o.scopeField]: scope } : {}),
107
+ ...(o.scopeField ? { [o.scopeField]: scope } : {}),
91
108
  },
92
109
  overrideAccess: true,
93
110
  context: ctx,
@@ -107,13 +124,17 @@ export async function startCheckout(payload, args) {
107
124
  throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
108
125
  return { url: session.url, membership: String(membership.id) };
109
126
  }
110
- /** Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice). */
127
+ /**
128
+ * Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
129
+ * With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
130
+ * site can't be changed (404) until it is given one.
131
+ */
111
132
  export async function changeMembership(payload, membershipId, choice) {
112
133
  const o = membershipOf(payload);
113
134
  const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 1, overrideAccess: true }));
114
135
  if (!m.stripe?.subscription || !['active', 'past_due'].includes(m.status))
115
136
  throw new APIError('Only a running membership can be changed.', 409, undefined, true);
116
- const scope = o.scopeField ? idOf(m[o.scopeField]) : null;
137
+ const scope = o.scopeField ? requireScope(o, idOf(m[o.scopeField])) : null;
117
138
  const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
118
139
  const stripe = stripeOf(o);
119
140
  const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
@@ -148,8 +169,10 @@ export async function portalLink(payload, membershipId, returnURL) {
148
169
  return (await stripeOf(o).billingPortal.sessions.create({ customer: m.stripe.customer, return_url: returnURL })).url;
149
170
  }
150
171
  const statusFrom = (s) => s === 'active' || s === 'trialing' ? 'active' : s === 'past_due' || s === 'unpaid' ? 'past_due' : s === 'incomplete' ? 'incomplete' : s === 'paused' ? 'past_due' : 'canceled';
151
- const recordOf = (m) => ({
172
+ const scopeOfRow = (o, m) => (o.scopeField ? knownScope(idOf(m[o.scopeField])) : null);
173
+ const recordOf = (o, m) => ({
152
174
  id: String(m.id),
175
+ scope: scopeOfRow(o, m),
153
176
  user: String(idOf(m.user)),
154
177
  kind: m.kind,
155
178
  tier: idOf(m.tier),
@@ -162,7 +185,7 @@ const recordOf = (m) => ({
162
185
  async function setMembership(payload, o, m, data) {
163
186
  const updated = (await payload.update({ collection: o.memberships, id: m.id, data: data, overrideAccess: true, depth: 0, context: ctx }));
164
187
  if (data.status && data.status !== m.status && o.onStatusChange)
165
- await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
188
+ await o.onStatusChange({ payload, membership: recordOf(o, updated), previous: m.status ?? null });
166
189
  return updated;
167
190
  }
168
191
  async function findBy(payload, o, where) {
@@ -211,7 +234,7 @@ export async function handleStripeEvent(payload, event) {
211
234
  try {
212
235
  payment = (await payload.create({
213
236
  collection: o.payments,
214
- data: { membership: m.id, user: idOf(m.user), amount: obj.amount_paid, currency: obj.currency ?? m.currency, paidAt, invoiceId: obj.id, tier: idOf(m.tier), pledges, ...(o.scopeField && m[o.scopeField] ? { [o.scopeField]: idOf(m[o.scopeField]) } : {}) },
237
+ data: { membership: m.id, user: idOf(m.user), amount: obj.amount_paid, currency: obj.currency ?? m.currency, paidAt, invoiceId: obj.id, tier: idOf(m.tier), pledges, ...(scopeOfRow(o, m) !== null ? { [o.scopeField]: idOf(m[o.scopeField]) } : {}) },
215
238
  overrideAccess: true,
216
239
  context: ctx,
217
240
  // One document, kept unique by the invoiceId index; no transaction needed. Inside one,
@@ -240,12 +263,12 @@ export async function handleStripeEvent(payload, event) {
240
263
  (await payload.db.updateOne({ collection: memberships, where: { and: [{ id: { equals: m.id } }, { status: { not_equals: 'active' } }] }, data: { status: 'active' } }));
241
264
  const updated = (await payload.findByID({ collection: memberships, id: m.id, depth: 0, overrideAccess: true }));
242
265
  if (activated && o.onStatusChange)
243
- await o.onStatusChange({ payload, membership: recordOf(updated), previous: m.status ?? null });
266
+ await o.onStatusChange({ payload, membership: recordOf(o, updated), previous: m.status ?? null });
244
267
  if (o.onPayment)
245
268
  await o.onPayment({
246
269
  payload,
247
- membership: recordOf(updated),
248
- payment: { id: String(payment.id), membership: String(m.id), user: String(idOf(m.user)), amount: obj.amount_paid, currency: payment.currency, paidAt, invoiceId: obj.id, pledges: pledges, tier: idOf(m.tier) },
270
+ membership: recordOf(o, updated),
271
+ payment: { id: String(payment.id), membership: String(m.id), user: String(idOf(m.user)), amount: obj.amount_paid, currency: payment.currency, paidAt, invoiceId: obj.id, pledges: pledges, tier: idOf(m.tier), scope: scopeOfRow(o, m) },
249
272
  });
250
273
  return 'handled';
251
274
  }
@@ -281,10 +304,21 @@ export async function handleStripeEvent(payload, event) {
281
304
  * The backers wall: active members who chose to be shown, under their tier or
282
305
  * under each category they support, A–Z within each (user decision for
283
306
  * the original site). Groups follow the admin's (drag-and-drop) order.
307
+ *
308
+ * With `scopeField`, pass the site's id as `scope` for that site's wall, or `allSites: true` for
309
+ * every site's together. Anything else throws, so a wall never lists more than was asked for.
310
+ * Without `scopeField`, both are ignored.
284
311
  */
285
312
  export async function getBackers(payload, opts = {}) {
286
313
  const o = membershipOf(payload);
287
- const scoped = (w) => ({ and: [...w, ...(o.scopeField && opts.scope ? [{ [o.scopeField]: { equals: opts.scope } }] : [])] });
314
+ let scope = null;
315
+ if (o.scopeField) {
316
+ scope = knownScope(opts.scope);
317
+ const allSites = opts.allSites === true;
318
+ if (allSites === (scope !== null))
319
+ throw new Error('getBackers needs either a scope (the site’s id as a non-empty string) or allSites: true, not both, when scopeField is set.');
320
+ }
321
+ const scoped = (w) => ({ and: [...w, ...(o.scopeField && scope !== null ? [{ [o.scopeField]: { equals: scope } }] : [])] });
288
322
  const read = { depth: 0, pagination: false, overrideAccess: true, locale: opts.locale };
289
323
  const [members, tiers, categories] = await Promise.all([
290
324
  payload.find({ collection: o.memberships, where: scoped([{ status: { equals: 'active' } }, { 'wall.show': { equals: true } }]), select: { kind: true, tier: true, pledges: true, wall: true, startedAt: true }, ...read }),
@@ -311,9 +345,14 @@ export async function getBackers(payload, opts = {}) {
311
345
  categories: categories.docs.map((c) => ({ group: c, backers: az(byCategory.get(String(c.id)) ?? []) })).filter((g) => g.backers.length),
312
346
  };
313
347
  }
314
- /** The signed-in member's current membership in a scope (for account pages). */
348
+ /**
349
+ * The signed-in member's current membership in a scope (for account pages). With `scopeField`, `scope`
350
+ * must be the site's id as a non-empty string, or this throws.
351
+ */
315
352
  export async function myMembership(payload, userId, scope = null) {
316
353
  const o = membershipOf(payload);
317
- const where = { and: [{ user: { equals: userId } }, { status: { not_equals: 'pending' } }, ...(o.scopeField && scope ? [{ [o.scopeField]: { equals: scope } }] : [])] };
354
+ if (o.scopeField && knownScope(scope) === null)
355
+ throw new Error('myMembership needs a scope (the site’s id as a non-empty string) when scopeField is set.');
356
+ const where = { and: [{ user: { equals: userId } }, { status: { not_equals: 'pending' } }, ...(o.scopeField ? [{ [o.scopeField]: { equals: scope } }] : [])] };
318
357
  return (await payload.find({ collection: o.memberships, where, sort: '-createdAt', limit: 1, depth: 1, overrideAccess: true })).docs[0] ?? null;
319
358
  }
@@ -64,12 +64,12 @@ const wallShow = (o) => async (args) => {
64
64
  * (`via` rewrites it for a collection that holds the rows indirectly), anything else is no. A new
65
65
  * row (`create`) must match the query in its own data.
66
66
  */
67
- function scopedManager(o, via = (w) => w, collection) {
67
+ function scopedManager(o, via = (w) => w, collection, target = collection) {
68
68
  // An update by a limited manager must leave the row inside their query: the existing row with the
69
69
  // incoming data merged over it is matched in memory, so a row can't be moved out of scope or into
70
70
  // another site. Nothing to check unless the data touches a field the query names.
71
71
  const update = async ({ req, id, data }) => {
72
- const scope = await managerScope(o, req);
72
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
73
73
  if (scope === true)
74
74
  return true;
75
75
  if (!scope)
@@ -89,11 +89,11 @@ function scopedManager(o, via = (w) => w, collection) {
89
89
  return where;
90
90
  };
91
91
  const rows = () => async ({ req }) => {
92
- const scope = await managerScope(o, req);
92
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
93
93
  return scope === true ? true : scope ? via(scope) : false;
94
94
  };
95
95
  const create = async ({ req, data }) => {
96
- const scope = await managerScope(o, req);
96
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
97
97
  return scope === true || (scope !== null && matchesWhere(scope, data));
98
98
  };
99
99
  return { create, update: collection ? update : rows(), remove: rows() };
@@ -103,12 +103,12 @@ function referencedFields(where) {
103
103
  return Object.entries(where).flatMap(([k, v]) => (k === 'and' || k === 'or' ? v.flatMap(referencedFields) : [k.split('.')[0]]));
104
104
  }
105
105
  /** Managers read what `canManage` reaches and members their own rows; anyone else gets nothing. */
106
- function ownOrScoped(o, via = (w) => w) {
106
+ function ownOrScoped(o, via = (w) => w, target) {
107
107
  return async ({ req }) => {
108
108
  if (!req.user)
109
109
  return false;
110
110
  const own = { user: { equals: req.user.id } };
111
- const scope = await managerScope(o, req);
111
+ const scope = await managerScope(o, req, target ? { collection: target, via } : undefined);
112
112
  if (scope === true)
113
113
  return true;
114
114
  return scope ? { or: [via(scope), own] } : own;
@@ -202,7 +202,7 @@ function everyLocaleInScope(o, target) {
202
202
  const codes = localeCodes(req);
203
203
  if (!('localized' in field && field.localized) || !codes.length)
204
204
  return value;
205
- const scope = await managerScope(o, req);
205
+ const scope = await managerScope(o, req, { collection: target });
206
206
  if (scope === true || !scope)
207
207
  return value; // no scope at all is refused by access
208
208
  const existing = (siblingDocWithLocales?.[field.name] ?? {});
@@ -229,7 +229,7 @@ function publicRead(o, slug) {
229
229
  if (!(versions && typeof versions === 'object' && versions.drafts))
230
230
  return true;
231
231
  const published = { or: [{ _status: { equals: 'published' } }, { _status: { exists: false } }] };
232
- const scope = await managerScope(o, req);
232
+ const scope = await managerScope(o, req, { collection: slug });
233
233
  if (scope === true)
234
234
  return true;
235
235
  return scope ? { or: [published, scope] } : published;
@@ -238,7 +238,7 @@ function publicRead(o, slug) {
238
238
  /** Field access for managers: judged on the particular row, never on a bare yes. */
239
239
  function managerFieldOn(o, collection) {
240
240
  return async ({ req, id, doc, data }) => {
241
- const scope = await managerScope(o, req);
241
+ const scope = await managerScope(o, req, { collection });
242
242
  if (scope === true)
243
243
  return true;
244
244
  if (!scope)
@@ -317,7 +317,7 @@ export function membershipsCollection(o) {
317
317
  const { update, remove } = scopedManager(o, undefined, o.memberships);
318
318
  const managerField = managerFieldOn(o, o.memberships);
319
319
  // A manager reads what `canManage` reaches; members read their own (the plugin's own query, never the site's answer).
320
- const ownOrManager = ownOrScoped(o);
320
+ const ownOrManager = ownOrScoped(o, undefined, o.memberships);
321
321
  const nobody = () => false;
322
322
  return {
323
323
  slug: o.memberships,
@@ -325,7 +325,7 @@ export function membershipsCollection(o) {
325
325
  admin: {
326
326
  useAsTitle: 'label',
327
327
  defaultColumns: ['label', 'kind', 'amount', 'interval', 'status', 'currentPeriodEnd'],
328
- description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
328
+ description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the staff notes here. Managers can hide a wall entry through the wall endpoint.',
329
329
  },
330
330
  // Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
331
331
  access: { read: ownOrManager, readVersions: managersReadVersions(o, o.memberships), create: nobody, update, delete: remove },
@@ -425,8 +425,8 @@ export function membershipsCollection(o) {
425
425
  };
426
426
  }
427
427
  export function paymentsCollection(o) {
428
- const { remove } = scopedManager(o, viaMembership);
429
- const ownOrManager = ownOrScoped(o, viaMembership);
428
+ const { remove } = scopedManager(o, viaMembership, undefined, o.payments);
429
+ const ownOrManager = ownOrScoped(o, viaMembership, o.payments);
430
430
  return {
431
431
  slug: o.payments,
432
432
  labels: { singular: 'Membership payment', plural: 'Membership payments' },
package/dist/endpoints.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { managerReaches } from './access.js';
2
- import { cancelMembership, changeMembership, handleStripeEvent, membershipOf, portalLink, startCheckout } from './api.js';
2
+ import { cancelMembership, changeMembership, handleStripeEvent, knownScope, membershipOf, portalLink, startCheckout } from './api.js';
3
3
  const json = (body, status = 200) => Response.json(body, { status });
4
4
  const fail = (err) => {
5
5
  const e = err;
@@ -10,16 +10,16 @@ const origin = (req) => membershipOf(req.payload).publicURL ?? req.payload.confi
10
10
  /** Same-site paths only. */
11
11
  const path = (p, fallback) => (typeof p === 'string' && /^\/(?!\/)/.test(p) ? p : fallback);
12
12
  /**
13
- * The request's site, from `scopeOf`. A throw or rejection counts as no site, so the caller
14
- * refuses as it would for an unknown site. Only the error's name is logged: its message could
15
- * carry the host's request details.
13
+ * The request's site, from `scopeOf`: a non-empty string, or `null` for anything else. A throw or
14
+ * rejection counts as no site, so the caller refuses as it would for an unknown site. Only the
15
+ * error's name is logged: its message could carry the host's request details.
16
16
  */
17
17
  async function siteOf(req) {
18
18
  const o = membershipOf(req.payload);
19
19
  if (!o.scopeOf)
20
20
  return null;
21
21
  try {
22
- return await o.scopeOf(req);
22
+ return knownScope(await o.scopeOf(req));
23
23
  }
24
24
  catch (err) {
25
25
  req.payload.logger.warn(`Membership: scopeOf failed (${err instanceof Error ? err.name : typeof err}); treated as no site`);
@@ -42,9 +42,9 @@ async function ownMembership(req, { memberOnly = false } = {}) {
42
42
  const m = await req.payload.findByID({ collection, id, depth: 0, overrideAccess: true, disableErrors: true });
43
43
  if (!m)
44
44
  return null;
45
- if (o.scopeField && o.scopeOf) {
45
+ if (o.scopeField) {
46
46
  const here = await siteOf(req);
47
- if (here == null || idOf(m[o.scopeField]) !== String(here))
47
+ if (here === null || idOf(m[o.scopeField]) !== here)
48
48
  return null;
49
49
  }
50
50
  if (idOf(m.user) === String(req.user.id))
package/dist/guard.js CHANGED
@@ -78,6 +78,39 @@ function checkFieldValue(field, v, req, depth, locales) {
78
78
  }
79
79
  refuseBadKeys(v, null, req, depth);
80
80
  }
81
+ // A group is an object. Payload's field hooks read inside it before any access rule runs, so a null
82
+ // (or any non-object) for a group, `wall: null` on a membership for one, would end as a 500. It is a
83
+ // clean 400 instead, for every caller, and nothing is saved.
84
+ function refuseNullGroups(data, fields, req) {
85
+ if (!data || typeof data !== 'object' || Array.isArray(data))
86
+ return;
87
+ for (const [name, f] of named(fields)) {
88
+ if (!(name in data))
89
+ continue;
90
+ const v = data[name];
91
+ if (v === undefined)
92
+ continue; // undefined means not sent
93
+ if (f.type === 'group') {
94
+ if (v === null || typeof v !== 'object' || Array.isArray(v))
95
+ throw new APIError(`${name} must be an object.`, 400, undefined, true);
96
+ refuseNullGroups(v, f.fields, req);
97
+ }
98
+ else if (f.type === 'array' && Array.isArray(v)) {
99
+ for (const row of v)
100
+ refuseNullGroups(row, f.fields, req);
101
+ }
102
+ else if (f.type === 'blocks' && Array.isArray(v)) {
103
+ // A block row is checked against the block its blockType names, whether the host listed the block here or by reference.
104
+ const blocks = [...(f.blocks ?? []), ...(f.blockReferences ?? []).map((b) => (typeof b === 'string' ? req.payload.config.blocks?.find((x) => x.slug === b) : b))];
105
+ for (const row of v) {
106
+ const type = row && typeof row === 'object' ? row.blockType : undefined;
107
+ const block = blocks.find((b) => b && b.slug === type);
108
+ if (block)
109
+ refuseNullGroups(row, block.fields, req);
110
+ }
111
+ }
112
+ }
113
+ }
81
114
  /**
82
115
  * Added at the front of the collection's `beforeOperation` hooks after the host's overrides, so it
83
116
  * sees the data as the request sent it, ahead of the collection's other hooks. A plugin that runs
@@ -95,6 +128,7 @@ export function writeGuard(o) {
95
128
  // passes a request body straight to it gets the same check.
96
129
  if (operation === 'create' || operation === 'update') {
97
130
  refuseBadKeys(a.data, collection.fields, req);
131
+ refuseNullGroups(a.data, collection.fields, req);
98
132
  return args;
99
133
  }
100
134
  if (operation === 'restoreVersion' && !overrideAccess) {
package/dist/plugin.js CHANGED
@@ -9,6 +9,10 @@ import { cancelEndpoint, changeEndpoint, checkoutEndpoint, portalEndpoint, wallE
9
9
  * `getBackers` builds an opt-in backers wall, A–Z within each tier/category.
10
10
  */
11
11
  export const membershipPlugin = (options = {}) => (config) => {
12
+ const hasField = typeof options.scopeField === 'string' && options.scopeField !== '';
13
+ const hasOf = typeof options.scopeOf === 'function';
14
+ if ((options.scopeField !== undefined || options.scopeOf !== undefined) && !(hasField && hasOf))
15
+ throw new Error('Membership: set scopeField and scopeOf together (a field name and a function), or neither.');
12
16
  let client = options.stripe;
13
17
  const o = {
14
18
  tiers: options.slugs?.tiers ?? 'membership-tiers',
package/dist/types.d.ts CHANGED
@@ -24,9 +24,13 @@ export type PaymentRecord = {
24
24
  amount: number;
25
25
  }[];
26
26
  tier: string | null;
27
+ /** The membership's site (its `scopeField`), or `null` without `scopeField` or when the row has none. */
28
+ scope: string | null;
27
29
  };
28
30
  export type MembershipRecord = {
29
31
  id: string;
32
+ /** The membership's site (its `scopeField`), or `null` without `scopeField` or when the row has none. */
33
+ scope: string | null;
30
34
  user: string;
31
35
  kind: 'tier' | 'pledge';
32
36
  tier: string | null;
@@ -118,9 +122,15 @@ export type MembershipPluginOptions = {
118
122
  currency?: string;
119
123
  /** Public origin for Stripe return links. Default: `serverURL`. */
120
124
  publicURL?: string;
121
- /** A field that separates owners (e.g. `tenant`): new tiers/categories go A–Z among their own; memberships are per scope. */
125
+ /**
126
+ * A field that separates owners (e.g. `tenant`): new tiers/categories go A–Z among their own; memberships are per scope.
127
+ * Set it together with `scopeOf`, or neither: the plugin refuses to build with only one.
128
+ */
122
129
  scopeField?: string;
123
- /** The scope of a request (e.g. the site of the request's host), stored on new memberships. */
130
+ /**
131
+ * The scope of a request (e.g. the site of the request's host) as the site's id in a non-empty string, stored on new
132
+ * memberships. Anything else (`null`, an empty string, a number, a throw) is no site: checkout and the member endpoints answer 404.
133
+ */
124
134
  scopeOf?: (req: PayloadRequest) => Promise<string | null> | string | null;
125
135
  /** Called once per paid invoice (idempotent: never twice for the same invoice). Award perks, votes, credits here. */
126
136
  onPayment?: (args: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Memberships for Payload: Patreon-style tiers or pick-your-own-amount pledges to categories, billed as Stripe subscriptions, with a backers wall and hooks for perks.",
5
5
  "homepage": "https://github.com/ExtantApe/payload-plugin-membership#readme",
6
6
  "bugs": {