@extantape/payload-plugin-membership 0.1.3 → 0.2.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
 
@@ -65,7 +65,7 @@ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-we
65
65
  | `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
66
66
  | `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
67
67
  | `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 |
68
+ | `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice. A manager may only send `show: false` |
69
69
 
70
70
  Amounts are in cents. Server code can call `startCheckout`, `changeMembership`, `cancelMembership`,
71
71
  `portalLink`, `myMembership` and `getBackers` directly.
@@ -76,7 +76,7 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
76
76
  |---|---|---|
77
77
  | `slugs` | `membership-tiers`, `membership-categories`, `memberships`, `membership-payments` | |
78
78
  | `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) |
79
+ | `canManage` | nobody | Who manages tiers, categories and memberships in the admin: `true`, or a `Where` for one site's rows. See [Access](#access) |
80
80
  | `canCheckout` | always | E.g. off in development. Only `true` allows a checkout |
81
81
  | `stripeSecretKey` / `stripe` | | Key, or a ready client (tests) |
82
82
  | `webhookSecret` | | Signing secret of the webhook endpoint |
@@ -89,28 +89,77 @@ Amounts are in cents. Server code can call `startCheckout`, `changeMembership`,
89
89
 
90
90
  ## Access
91
91
 
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.
92
+ `canManage` decides everything a manager can do. It gets `{ req }` and answers one of three things:
93
+
94
+ - `true`: a manager of every row.
95
+ - A `Where`, such as `{ tenant: { equals: siteId } }`: a manager of only the rows it matches. Write it
96
+ against the memberships collection and the `scopeField` of tiers and categories. For payments the
97
+ plugin applies it through each payment's `membership`.
98
+ - Anything else is no: `false`, `null`, `0`, `''`, `1`, `'yes'`, an array, an empty `{}` or `{ and: [] }`,
99
+ a field with no operator, an operator Payload doesn't have or the plugin doesn't take (a typo such as
100
+ `equal` included), a value that would match every row (`like: ''`, `contains: ''`, `not_in: []`,
101
+ `all: []`), a query that doesn't run against the memberships collection (an unknown field), or an
102
+ error thrown or rejected. The request is refused cleanly, never a 500. An empty `{}` would match
103
+ every row, so it is a no. Return `true` to mean all. The accepted operators are `equals`,
104
+ `not_equals`, `in`, `not_in`, `all`, `exists`, `greater_than`, `greater_than_equal`, `less_than`,
105
+ `less_than_equal`, `like` and `contains`. `in: []` is accepted and matches nothing.
106
+
107
+ Nobody who isn't signed in is a manager, whatever `canManage` says.
108
+
109
+ ```ts
110
+ canManage: ({ req }) => {
111
+ const user = req.user as { role?: string; site?: string } | null
112
+ if (user?.role === 'admin') return true
113
+ if (user?.role === 'manager' && user.site) return { site: { equals: user.site } }
114
+ return false
115
+ }
116
+ ```
117
+
118
+ A manager limited by a `Where` reaches only the matching memberships, payments, tiers and categories:
119
+ list, read, edit, delete, REST and GraphQL alike, and the endpoints below. A new tier or category
120
+ must match the `Where` in its own data. The plugin checks `equals`, `not_equals`, `in`, `not_in`,
121
+ `exists`, `and` and `or` there; any other operator is a no for a create. An update that names a
122
+ field your `Where` uses is checked the same way, on the stored row with the new data merged over it, so
123
+ a limited manager can't move a row out of their scope or into another one. An update that leaves those
124
+ fields alone isn't checked again.
125
+
126
+ `notes`, `stripe` and `stripeProduct` are judged row by row with the same answer, so a manager of
127
+ site A never reads site B's notes or Stripe ids, even in a list that includes site B's rows (for
128
+ example a membership they hold as a member there).
96
129
 
97
130
  | Where | A manager | A signed-in member | Signed out |
98
131
  |---|---|---|---|
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 |
132
+ | Tiers, categories | Reads; creates, edits, deletes within their scope | Reads | Reads |
133
+ | Their `stripeProduct` (field) | Reads and writes within their scope | Never sees it | Never sees it |
134
+ | Memberships | Reads and edits within their scope, deletes within their scope | Reads their own | Nothing |
135
+ | A membership's `stripe` and `notes` (fields) | Reads and writes within their scope | Never sees them | Nothing |
136
+ | Payments | Reads and deletes within their scope | Reads their own | Nothing |
137
+ | `cancel` endpoint | A membership within their scope, on this request's site | Their own | 404 |
138
+ | `wall` endpoint | Only to hide (`show: false`), within their scope | Their own, show and name | 404 |
139
+ | `change`, `portal` endpoints | Never | Their own | 404 |
140
+
141
+ Only the member changes their own plan, opens their own Stripe billing portal, shows themselves on the
142
+ backers wall or sets the wall name. A manager, even one who manages everything, gets a 404 on `change`
143
+ and `portal`, and may only hide a wall entry (`show: false`, for an offensive name or a takedown
144
+ request). Managers keep `cancel`. (Decided 2026-11-23.)
145
+
146
+ This is enforced in field access too, not just in the endpoints, so editing a membership through
147
+ Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
148
+ `kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
149
+ `stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit.
150
+ Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
151
+ set a category's `parent` only to a category in their scope.
105
152
 
106
153
  Nobody creates memberships or payments directly: checkout and Stripe do. The member endpoints answer
107
154
  404, not 403, to anyone who may not use them, so they don't say whether a membership exists.
108
155
 
109
156
  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).
157
+ filter. A manager's query comes only from `canManage`, and only when it passes the checks above.
158
+ `canCheckout` follows the exact-`true` rule: only `true` lets a checkout start, and anything else,
159
+ an error included, refuses it with "Memberships are not available here yet." (503).
160
+
161
+ Upgrading: a `canManage` that returned `true` or `false` works as before. One that returned an object
162
+ (it was a no) now has that object used as a query, so return `false` if you meant no.
114
163
 
115
164
  `overrides` can change a collection's `access`; if you do, your rules replace these.
116
165
 
package/dist/access.d.ts CHANGED
@@ -1,8 +1,34 @@
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
+ * Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
25
+ * `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
26
+ */
27
+ export declare function matchesWhere(where: Where, data: Record<string, unknown> | undefined): boolean;
28
+ /**
29
+ * Whether this manager may reach one row: `true` always, a query only when it matches that row
30
+ * (checked against the database), nobody else. The answer is kept for the request.
31
+ */
32
+ export declare function managerReaches(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, collection: string, id: unknown, via?: (w: Where) => Where): Promise<boolean>;
7
33
  /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
