@extantape/payload-plugin-membership 0.5.1 → 0.5.3

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
@@ -75,14 +75,64 @@ In Stripe, add a webhook endpoint `https://<your site>/api/memberships/stripe-we
75
75
  | Endpoint | Body | Result |
76
76
  |---|---|---|
77
77
  | `POST /api/memberships/checkout` | `{ tier }` or `{ pledges: [{ category, amount }] }`, `interval` (`month`/`year`), `wall?: { show, name }`, `successPath?`, `cancelPath?` | `{ url }` of Stripe Checkout |
78
- | `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership (from the next invoice) |
79
- | `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period |
78
+ | `POST /api/memberships/:id/change` | `{ tier }` or `{ pledges }` | the updated membership as the caller can read it (from the next invoice) |
79
+ | `POST /api/memberships/:id/cancel` | | cancels at the end of the paid period; answers with the membership as the caller can read it |
80
80
  | `POST /api/memberships/:id/portal` | `{ returnPath? }` | `{ url }` of Stripe's customer portal |
81
81
  | `POST /api/memberships/:id/wall` | `{ show, name }` | the member's backers-wall choice. A manager may only send `show: false` |
82
82
 
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
+
93
+ `change` and `cancel` call Stripe first and save the membership after. If that save loses to another
94
+ save made at the same moment, Stripe has already taken the change, so they answer 409 with
95
+ `Your change went through with Stripe. Your membership will update shortly.` Don't send it again.
96
+ Nothing of the lost save is stored, and the membership catches up when Stripe's
97
+ `customer.subscription.updated` event arrives. For that, `change` writes the new plan (tier or
98
+ pledges, and the amount) into the subscription's metadata under `membershipPlan`, in the same Stripe
99
+ call, and the webhook reads it from the subscription as Stripe holds it at that moment. Once a
100
+ subscription carries a plan there, that plan is what the membership follows, so change plans through
101
+ `change` or `changeMembership`. A plan that names a tier or category that no longer exists, or one
102
+ from another site, is left out and the membership keeps what it has. `change` also sends Stripe an
103
+ idempotency key made from the membership, the new plan and the subscription's current items, so the
104
+ same change sent to Stripe twice is one change there. `cancel` sends no key: asking twice does no
105
+ harm. `changeMembership` and `cancelMembership` throw the same 409 to server code. The clash is
106
+ logged at error level with the membership's id.
107
+
108
+ `change` and `cancel` answer with the membership read again with the caller's own access, so the body is what
109
+ `GET /api/memberships/:id` would give them. A member's answer has no `stripe` ids, no staff `notes` and no
110
+ `changingUntil`; staff get what staff can read, and still never `changingUntil`.
111
+
112
+ Changing plan after a cancel keeps the membership going. `change` tells Stripe not to cancel at the end of
113
+ the period, so the cancel is lifted, whoever made it, and the member has to cancel again to stop it.
114
+
115
+ One change of plan or cancel runs at a time for a membership. `change` and `cancel` (staff cancel
116
+ included, it is the same endpoint) hold the membership before they call Stripe and give it back when
117
+ they are done. A second change or cancel sent meanwhile answers 409 with
118
+ `Another change to this membership is in progress. Try again in a moment.` Nothing is sent to Stripe
119
+ for it and nothing is stored, so it is safe to send again. This also means a cancel can't be undone
120
+ by a change that was already at Stripe. The hold lasts two minutes at most, so a process that stops
121
+ halfway can't leave a membership stuck. It lives in a hidden `changingUntil` field that only the
122
+ plugin writes. It shows up in the GraphQL types, reads return null, and `where`, `sort` and
123
+ `select` on it are refused.
124
+
125
+ The hold is atomic on MongoDB, where it is tested. On Postgres and SQLite it has not been run:
126
+ `updateOne` with a `where` may be a read followed by a write there, so two claims could both win. The
127
+ `changingUntil` field also needs a migration on those adapters, or changes will fail.
128
+
129
+ On `customer.subscription.updated` the webhook reads the subscription from Stripe and takes the
130
+ status, `cancelAtPeriodEnd`, the period end and the plan from what Stripe holds at that moment. The
131
+ event's own copy isn't used, so an older event that arrives late can't undo a cancel or bring an
132
+ older plan back. A subscription event reaches only the membership that already holds that
133
+ subscription's id, which `checkout.session.completed` sets. An event for any other subscription is
134
+ ignored.
135
+
86
136
  ## Options
87
137
 
88
138
  | Option | Default | |
@@ -185,7 +235,11 @@ A manager of a membership hides its wall entry in the admin form by clearing the
185
235
  saving. The box is open to them only while the entry is shown. Once it is hidden the box is
186
236
  read-only, and only the member can show it again, through the wall endpoint. The wall endpoint
187
237
  (`POST /api/memberships/:id/wall` with `show: false`), REST and the Local API hide an entry too. One
188
- check decides all of them, so the admin form allows what the wall endpoint allows. A save
238
+ check decides who may hide on all of them, so the admin form allows what the wall endpoint allows.
239
+ The wall endpoint also looks the membership up on the request's site first. With `scopeField`, a
240
+ membership with no site is on no site, so the wall endpoint answers 404 for it, while a manager of
241
+ every row (`canManage` answering `true`) can still hide it through the field: the admin form, REST
242
+ or the Local API. A save
189
243
  from a manager that sets `show` to `true` leaves the entry hidden and saves the other fields.
190
244
  Server code that writes with `overrideAccess` (checkout, Stripe events) is unchanged. A manager can
191
245
  set a category's `parent` only to a category in their scope. That is judged on the parent the row
package/dist/api.d.ts CHANGED
@@ -33,13 +33,18 @@ export declare function startCheckout(payload: Payload, args: Choice & {
33
33
  url: string;
34
34
  membership: string;
35
35
  }>;
36
+ /** What a member is told when Stripe took the change and the membership's own save lost to another save made at the same moment. */
37
+ export declare const WENT_THROUGH_MESSAGE = "Your change went through with Stripe. Your membership will update shortly.";
38
+ /** How long a change of plan or a cancel may hold a membership. Past this, a claim left by a process that stopped no longer blocks. */
39
+ export declare const CHANGE_HOLD_MS: number;
40
+ export declare const CHANGE_IN_PROGRESS_MESSAGE = "Another change to this membership is in progress. Try again in a moment.";
36
41
  /**
37
42
  * Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
38
43
  * With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
39
44
  * site can't be changed (404) until it is given one.
40
45
  */
41
46
  export declare function changeMembership(payload: Payload, membershipId: string, choice: Omit<Choice, 'interval'>): Promise<Doc>;
42
- /** Cancels at the end of the paid period (the member keeps their perks until then). */
47
+ /** Cancels at the end of the paid period (the member keeps their perks until then). Takes the same hold as a change of plan. */
43
48
  export declare function cancelMembership(payload: Payload, membershipId: string): Promise<Doc>;
44
49
  /** Stripe's customer portal (payment method, invoices, cancel). */
45
50
  export declare function portalLink(payload: Payload, membershipId: string, returnURL: string): Promise<string>;
package/dist/api.js CHANGED
@@ -1,5 +1,7 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { APIError } from 'payload';
2
3
  import { checkoutAllowed } from './access.js';
4
+ import { isDatabaseWriteConflict } from './guard.js';
3
5
  const idOf = (v) => (v && typeof v === 'object' ? String(v.id) : v ? String(v) : null);
4
6
  const ctx = { membershipSync: true };
5
7
  export const membershipOf = (payload) => payload.config.custom?.membership;
@@ -124,6 +126,125 @@ export async function startCheckout(payload, args) {
124
126
  throw new APIError('Stripe did not return a checkout page.', 502, undefined, true);
125
127
  return { url: session.url, membership: String(membership.id) };
126
128
  }
129
+ /** The subscription metadata keys that hold the plan, in pieces of at most 500 characters (Stripe's limit for one value). */
130
+ const PLAN_KEY = /^membershipPlan\d*$/;
131
+ const planKey = (i) => (i === 0 ? 'membershipPlan' : `membershipPlan${i}`);
132
+ /**
133
+ * The plan as subscription metadata, sent in the same Stripe call that changes the subscription, so
134
+ * Stripe holds what the membership should say. Pieces left over from a longer plan are cleared.
135
+ */
136
+ function planMetadata(plan, existing) {
137
+ const text = JSON.stringify({ k: plan.kind, t: plan.tier, p: plan.pledges.map((p) => [p.category, p.amount]), a: plan.amount });
138
+ const out = {};
139
+ for (const k of Object.keys(existing ?? {}))
140
+ if (PLAN_KEY.test(k))
141
+ out[k] = ''; // an empty value removes the key
142
+ for (let i = 0; i * 500 < text.length; i++)
143
+ out[planKey(i)] = text.slice(i * 500, (i + 1) * 500);
144
+ return out;
145
+ }
146
+ const wholeAmount = (v) => typeof v === 'number' && Number.isInteger(v) && v > 0;
147
+ /** The plan in a subscription's metadata, or `null` when there is none or it isn't exactly the shape `planMetadata` writes. */
148
+ function planFrom(metadata) {
149
+ let text = '';
150
+ for (let i = 0; typeof metadata?.[planKey(i)] === 'string' && metadata[planKey(i)] !== ''; i++)
151
+ text += metadata[planKey(i)];
152
+ if (!text)
153
+ return null;
154
+ try {
155
+ const v = JSON.parse(text);
156
+ if (!v || typeof v !== 'object' || !wholeAmount(v.a) || !Array.isArray(v.p))
157
+ return null;
158
+ const pledges = [];
159
+ for (const row of v.p) {
160
+ if (!Array.isArray(row) || row.length !== 2 || typeof row[0] !== 'string' || row[0] === '' || !wholeAmount(row[1]))
161
+ return null;
162
+ pledges.push({ category: row[0], amount: row[1] });
163
+ }
164
+ if (v.k === 'tier')
165
+ return typeof v.t === 'string' && v.t !== '' && pledges.length === 0 ? { kind: 'tier', tier: v.t, pledges, amount: v.a } : null;
166
+ if (v.k !== 'pledge' || v.t !== null || pledges.length === 0 || pledges.length > 20)
167
+ return null;
168
+ if (new Set(pledges.map((p) => p.category)).size !== pledges.length || pledges.reduce((sum, p) => sum + p.amount, 0) !== v.a)
169
+ return null;
170
+ return { kind: 'pledge', tier: null, pledges, amount: v.a };
171
+ }
172
+ catch {
173
+ return null;
174
+ }
175
+ }
176
+ const samePlan = (m, plan) => m.kind === plan.kind &&
177
+ idOf(m.tier) === plan.tier &&
178
+ m.amount === plan.amount &&
179
+ JSON.stringify((m.pledges ?? []).map((p) => [idOf(p.category), p.amount])) === JSON.stringify(plan.pledges.map((p) => [p.category, p.amount]));
180
+ /**
181
+ * The plan a membership should be given from its own subscription as Stripe holds it now (`live`),
182
+ * or `null` to leave it alone. A plan that names a tier or category that is gone, or one from
183
+ * another site, is left out, and the membership keeps what it has.
184
+ */
185
+ async function planToApply(payload, o, m, live) {
186
+ if (!m.stripe?.subscription || m.stripe.subscription !== live.id)
187
+ return null;
188
+ const plan = planFrom(live.metadata);
189
+ if (!plan || samePlan(m, plan))
190
+ return null;
191
+ const site = scopeOfRow(o, m);
192
+ const usable = (d) => Boolean(d) && (!o.scopeField || (site !== null && idOf(d[o.scopeField]) === site));
193
+ const rows = plan.kind === 'tier' ? [[o.tiers, plan.tier]] : plan.pledges.map((p) => [o.categories, p.category]);
194
+ const names = [];
195
+ for (const [slug, id] of rows) {
196
+ const row = (await payload.findByID({ collection: slug, id, depth: 0, overrideAccess: true, disableErrors: true }).catch(() => null));
197
+ if (!usable(row)) {
198
+ payload.logger.warn({ membership: String(m.id) }, 'Membership: the plan on the Stripe subscription names a tier or category that isn’t available, so the membership was left as it is');
199
+ return null;
200
+ }
201
+ names.push(String(row.name));
202
+ }
203
+ const user = (await payload.findByID({ collection: o.users, id: idOf(m.user), depth: 0, overrideAccess: true, disableErrors: true }).catch(() => null));
204
+ return { kind: plan.kind, tier: plan.tier, pledges: plan.pledges, amount: plan.amount, label: `${user?.name || user?.email || 'Member'} · ${names.join(', ')}`.slice(0, 200) };
205
+ }
206
+ /** What a member is told when Stripe took the change and the membership's own save lost to another save made at the same moment. */
207
+ export const WENT_THROUGH_MESSAGE = 'Your change went through with Stripe. Your membership will update shortly.';
208
+ /** How long a change of plan or a cancel may hold a membership. Past this, a claim left by a process that stopped no longer blocks. */
209
+ export const CHANGE_HOLD_MS = 2 * 60 * 1000;
210
+ export const CHANGE_IN_PROGRESS_MESSAGE = 'Another change to this membership is in progress. Try again in a moment.';
211
+ /**
212
+ * Claims a membership for one change of plan: a single conditional write that sets `changingUntil`
213
+ * only when no claim is held or the one held has run out. Returns the value to release with, or
214
+ * `null` when another change holds it. Outside any transaction, so two claims can't both succeed.
215
+ */
216
+ async function claimForChange(payload, o, id) {
217
+ const now = Date.now();
218
+ const until = new Date(now + CHANGE_HOLD_MS).toISOString();
219
+ const free = { or: [{ changingUntil: { exists: false } }, { changingUntil: { equals: null } }, { changingUntil: { less_than: new Date(now).toISOString() } }] };
220
+ const claimed = await payload.db.updateOne({ collection: o.memberships, where: { and: [{ id: { equals: id } }, free] }, data: { changingUntil: until } });
221
+ return claimed ? until : null;
222
+ }
223
+ /** Gives a claim back, only if it is still this one. A failure here is logged and left to the expiry. */
224
+ async function releaseChange(payload, o, id, until) {
225
+ try {
226
+ await payload.db.updateOne({ collection: o.memberships, where: { and: [{ id: { equals: id } }, { changingUntil: { equals: until } }] }, data: { changingUntil: null }, returning: false });
227
+ }
228
+ catch (err) {
229
+ payload.logger.warn({ err, membership: String(id) }, 'Membership: a change’s claim on the membership couldn’t be released; it runs out by itself');
230
+ }
231
+ }
232
+ /**
233
+ * Saves a membership after Stripe has already taken the change. When the save loses to another
234
+ * save made at the same moment, nothing of it is stored and Stripe's next subscription event brings
235
+ * the membership up to date, so the caller gets a 409 that says so. Any other error is passed on.
236
+ */
237
+ async function saveAfterStripe(payload, o, id, data) {
238
+ try {
239
+ return (await payload.update({ collection: o.memberships, id: id, data: data, overrideAccess: true, context: ctx }));
240
+ }
241
+ catch (err) {
242
+ if (!isDatabaseWriteConflict(err))
243
+ throw err;
244
+ payload.logger.error({ err, membership: String(id) }, 'Membership: Stripe took the change, and the membership’s save lost to another save at the same moment. The next subscription event updates it.');
245
+ throw new APIError(WENT_THROUGH_MESSAGE, 409, undefined, true);
246
+ }
247
+ }
127
248
  /**
128
249
  * Changes the tier or pledges of a running membership (same interval; takes effect from the next invoice).
129
250
  * With `scopeField`, only to tiers and categories of the membership's own site; a membership with no
@@ -137,28 +258,56 @@ export async function changeMembership(payload, membershipId, choice) {
137
258
  const scope = o.scopeField ? requireScope(o, idOf(m[o.scopeField])) : null;
138
259
  const { kind, lines, tier, pledges } = await linesFor(payload, o, { ...choice, interval: m.interval }, scope);
139
260
  const stripe = stripeOf(o);
261
+ // One change of plan at a time: two at once would each swap the same items and Stripe could end
262
+ // up billing both. A second change is refused here, before Stripe hears of it.
263
+ const claim = await claimForChange(payload, o, m.id);
264
+ if (!claim)
265
+ throw new APIError(CHANGE_IN_PROGRESS_MESSAGE, 409, undefined, true);
266
+ try {
267
+ return await changeClaimed(payload, o, stripe, m, { kind, lines, tier, pledges });
268
+ }
269
+ finally {
270
+ await releaseChange(payload, o, m.id, claim);
271
+ }
272
+ }
273
+ async function changeClaimed(payload, o, stripe, read, { kind, lines, tier, pledges }) {
274
+ // Read again now that the claim is held: an earlier change may have finished in between.
275
+ const m = (await payload.findByID({ collection: o.memberships, id: read.id, depth: 1, overrideAccess: true }));
276
+ if (!m.stripe?.subscription || m.stripe.subscription !== read.stripe.subscription || m.interval !== read.interval || !['active', 'past_due'].includes(m.status))
277
+ throw new APIError('Only a running membership can be changed.', 409, undefined, true);
140
278
  const sub = await stripe.subscriptions.retrieve(m.stripe.subscription);
279
+ const plan = { kind, tier: tier ? String(tier.id) : null, pledges, amount: lines.reduce((sum, l) => sum + l.amount, 0) };
280
+ // The same change sent twice against the same subscription items is one change to Stripe.
281
+ const items = sub.items.data.map((i) => i.id);
282
+ const idempotencyKey = `membership-change-${createHash('sha256').update(JSON.stringify([String(m.id), plan.kind, plan.tier, plan.pledges.map((p) => [p.category, p.amount]), plan.amount, [...items].sort()])).digest('hex')}`;
141
283
  await stripe.subscriptions.update(sub.id, {
142
- items: [...sub.items.data.map((i) => ({ id: i.id, deleted: true })), ...lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, m.interval) }))],
284
+ items: [...items.map((id) => ({ id, deleted: true })), ...lines.map((l) => ({ quantity: 1, price_data: priceData(o, l, m.interval) }))],
285
+ metadata: planMetadata(plan, sub.metadata),
143
286
  proration_behavior: 'none',
144
287
  cancel_at_period_end: false,
145
- });
146
- return (await payload.update({
147
- collection: o.memberships,
148
- id: m.id,
149
- data: { kind, tier: tier ? tier.id : null, pledges, amount: lines.reduce((sum, l) => sum + l.amount, 0), cancelAtPeriodEnd: false, label: labelOf(typeof m.user === 'object' ? m.user : { email: '' }, kind, tier, lines) },
150
- overrideAccess: true,
151
- context: ctx,
152
- }));
288
+ }, { idempotencyKey });
289
+ return saveAfterStripe(payload, o, m.id, { kind, tier: tier ? tier.id : null, pledges, amount: plan.amount, cancelAtPeriodEnd: false, label: labelOf(typeof m.user === 'object' ? m.user : { email: '' }, kind, tier, lines) });
153
290
  }
154
- /** Cancels at the end of the paid period (the member keeps their perks until then). */
291
+ /** Cancels at the end of the paid period (the member keeps their perks until then). Takes the same hold as a change of plan. */
155
292
  export async function cancelMembership(payload, membershipId) {
156
293
  const o = membershipOf(payload);
157
294
  const m = (await payload.findByID({ collection: o.memberships, id: membershipId, depth: 0, overrideAccess: true }));
158
295
  if (!m.stripe?.subscription)
159
296
  throw new APIError('This membership has no subscription to cancel.', 409, undefined, true);
160
- await stripeOf(o).subscriptions.update(m.stripe.subscription, { cancel_at_period_end: true });
161
- return (await payload.update({ collection: o.memberships, id: m.id, data: { cancelAtPeriodEnd: true }, overrideAccess: true, context: ctx }));
297
+ const stripe = stripeOf(o);
298
+ // A cancel takes the same hold as a change of plan. Without it, a change already at Stripe would
299
+ // send cancel_at_period_end: false after the cancel and quietly undo it. The loser gets a 409
300
+ // before anything reaches Stripe.
301
+ const claim = await claimForChange(payload, o, m.id);
302
+ if (!claim)
303
+ throw new APIError(CHANGE_IN_PROGRESS_MESSAGE, 409, undefined, true);
304
+ try {
305
+ await stripe.subscriptions.update(m.stripe.subscription, { cancel_at_period_end: true });
306
+ return await saveAfterStripe(payload, o, m.id, { cancelAtPeriodEnd: true });
307
+ }
308
+ finally {
309
+ await releaseChange(payload, o, m.id, claim);
310
+ }
162
311
  }
163
312
  /** Stripe's customer portal (payment method, invoices, cancel). */
164
313
  export async function portalLink(payload, membershipId, returnURL) {
@@ -282,13 +431,28 @@ export async function handleStripeEvent(payload, event) {
282
431
  }
283
432
  case 'customer.subscription.updated':
284
433
  case 'customer.subscription.deleted': {
285
- const sub = obj;
286
- const m = (await findBy(payload, o, { 'stripe.subscription': { equals: sub.id } })) ?? (sub.metadata?.membership ? await findBy(payload, o, { id: { equals: sub.metadata.membership } }) : undefined);
287
- if (!m)
434
+ const named = obj;
435
+ // Only the membership that already holds this subscription: an event for any other
436
+ // subscription changes nothing, whatever its metadata says.
437
+ const m = typeof named.id === 'string' && named.id !== '' ? await findBy(payload, o, { 'stripe.subscription': { equals: named.id } }) : undefined;
438
+ if (!m || m.stripe?.subscription !== named.id)
288
439
  return 'ignored';
440
+ // Stripe can deliver an update late or out of order, so an update only says something may have
441
+ // changed: the status, the cancel flag, the period end and the plan are read from the
442
+ // subscription as Stripe holds it now. A deleted subscription is final, and is taken as sent.
443
+ let sub = named;
444
+ if (event.type === 'customer.subscription.updated') {
445
+ const live = await stripeOf(o).subscriptions.retrieve(named.id);
446
+ if (!live || live.id !== named.id || typeof live.status !== 'string')
447
+ return 'ignored';
448
+ sub = live;
449
+ }
289
450
  const status = event.type === 'customer.subscription.deleted' ? 'canceled' : statusFrom(sub.status);
290
451
  const end = periodEndOf(sub);
452
+ // A change of plan whose own save didn't land is brought in here.
453
+ const plan = event.type === 'customer.subscription.updated' ? await planToApply(payload, o, m, sub) : null;
291
454
  await setMembership(payload, o, m, {
455
+ ...(plan ?? {}),
292
456
  status,
293
457
  cancelAtPeriodEnd: Boolean(sub.cancel_at_period_end),
294
458
  ...(end ? { currentPeriodEnd: new Date(end * 1000).toISOString() } : {}),
@@ -422,6 +422,24 @@ export function membershipsCollection(o) {
422
422
  ],
423
423
  },
424
424
  { name: 'notes', type: 'textarea', access: { read: managerField, update: managerField }, hooks: fresh(), admin: { position: 'sidebar' } },
425
+ {
426
+ // Held for a moment by a change of plan or a cancel, so two can't reach Stripe at once. Written only by
427
+ // the plugin's own atomic claim and release; like totalPaid it is left out of every save, so
428
+ // a whole-document save can't put an older value back. It appears in the GraphQL types, but reads
429
+ // return null, and where, sort and select on it are refused.
430
+ name: 'changingUntil',
431
+ type: 'date',
432
+ access: { read: () => false, create: () => false, update: () => false },
433
+ hooks: {
434
+ beforeChange: [
435
+ ({ siblingData }) => {
436
+ delete siblingData.changingUntil;
437
+ return undefined;
438
+ },
439
+ ],
440
+ },
441
+ admin: { hidden: true, readOnly: true },
442
+ },
425
443
  ],
426
444
  timestamps: true,
427
445
  };
package/dist/endpoints.js CHANGED
@@ -56,6 +56,15 @@ async function ownMembership(req, { memberOnly = false } = {}) {
56
56
  const visible = await req.payload.count({ collection, where: { id: { equals: m.id } }, overrideAccess: false, user: req.user, req });
57
57
  return visible.totalDocs > 0 ? m : null;
58
58
  }
59
+ /**
60
+ * The membership as this request's user may read it: what `GET /:id` would answer. The save behind
61
+ * `change` and `cancel` runs with full access, so its document is never sent. A row the user can't
62
+ * read comes back as its id alone.
63
+ */
64
+ async function readableAs(req, saved) {
65
+ const found = await req.payload.findByID({ collection: membershipOf(req.payload).memberships, id: String(saved.id), overrideAccess: false, user: req.user, req, disableErrors: true });
66
+ return found ?? { id: saved.id };
67
+ }
59
68
  /** POST /api/<memberships>/checkout { tier? | pledges?, interval, wall?, successPath?, cancelPath? } → { url } */
60
69
  export const checkoutEndpoint = {
61
70
  path: '/checkout',
@@ -94,7 +103,7 @@ export const changeEndpoint = {
94
103
  return json({ error: 'Not found.' }, 404);
95
104
  try {
96
105
  const b = await body(req);
97
- return json({ membership: await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null }) });
106
+ return json({ membership: await readableAs(req, await changeMembership(req.payload, String(m.id), { tier: b.tier ?? null, pledges: Array.isArray(b.pledges) ? b.pledges : null })) });
98
107
  }
99
108
  catch (err) {
100
109
  return fail(err);
@@ -110,7 +119,7 @@ export const cancelEndpoint = {
110
119
  if (!m)
111
120
  return json({ error: 'Not found.' }, 404);
112
121
  try {
113
- return json({ membership: await cancelMembership(req.payload, String(m.id)) });
122
+ return json({ membership: await readableAs(req, await cancelMembership(req.payload, String(m.id))) });
114
123
  }
115
124
  catch (err) {
116
125
  return fail(err);
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
- /** Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's overrides. */
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
- /** Puts the guard in front of the collection's `beforeOperation` hooks as they are after the host's overrides. */
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/dist/types.d.ts CHANGED
@@ -68,7 +68,9 @@ export type StripeLike = {
68
68
  };
69
69
  subscriptions: {
70
70
  retrieve: (id: string) => Promise<StripeSubscription>;
71
- update: (id: string, params: Record<string, unknown>) => Promise<StripeSubscription>;
71
+ update: (id: string, params: Record<string, unknown>, options?: {
72
+ idempotencyKey?: string;
73
+ }) => Promise<StripeSubscription>;
72
74
  };
73
75
  webhooks: {
74
76
  constructEvent: (payload: string, signature: string, secret: string) => StripeEvent;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-membership",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
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": {