@extantape/payload-plugin-hats 0.6.2 → 0.7.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
@@ -2,7 +2,7 @@
2
2
 
3
3
  Linked accounts and role hats for Payload. One person links their accounts and switches between them, and an account with several roles acts in one at a time. Switching up into a sensitive role asks for a second factor.
4
4
 
5
- **Status:** early, 0.x. All 238 tests pass. The server ones run against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The redesigned switch has unit tests for its order, gating, button markup, code screen and focus targets, and was run in a browser at 390 and 1280 px wide on a local copy of a site with made-up accounts: keyboard open, Escape, the focus trap, Cancel back to the hat, a one-tap switch and the note after it (that browser run was before the button and note changes below, and wasn't repeated). A real authenticator code wasn't tried with the new switch; the server refused the made-up code, as it should. It isn't in use on any site yet.
5
+ **Status:** early, 0.x. All 356 tests pass. The server ones run against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The redesigned switch has unit tests for its order, gating, button markup, code screen and focus targets, and was run in a browser at 390 and 1280 px wide on a local copy of a site with made-up accounts: keyboard open, Escape, the focus trap, Cancel back to the hat, a one-tap switch and the note after it (that browser run was before the button and note changes below, and wasn't repeated). A real authenticator code wasn't tried with the new switch; the server refused the made-up code, as it should. It isn't in use on any site yet.
6
6
 
7
7
  ## What it does
8
8
 
@@ -14,6 +14,7 @@ Linked accounts and role hats for Payload. One person links their accounts and s
14
14
  - **One code for the whole set.** `stepUp.rememberPer: 'set'` remembers a good code for every account in the same linked set, for the same 3 hours, so one two-step covers the person. The default, `'account'`, is unchanged. An account in no set is remembered on its own either way. `stepUp.available` and `stepUp.verify` also get `signedIn` (the account that actually signed in) and `set` (the linked set's id, or `null`), so a site can check against one two-step for the person. `user` stays the account being switched into.
15
15
  - **Hidden hats.** Set `hidden: true` on a hat in `hatsOf` and it isn't offered: it's left out of the switch, out of its Back to row, and out of `GET /hats`. A linked switch that names no hat goes to the account's narrowest hat only when that hat is offered, and is refused otherwise (`chooseHat`); it never moves up to a wider one. A switch into a hidden hat is refused through `POST /hats/switch` and `switchSession` alike, with the same `chooseHat` answer an unknown hat gets, before any code is asked for. Only a missing `hidden` or exactly `false` offers a hat: any other value, `'false'` or `null` included, hides it. See **What hidden doesn't do** below.
16
16
  - **Revocation.** Unlinking, deleting a row, losing a role or deleting an account ends every session switched into or through it. Switched sessions also re-check their set on every request. An ended session's record is kept, marked revoked, so a session that Payload writes back by accident (two writes to an account's sessions at once) stays signed out. Old records are deleted once their Payload session is gone, at most 50 per switch. A switched session whose signed-in account no longer exists is refused and ended, even if the clean-up after that account's delete didn't finish. If the database fails during that clean-up, or while an unlink dissolves a set, the call answers with an error. A single delete or unlink with a transaction is then undone; in other cases the account can be deleted with some of its link rows left (see the limits under Upgrading).
17
+ - **Linking from server code.** `linkAccounts` and `approveLink` link and approve from your own code, with no emails and the same approval rule as the admin form. `checkLinks` lists sets written by hand that break the rules. See **Linking from your own server code** below.
17
18
  - **Link limits.** Pass `limit` to rate-limit link requests. Key it by the email address as well as the person, so many accounts can't each ask for the same address. It must answer exactly `true` to allow one. Any other answer, or a throw, refuses the request with `tooMany` (429) and nothing is sent.
18
19
 
19
20
  Needs Payload sessions (`auth.useSessions`, on by default).
@@ -126,6 +127,50 @@ export async function POST(request: Request) {
126
127
  - Going back down to the account the person signed in with needs no new sign-in: the session's `via` keeps that account. With a gain-based `stepUpWhen` going down asks for no code. That holds while the link is approved and `blocked()` allows it. Unlinking, losing the role or deleting the account ends switched sessions, and the person signs in again. `onEvent`'s `switched` carries `via`, so admin work stays recorded against the staff account.
127
128
  - For one code per sitting across a person's accounts, use a gain-based `stepUpWhen` with `stepUp.rememberPer: 'set'`, and don't set `sensitive` on those hats. One code covers the whole set for `stepUp.rememberMinutes` (default 180), then it asks again. The plugin offers no "first entry ever": the expiry is what makes step-up worth having.
128
129
 
130
+ ## Linking from your own server code
131
+
132
+ `linkAccounts(req, { account, with, approve? })` puts two accounts in one linked set from your own code, for example after your site has checked who the person is in its own way. `approveLink(req, { account })` approves a confirmed account. Both skip the emails: your site has already done the checking, and it tells the people involved itself. The plugin sends no email and runs no age check here. Your site decides who may be linked.
133
+
134
+ ```ts
135
+ import { approveLink, linkAccounts } from '@extantape/payload-plugin-hats'
136
+
137
+ // Inside your own route or hook, with the request Payload gave you (its transaction is joined).
138
+ const result = await linkAccounts(req, { account: childId, with: parentId })
139
+ if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status })
140
+ // Later, an approver who isn't in the set, signed in on `req`:
141
+ const approved = await approveLink(req, { account: childId })
142
+ ```
143
+
144
+ - `account` joins the set `with` is in, or the two start a new set. Both rows come out confirmed, with no token, `addedBy` set to the signed-in account (or empty when nobody is signed in) and `confirmedAt` set. Pass `approve: true` to approve them in the same call. That needs `req.user` to be an approver outside the set, as below, and the approver check then comes first, before anything about the accounts.
145
+ - `approveLink` acts for `req.user`, the approver signed in on the request, and takes no approver id. It runs the same rule as the admin form: `canApproveLinks` must answer exactly `true`, and an approver who is in the set, joining it, or signed in through an account in it is refused. That check comes before anything about the row, so someone who can't approve learns nothing about it.
146
+ - Both return `{ ok: true, link, rows, already }` or `{ ok: false, status, reason, message }`, and don't throw for a refusal. `rows` lists the named accounts' rows as `{ account, status }` after the call. A repeat of a call that already happened answers `already: true` and writes nothing. Asking `linkAccounts` to approve a confirmed pair approves it.
147
+ - Ids must be written exactly as your users collection writes them. Any other key in the input is ignored.
148
+ - They join `req`'s transaction, so an error in your code after the call rolls the rows back with everything else. Without a transaction, the rows are written in order and removed again if a later write fails, as the email confirmation does. Invitations still open for either account are released, and that undo puts them back as they were. The undo removes the call's rows first and puts invitations back after, so a `failed` answer never leaves a link standing. If an invitation can't be put back, the answer is `failed` with a message saying nothing is linked but an open invitation to one of the accounts was canceled. That invitation stays canceled, and the person who sent it has to send it again; the warning in the log gives only how many. If removing the call's own rows fails too, the message says the accounts may still be linked: look at their member rows before trying again, because a retry would then answer that they're linked already.
149
+ - **A database error inside your transaction ends it.** Payload aborts the whole transaction on such an error and clears `req.transactionID`, so your own earlier writes in it are rolled back too. The answer is then `failed`, with a message saying the transaction ended. Treat the transaction as gone and start again.
150
+ - If `req.transactionID` names a transaction that has already ended, nothing is written and the answer is `failed`. A promise there (Payload puts one while it starts a transaction) is waited for and replaced by the id it gives, as Payload does itself. One that rejected never started a transaction, so it gets the same ended-transaction answer, with nothing written. The plugin checks this in the adapter's list of open transactions (`payload.db.sessions`), before writing and again after. Payload's MongoDB adapter keeps that list, and this is tested there. Its SQL adapters keep a list under the same name, which isn't tested here, and an adapter without one isn't checked.
151
+ - If the set dissolves while an account joins it (another member left a set of two), nobody is left alone in a set that isn't there. Joining writes the set's own record, and dissolving deletes it. With transactions, MongoDB refuses whichever of the two writes it second: either the join answers `failed` and its row is undone, or the unlink, row delete or account deletion that would have dissolved the set fails with the error `Hats: a linked set was being changed at the same moment, so this couldn't finish. Try again.`, changes nothing and sends no events, and the join stands. Trying the unlink or deletion again works. Two calls joining the same set at the same moment can also collide this way, and one answers `failed`; try it again. Inside your own transaction the join holds the set's record until you commit, so an unlink from that set fails meanwhile. Without transactions, a dissolve also removes any row written for the set after it read it, so a join that answers `ok` at that moment may be gone a moment later, along with the rest of the set, and the events for it have already fired. This is tested on MongoDB with and without transactions, with the dissolve held at three points while the join runs, and with a row delete and an account deletion losing to a join; SQL isn't tested.
152
+ - **When the `unlinked` and `sessions-revoked` events from a leaving or an account deletion go out.** With a transaction, they wait until it commits, and they're dropped when it's rolled back or its commit fails. That covers a bulk delete too: when one of its documents loses to a join, the whole delete is undone and none of them reports anything. It covers a site's own afterDelete hook that throws after the plugin's, which undoes the delete and sends nothing. Without a transaction, they go out when the plugin's clean-up ends, and also when it fails part way, because what it changed by then stays changed. A site hook that throws after the plugin's can't undo that clean-up either, so its events stand. A plain database error in one account's clean-up during a bulk delete is different: Payload doesn't end the shared transaction for it, and commits the other accounts along with what that account's clean-up changed before the error. The delete answers with an error, and the events for everything that was committed go out, that account's included. Tested on MongoDB with and without transactions (bulk deletes of member rows and of accounts with one losing to a join, a bulk account delete with one clean-up failing at the database, a throwing site hook, a dissolve that fails); SQL isn't tested. A host transaction that's never committed or rolled back keeps its waiting events in memory. When a commit has events waiting, it sends them before it returns, one after another, waiting up to 2 seconds for each handler, so a hanging handler delays the delete's answer by up to 2 seconds per event.
153
+ - **After a transaction ends under the plugin's clean-up.** In a bulk delete Payload runs the documents side by side in one transaction. The transaction ends for all of them when one document loses to a join (MongoDB aborts it), and with `bulkOperationsSingleTransaction: true` on the adapter, when any document fails. From then on every call the clean-up of any other document makes through the adapter's `count`, `create`, `deleteMany`, `deleteOne`, `find`, `findOne`, `updateMany`, `updateOne` and `upsert`, reads included, is refused with `Hats: the transaction this change ran in ended (another change in it failed), so the plugin's clean-up stopped there. Try again.` The check runs when the adapter looks up the call's transaction, so a call already under way when the transaction ends is refused too, and none of the plugin's own clean-up is written outside the transaction. Other adapter methods aren't tied to the transaction this way: a hook of yours that runs inside the clean-up and calls `createVersion`, `updateGlobal` or another version, global or job method isn't refused. This needs the adapter's list of open transactions (`payload.db.sessions`), as above. In the default mode a plain database error in one document doesn't end the transaction: Payload commits the others, and the failed document's clean-up is left half done (a set can be left with one member, for example). Look at that account's set after such an error, or turn on `bulkOperationsSingleTransaction` so the whole delete is undone instead. Tested on MongoDB with transactions: the join case, the plain error case in the default mode, and a transaction rolled back just before the clean-up's own delete of a member row, with `req.transactionID` still set and cleared. Single-transaction mode itself isn't in this repo's tests; the security review's probe of it (a site hook refusing one account of a bulk delete) left every row in place in six of six runs.
154
+ - The events are `link-requested` (for a new set), `link-confirmed` for each account that joined, and `link-approved` for each approval, with ids only and `source: 'server'`. They go through the same bounded path as the others: a handler that throws or hangs can't fail the call. A call's events are sent side by side, the handler called once per event in that order, so a handler that hangs holds the call for 2 seconds at most in all.
155
+ - To move an account to another set, unlink it, then link it, in one transaction. There is no move function.
156
+
157
+ | Reason | Status | When |
158
+ | --- | --- | --- |
159
+ | `linkingOff` | 409 | `canApproveLinks` isn't set, so linking is off. |
160
+ | `blocked` | 409 | `blocked(req)` refuses, or throws. A check that throws or gives an answer that isn't a reason says linking isn't available right now. |
161
+ | `notAccount` | 404 | An id isn't exact, or there's no such account. |
162
+ | `sameAccount` | 400 | `account` and `with` are the same. |
163
+ | `otherSet` | 409 | `account` is already in a different set. |
164
+ | `setFull` | 409 | The set would pass `maxLinked`, or its approved accounts would. |
165
+ | `notApprover` | 403 | Approving, and `req.user` isn't an approver. |
166
+ | `ownSet` | 403 | Approving a set the approver is in, is joining, or signed in through. |
167
+ | `notConfirmed` | 409 | The account's row is still waiting for its email, or, for `approveLink`, it's in no set. |
168
+ | `failed` | 500 | Anything else went wrong, the set dissolved during the call, or the request's transaction has ended. The call's writes are undone, as above; the message says when an invitation stayed canceled or the undo didn't finish. |
169
+
170
+ Show people one plain message for every refusal, such as "Those accounts couldn't be linked. Ask an administrator." The reasons are for your logs and your own code.
171
+
172
+ `checkLinks(payload)` reads every set and returns only the ones that break the plugin's rules, as `{ link, problems, rows }` with ids only: `overFull` (more than `maxLinked` rows), `alone` (one account), `noApprover` (approved with no approver), `selfApproved` (approved by an account in the set), `liveToken` (a confirmed or approved row that still has a token), `missingAccount` and `missingSet`. It changes nothing. Run it once after writing link rows by hand, or after an import.
173
+
129
174
  ## Upgrading from 0.4.0
130
175
 
131
176
  Sets already approved keep working, and requests still pending from 0.4.0 complete through their old links with the same confirmations and approval.
@@ -149,7 +194,7 @@ Everything else that changes for a host, in full:
149
194
  11. `POST /hats/unlink` and `POST /hats/switch` take only an exact account id. Anything else, including the text `null`, is refused (`notInSet` on unlink, `notLinked` on switch) before any database query.
150
195
  12. A database failure during the plugin's clean-up after an account delete, during an unlink, or during an approver's delete of a member row now fails that call. For a single delete with a transaction the whole change is undone; for a bulk delete, or without a transaction, see the limits below.
151
196
 
152
- Limits to know about: with `autoIndex` off and no `holds` index, requests arriving together can each send an invitation. Don't call the link endpoint's handler inside a transaction your own code opened: a refused claim ends it. Anyone signed in can hold an account's one open invitation until it expires (`confirmHours`), which delays other invitations to that account. Without transactions, a database failure part way through an account's clean-up leaves the account deleted and some of its rows behind; sessions through it are still refused. In a bulk delete on MongoDB with transactions, one account's failed clean-up ends Payload's shared transaction: the error is reported, but that account itself is still deleted, with its member row, set, requests and session record left behind (sessions through it stay refused), and the other accounts in the call can be deleted too. Delete linked accounts one at a time.
197
+ Limits to know about: with `autoIndex` off and no `holds` index, requests arriving together can each send an invitation. Don't call the link endpoint's handler inside a transaction your own code opened: a refused claim ends it. Anyone signed in can hold an account's one open invitation until it expires (`confirmHours`), which delays other invitations to that account. Without transactions, a database failure part way through an account's clean-up leaves the account deleted and some of its rows behind; sessions through it are still refused. In a bulk delete on MongoDB with transactions, an account losing to a join (or any failure, with `bulkOperationsSingleTransaction`) ends Payload's shared transaction for every account in the call. The plugin's clean-up stops there (see above), but Payload itself can still delete an account it hadn't reached yet, outside any transaction (this case isn't tested), so that account can be deleted with their member rows, sets, requests and session records left behind (sessions through it stay refused). Delete linked accounts one at a time. Deleting an account clears the starter only on sets that account started. The plugin wraps the database adapter's `commitTransaction` and `rollbackTransaction`, and its `count`, `create`, `deleteMany`, `deleteOne`, `find`, `findOne`, `updateMany`, `updateOne` and `upsert`, once at start-up, for the whole process, and never puts them back. The nine data methods only change a call made inside the plugin's clean-up; any other call passes straight through. Events held for a transaction go out when `commitTransaction` is called for it, so a host that aborts a MongoDB session directly (not through `rollbackTransaction`) and then calls `commitTransaction` with that id gets events for a delete that was rolled back. End your transactions through the adapter's two methods. With `bulkOperationsSingleTransaction`, a document's own database error can read as `another change in it failed`, and the try-again collision message can appear on a rollback that had no real collision; nothing is written either way.
153
198
 
154
199
  The changelog lists every change.
155
200
 
@@ -0,0 +1,26 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import { type ResolvedHatsOptions } from './types.js';
3
+ /** Why an approval is refused. The admin form and `approveLink` share these, so the two can't drift. */
4
+ export type ApprovalRefusal = {
5
+ reason: 'notApprover' | 'ownSet' | 'setFull';
6
+ message: string;
7
+ };
8
+ /**
9
+ * Whether the request's user may approve links: signed in to the site's users collection, linking on, and
10
+ * `canApproveLinks` answering exactly `true`. A truthy value or a thrown error is a no.
11
+ */
12
+ export declare function isApprover(opts: ResolvedHatsOptions, req: PayloadRequest): Promise<boolean>;
13
+ /**
14
+ * The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
15
+ * - `req.user` isn't an approver (`notApprover`);
16
+ * - the approver, or the account they signed in with (`via`), is in the set or is one of the accounts joining it
17
+ * (`ownSet`), so nobody approves their own link;
18
+ * - the set's approved rows, leaving out `except`, plus `approving` would pass `maxLinked` (`setFull`).
19
+ * `link` is null for a set that doesn't exist yet. Returns null when the approval may go ahead.
20
+ */
21
+ export declare function approvalRefusal(req: PayloadRequest, opts: ResolvedHatsOptions, args: {
22
+ link: string | null;
23
+ joining?: string[];
24
+ approving: number;
25
+ except?: string;
26
+ }): Promise<ApprovalRefusal | null>;
@@ -0,0 +1,48 @@
1
+ import { exactlyTrue } from './access.js';
2
+ import { hatsStateOf } from './state.js';
3
+ import { MEMBERS } from './types.js';
4
+ /**
5
+ * Whether the request's user may approve links: signed in to the site's users collection, linking on, and
6
+ * `canApproveLinks` answering exactly `true`. A truthy value or a thrown error is a no.
7
+ */
8
+ export async function isApprover(opts, req) {
9
+ const user = req.user;
10
+ if (!user || user.collection !== opts.users || !opts.canApproveLinks)
11
+ return false;
12
+ const ask = opts.canApproveLinks;
13
+ return exactlyTrue(() => ask({ req, user }));
14
+ }
15
+ /**
16
+ * The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
17
+ * - `req.user` isn't an approver (`notApprover`);
18
+ * - the approver, or the account they signed in with (`via`), is in the set or is one of the accounts joining it
19
+ * (`ownSet`), so nobody approves their own link;
20
+ * - the set's approved rows, leaving out `except`, plus `approving` would pass `maxLinked` (`setFull`).
21
+ * `link` is null for a set that doesn't exist yet. Returns null when the approval may go ahead.
22
+ */
23
+ export async function approvalRefusal(req, opts, args) {
24
+ if (!(await isApprover(opts, req)))
25
+ return { reason: 'notApprover', message: 'You can’t approve links.' };
26
+ const me = req.user;
27
+ const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
28
+ const ownSet = { reason: 'ownSet', message: 'You can’t approve a set you belong to. Ask another administrator.' };
29
+ if ((args.joining ?? []).some((j) => people.includes(j)))
30
+ return ownSet;
31
+ if (args.link != null) {
32
+ const mine = await req.payload.count({ collection: MEMBERS, where: { and: [{ link: { equals: args.link } }, { user: { in: people } }] }, overrideAccess: true, req });
33
+ if (mine.totalDocs > 0)
34
+ return ownSet;
35
+ }
36
+ // The size limit holds at approval too, whatever happened before: a set never has more approved accounts than maxLinked.
37
+ const approved = args.link == null
38
+ ? 0
39
+ : (await req.payload.count({
40
+ collection: MEMBERS,
41
+ where: { and: [{ link: { equals: args.link } }, { status: { equals: 'approved' } }, ...(args.except != null ? [{ id: { not_equals: args.except } }] : [])] },
42
+ overrideAccess: true,
43
+ req,
44
+ })).totalDocs;
45
+ if (approved + args.approving > opts.maxLinked)
46
+ return { reason: 'setFull', message: `A set can hold at most ${opts.maxLinked} accounts.` };
47
+ return null;
48
+ }
@@ -1,7 +1,7 @@
1
1
  import { APIError, validations } from 'payload';
2
- import { exactlyTrue } from './access.js';
2
+ import { approvalRefusal, isApprover } from './approval.js';
3
3
  import { dissolveIfAlone, revokeSessions } from './sessions.js';
4
- import { hatsStateOf, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
4
+ import { holdEvents, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
5
5
  import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
6
6
  const internal = isInternal;
7
7
  /**
@@ -17,18 +17,10 @@ const requiredOnWrite = (value, options) => validations.relationship(value, { ..
17
17
  * there needs the column to take null. On SQL databases the column is nullable and the rule moves to validation.
18
18
  */
19
19
  const requiredAccount = (sql) => (sql ? { validate: requiredOnWrite } : { required: true });
20
- /**
21
- * Whether the request's user may approve links. A person never approves their own link: an approver who is (or
22
- * who signed in as) a member of the set is refused, so the owner's own links need another approver. Only an exact
23
- * `true` from `canApproveLinks` counts: a truthy value or a thrown error is a no.
24
- */
25
- async function approver(opts, req) {
26
- const user = req.user;
27
- if (!user || user.collection !== opts.users || !opts.canApproveLinks)
28
- return false;
29
- const ask = opts.canApproveLinks;
30
- return exactlyTrue(() => ask({ req, user }));
31
- }
20
+ /** Whether the request's user may approve links (see `isApprover`). Who may approve a given set is `approvalRefusal`. */
21
+ const approver = isApprover;
22
+ /** The admin form's statuses for each refusal, as before `approveLink` shared the rule. */
23
+ const HOOK_STATUS = { notApprover: 403, ownSet: 403, setFull: 400 };
32
24
  export function hatCollections(opts, sql) {
33
25
  const canApprove = ({ req }) => approver(opts, req);
34
26
  const never = () => false;
@@ -91,36 +83,24 @@ export function hatCollections(opts, sql) {
91
83
  return data;
92
84
  if (originalDoc.status !== 'confirmed' || data.status !== 'approved')
93
85
  throw new APIError('Only a confirmed account can be approved, and an approval can’t be undone here: delete the row to unlink.', 400, undefined, true);
94
- const me = req.user;
95
- const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
96
- const mine = await req.payload.count({
97
- collection: MEMBERS,
98
- where: { and: [{ link: { equals: idOf(originalDoc.link) } }, { user: { in: people } }] },
99
- overrideAccess: true,
100
- req,
101
- });
102
- if (mine.totalDocs > 0)
103
- throw new APIError('You can’t approve a set you belong to. Ask another administrator.', 403, undefined, true);
104
- // The size limit holds at approval too, whatever happened before: a set never has more approved accounts than maxLinked.
105
- const approved = await req.payload.count({
106
- collection: MEMBERS,
107
- where: { and: [{ link: { equals: idOf(originalDoc.link) } }, { status: { equals: 'approved' } }, { id: { not_equals: originalDoc.id } }] },
108
- overrideAccess: true,
109
- req,
110
- });
111
- if (approved.totalDocs + 1 > opts.maxLinked)
112
- throw new APIError(`A set can hold at most ${opts.maxLinked} accounts.`, 400, undefined, true);
113
- return { ...data, approvedBy: me.id, approvedAt: new Date().toISOString() };
86
+ // The same rule `approveLink` runs: an approver outside the set, with room for one more approved account.
87
+ const refused = await approvalRefusal(req, opts, { link: idOf(originalDoc.link), approving: 1, except: String(originalDoc.id) });
88
+ if (refused)
89
+ throw new APIError(refused.message, HOOK_STATUS[refused.reason], undefined, true);
90
+ return { ...data, approvedBy: req.user.id, approvedAt: new Date().toISOString() };
114
91
  }),
115
92
  ],
116
93
  afterChange: [
117
94
  ownHook(async ({ doc, previousDoc, operation, req }) => {
95
+ // Through the bounded path like every other link event, so a slow or failing handler can't fail an approval.
118
96
  if (operation === 'update' && previousDoc?.status !== 'approved' && doc.status === 'approved' && !internal(req))
119
- await opts.onEvent?.({ type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
97
+ await tell(req.payload, req, { type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
120
98
  }),
121
99
  ],
122
100
  afterDelete: [
123
- ownHook(async ({ doc, req }) => {
101
+ // Events wait for the delete's transaction to commit, the dissolve included, so a delete that's undone
102
+ // reports nothing (see `holdEvents`).
103
+ ownHook(async ({ doc, req }) => holdEvents(req, async () => {
124
104
  const link = idOf(doc.link);
125
105
  const account = idOf(doc.user);
126
106
  await revokeSessions(req.payload, { and: [{ link: { equals: link } }, { or: [{ user: { equals: account } }, { via: { equals: account } }] }] }, 'unlinked', req);
@@ -128,7 +108,7 @@ export function hatCollections(opts, sql) {
128
108
  await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: req.user ? String(req.user.id) : null });
129
109
  if (!isDissolving(req))
130
110
  await dissolveIfAlone(req.payload, link, req);
131
- }),
111
+ })),
132
112
  ],
133
113
  },
134
114
  };
@@ -1,6 +1,19 @@
1
1
  import { type Endpoint, type PayloadRequest } from 'payload';
2
2
  import { revokeSessions } from './sessions.js';
3
3
  import { type Hat, type HatsUser, type ResolvedHatsOptions } from './types.js';
4
+ export declare const loadUser: (req: PayloadRequest, id: string) => Promise<HatsUser | null>;
5
+ export declare const labelOf: (u: HatsUser) => string;
6
+ export declare function members(req: PayloadRequest, link: string): Promise<{
7
+ id: string;
8
+ user: unknown;
9
+ status: string;
10
+ }[]>;
11
+ export declare function membershipOf(req: PayloadRequest, userId: string): Promise<{
12
+ id: string;
13
+ link: unknown;
14
+ user: unknown;
15
+ status: string;
16
+ } | null>;
4
17
  /**
5
18
  * Whether the switch is shown (and so allowed). The site's `showSwitch` gets every hat, hidden ones included, with
6
19
  * their flags. The default counts only hats that are offered: more than one on this account, or on a linked account.
@@ -38,5 +51,7 @@ export type SwitchInput = {
38
51
  * `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
39
52
  */
40
53
  export declare function runSwitch(req: PayloadRequest, input: SwitchInput | null | undefined): Promise<SwitchResult>;
54
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
55
+ export declare function exactId(req: PayloadRequest, opts: ResolvedHatsOptions, v: unknown): boolean;
41
56
  export declare const hatEndpoints: Endpoint[];
42
57
  export { revokeSessions };
package/dist/endpoints.js CHANGED
@@ -29,13 +29,13 @@ async function actor(req) {
29
29
  refuse('Sign in first.', 401, 'signIn');
30
30
  return { opts, user: user, full: full, state: state, person: state.via ?? String(user.id) };
31
31
  }
32
- const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
33
- const labelOf = (u) => String(u.email ?? u.id);
34
- async function members(req, link) {
32
+ export const loadUser = async (req, id) => (await req.payload.findByID({ collection: hatsOptions(req.payload).users, id, depth: 0, overrideAccess: true, showHiddenFields: true, disableErrors: true, req }));
33
+ export const labelOf = (u) => String(u.email ?? u.id);
34
+ export async function members(req, link) {
35
35
  const { docs } = await req.payload.find({ collection: MEMBERS, where: { link: { equals: link } }, limit: 0, depth: 0, overrideAccess: true, pagination: false, req });
36
36
  return docs;
37
37
  }
38
- async function membershipOf(req, userId) {
38
+ export async function membershipOf(req, userId) {
39
39
  const { docs } = await req.payload.find({ collection: MEMBERS, where: { user: { equals: userId } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
40
40
  const row = docs[0] ?? null;
41
41
  // Only a row for exactly this account: on MongoDB the text "null" can match a row whose account was cleared.
@@ -373,9 +373,6 @@ const requestLink = {
373
373
  refuse('Too many link requests. Try again later.', 429, 'tooMany');
374
374
  }
375
375
  const work = async () => {
376
- const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
377
- const found = docs[0];
378
- let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
379
376
  // One record for every request, with the same fields. Only a real invitation's token can ever be used.
380
377
  const token = newToken();
381
378
  const hours = opts.confirmHours;
@@ -386,15 +383,9 @@ const requestLink = {
386
383
  overrideAccess: true,
387
384
  req,
388
385
  })));
389
- // One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
390
- // rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
391
- // the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
392
- // means no invitation, so the asker sees the same thing either way.
393
- const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
394
- const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
395
- if (!claimed)
396
- target = null;
397
- // The asker's own note is the same every time and leaves the address out, so it can't tell them anything.
386
+ // The asker's own note is the same every time and leaves the address out, so it can't tell them anything. It
387
+ // goes before anything that depends on the address (looking it up, checking its set, claiming it), so the
388
+ // work done before it, and when it arrives, is the same for a real address and a made-up one.
398
389
  try {
399
390
  await opts.sendEmail({
400
391
  payload: req.payload,
@@ -406,6 +397,17 @@ const requestLink = {
406
397
  catch (err) {
407
398
  req.payload.logger.warn({ err }, 'Hats: link request note not sent');
408
399
  }
400
+ const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
401
+ const found = docs[0];
402
+ let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
403
+ // One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
404
+ // rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
405
+ // the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
406
+ // means no invitation, so the asker sees the same thing either way.
407
+ const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
408
+ const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
409
+ if (!claimed)
410
+ target = null;
409
411
  if (!target)
410
412
  return;
411
413
  try {
@@ -574,7 +576,7 @@ const confirm = {
574
576
  },
575
577
  };
576
578
  /** Whether `v` is an account id written the one way the users collection writes its ids. */
577
- function exactId(req, opts, v) {
579
+ export function exactId(req, opts, v) {
578
580
  if (typeof v !== 'string' && typeof v !== 'number')
579
581
  return false;
580
582
  const s = String(v);
package/dist/index.d.ts CHANGED
@@ -5,6 +5,8 @@ export { hatsStateOf } from './state.js';
5
5
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
6
6
  export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
7
7
  export type { SwitchInput, SwitchResult };
8
+ export { approveLink, checkLinks, linkAccounts } from './link.js';
9
+ export type { ApproveInput, LinkCheck, LinkInput, LinkProblem, LinkReason, LinkResult, LinkRowStatus } from './link.js';
8
10
  /**
9
11
  * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
10
12
  * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
@@ -19,11 +21,5 @@ export declare const switchSession: (req: PayloadRequest, input: {
19
21
  hat?: string;
20
22
  code?: string;
21
23
  }) => Promise<SwitchResult>;
22
- export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
23
- /**
24
- * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
25
- * holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
26
- * factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
27
- * the membership or the account's roles change.
28
- */
24
+ export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, LinkSource, StepUpContext } from './types.js';
29
25
  export declare const hats: (options: HatsOptions) => Plugin;
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { hatCollections } from './collections.js';
2
2
  import { hatEndpoints, runSwitch } from './endpoints.js';
3
3
  import { revokeSessions, wrapStrategies } from './sessions.js';
4
- import { asPlugin, changeWhere, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks } from './state.js';
4
+ import { asPlugin, changeWhere, holdEvents, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks, watchTransactions } from './state.js';
5
5
  import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
6
6
  export { hatsStateOf } from './state.js';
7
7
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
8
8
  export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
9
+ export { approveLink, checkLinks, linkAccounts } from './link.js';
9
10
  /**
10
11
  * Switch the signed-in person's hat or account from a site's own route, without the picker. It runs the same code as
11
12
  * `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
@@ -22,6 +23,8 @@ export const switchSession = (req, input) => runSwitch(req, input);
22
23
  * factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
23
24
  * the membership or the account's roles change.
24
25
  */
26
+ /** A set's label once the account that started it is deleted (its old label names that account). */
27
+ const DELETED_STARTER = 'Started by a deleted account';
25
28
  export const hats = (options) => (config) => {
26
29
  const opts = {
27
30
  users: 'users',
@@ -63,9 +66,14 @@ export const hats = (options) => (config) => {
63
66
  // nothing here. It runs before the site's own afterDelete hooks, inside the delete's transaction where there is
64
67
  // one. On SQL databases the foreign keys have already set these columns to null, so null rows go too. Payload runs
65
68
  // a bulk delete's documents side by side; `serial` runs this one account at a time. Any database failure in here
66
- // throws, so the delete fails with it: with a transaction the whole delete is undone, and without one the caller
69
+ // throws, so the delete fails with it: with a transaction that Payload then ends, the whole delete is undone (a
70
+ // plain error in one document of a default bulk delete doesn't end it, see the README), and without one the caller
67
71
  // still gets the error (a switched session through the deleted account is refused anyway, see `applyHat`).
68
- const afterDelete = ownHook(async ({ id, req }) => {
72
+ // Its events (a leaving, revoked sessions) wait for the delete's transaction to commit, or for this to finish
73
+ // without one (see `holdEvents`). Once that transaction has ended under it, every database call made from here
74
+ // is refused at the moment the adapter looks up its transaction, one already under way included (see
75
+ // `watchTransactions`), so nothing of it is written outside the transaction.
76
+ const afterDelete = ownHook(async ({ id, req }) => holdEvents(req, async () => {
69
77
  const p = req.payload;
70
78
  const me = relId(p, opts.users, id);
71
79
  const mineOrGone = (field) => ({ or: [{ [field]: { equals: me } }, { [field]: { exists: false } }] });
@@ -79,12 +87,15 @@ export const hats = (options) => (config) => {
79
87
  // deleting an account frees nothing the asker could notice. At most one request holds the account.
80
88
  await changeWhere(p, { collection: REQUESTS, where: { or: [{ account: { equals: me } }, { holds: { equals: `account:${String(id)}` } }] }, data: { account: null, holds: `none:${newToken()}`, tokenHash: null }, overrideAccess: true, req });
81
89
  // Who started a set, added or approved an account: cleared, along with the set's label, which names them.
82
- await changeWhere(p, { collection: LINKS, where: mineOrGone('requestedBy'), data: { requestedBy: null, label: 'Started by a deleted account' }, overrideAccess: true, req });
90
+ // Only sets this account started: on SQL its foreign key has already cleared `requestedBy`, so a cleared one
91
+ // still carrying a starter's name counts too. Sets cleared before keep their label and aren't written again.
92
+ const startedBy = { or: [{ requestedBy: { equals: me } }, { and: [{ requestedBy: { exists: false } }, { label: { not_equals: DELETED_STARTER } }] }] };
93
+ await changeWhere(p, { collection: LINKS, where: startedBy, data: { requestedBy: null, label: DELETED_STARTER }, overrideAccess: true, req });
83
94
  for (const field of ['addedBy', 'approvedBy'])
84
95
  await changeWhere(p, { collection: MEMBERS, where: { and: [{ [field]: { equals: me } }, { user: { exists: true } }] }, data: { [field]: null }, overrideAccess: true, req });
85
96
  }));
86
97
  await revokeSessions(p, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
87
- });
98
+ }));
88
99
  const afterLogout = ownHook(async ({ req }) => {
89
100
  const sid = req.user?._sid;
90
101
  if (sid)
@@ -114,6 +125,7 @@ export const hats = (options) => (config) => {
114
125
  custom: { ...config.custom, hats: opts },
115
126
  onInit: async (payload) => {
116
127
  unmarkForeignHooks(payload);
128
+ watchTransactions(payload);
117
129
  await onInit?.(payload);
118
130
  wrapStrategies(payload, opts);
119
131
  },
package/dist/link.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { Payload, PayloadRequest } from 'payload';
2
+ /** Why `linkAccounts` or `approveLink` refused. Each comes with a fixed status; see the README for the table. */
3
+ export type LinkReason = 'linkingOff' | 'blocked' | 'notAccount' | 'sameAccount' | 'otherSet' | 'setFull' | 'notApprover' | 'ownSet' | 'notConfirmed' | 'failed';
4
+ export type LinkRowStatus = 'requested' | 'confirmed' | 'approved';
5
+ /**
6
+ * What a server link came to. `rows` are the member rows of the accounts the call named, as they stand after it.
7
+ * `already` is true when the call asked for what was already so: nothing was written and no event fired.
8
+ */
9
+ export type LinkResult = {
10
+ ok: true;
11
+ link: string | number;
12
+ rows: Array<{
13
+ account: string | number;
14
+ status: LinkRowStatus;
15
+ }>;
16
+ already: boolean;
17
+ } | {
18
+ ok: false;
19
+ status: number;
20
+ reason: LinkReason;
21
+ message: string;
22
+ };
23
+ export type LinkInput = {
24
+ /** The account joining. */
25
+ account: string | number;
26
+ /** An account already in the set, or one to start a set with. */
27
+ with: string | number;
28
+ /** Approve the new rows too, as `req.user`. Default false: they wait for an approver. */
29
+ approve?: boolean;
30
+ };
31
+ export type ApproveInput = {
32
+ /** An account whose member row is confirmed. */
33
+ account: string | number;
34
+ };
35
+ /**
36
+ * Link two accounts from the site's own server code, for a flow where both people already agreed. It runs the
37
+ * plugin's own checks every time and has no option that loosens one. Joins `req`'s transaction when there is one;
38
+ * without one, it writes in order and undoes its own rows on failure. Never throws for a refusal.
39
+ */
40
+ export declare const linkAccounts: (req: PayloadRequest, input: LinkInput) => Promise<LinkResult>;
41
+ /** Approve a confirmed account's row as the approver signed in on `req`, under the admin form's rule. Never throws for a refusal. */
42
+ export declare const approveLink: (req: PayloadRequest, input: ApproveInput) => Promise<LinkResult>;
43
+ /** A rule a set breaks. Sets the plugin wrote itself never break these; rows written by hand may. */
44
+ export type LinkProblem =
45
+ /** More member rows, of any status, than `maxLinked`. */
46
+ 'overFull'
47
+ /** Fewer than two member rows: a set of one isn't a link. */
48
+ | 'alone'
49
+ /** An approved row with no approver recorded. */
50
+ | 'noApprover'
51
+ /** An approved row whose approver is a member of the same set. */
52
+ | 'selfApproved'
53
+ /** A confirmed or approved row that still holds a confirmation token. */
54
+ | 'liveToken'
55
+ /** A row with no account, or whose account doesn't exist. */
56
+ | 'missingAccount'
57
+ /** Member rows that point at a set that doesn't exist. */
58
+ | 'missingSet';
59
+ export type LinkCheck = {
60
+ link: string | number;
61
+ problems: LinkProblem[];
62
+ rows: Array<string | number>;
63
+ };
64
+ /**
65
+ * Lists the sets that break the plugin's rules, for rows written outside it (through the database adapter, say). It
66
+ * only reads and changes nothing: what to do about a set is the site's call. Results hold ids only.
67
+ */
68
+ export declare function checkLinks(payloadOrReq: Payload | PayloadRequest): Promise<LinkCheck[]>;
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
package/dist/state.js CHANGED
@@ -106,17 +106,206 @@ export function unmarkForeignHooks(payload) {
106
106
  }
107
107
  }
108
108
  export async function removeWhere(payload, args) {
109
- const result = (await payload.delete(args));
109
+ stillInTransaction(args.req);
110
+ const result = (await renamed(payload.delete(args)));
110
111
  if (result.errors?.length)
111
- throw new Error(`Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be removed.`);
112
+ throw bulkError(result.errors, `Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be removed.`);
112
113
  return result;
113
114
  }
114
115
  export async function changeWhere(payload, args) {
115
- const result = (await payload.update(args));
116
+ stillInTransaction(args.req);
117
+ const result = (await renamed(payload.update(args)));
116
118
  if (result.errors?.length)
117
- throw new Error(`Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be changed.`);
119
+ throw bulkError(result.errors, `Hats: ${result.errors.length} ${String(args.collection)} row(s) couldn't be changed.`);
118
120
  return result;
119
121
  }
122
+ /**
123
+ * What the caller sees when a plugin write collided with another change to the same linked set (an account joining
124
+ * it while this one leaves, say): the database refused one of the two, and trying again works.
125
+ */
126
+ export const COLLIDED = 'Hats: a linked set was being changed at the same moment, so this couldn\'t finish. Try again.';
127
+ const collided = (message) => message === COLLIDED || /write ?conflict|NoSuchTransaction|transaction\b[^.]*\bhas been aborted/i.test(message);
128
+ const messageOf = (e) => String(e?.message ?? '');
129
+ function bulkError(errors, plain) {
130
+ const messages = errors.map(messageOf);
131
+ // A collision says so even when later calls were then refused because it ended the transaction.
132
+ return new Error(messages.some(collided) ? COLLIDED : messages.includes(ENDED) ? ENDED : plain);
133
+ }
134
+ /** The write's own error, or COLLIDED in its place when the database refused it for a collision. */
135
+ async function renamed(write) {
136
+ try {
137
+ return await write;
138
+ }
139
+ catch (error) {
140
+ throw collided(messageOf(error)) ? new Error(COLLIDED) : error;
141
+ }
142
+ }
143
+ const holds = new AsyncLocalStorage();
144
+ /** Events waiting for their transaction to commit, by transaction id. */
145
+ const afterCommit = new Map();
146
+ /** Transactions rolled back lately, and the last transaction a hold saw on each request. */
147
+ const ended = new Set();
148
+ /** Transactions the database refused a write in for a collision lately. Calls refused after that say COLLIDED. */
149
+ const collidedIn = new Set();
150
+ const remember = (set, key) => {
151
+ set.add(key);
152
+ // Only the latest few matter (a bulk operation's siblings check right after); the oldest go first.
153
+ if (set.size > 1000)
154
+ set.delete(set.values().next().value);
155
+ };
156
+ /** Why a transaction ended: a collision says so, anything else is ENDED. */
157
+ const endedError = (tx) => new Error(tx !== undefined && collidedIn.has(tx) ? COLLIDED : ENDED);
158
+ const lastTx = new WeakMap();
159
+ // Payload leaves a promise in `transactionID` while one starts (and for good on a database without transactions). It
160
+ // may come from another realm, so it's recognized by its `then`, and only a string or number counts as a transaction.
161
+ const thenable = (t) => typeof t?.then === 'function';
162
+ const liveTx = (req) => {
163
+ const t = req.transactionID;
164
+ return (typeof t === 'string' && t !== '') || typeof t === 'number' ? t : undefined;
165
+ };
166
+ /**
167
+ * What the caller sees when the transaction a change ran in ended under it (another document of the same bulk delete
168
+ * failed, say). The plugin stops there, so nothing of its clean-up is written outside the transaction.
169
+ */
170
+ export 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.";
171
+ /** Throws ENDED when the hold this request is in started inside a transaction that has since ended. */
172
+ export function stillInTransaction(req) {
173
+ const hold = req ? holds.getStore()?.get(req) : undefined;
174
+ if (req && hold?.tx !== undefined && liveTx(req) !== hold.tx)
175
+ throw endedError(hold.tx);
176
+ }
177
+ export async function holdEvents(req, fn) {
178
+ if (holds.getStore()?.has(req))
179
+ return await fn();
180
+ const raw = req.transactionID;
181
+ if (thenable(raw))
182
+ await Promise.resolve(raw).catch(() => undefined);
183
+ const tx = liveTx(req);
184
+ if (tx !== undefined)
185
+ lastTx.set(req, tx);
186
+ else {
187
+ // The request's transaction was rolled back before this hook started (a sibling document failed first): its
188
+ // clean-up would write outside any transaction, so it doesn't start.
189
+ const was = lastTx.get(req);
190
+ if (was !== undefined && ended.has(was))
191
+ throw endedError(was);
192
+ }
193
+ const hold = { queue: [], tx };
194
+ const now = new Map(holds.getStore() ?? []);
195
+ now.set(req, hold);
196
+ let result;
197
+ try {
198
+ result = await holds.run(now, fn);
199
+ }
200
+ catch (error) {
201
+ await release(req, hold);
202
+ throw error;
203
+ }
204
+ await release(req, hold);
205
+ return result;
206
+ }
207
+ /**
208
+ * Hands a hold's events on when `fn` ends, whether or not it threw: sent now without a transaction, otherwise left
209
+ * for the commit while the transaction is still the live one. A throw doesn't drop them by itself, because Payload
210
+ * doesn't always end the transaction for it (a bulk delete commits the documents that didn't fail), and what was
211
+ * changed before the throw is then kept.
212
+ */
213
+ async function release(req, hold) {
214
+ if (hold.tx === undefined)
215
+ return await sendAll(req, hold.queue);
216
+ if (liveTx(req) !== hold.tx || !hold.queue.length)
217
+ return;
218
+ const list = afterCommit.get(hold.tx) ?? [];
219
+ for (const event of hold.queue.splice(0))
220
+ list.push({ req, event });
221
+ afterCommit.set(hold.tx, list);
222
+ }
223
+ async function sendAll(req, queue) {
224
+ for (const event of queue.splice(0))
225
+ await send(req.payload, req, event);
226
+ }
227
+ /**
228
+ * Wraps the database adapter's commit and rollback so held events follow their transaction. Payload commits and rolls
229
+ * back through these two methods for every operation that opens a transaction; a host transaction goes through them
230
+ * too when the host ends it.
231
+ */
232
+ const WATCHED = Symbol.for('extantape.hats.transactions');
233
+ export function watchTransactions(payload) {
234
+ const db = payload.db;
235
+ if (db[WATCHED])
236
+ return;
237
+ db[WATCHED] = true;
238
+ const commit = db.commitTransaction;
239
+ const rollback = db.rollbackTransaction;
240
+ // A transaction id is a string or a number. A promise in its place (notx mode keeps one there) never held any
241
+ // events, so it is passed straight through: the wrapper adds no wait to a commit with nothing held.
242
+ const keyOf = (id) => (typeof id === 'string' && id !== '') || typeof id === 'number' ? id : undefined;
243
+ if (typeof commit === 'function')
244
+ db.commitTransaction = async function (id) {
245
+ const key = keyOf(id);
246
+ const pending = key === undefined ? undefined : afterCommit.get(key);
247
+ if (!pending)
248
+ return commit.call(this, id);
249
+ afterCommit.delete(key);
250
+ await commit.call(this, id);
251
+ for (const p of pending)
252
+ await send(payload, p.req, p.event);
253
+ };
254
+ if (typeof rollback === 'function')
255
+ db.rollbackTransaction = async function (id) {
256
+ const key = keyOf(id);
257
+ if (key !== undefined) {
258
+ afterCommit.delete(key);
259
+ remember(ended, key);
260
+ }
261
+ await rollback.call(this, id);
262
+ };
263
+ // Database calls made inside a hold that started in a transaction are pinned to that transaction. Payload ends a
264
+ // shared transaction by removing it from the adapter's open sessions and then clearing `req.transactionID`; a call
265
+ // that looks up its session after that (Payload's own writes for a plugin delete included) would find none, or start
266
+ // a new transaction, and write outside the one it belongs to. Here the call gets a request whose transaction id
267
+ // is read at the moment the adapter looks up its session, and refuses with ENDED when that transaction is gone, so
268
+ // no check-then-write gap is left.
269
+ const sessions = () => db.sessions;
270
+ const pinned = (req, tx) => Object.create(req, {
271
+ transactionID: {
272
+ enumerable: true,
273
+ configurable: true,
274
+ get() {
275
+ const open = sessions();
276
+ // An adapter without a list of open sessions can't be checked (said in the README).
277
+ if (!open || typeof open !== 'object')
278
+ return tx;
279
+ const session = open[String(tx)];
280
+ if (!session || (typeof session.inTransaction === 'function' && !session.inTransaction()))
281
+ throw endedError(tx);
282
+ return tx;
283
+ },
284
+ set() { },
285
+ },
286
+ });
287
+ for (const name of PINNED) {
288
+ const fn = db[name];
289
+ if (typeof fn !== 'function')
290
+ continue;
291
+ db[name] = function (args, ...rest) {
292
+ const req = args?.req;
293
+ const hold = req ? holds.getStore()?.get(req) : undefined;
294
+ if (!req || hold?.tx === undefined)
295
+ return fn.call(this, args, ...rest);
296
+ const tx = hold.tx;
297
+ const result = fn.call(this, { ...args, req: pinned(req, tx) }, ...rest);
298
+ // A collision ends the transaction, and the calls refused after it then report the collision too.
299
+ return Promise.resolve(result).catch((error) => {
300
+ if (collided(messageOf(error)))
301
+ remember(collidedIn, tx);
302
+ throw error;
303
+ });
304
+ };
305
+ }
306
+ }
307
+ /** The adapter calls pinned to a hold's transaction: every read and write Payload makes for a collection. */
308
+ const PINNED = ['count', 'create', 'deleteMany', 'deleteOne', 'find', 'findOne', 'updateMany', 'updateOne', 'upsert'];
120
309
  /**
121
310
  * An id as a relationship to `slug` stores it: a number where that collection's ids are numbers (SQL adapters by
122
311
  * default, or a custom number id), otherwise as it is. The plugin compares ids as strings, so every id it writes
@@ -171,6 +360,16 @@ export function safeName(error) {
171
360
  * `TELL_MS` is left to finish unwaited, so a handler can never block or undo what already happened.
172
361
  */
173
362
  export async function tell(payload, req, event) {
363
+ if (!hatsOptions(payload).onEvent)
364
+ return;
365
+ const hold = req ? holds.getStore()?.get(req) : undefined;
366
+ if (hold) {
367
+ hold.queue.push(event);
368
+ return;
369
+ }
370
+ await send(payload, req, event);
371
+ }
372
+ async function send(payload, req, event) {
174
373
  const onEvent = hatsOptions(payload).onEvent;
175
374
  if (!onEvent)
176
375
  return;
package/dist/types.d.ts CHANGED
@@ -147,23 +147,28 @@ export type HatsOptions = {
147
147
  */
148
148
  linkAnswerMs?: number;
149
149
  };
150
+ /** `'server'` on link events from `linkAccounts` and `approveLink`. Missing on events from the endpoints and the admin form. */
151
+ export type LinkSource = 'server';
150
152
  export type HatsEvent = {
151
153
  type: 'link-requested';
152
154
  req: PayloadRequest; /** The asker's set. When the asker had none, this fires as the set is made, just before `link-confirmed`, and `req` is the confirming request. */
153
155
  link: string;
154
156
  by: string;
155
157
  account: string;
158
+ source?: LinkSource;
156
159
  } | {
157
160
  type: 'link-confirmed';
158
161
  payload: Payload;
159
162
  link: string;
160
163
  account: string;
164
+ source?: LinkSource;
161
165
  } | {
162
166
  type: 'link-approved';
163
167
  req: PayloadRequest;
164
168
  link: string;
165
169
  account: string;
166
170
  by: string;
171
+ source?: LinkSource;
167
172
  } | {
168
173
  type: 'unlinked';
169
174
  payload: Payload;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
5
5
  "keywords": [
6
6
  "payload",