8
34
  export declare const checkoutAllowed: (o: Pick<ResolvedMembership, "canCheckout">, payload: Payload) => Promise<boolean>;
package/dist/access.js CHANGED
@@ -7,7 +7,162 @@ 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
+ const idOf = (v) => (v && typeof v === 'object' && 'id' in v ? v.id : v);
104
+ const same = (a, b) => a != null && b != null && String(idOf(a)) === String(idOf(b));
105
+ /**
106
+ * Checks a query against data in memory (a row about to be created). Supports `equals`, `not_equals`,
107
+ * `in`, `not_in`, `exists`, `and` and `or`; anything else is no, so an unknown operator fails closed.
108
+ */
109
+ export function matchesWhere(where, data) {
110
+ if (!data)
111
+ return false;
112
+ return Object.entries(where).every(([k, v]) => {
113
+ if (k === 'and')
114
+ return v.every((x) => matchesWhere(x, data));
115
+ if (k === 'or')
116
+ return v.some((x) => matchesWhere(x, data));
117
+ const value = data[k];
118
+ return Object.entries(v).every(([op, arg]) => {
119
+ switch (op) {
120
+ case 'equals':
121
+ return same(value, arg);
122
+ case 'not_equals':
123
+ return value != null && !same(value, arg);
124
+ case 'in':
125
+ return Array.isArray(arg) && arg.some((a) => same(value, a));
126
+ case 'not_in':
127
+ return value != null && Array.isArray(arg) && !arg.some((a) => same(value, a));
128
+ case 'exists':
129
+ return (value != null) === Boolean(arg);
130
+ default:
131
+ return false;
132
+ }
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * Whether this manager may reach one row: `true` always, a query only when it matches that row
138
+ * (checked against the database), nobody else. The answer is kept for the request.
139
+ */
140
+ export async function managerReaches(o, req, collection, id, via = (w) => w) {
141
+ const scope = await managerScope(o, req);
142
+ if (scope === true)
143
+ return true;
144
+ if (!scope || id == null || id === '')
145
+ return false;
146
+ const cache = (req.context.membershipReach ??= new Map());
147
+ const key = `${collection}:${String(id)}:${JSON.stringify(scope)}`;
148
+ const known = cache.get(key);
149
+ if (known !== undefined)
150
+ return known;
151
+ let reached = false;
152
+ try {
153
+ const found = await req.payload.count({
154
+ collection: collection,
155
+ where: { and: [{ id: { equals: id } }, via(scope)] },
156
+ overrideAccess: true,
157
+ req,
158
+ });
159
+ reached = found.totalDocs > 0;
160
+ }
161
+ catch {
162
+ reached = false;
163
+ }
164
+ cache.set(key, reached);
165
+ return reached;
166
+ }
12
167
  /** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
13
168
  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,5 +1,5 @@
1
1
  import { generateKeyBetween } from 'payload/shared';
2
- import { isManager } from './access.js';
2
+ import { managerReaches, managerScope, matchesWhere, viaMembership } from './access.js';
3
3
  const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
4
  /** Drag-and-drop ordered (Payload `orderable`); a new record goes between its alphabetical neighbours. */
5
5
  const placeAlphabetically = (o, slug, field) => async ({ data, operation, req }) => {
@@ -28,11 +28,102 @@ const placeAlphabetically = (o, slug, field) => async ({ data, operation, req })
28
28
  }
29
29
  return data;
30
30
  };
31
+ /** No write through the API for anyone: only the plugin's own server code (with overrideAccess) changes these. */
32
+ const LOCKED = { update: () => false };
33
+ /** Only the member whose row it is. */
34
+ const memberOnly = ({ req, doc }) => Boolean(req.user) && String(idOf(doc?.user)) === String(req.user.id);
35
+ /** Only the member sets `wall.show` to true; a manager may only hide (`false`), e.g. for an offensive name or a takedown request. */
36
+ const wallShow = (o) => async (args) => {
37
+ if (await memberOnly(args))
38
+ return true;
39
+ if (args.siblingData?.show !== false)
40
+ return false;
41
+ const scope = await managerScope(o, args.req);
42
+ if (scope === true)
43
+ return true;
44
+ const id = args.id ?? args.doc?.id;
45
+ return Boolean(scope) && id != null && managerReaches(o, args.req, o.memberships, id);
46
+ };
47
+ /**
48
+ * Manager access by `canManage`'s answer: `true` is every row, a query is only the rows it matches
49
+ * (`via` rewrites it for a collection that holds the rows indirectly), anything else is no. A new
50
+ * row (`create`) must match the query in its own data.
51
+ */
52
+ function scopedManager(o, via = (w) => w, collection) {
53
+ // An update by a limited manager must leave the row inside their query: the existing row with the
54
+ // incoming data merged over it is matched in memory, so a row can't be moved out of scope or into
55
+ // another site. Nothing to check unless the data touches a field the query names.
56
+ const update = async ({ req, id, data }) => {
57
+ const scope = await managerScope(o, req);
58
+ if (scope === true)
59
+ return true;
60
+ if (!scope)
61
+ return false;
62
+ const where = via(scope);
63
+ if (data && collection && referencedFields(scope).some((k) => k in data)) {
64
+ let merged = data;
65
+ if (id != null) {
66
+ const existing = await req.payload.findByID({ collection: collection, id, depth: 0, overrideAccess: true, disableErrors: true, req });
67
+ if (!existing)
68
+ return false;
69
+ merged = { ...existing, ...data };
70
+ }
71
+ if (!matchesWhere(scope, merged))
72
+ return false;
73
+ }
74
+ return where;
75
+ };
76
+ const rows = () => async ({ req }) => {
77
+ const scope = await managerScope(o, req);
78
+ return scope === true ? true : scope ? via(scope) : false;
79
+ };
80
+ const create = async ({ req, data }) => {
81
+ const scope = await managerScope(o, req);
82
+ return scope === true || (scope !== null && matchesWhere(scope, data));
83
+ };
84
+ return { create, update: collection ? update : rows(), remove: rows() };
85
+ }
86
+ /** Top-level field names a query mentions. */
87
+ function referencedFields(where) {
88
+ return Object.entries(where).flatMap(([k, v]) => (k === 'and' || k === 'or' ? v.flatMap(referencedFields) : [k.split('.')[0]]));
89
+ }
90
+ /** Managers read what `canManage` reaches and members their own rows; anyone else gets nothing. */
91
+ function ownOrScoped(o, via = (w) => w) {
92
+ return async ({ req }) => {
93
+ if (!req.user)
94
+ return false;
95
+ const own = { user: { equals: req.user.id } };
96
+ const scope = await managerScope(o, req);
97
+ if (scope === true)
98
+ return true;
99
+ return scope ? { or: [via(scope), own] } : own;
100
+ };
101
+ }
102
+ /** A relationship may only be set to a row the manager reaches (nothing to check when it isn't being set). */
103
+ function inScope(o, target) {
104
+ return async ({ req, siblingData, data }) => {
105
+ const sent = siblingData?.parent ?? data?.parent;
106
+ if (sent == null || sent === '')
107
+ return true;
108
+ return managerReaches(o, req, target, idOf(sent));
109
+ };
110
+ }
111
+ /** Field access for managers: judged on the particular row, never on a bare yes. */
112
+ function managerFieldOn(o, collection) {
113
+ return async ({ req, id, doc, data }) => {
114
+ const scope = await managerScope(o, req);
115
+ if (scope === true)
116
+ return true;
117
+ if (!scope)
118
+ return false;
119
+ const rowId = id ?? doc?.id;
120
+ return rowId != null ? managerReaches(o, req, collection, rowId) : matchesWhere(scope, data);
121
+ };
122
+ }
31
123
  const money = (name, label, description) => ({ name, label, type: 'number', min: 0, admin: { description: `${description} In cents (e.g. 500 = 5.00).` } });
32
124
  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);
125
+ const { create, update, remove } = scopedManager(o, undefined, o.tiers);
126
+ const managerField = managerFieldOn(o, o.tiers);
36
127
  return {
37
128
  slug: o.tiers,
38
129
  labels: { singular: 'Membership tier', plural: 'Membership tiers' },
@@ -41,7 +132,7 @@ export function tiersCollection(o) {
41
132
  defaultColumns: ['name', 'monthly', 'yearly', 'active'],
42
133
  description: 'Fixed-price levels (Patreon-style). Shown in this order: drag rows to change it.',
43
134
  },
44
- access: { read: () => true, create: manager, update: manager, delete: manager },
135
+ access: { read: () => true, create, update, delete: remove },
45
136
  orderable: true,
46
137
  defaultSort: '_order',
47
138
  hooks: { beforeChange: [placeAlphabetically(o, o.tiers, 'name')] },
@@ -65,9 +156,8 @@ export function tiersCollection(o) {
65
156
  };
66
157
  }
67
158
  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);
159
+ const { create, update, remove } = scopedManager(o, undefined, o.categories);
160
+ const managerField = managerFieldOn(o, o.categories);
71
161
  return {
72
162
  slug: o.categories,
73
163
  labels: { singular: 'Membership category', plural: 'Membership categories' },
@@ -76,14 +166,14 @@ export function categoriesCollection(o) {
76
166
  defaultColumns: ['name', 'parent', 'minimum', 'active'],
77
167
  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
168
  },
79
- access: { read: () => true, create: manager, update: manager, delete: manager },
169
+ access: { read: () => true, create, update, delete: remove },
80
170
  orderable: true,
81
171
  defaultSort: '_order',
82
172
  hooks: { beforeChange: [placeAlphabetically(o, o.categories, 'name')] },
83
173
  fields: [
84
174
  { name: 'name', type: 'text', required: true },
85
175
  { 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.' } },
176
+ { name: 'parent', type: 'relationship', relationTo: o.categories, access: { create: inScope(o, o.categories), update: inScope(o, o.categories) }, admin: { position: 'sidebar', description: 'Optional: nest under a broader category.' } },
87
177
  { name: 'description', type: 'textarea' },
88
178
  money('minimum', 'Minimum per month', 'Smallest monthly amount for this category (yearly: 12×).'),
89
179
  {
@@ -99,17 +189,10 @@ export function categoriesCollection(o) {
99
189
  };
100
190
  }
101
191
  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
- };
192
+ const { update, remove } = scopedManager(o, undefined, o.memberships);
193
+ const managerField = managerFieldOn(o, o.memberships);
194
+ // A manager reads what `canManage` reaches; members read their own (the plugin's own query, never the site's answer).
195
+ const ownOrManager = ownOrScoped(o);
113
196
  const nobody = () => false;
114
197
  return {
115
198
  slug: o.memberships,
@@ -120,30 +203,32 @@ export function membershipsCollection(o) {
120
203
  description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the wall name or notes here.',
121
204
  },
122
205
  // 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 },
206
+ access: { read: ownOrManager, create: nobody, update, delete: remove },
124
207
  fields: [
125
- { name: 'label', type: 'text', admin: { readOnly: true } },
126
- { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, admin: { readOnly: true } },
208
+ { name: 'label', type: 'text', access: LOCKED, admin: { readOnly: true } },
209
+ { name: 'user', type: 'relationship', relationTo: o.users, required: true, index: true, access: LOCKED, admin: { readOnly: true } },
127
210
  {
128
211
  type: 'row',
129
212
  fields: [
130
- { name: 'kind', type: 'select', required: true, options: [{ label: 'Tier', value: 'tier' }, { label: 'Pledge to categories', value: 'pledge' }], admin: { width: '33%', readOnly: true } },
213
+ { 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
214
  {
132
215
  name: 'status',
133
216
  type: 'select',
134
217
  required: true,
135
218
  defaultValue: 'pending',
136
219
  index: true,
220
+ access: LOCKED,
137
221
  options: ['pending', 'incomplete', 'active', 'past_due', 'canceled'].map((v) => ({ label: v.replace('_', ' '), value: v })),
138
222
  admin: { width: '33%', readOnly: true },
139
223
  },
140
- { name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], admin: { width: '34%', readOnly: true } },
224
+ { name: 'interval', type: 'select', required: true, options: [{ label: 'Monthly', value: 'month' }, { label: 'Yearly', value: 'year' }], access: LOCKED, admin: { width: '34%', readOnly: true } },
141
225
  ],
142
226
  },
143
- { name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
227
+ { name: 'tier', type: 'relationship', relationTo: o.tiers, index: true, access: LOCKED, admin: { readOnly: true, condition: (d) => d?.kind === 'tier' } },
144
228
  {
145
229
  name: 'pledges',
146
230
  type: 'array',
231
+ access: LOCKED,
147
232
  admin: { readOnly: true, condition: (d) => d?.kind === 'pledge' },
148
233
  fields: [
149
234
  { name: 'category', type: 'relationship', relationTo: o.categories, required: true, index: true },
@@ -153,8 +238,8 @@ export function membershipsCollection(o) {
153
238
  {
154
239
  type: 'row',
155
240
  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 } },
241
+ { name: 'amount', type: 'number', required: true, min: 0, access: LOCKED, admin: { width: '33%', readOnly: true, description: 'Per interval, in cents.' } },
242
+ { name: 'currency', type: 'text', required: true, access: LOCKED, admin: { width: '33%', readOnly: true } },
158
243
  {
159
244
  name: 'totalPaid',
160
245
  type: 'number',
@@ -180,10 +265,10 @@ export function membershipsCollection(o) {
180
265
  {
181
266
  type: 'row',
182
267
  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 } },
268
+ { name: 'startedAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
269
+ { name: 'currentPeriodEnd', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
270
+ { name: 'cancelAtPeriodEnd', type: 'checkbox', access: LOCKED, admin: { width: '25%', readOnly: true } },
271
+ { name: 'canceledAt', type: 'date', access: LOCKED, admin: { width: '25%', readOnly: true } },
187
272
  ],
188
273
  },
189
274
  {
@@ -192,15 +277,15 @@ export function membershipsCollection(o) {
192
277
  type: 'group',
193
278
  admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
194
279
  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 },
280
+ { name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false, access: { update: wallShow(o) } },
281
+ { name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80, access: { update: memberOnly } },
197
282
  ],
198
283
  },
199
284
  // Stripe references: managers only, never in public responses.
200
285
  {
201
286
  name: 'stripe',
202
287
  type: 'group',
203
- access: { read: managerField, create: managerField, update: managerField },
288
+ access: { read: managerField, create: LOCKED.update, update: LOCKED.update },
204
289
  admin: { position: 'sidebar', readOnly: true },
205
290
  fields: [
206
291
  { name: 'customer', type: 'text', index: true },
@@ -214,21 +299,13 @@ export function membershipsCollection(o) {
214
299
  };
215
300
  }
216
301
  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
- };
302
+ const { remove } = scopedManager(o, viaMembership);
303
+ const ownOrManager = ownOrScoped(o, viaMembership);
227
304
  return {
228
305
  slug: o.payments,
229
306
  labels: { singular: 'Membership payment', plural: 'Membership payments' },
230
307
  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 },
308
+ access: { read: ownOrManager, create: () => false, update: () => false, delete: remove },
232
309
  fields: [
233
310
  { name: 'membership', type: 'relationship', relationTo: o.memberships, required: true, index: true },
234
311
  { 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
  });
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.2.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": {