@extantape/payload-plugin-membership 0.5.0 → 0.5.2
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 +20 -3
- package/dist/access.d.ts +28 -0
- package/dist/access.js +47 -0
- package/dist/collections.js +16 -14
- package/dist/endpoints.js +8 -7
- package/dist/guard.d.ts +21 -2
- package/dist/guard.js +30 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -83,6 +83,13 @@ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-we
|
|
|
83
83
|
Amounts are in cents. Server code can call `startCheckout`, `changeMembership`, `cancelMembership`,
|
|
84
84
|
`portalLink`, `myMembership` and `getBackers` directly.
|
|
85
85
|
|
|
86
|
+
When two saves reach one record at the same moment, MongoDB keeps one and refuses the other. Over REST
|
|
87
|
+
the refused save answers 409 (`Another change to this record was being saved at the same moment, so
|
|
88
|
+
this one was not saved. Try again.`) and nothing of it is stored, so send it again. This covers
|
|
89
|
+
saves of a single record only: Payload's own REST routes by id for the plugin's four collections,
|
|
90
|
+
and the wall endpoint. A bulk PATCH (one with a `where`) that meets a conflict still answers 500,
|
|
91
|
+
with nothing of it stored. GraphQL and the Local API pass on the database's error as before.
|
|
92
|
+
|
|
86
93
|
## Options
|
|
87
94
|
|
|
88
95
|
| Option | Default | |
|
|
@@ -168,6 +175,7 @@ example a membership they hold as a member there).
|
|
|
168
175
|
| Payments | Reads and deletes within their scope | Reads their own | Nothing |
|
|
169
176
|
| `cancel` endpoint | A membership within their scope, on this request's site | Their own | 404 |
|
|
170
177
|
| `wall` endpoint | Only to hide (`show: false`), within their scope | Their own, show and name | 404 |
|
|
178
|
+
| A membership's `wall.show` (field, the admin form included) | Only to hide, within their scope | Through the `wall` endpoint | Nothing |
|
|
171
179
|
| `change`, `portal` endpoints | Never | Their own | 404 |
|
|
172
180
|
|
|
173
181
|
Only the member changes their own plan, opens their own Stripe billing portal, shows themselves on the
|
|
@@ -178,9 +186,18 @@ request). Managers keep `cancel`. (Decided 2026-11-23.)
|
|
|
178
186
|
This is enforced in field access too, not just in the endpoints, so editing a membership through
|
|
179
187
|
Payload's own REST, GraphQL or admin can't get around it. A manager can't write a membership's `user`,
|
|
180
188
|
`kind`, `status`, `interval`, `tier`, `pledges`, `amount`, `currency`, `label`, the period dates or the
|
|
181
|
-
`stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit
|
|
182
|
-
|
|
183
|
-
|
|
189
|
+
`stripe` group, or `wall.name`, and can only set `wall.show` to `false`. Only `notes` is theirs to edit, plus hiding a wall entry.
|
|
190
|
+
|
|
191
|
+
A manager of a membership hides its wall entry in the admin form by clearing the `show` box and
|
|
192
|
+
saving. The box is open to them only while the entry is shown. Once it is hidden the box is
|
|
193
|
+
read-only, and only the member can show it again, through the wall endpoint. The wall endpoint
|
|
194
|
+
(`POST /api/memberships/:id/wall` with `show: false`), REST and the Local API hide an entry too. One
|
|
195
|
+
check decides who may hide on all of them, so the admin form allows what the wall endpoint allows.
|
|
196
|
+
The wall endpoint also looks the membership up on the request's site first. With `scopeField`, a
|
|
197
|
+
membership with no site is on no site, so the wall endpoint answers 404 for it, while a manager of
|
|
198
|
+
every row (`canManage` answering `true`) can still hide it through the field: the admin form, REST
|
|
199
|
+
or the Local API. A save
|
|
200
|
+
from a manager that sets `show` to `true` leaves the entry hidden and saves the other fields.
|
|
184
201
|
Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
|
|
185
202
|
set a category's `parent` only to a category in their scope. That is judged on the parent the row
|
|
186
203
|
ends up with, whether the save is a create, an update, a duplicate (which keeps the original's parent
|
package/dist/access.d.ts
CHANGED
|
@@ -38,5 +38,33 @@ export declare function matchesWhere(where: Where, data: Record<string, unknown>
|
|
|
38
38
|
* (checked against the database), nobody else. The answer is kept for the request.
|
|
39
39
|
*/
|
|
40
40
|
export declare function managerReaches(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, collection: string, id: unknown, via?: (w: Where) => Where): Promise<boolean>;
|
|
41
|
+
/** Who the signed-in user is to one membership: its member, a manager who reaches it, or nobody. */
|
|
42
|
+
export type MembershipRole = 'member' | 'manager' | null;
|
|
43
|
+
type Row = {
|
|
44
|
+
id?: unknown;
|
|
45
|
+
user?: unknown;
|
|
46
|
+
} | null | undefined;
|
|
47
|
+
/**
|
|
48
|
+
* The one answer to who someone is to a membership. The member's own row comes first, so a manager
|
|
49
|
+
* who is also the member counts as the member. A manager is judged on this very row.
|
|
50
|
+
*/
|
|
51
|
+
export declare function membershipRole(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, row: Row): Promise<MembershipRole>;
|
|
52
|
+
/**
|
|
53
|
+
* The one rule for a membership's `wall.show`, used by the wall endpoint and by the field's access
|
|
54
|
+
* (REST, GraphQL, the Local API and the admin form): the member may set anything, a manager who
|
|
55
|
+
* reaches the row may only hide it (exactly `false`), and nobody else may change it.
|
|
56
|
+
*/
|
|
57
|
+
export declare function wallShowChange(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, row: Row, show: unknown): Promise<{
|
|
58
|
+
role: MembershipRole;
|
|
59
|
+
allowed: boolean;
|
|
60
|
+
}>;
|
|
61
|
+
/**
|
|
62
|
+
* Whether the admin form's show box is open to this user for a stored row. A checkbox can only flip
|
|
63
|
+
* the stored value, so the answer is `wallShowChange` for the opposite of what is stored: a manager
|
|
64
|
+
* gets the box while the entry is shown and loses it once it is hidden. The stored row is read here,
|
|
65
|
+
* because the data Payload passes at this point can be unsaved form values. A row that can't be read is no.
|
|
66
|
+
*/
|
|
67
|
+
export declare function wallShowOpen(o: Pick<ResolvedMembership, 'canManage' | 'memberships'>, req: PayloadRequest, id: unknown): Promise<boolean>;
|
|
41
68
|
/** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
|
|
42
69
|
export declare const checkoutAllowed: (o: Pick<ResolvedMembership, "canCheckout">, payload: Payload) => Promise<boolean>;
|
|
70
|
+
export {};
|
package/dist/access.js
CHANGED
|
@@ -187,5 +187,52 @@ export async function managerReaches(o, req, collection, id, via = (w) => w) {
|
|
|
187
187
|
cache.set(key, reached);
|
|
188
188
|
return reached;
|
|
189
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* The one answer to who someone is to a membership. The member's own row comes first, so a manager
|
|
192
|
+
* who is also the member counts as the member. A manager is judged on this very row.
|
|
193
|
+
*/
|
|
194
|
+
export async function membershipRole(o, req, row) {
|
|
195
|
+
if (!req.user || !row)
|
|
196
|
+
return null;
|
|
197
|
+
if (same(row.user, req.user.id))
|
|
198
|
+
return 'member';
|
|
199
|
+
return row.id != null && (await managerReaches(o, req, o.memberships, row.id)) ? 'manager' : null;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* The one rule for a membership's `wall.show`, used by the wall endpoint and by the field's access
|
|
203
|
+
* (REST, GraphQL, the Local API and the admin form): the member may set anything, a manager who
|
|
204
|
+
* reaches the row may only hide it (exactly `false`), and nobody else may change it.
|
|
205
|
+
*/
|
|
206
|
+
export async function wallShowChange(o, req, row, show) {
|
|
207
|
+
const role = await membershipRole(o, req, row);
|
|
208
|
+
return { role, allowed: role === 'member' || (role === 'manager' && show === false) };
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Whether the admin form's show box is open to this user for a stored row. A checkbox can only flip
|
|
212
|
+
* the stored value, so the answer is `wallShowChange` for the opposite of what is stored: a manager
|
|
213
|
+
* gets the box while the entry is shown and loses it once it is hidden. The stored row is read here,
|
|
214
|
+
* because the data Payload passes at this point can be unsaved form values. A row that can't be read is no.
|
|
215
|
+
*/
|
|
216
|
+
export async function wallShowOpen(o, req, id) {
|
|
217
|
+
if (!req.user || id == null || id === '')
|
|
218
|
+
return false;
|
|
219
|
+
try {
|
|
220
|
+
const stored = (await req.payload.findByID({
|
|
221
|
+
collection: o.memberships,
|
|
222
|
+
id: id,
|
|
223
|
+
depth: 0,
|
|
224
|
+
overrideAccess: true,
|
|
225
|
+
disableErrors: true,
|
|
226
|
+
select: { user: true, wall: true },
|
|
227
|
+
req,
|
|
228
|
+
}));
|
|
229
|
+
if (!stored)
|
|
230
|
+
return false;
|
|
231
|
+
return (await wallShowChange(o, req, stored, stored.wall?.show !== true)).allowed;
|
|
232
|
+
}
|
|
233
|
+
catch {
|
|
234
|
+
return false;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
190
237
|
/** Checkout is allowed here: no `canCheckout`, or `canCheckout` answered exactly `true`. */
|
|
191
238
|
export const checkoutAllowed = (o, payload) => o.canCheckout ? exactlyTrue(() => o.canCheckout({ payload })) : Promise.resolve(true);
|
package/dist/collections.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { APIError } from 'payload';
|
|
2
2
|
import { generateKeyBetween } from 'payload/shared';
|
|
3
|
-
import { inVersions, managerReaches, managerScope, matchesWhere, viaMembership } from './access.js';
|
|
3
|
+
import { inVersions, managerReaches, managerScope, matchesWhere, viaMembership, wallShowChange, wallShowOpen } from './access.js';
|
|
4
4
|
const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
|
|
5
5
|
/** Drag-and-drop ordered (Payload `orderable`); a new record goes between its alphabetical neighbours. */
|
|
6
6
|
const placeAlphabetically = (o, slug, field) => async ({ data, operation, req }) => {
|
|
@@ -47,17 +47,19 @@ const stripeProductField = (read) => ({
|
|
|
47
47
|
const fresh = (value = null) => ({ beforeDuplicate: [() => value] });
|
|
48
48
|
/** Only the member whose row it is. */
|
|
49
49
|
const memberOnly = ({ req, doc }) => Boolean(req.user) && String(idOf(doc?.user)) === String(req.user.id);
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
|
|
50
|
+
/**
|
|
51
|
+
* Update access for `wall.show`, by the rule the wall endpoint uses (`wallShowChange`): the member
|
|
52
|
+
* sets anything, a manager who reaches the row may only hide it (`false`), e.g. for an offensive name
|
|
53
|
+
* or a takedown request. On a save Payload passes the incoming group as `siblingData`, and the new
|
|
54
|
+
* value is judged. When Payload works out what the admin form may edit it passes no `siblingData`,
|
|
55
|
+
* and the box is open when flipping the stored value would be allowed.
|
|
56
|
+
*/
|
|
57
|
+
const wallShow = (o) => async ({ req, id, doc, siblingData }) => {
|
|
58
|
+
const row = doc;
|
|
59
|
+
const rowId = id ?? row?.id;
|
|
60
|
+
if (siblingData === undefined)
|
|
61
|
+
return wallShowOpen(o, req, rowId);
|
|
62
|
+
return (await wallShowChange(o, req, { id: rowId, user: row?.user }, siblingData?.show)).allowed;
|
|
61
63
|
};
|
|
62
64
|
/**
|
|
63
65
|
* Manager access by `canManage`'s answer: `true` is every row, a query is only the rows it matches
|
|
@@ -325,7 +327,7 @@ export function membershipsCollection(o) {
|
|
|
325
327
|
admin: {
|
|
326
328
|
useAsTitle: 'label',
|
|
327
329
|
defaultColumns: ['label', 'kind', 'amount', 'interval', 'status', 'currentPeriodEnd'],
|
|
328
|
-
description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the staff notes here.
|
|
330
|
+
description: 'Members’ subscriptions. Created and updated by checkout and Stripe; edit the staff notes here. A manager can hide a backers wall entry by clearing its box.',
|
|
329
331
|
},
|
|
330
332
|
// Created by checkout and updated by Stripe webhooks; members manage theirs through the plugin's endpoints.
|
|
331
333
|
access: { read: ownOrManager, readVersions: managersReadVersions(o, o.memberships), create: nobody, update, delete: remove },
|
|
@@ -401,7 +403,7 @@ export function membershipsCollection(o) {
|
|
|
401
403
|
name: 'wall',
|
|
402
404
|
label: 'Backers wall',
|
|
403
405
|
type: 'group',
|
|
404
|
-
admin: { description: 'Members choose whether and how they appear; nothing is public otherwise.' },
|
|
406
|
+
admin: { description: 'Members choose whether and how they appear; nothing is public otherwise. A manager can clear the box to hide an entry. Only the member can show it again.' },
|
|
405
407
|
fields: [
|
|
406
408
|
{ name: 'show', label: 'Show on the backers wall', type: 'checkbox', defaultValue: false, access: { update: wallShow(o) }, hooks: fresh(false) },
|
|
407
409
|
{ name: 'name', label: 'Name on the wall', type: 'text', maxLength: 80, access: { update: memberOnly }, hooks: fresh() },
|
package/dist/endpoints.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { membershipRole, wallShowChange } from './access.js';
|
|
2
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) => {
|
|
@@ -47,11 +47,10 @@ async function ownMembership(req, { memberOnly = false } = {}) {
|
|
|
47
47
|
if (here === null || idOf(m[o.scopeField]) !== here)
|
|
48
48
|
return null;
|
|
49
49
|
}
|
|
50
|
-
|
|
50
|
+
const role = await membershipRole(o, req, m);
|
|
51
|
+
if (role === 'member')
|
|
51
52
|
return m;
|
|
52
|
-
if (memberOnly)
|
|
53
|
-
return null;
|
|
54
|
-
if (!(await managerReaches(o, req, o.memberships, m.id)))
|
|
53
|
+
if (memberOnly || role !== 'manager')
|
|
55
54
|
return null;
|
|
56
55
|
// And the collection's own read access, so rules the host added there (a tenant plugin's, say) apply too.
|
|
57
56
|
const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
|
|
@@ -144,10 +143,12 @@ export const wallEndpoint = {
|
|
|
144
143
|
if (!m)
|
|
145
144
|
return json({ error: 'Not found.' }, 404);
|
|
146
145
|
const b = await body(req);
|
|
147
|
-
const member = idOf(m.user) === String(req.user.id);
|
|
148
146
|
// Only the member shows themselves on the wall or changes the name; a manager may only hide it.
|
|
149
|
-
|
|
147
|
+
// The same check answers for the field in the admin form and the other APIs.
|
|
148
|
+
const { role, allowed } = await wallShowChange(membershipOf(req.payload), req, m, b.show);
|
|
149
|
+
if (!allowed)
|
|
150
150
|
return json({ error: 'Only the member can do that.' }, 403);
|
|
151
|
+
const member = role === 'member';
|
|
151
152
|
const name = member ? (typeof b.name === 'string' ? b.name.trim().slice(0, 80) : '') : (m.wall?.name ?? '');
|
|
152
153
|
const updated = await req.payload.update({
|
|
153
154
|
collection: membershipOf(req.payload).memberships,
|
package/dist/guard.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CollectionBeforeOperationHook, CollectionConfig, Field, PayloadRequest } from 'payload';
|
|
1
|
+
import type { CollectionAfterErrorHook, CollectionBeforeOperationHook, CollectionConfig, Field, PayloadRequest } from 'payload';
|
|
2
2
|
import type { ResolvedMembership } from './types.js';
|
|
3
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
4
|
/**
|
|
@@ -17,5 +17,24 @@ export declare function refuseBadKeys(data: unknown, fields: Field[] | null | un
|
|
|
17
17
|
* restore a version that is itself inside their scope. A version that can't be read is refused.
|
|
18
18
|
*/
|
|
19
19
|
export declare function writeGuard(o: ResolvedMembership): CollectionBeforeOperationHook;
|
|
20
|
-
/**
|
|
20
|
+
/** The answer to a REST save the database refused because another save to the same record committed first. */
|
|
21
|
+
export declare const SAME_MOMENT_MESSAGE = "Another change to this record was being saved at the same moment, so this one was not saved. Try again.";
|
|
22
|
+
/**
|
|
23
|
+
* The database's own write conflict, and only that: MongoDB's code 112 or its code name. The
|
|
24
|
+
* message is never read, so another error that happens to mention a write conflict keeps its answer.
|
|
25
|
+
*/
|
|
26
|
+
export declare function isDatabaseWriteConflict(error: unknown): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Two saves to one record at the same moment: the database lets one commit and aborts the other's
|
|
29
|
+
* transaction, so nothing of the other is stored. Over REST that one answers 409 with plain words
|
|
30
|
+
* and the caller sends it again. Every other error is left as it is. The save isn't retried here:
|
|
31
|
+
* a host's hooks may already have run for it. GraphQL and Local API callers get the database's
|
|
32
|
+
* error unchanged.
|
|
33
|
+
*/
|
|
34
|
+
export declare const sameMomentConflict: CollectionAfterErrorHook;
|
|
35
|
+
/**
|
|
36
|
+
* Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's
|
|
37
|
+
* overrides, and the same-moment answer in front of its `afterError` hooks, so a host's own hook
|
|
38
|
+
* still sees the error and can answer differently.
|
|
39
|
+
*/
|
|
21
40
|
export declare function guarded(o: ResolvedMembership, c: CollectionConfig): CollectionConfig;
|
package/dist/guard.js
CHANGED
|
@@ -149,7 +149,35 @@ export function writeGuard(o) {
|
|
|
149
149
|
return args;
|
|
150
150
|
};
|
|
151
151
|
}
|
|
152
|
-
/**
|
|
152
|
+
/** The answer to a REST save the database refused because another save to the same record committed first. */
|
|
153
|
+
export const SAME_MOMENT_MESSAGE = 'Another change to this record was being saved at the same moment, so this one was not saved. Try again.';
|
|
154
|
+
/**
|
|
155
|
+
* The database's own write conflict, and only that: MongoDB's code 112 or its code name. The
|
|
156
|
+
* message is never read, so another error that happens to mention a write conflict keeps its answer.
|
|
157
|
+
*/
|
|
158
|
+
export function isDatabaseWriteConflict(error) {
|
|
159
|
+
const e = error;
|
|
160
|
+
if (!e || typeof e !== 'object')
|
|
161
|
+
return false;
|
|
162
|
+
return e.code === 112 || e.codeName === 'WriteConflict';
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Two saves to one record at the same moment: the database lets one commit and aborts the other's
|
|
166
|
+
* transaction, so nothing of the other is stored. Over REST that one answers 409 with plain words
|
|
167
|
+
* and the caller sends it again. Every other error is left as it is. The save isn't retried here:
|
|
168
|
+
* a host's hooks may already have run for it. GraphQL and Local API callers get the database's
|
|
169
|
+
* error unchanged.
|
|
170
|
+
*/
|
|
171
|
+
export const sameMomentConflict = ({ error }) => {
|
|
172
|
+
if (!isDatabaseWriteConflict(error))
|
|
173
|
+
return;
|
|
174
|
+
return { status: 409, response: { errors: [{ message: SAME_MOMENT_MESSAGE }] } };
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's
|
|
178
|
+
* overrides, and the same-moment answer in front of its `afterError` hooks, so a host's own hook
|
|
179
|
+
* still sees the error and can answer differently.
|
|
180
|
+
*/
|
|
153
181
|
export function guarded(o, c) {
|
|
154
|
-
return { ...c, hooks: { ...c.hooks, beforeOperation: [writeGuard(o), ...(c.hooks?.beforeOperation ?? [])] } };
|
|
182
|
+
return { ...c, hooks: { ...c.hooks, beforeOperation: [writeGuard(o), ...(c.hooks?.beforeOperation ?? [])], afterError: [sameMomentConflict, ...(c.hooks?.afterError ?? [])] } };
|
|
155
183
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@extantape/payload-plugin-membership",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
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": {
|