@extantape/payload-plugin-hats 0.6.2 → 0.8.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/dist/link.js ADDED
@@ -0,0 +1,427 @@
1
+ import { blockedBy, CANT_CHECK } from './access.js';
2
+ import { approvalRefusal } from './approval.js';
3
+ import { exactId, labelOf, loadUser, members, membershipOf } from './endpoints.js';
4
+ import { asPlugin, DISSOLVING, hatsOptions, idOf, newToken, relId, removeWhere, serial, tell, withMark } from './state.js';
5
+ import { LINKS, MEMBERS, REQUESTS } from './types.js';
6
+ class Refused extends Error {
7
+ result;
8
+ constructor(result) {
9
+ super(result.reason);
10
+ this.result = result;
11
+ }
12
+ }
13
+ const STATUS = { linkingOff: 409, blocked: 409, notAccount: 404, sameAccount: 400, otherSet: 409, setFull: 409, notApprover: 403, ownSet: 403, notConfirmed: 409, failed: 500 };
14
+ const refusal = (reason, message) => ({ ok: false, status: STATUS[reason], reason, message });
15
+ const refuse = (reason, message) => {
16
+ throw new Refused(refusal(reason, message));
17
+ };
18
+ const MESSAGES = {
19
+ linkingOff: 'Linking accounts isn’t turned on here.',
20
+ notAccount: 'There’s no such account.',
21
+ sameAccount: 'An account can’t be linked with itself.',
22
+ otherSet: 'That account is already in another linked set.',
23
+ notConfirmed: 'That account isn’t waiting for approval.',
24
+ failed: 'Linking didn’t work. Try again.',
25
+ /** The site's `blocked` check failed or gave an answer that isn't a reason: the link version of the switch's wording. */
26
+ cantCheck: 'Linking isn’t available right now. Try again later.',
27
+ /** `req.transactionID` names a transaction the database adapter no longer has open. */
28
+ txGone: 'The request’s transaction has already ended, so nothing was linked. Start a new transaction and try again.',
29
+ /** A database error during the call made Payload end the request's transaction. */
30
+ txEnded: 'Linking didn’t work, and the database ended the request’s transaction, so every earlier write in it was rolled back too.',
31
+ /** The call's rows are gone, but an invitation it released couldn't be put back. */
32
+ inviteLost: 'Linking didn’t work and nothing is linked, but an open invitation to one of these accounts was canceled and has to be sent again.',
33
+ /** Removing the call's own rows failed too, so they may still stand. */
34
+ undoFailed: 'Linking didn’t work, and undoing it didn’t finish either, so these accounts may still be linked. Check them before trying again.',
35
+ };
36
+ const setFullMessage = (opts) => `A set can hold at most ${opts.maxLinked} accounts.`;
37
+ const RANK = { requested: 0, confirmed: 1, approved: 2 };
38
+ /** Runs a server link, turning every refusal and every unexpected error into a result. Never throws. */
39
+ async function settle(req, what, fn) {
40
+ let before = 'none';
41
+ let result;
42
+ try {
43
+ before = await txState(req);
44
+ // A transaction rolled back already, or one that never started: anything written now would land outside it, so
45
+ // nothing is.
46
+ if (before === 'gone')
47
+ return refusal('failed', MESSAGES.txGone);
48
+ // A transaction id still in a promise is replaced by the id it gave, as Payload does once a transaction it
49
+ // starts is open, so every read and write in the call sees the same transaction.
50
+ const raw = req.transactionID;
51
+ // `instanceof Promise` is the check Payload's own initTransaction uses. A promise from another realm fails it and
52
+ // stays as it is, and the open-transaction check (txState) finds no such transaction and refuses it: it fails closed.
53
+ if (raw instanceof Promise)
54
+ req.transactionID = await raw;
55
+ result = await fn();
56
+ }
57
+ catch (error) {
58
+ if (error instanceof Refused)
59
+ result = error.result;
60
+ else {
61
+ req.payload?.logger?.warn({ msg: `Hats: ${what} failed after an unexpected error` });
62
+ result = refusal('failed', MESSAGES.failed);
63
+ }
64
+ }
65
+ // Payload aborts a transaction on a database error inside it and clears `req.transactionID`, taking the host's
66
+ // earlier writes with it. The answer says so, so the host doesn't carry on as if its own writes still stood.
67
+ if (!result.ok && result.reason === 'failed' && before === 'live' && (await txState(req).catch(() => 'gone')) !== 'live') {
68
+ req.payload?.logger?.warn({ msg: `Hats: ${what} failed and the request's transaction was ended` });
69
+ return refusal('failed', MESSAGES.txEnded);
70
+ }
71
+ return result;
72
+ }
73
+ /**
74
+ * Whether the transaction `req` names is still open. Payload's adapters keep their open transactions in
75
+ * `payload.db.sessions` by id and drop one at commit or rollback, then write with no transaction for an id they don't
76
+ * hold. An adapter without that list can't be checked (`unknown`), and the call goes ahead as before.
77
+ */
78
+ async function txState(req) {
79
+ const raw = req.transactionID;
80
+ // Payload sets a promise here while a transaction is starting. One that rejected never started: nothing can join it.
81
+ let id = raw;
82
+ // Same check as Payload's initTransaction. A promise it misses (another realm) isn't a string or number, so it is
83
+ // never found among the open transactions and the call is refused: it fails closed.
84
+ if (raw instanceof Promise) {
85
+ try {
86
+ id = await raw;
87
+ }
88
+ catch {
89
+ return 'gone';
90
+ }
91
+ }
92
+ if (id == null || id === '')
93
+ return 'none';
94
+ const sessions = req.payload?.db?.sessions;
95
+ if (!sessions || typeof sessions !== 'object')
96
+ return 'unknown';
97
+ const session = sessions[String(id)];
98
+ if (!session)
99
+ return 'gone';
100
+ if (typeof session.inTransaction === 'function' && !session.inTransaction())
101
+ return 'gone';
102
+ return 'live';
103
+ }
104
+ /** Refuses when the request had an open transaction and it has ended since, so no row is written outside it. */
105
+ async function stillOpen(req, had) {
106
+ if (had === 'live' && (await txState(req)) !== 'live')
107
+ refuse('failed', MESSAGES.txEnded);
108
+ }
109
+ /** Linking on, and the site's `blocked` allowing it, read exactly as the endpoints read them. */
110
+ async function gate(req, opts) {
111
+ if (!opts.canApproveLinks)
112
+ refuse('linkingOff', MESSAGES.linkingOff);
113
+ if (opts.blocked) {
114
+ const ask = opts.blocked;
115
+ const why = await blockedBy(() => ask(req));
116
+ if (why !== null)
117
+ refuse('blocked', why === CANT_CHECK ? MESSAGES.cantCheck : why);
118
+ }
119
+ }
120
+ /** The account for an id written exactly as the users collection writes its ids, or `notAccount`. */
121
+ async function accountFor(req, opts, v) {
122
+ if (!exactId(req, opts, v))
123
+ return refuse('notAccount', MESSAGES.notAccount);
124
+ const user = await loadUser(req, String(v));
125
+ // A database may read another spelling as the same id (MongoDB takes an ObjectId in capitals); only the exact one counts.
126
+ if (!user || String(user.id) !== String(v))
127
+ refuse('notAccount', MESSAGES.notAccount);
128
+ return user;
129
+ }
130
+ /** The signed-in account on `req`, when it's one of the site's users, else null. */
131
+ const actingId = (req, opts) => {
132
+ const u = req.user;
133
+ return u && u.collection === opts.users ? u.id : null;
134
+ };
135
+ /**
136
+ * Removes the rows and set a call made, under the dissolving mark so the set isn't dissolved part way, then puts back
137
+ * any invitation it released. Rows go first, so a call that answers `failed` never leaves a link standing because an
138
+ * invitation couldn't be restored. Answers `undoFailed` when a row may still stand, `inviteLost` when the rows are gone
139
+ * but an invitation stayed canceled, and null when everything was put back.
140
+ */
141
+ async function undo(req, made) {
142
+ try {
143
+ await withMark(req, DISSOLVING, () => asPlugin(req, async () => {
144
+ for (const id of made.rows)
145
+ await removeWhere(req.payload, { collection: MEMBERS, where: { id: { equals: id } }, overrideAccess: true, req });
146
+ if (made.link)
147
+ await removeWhere(req.payload, { collection: LINKS, where: { id: { equals: made.link } }, overrideAccess: true, req });
148
+ }));
149
+ }
150
+ catch {
151
+ req.payload.logger.warn({ msg: 'Hats: server link clean-up didn’t finish; the new rows may remain' });
152
+ return refusal('failed', MESSAGES.undoFailed);
153
+ }
154
+ let lost = 0;
155
+ // Each one is tried, so one that fails doesn't keep the rest canceled.
156
+ for (const r of made.released) {
157
+ try {
158
+ await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: r.id, data: r.data, overrideAccess: true, req }));
159
+ }
160
+ catch {
161
+ lost++;
162
+ }
163
+ }
164
+ if (lost) {
165
+ req.payload.logger.warn({ msg: `Hats: server link undone, but ${lost} canceled invitation(s) couldn’t be put back` });
166
+ return refusal('failed', MESSAGES.inviteLost);
167
+ }
168
+ return null;
169
+ }
170
+ const rowsOf = async (req, users) => {
171
+ const out = [];
172
+ for (const u of users) {
173
+ const row = await membershipOf(req, String(u.id));
174
+ if (row)
175
+ out.push({ account: u.id, status: row.status });
176
+ }
177
+ return out;
178
+ };
179
+ const fire = (req, event) => tell(req.payload, req, event);
180
+ /**
181
+ * Fires a call's events side by side. Each handler is called in order, and each wait is bounded by `tell`, so a
182
+ * handler that hangs holds the call for one bound at most, however many events there are.
183
+ */
184
+ const fireAll = (req, events) => Promise.all(events.map((e) => fire(req, e)));
185
+ /**
186
+ * Approves one confirmed row as `req.user`. Shared by `approveLink` and a repeat `linkAccounts` that asks for
187
+ * approval. The approval rule is the admin form's (`approvalRefusal`), run before the write; the count runs again
188
+ * after it, so two approvals racing for the last place can't both stay.
189
+ */
190
+ async function approveRow(req, opts, row) {
191
+ const link = idOf(row.link);
192
+ const refused = await approvalRefusal(req, opts, { link, approving: 1, except: String(row.id) });
193
+ if (refused)
194
+ refuse(refused.reason, refused.message);
195
+ const by = actingId(req, opts);
196
+ const had = await txState(req);
197
+ await serial(req, () => asPlugin(req, async () => {
198
+ await stillOpen(req, had);
199
+ await req.payload.update({ collection: MEMBERS, id: row.id, data: { status: 'approved', approvedBy: relId(req.payload, opts.users, by), approvedAt: new Date().toISOString() }, overrideAccess: true, req });
200
+ const approved = await req.payload.count({ collection: MEMBERS, where: { and: [{ link: { equals: link } }, { status: { equals: 'approved' } }] }, overrideAccess: true, req });
201
+ if (approved.totalDocs > opts.maxLinked) {
202
+ await req.payload.update({ collection: MEMBERS, id: row.id, data: { status: 'confirmed', approvedBy: null, approvedAt: null }, overrideAccess: true, req });
203
+ refuse('setFull', setFullMessage(opts));
204
+ }
205
+ }));
206
+ await fire(req, { type: 'link-approved', req, link, account: idOf(row.user), by: String(by), source: 'server' });
207
+ }
208
+ async function linkCore(req, input) {
209
+ const opts = hatsOptions(req.payload);
210
+ await gate(req, opts);
211
+ const approve = input.approve === true;
212
+ // Who approves is checked before anything about the accounts, as in `approveLink`, so a caller who can't approve
213
+ // learns nothing about them from the answer. The checks that need the set run below.
214
+ if (approve) {
215
+ const notYou = await approvalRefusal(req, opts, { link: null, approving: 0 });
216
+ if (notYou)
217
+ refuse(notYou.reason, notYou.message);
218
+ }
219
+ const account = await accountFor(req, opts, input.account);
220
+ const other = await accountFor(req, opts, input.with);
221
+ const a = String(account.id);
222
+ const w = String(other.id);
223
+ if (a === w)
224
+ refuse('sameAccount', MESSAGES.sameAccount);
225
+ const want = approve ? 'approved' : 'confirmed';
226
+ const mineA = await membershipOf(req, a);
227
+ const mineW = await membershipOf(req, w);
228
+ const existing = mineW ? idOf(mineW.link) : null;
229
+ // A repeat: the account is in the set already. Same or higher status is done; a confirmed row asked to be approved
230
+ // is approved as `approveLink` would. A row still waiting for its own email isn't confirmed by the server.
231
+ if (mineA) {
232
+ if (!existing || idOf(mineA.link) !== existing)
233
+ refuse('otherSet', MESSAGES.otherSet);
234
+ const row = mineA;
235
+ if (RANK[row.status] >= RANK[want])
236
+ return { ok: true, link: relId(req.payload, LINKS, existing), rows: await rowsOf(req, [account, other]), already: true };
237
+ if (row.status === 'requested')
238
+ refuse('notConfirmed', MESSAGES.notConfirmed);
239
+ await approveRow(req, opts, row);
240
+ return { ok: true, link: relId(req.payload, LINKS, existing), rows: await rowsOf(req, [account, other]), already: false };
241
+ }
242
+ const adding = existing ? 1 : 2;
243
+ // Rows of every status count, so a set written by hand past the limit is never added to.
244
+ if (existing && (await members(req, existing)).length + adding > opts.maxLinked)
245
+ refuse('setFull', setFullMessage(opts));
246
+ if (approve) {
247
+ const refused = await approvalRefusal(req, opts, { link: existing, joining: existing ? [a] : [a, w], approving: adding });
248
+ if (refused)
249
+ refuse(refused.reason, refused.message);
250
+ }
251
+ const by = actingId(req, opts);
252
+ const made = { rows: [], released: [] };
253
+ const had = await txState(req);
254
+ const now = new Date().toISOString();
255
+ const rowData = (user, link) => ({
256
+ link: relId(req.payload, LINKS, link),
257
+ user: relId(req.payload, opts.users, user.id),
258
+ status: want,
259
+ confirmedAt: now,
260
+ addedBy: by == null ? null : relId(req.payload, opts.users, by),
261
+ ...(approve ? { approvedBy: relId(req.payload, opts.users, by), approvedAt: now } : {}),
262
+ });
263
+ const joined = existing ? [account] : [other, account];
264
+ let link = existing;
265
+ try {
266
+ await serial(req, () => asPlugin(req, async () => {
267
+ await stillOpen(req, had);
268
+ if (!link) {
269
+ link = String((await req.payload.create({ collection: LINKS, data: { requestedBy: relId(req.payload, opts.users, w), label: `Started by ${labelOf(other)}` }, overrideAccess: true, req })).id);
270
+ made.link = link;
271
+ }
272
+ for (const u of joined)
273
+ made.rows.push(String((await req.payload.create({ collection: MEMBERS, data: rowData(u, link), overrideAccess: true, req })).id));
274
+ // Joining a set writes the set's own record. Dissolving a set deletes that record, so with transactions the
275
+ // two can't both go through: whichever writes second gets a write conflict from the database and fails as a
276
+ // whole. Without that write, a dissolve already under way in another request (reading the set before this
277
+ // row existed) could commit after the checks below and leave this account alone in a set that's gone.
278
+ if (existing) {
279
+ const set = await req.payload.findByID({ collection: LINKS, id: link, depth: 0, overrideAccess: true, disableErrors: true, req });
280
+ if (!set)
281
+ refuse('failed', MESSAGES.failed);
282
+ await req.payload.update({ collection: LINKS, id: link, data: {}, depth: 0, overrideAccess: true, req });
283
+ }
284
+ // Checked again after the writes: an account deleted meanwhile, or another call filling the same set, undoes this one.
285
+ if (!(await loadUser(req, a)) || !(await loadUser(req, w)))
286
+ refuse('notAccount', MESSAGES.notAccount);
287
+ const inSet = await members(req, link);
288
+ if (inSet.length > opts.maxLinked)
289
+ refuse('setFull', setFullMessage(opts));
290
+ // The set may have dissolved meanwhile (another account left a set of two): it must still exist and hold this
291
+ // call's rows and at least one more, or the account would be left alone in a set that isn't there.
292
+ const setThere = (await req.payload.count({ collection: LINKS, where: { id: { equals: link } }, overrideAccess: true, req })).totalDocs === 1;
293
+ if (!setThere || inSet.length < 2 || made.rows.some((id) => !inSet.some((r) => String(r.id) === id)))
294
+ refuse('failed', MESSAGES.failed);
295
+ if (approve) {
296
+ const approved = await req.payload.count({ collection: MEMBERS, where: { and: [{ link: { equals: link } }, { status: { equals: 'approved' } }] }, overrideAccess: true, req });
297
+ if (approved.totalDocs > opts.maxLinked)
298
+ refuse('setFull', setFullMessage(opts));
299
+ }
300
+ // Open invitations to either account are released, as an account delete empties them: each account's one
301
+ // invitation place is free again, and a later confirmation would be refused by the one-set rule anyway.
302
+ // Each is noted before it changes, so an undo can put it back as it was.
303
+ for (const u of [account, other]) {
304
+ const { docs } = await req.payload.find({
305
+ collection: REQUESTS,
306
+ where: { or: [{ account: { equals: relId(req.payload, opts.users, u.id) } }, { holds: { equals: `account:${String(u.id)}` } }] },
307
+ depth: 0,
308
+ limit: 0,
309
+ pagination: false,
310
+ showHiddenFields: true,
311
+ overrideAccess: true,
312
+ req,
313
+ });
314
+ for (const d of docs) {
315
+ const data = { account: d.account == null ? null : relId(req.payload, opts.users, d.account), holds: d.holds, tokenHash: d.tokenHash ?? null };
316
+ await req.payload.update({ collection: REQUESTS, id: d.id, data: { account: null, holds: `none:${newToken()}`, tokenHash: null }, overrideAccess: true, req });
317
+ made.released.push({ id: String(d.id), data });
318
+ }
319
+ }
320
+ await stillOpen(req, had);
321
+ }));
322
+ }
323
+ catch (error) {
324
+ // Undo what this call wrote. A refusal found after the writes keeps its reason; a database error is `failed`,
325
+ // unless the account turns out to be in another set now (two calls raced for it and the unique index refused one).
326
+ const cleanUp = await undo(req, made);
327
+ if (cleanUp)
328
+ return cleanUp;
329
+ if (error instanceof Refused)
330
+ throw error;
331
+ const raced = await Promise.all([membershipOf(req, a), membershipOf(req, w)]).catch(() => null);
332
+ if (raced && raced.some((m, i) => m && (i === 0 || (existing ? idOf(m.link) !== existing : true))))
333
+ refuse('otherSet', MESSAGES.otherSet);
334
+ throw error;
335
+ }
336
+ // The rows are written by now, so a handler that fails or hangs can't undo or block them.
337
+ const told = [];
338
+ if (made.link)
339
+ told.push({ type: 'link-requested', req, link: made.link, by: w, account: a, source: 'server' });
340
+ for (const u of joined)
341
+ told.push({ type: 'link-confirmed', payload: req.payload, link: link, account: String(u.id), source: 'server' });
342
+ if (approve)
343
+ for (const u of joined)
344
+ told.push({ type: 'link-approved', req, link: link, account: String(u.id), by: String(by), source: 'server' });
345
+ await fireAll(req, told);
346
+ return { ok: true, link: relId(req.payload, LINKS, link), rows: await rowsOf(req, [account, other]), already: false };
347
+ }
348
+ async function approveCore(req, input) {
349
+ const opts = hatsOptions(req.payload);
350
+ await gate(req, opts);
351
+ // Who approves is checked before anything about the account or its row, so a caller who can't approve learns
352
+ // nothing from the answer, not even whether the account exists.
353
+ const notYou = await approvalRefusal(req, opts, { link: null, approving: 0 });
354
+ if (notYou)
355
+ refuse(notYou.reason, notYou.message);
356
+ const account = await accountFor(req, opts, input.account);
357
+ const row = (await membershipOf(req, String(account.id)));
358
+ if (!row)
359
+ refuse('notConfirmed', MESSAGES.notConfirmed);
360
+ const link = relId(req.payload, LINKS, idOf(row.link));
361
+ if (row.status === 'approved')
362
+ return { ok: true, link, rows: await rowsOf(req, [account]), already: true };
363
+ if (row.status !== 'confirmed')
364
+ refuse('notConfirmed', MESSAGES.notConfirmed);
365
+ await approveRow(req, opts, row);
366
+ return { ok: true, link, rows: await rowsOf(req, [account]), already: false };
367
+ }
368
+ /**
369
+ * Link two accounts from the site's own server code, for a flow where both people already agreed. It runs the
370
+ * plugin's own checks every time and has no option that loosens one. Joins `req`'s transaction when there is one;
371
+ * without one, it writes in order and undoes its own rows on failure. Never throws for a refusal.
372
+ */
373
+ export const linkAccounts = (req, input) => settle(req, 'server link', () => linkCore(req, { account: input?.account, with: input?.with, approve: input?.approve }));
374
+ /** Approve a confirmed account's row as the approver signed in on `req`, under the admin form's rule. Never throws for a refusal. */
375
+ export const approveLink = (req, input) => settle(req, 'server approval', () => approveCore(req, { account: input?.account }));
376
+ /**
377
+ * Lists the sets that break the plugin's rules, for rows written outside it (through the database adapter, say). It
378
+ * only reads and changes nothing: what to do about a set is the site's call. Results hold ids only.
379
+ */
380
+ export async function checkLinks(payloadOrReq) {
381
+ const isReq = 'payload' in payloadOrReq && payloadOrReq.payload != null;
382
+ const payload = isReq ? payloadOrReq.payload : payloadOrReq;
383
+ const req = isReq ? payloadOrReq : undefined;
384
+ const opts = hatsOptions(payload);
385
+ const read = { depth: 0, overrideAccess: true, pagination: false, limit: 0, req };
386
+ const sets = (await payload.find({ collection: LINKS, ...read })).docs;
387
+ const rows = (await payload.find({ collection: MEMBERS, showHiddenFields: true, ...read })).docs;
388
+ const userIds = [...new Set(rows.filter((r) => r.user != null).map((r) => idOf(r.user)))];
389
+ const known = new Set();
390
+ for (let i = 0; i < userIds.length; i += 100) {
391
+ const batch = userIds.slice(i, i + 100).map((id) => relId(payload, opts.users, id));
392
+ const found = await payload.find({ collection: opts.users, where: { id: { in: batch } }, ...read });
393
+ for (const u of found.docs)
394
+ known.add(idOf(u.id));
395
+ }
396
+ const byLink = new Map();
397
+ for (const r of rows) {
398
+ const k = idOf(r.link);
399
+ byLink.set(k, [...(byLink.get(k) ?? []), r]);
400
+ }
401
+ const setIds = new Map(sets.map((s) => [idOf(s.id), s.id]));
402
+ const out = [];
403
+ for (const key of new Set([...setIds.keys(), ...byLink.keys()])) {
404
+ const mine = byLink.get(key) ?? [];
405
+ const people = new Set(mine.filter((r) => r.user != null).map((r) => idOf(r.user)));
406
+ const problems = new Set();
407
+ if (!setIds.has(key))
408
+ problems.add('missingSet');
409
+ if (mine.length > opts.maxLinked)
410
+ problems.add('overFull');
411
+ if (mine.length < 2)
412
+ problems.add('alone');
413
+ for (const r of mine) {
414
+ if (r.user == null || !known.has(idOf(r.user)))
415
+ problems.add('missingAccount');
416
+ if (r.status === 'approved' && r.approvedBy == null)
417
+ problems.add('noApprover');
418
+ if (r.status === 'approved' && r.approvedBy != null && people.has(idOf(r.approvedBy)))
419
+ problems.add('selfApproved');
420
+ if (r.status !== 'requested' && r.tokenHash)
421
+ problems.add('liveToken');
422
+ }
423
+ if (problems.size)
424
+ out.push({ link: setIds.get(key) ?? relId(payload, LINKS, key), problems: [...problems], rows: mine.map((r) => r.id) });
425
+ }
426
+ return out;
427
+ }
package/dist/sessions.js CHANGED
@@ -1,4 +1,4 @@
1
- import { asPlugin, attachState, DISSOLVING, hatsOptions, idOf, relId, removeWhere, tell, withMark } from './state.js';
1
+ import { asPlugin, attachState, DISSOLVING, hatsOptions, idOf, relId, removeWhere, stillInTransaction, tell, withMark } from './state.js';
2
2
  import { LINKS, MEMBERS, SESSIONS } from './types.js';
3
3
  export async function sessionBySid(payload, sid, req) {
4
4
  const { docs } = await payload.find({ collection: SESSIONS, where: { sid: { equals: sid } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
@@ -26,6 +26,7 @@ export async function revokeSessions(payload, where, reason, req) {
26
26
  const live = { and: [where, { revokedAt: { exists: false } }] };
27
27
  const { docs } = await payload.find({ collection: SESSIONS, where: live, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
28
28
  for (const s of docs) {
29
+ stillInTransaction(req);
29
30
  await revokeSid(payload, s.user, s.sid, req);
30
31
  await tombstone(payload, s.id, req);
31
32
  }
@@ -46,6 +47,10 @@ export async function dissolveIfAlone(payload, link, req) {
46
47
  for (const d of docs)
47
48
  await removeWhere(payload, { collection: MEMBERS, where: { id: { equals: d.id } }, overrideAccess: true, req });
48
49
  await removeWhere(payload, { collection: LINKS, where: { id: { equals: link } }, overrideAccess: true, req });
50
+ // A row written for this set after the read above (an account joining at that moment, on a database without
51
+ // transactions) would be left alone in a set that's gone; it goes too. With transactions the join's write to
52
+ // the set's record conflicts with the delete above instead, and one of the two fails.
53
+ await removeWhere(payload, { collection: MEMBERS, where: { link: { equals: link } }, overrideAccess: true, req });
49
54
  }));
50
55
  await revokeSessions(payload, { link: { equals: link } }, 'set dissolved', req);
51
56
  }
package/dist/state.d.ts CHANGED
@@ -48,6 +48,20 @@ export declare function changeWhere(payload: Payload, args: ByWhere & {
48
48
  docs: unknown[];
49
49
  errors?: unknown[];
50
50
  }>;
51
+ /**
52
+ * What the caller sees when a plugin write collided with another change to the same linked set (an account joining
53
+ * it while this one leaves, say): the database refused one of the two, and trying again works.
54
+ */
55
+ export declare const COLLIDED = "Hats: a linked set was being changed at the same moment, so this couldn't finish. Try again.";
56
+ /**
57
+ * What the caller sees when the transaction a change ran in ended under it (another document of the same bulk delete
58
+ * failed, say). The plugin stops there, so nothing of its clean-up is written outside the transaction.
59
+ */
60
+ export declare const ENDED = "Hats: the transaction this change ran in ended (another change in it failed), so the plugin's clean-up stopped there. Try again.";
61
+ /** Throws ENDED when the hold this request is in started inside a transaction that has since ended. */
62
+ export declare function stillInTransaction(req: PayloadRequest | undefined): void;
63
+ export declare function holdEvents<T>(req: PayloadRequest, fn: () => Promise<T>): Promise<T>;
64
+ export declare function watchTransactions(payload: Payload): void;
51
65
  /**
52
66
  * An id as a relationship to `slug` stores it: a number where that collection's ids are numbers (SQL adapters by
53
67
  * default, or a custom number id), otherwise as it is. The plugin compares ids as strings, so every id it writes