@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/README.md +59 -3
- package/dist/approval.d.ts +26 -0
- package/dist/approval.js +48 -0
- package/dist/collections.js +17 -37
- package/dist/endpoints.d.ts +15 -0
- package/dist/endpoints.js +24 -20
- package/dist/index.d.ts +3 -7
- package/dist/index.js +20 -5
- package/dist/link.d.ts +68 -0
- package/dist/link.js +427 -0
- package/dist/sessions.js +6 -1
- package/dist/state.d.ts +14 -0
- package/dist/state.js +203 -4
- package/dist/stepup.d.ts +10 -3
- package/dist/stepup.js +21 -4
- package/dist/types.d.ts +10 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,18 +2,20 @@
|
|
|
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
|
|
5
|
+
**Status:** early, 0.x. All 366 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
|
|
|
9
9
|
- **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Unlinking is self-serve and immediate.
|
|
10
10
|
- **A link request answers the same way whatever the address.** The asker gets the same answer, the same note by email, the same records to read and the same wait (`linkAnswerMs`, default 2000 ms) whether or not the address has an account, whatever state it is in. Only an account that can be linked is invited, one open invitation per account from everyone (a unique key in the database holds this, even for requests that arrive together), and nothing joins a set until it confirms. Then the asker confirms from their own email. Open requests live in a `hat-requests` collection that no user can read and only the plugin can write, at most `maxLinked × 2` per account.
|
|
11
11
|
- **Hats.** Wearing a hat narrows the user before `req.user` exists, so every access rule follows it: admin, REST, GraphQL and the Local API with `req`. If narrowing fails, the request is signed out, never given full roles.
|
|
12
|
-
- **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 180 minutes (`stepUp.rememberMinutes`) per account,
|
|
12
|
+
- **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 180 minutes (`stepUp.rememberMinutes`) per account, per linked set or per hat (see below).
|
|
13
13
|
- **Step up on gain.** Pass `stepUpWhen` to decide for yourself when a switch asks for a code, in place of the `sensitive` flag. It gets the hat worn now (`from`) and the one it would become (`to`), each with the user as it would be worn, so a site can ask only when `to` holds a role or permission that `from` doesn't. Going down asks nothing, going up or sideways asks. Only an exact `false` skips the code. `true`, a throw or any other answer asks, so a broken check never lets a switch through.
|
|
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
|
+
- **One code per hat.** `stepUp.rememberPer: 'hat'` remembers a good code for that account and that hat only. Another hat on the same account asks again, and so does the same hat on a linked account. Pick it when a site's hats differ a lot in what they can do, for example a moderator hat and an owner hat on one account, and a code given for the smaller one shouldn't open the bigger one. It asks more often, so `'account'` suits a site whose sensitive hats are close to each other.
|
|
15
16
|
- **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
17
|
- **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).
|
|
18
|
+
- **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
19
|
- **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
20
|
|
|
19
21
|
Needs Payload sessions (`auth.useSessions`, on by default).
|
|
@@ -56,6 +58,16 @@ hats({
|
|
|
56
58
|
})
|
|
57
59
|
```
|
|
58
60
|
|
|
61
|
+
`stepUp.rememberPer` takes one of three values. Any other value stops startup.
|
|
62
|
+
|
|
63
|
+
| Value | A good code covers | Asks again for |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `'account'` (default) | every hat on the account it was given for | another account |
|
|
66
|
+
| `'set'` | every hat on every account in the same linked set (an account in no set: that account) | an account outside the set |
|
|
67
|
+
| `'hat'` | the one hat on the one account it was given for | any other hat, and the same hat on another account |
|
|
68
|
+
|
|
69
|
+
The three are alternatives and don't combine: there is no per-set-and-hat value. A hat belongs to one account's `hatsOf`, and the same hat id on a linked account can stand for different roles, so `'hat'` always counts the account too and never widens to the set. Every value expires after `rememberMinutes`, and only asks when `sensitive` or `stepUpWhen` says the switch needs a code. The memory is kept per session under the value in use, so after changing `rememberPer` on a running site, codes remembered under the old value stop counting and people are asked once more.
|
|
70
|
+
|
|
59
71
|
`wear` must return a narrowed copy of the user, never the user itself: Hats refuses the request if it gets the same object back, if a hat adds one the account doesn't hold, or if an ordinary hat keeps a sensitive one.
|
|
60
72
|
|
|
61
73
|
Endpoints, under the API route:
|
|
@@ -126,6 +138,50 @@ export async function POST(request: Request) {
|
|
|
126
138
|
- 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
139
|
- 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
140
|
|
|
141
|
+
## Linking from your own server code
|
|
142
|
+
|
|
143
|
+
`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.
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
import { approveLink, linkAccounts } from '@extantape/payload-plugin-hats'
|
|
147
|
+
|
|
148
|
+
// Inside your own route or hook, with the request Payload gave you (its transaction is joined).
|
|
149
|
+
const result = await linkAccounts(req, { account: childId, with: parentId })
|
|
150
|
+
if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status })
|
|
151
|
+
// Later, an approver who isn't in the set, signed in on `req`:
|
|
152
|
+
const approved = await approveLink(req, { account: childId })
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
- `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.
|
|
156
|
+
- `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.
|
|
157
|
+
- 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.
|
|
158
|
+
- Ids must be written exactly as your users collection writes them. Any other key in the input is ignored.
|
|
159
|
+
- 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.
|
|
160
|
+
- **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.
|
|
161
|
+
- 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.
|
|
162
|
+
- 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.
|
|
163
|
+
- **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.
|
|
164
|
+
- **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.
|
|
165
|
+
- 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.
|
|
166
|
+
- To move an account to another set, unlink it, then link it, in one transaction. There is no move function.
|
|
167
|
+
|
|
168
|
+
| Reason | Status | When |
|
|
169
|
+
| --- | --- | --- |
|
|
170
|
+
| `linkingOff` | 409 | `canApproveLinks` isn't set, so linking is off. |
|
|
171
|
+
| `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. |
|
|
172
|
+
| `notAccount` | 404 | An id isn't exact, or there's no such account. |
|
|
173
|
+
| `sameAccount` | 400 | `account` and `with` are the same. |
|
|
174
|
+
| `otherSet` | 409 | `account` is already in a different set. |
|
|
175
|
+
| `setFull` | 409 | The set would pass `maxLinked`, or its approved accounts would. |
|
|
176
|
+
| `notApprover` | 403 | Approving, and `req.user` isn't an approver. |
|
|
177
|
+
| `ownSet` | 403 | Approving a set the approver is in, is joining, or signed in through. |
|
|
178
|
+
| `notConfirmed` | 409 | The account's row is still waiting for its email, or, for `approveLink`, it's in no set. |
|
|
179
|
+
| `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. |
|
|
180
|
+
|
|
181
|
+
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.
|
|
182
|
+
|
|
183
|
+
`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.
|
|
184
|
+
|
|
129
185
|
## Upgrading from 0.4.0
|
|
130
186
|
|
|
131
187
|
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 +205,7 @@ Everything else that changes for a host, in full:
|
|
|
149
205
|
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
206
|
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
207
|
|
|
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,
|
|
208
|
+
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
209
|
|
|
154
210
|
The changelog lists every change.
|
|
155
211
|
|
|
@@ -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>;
|
package/dist/approval.js
ADDED
|
@@ -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
|
+
}
|
package/dist/collections.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { APIError, validations } from 'payload';
|
|
2
|
-
import {
|
|
2
|
+
import { approvalRefusal, isApprover } from './approval.js';
|
|
3
3
|
import { dissolveIfAlone, revokeSessions } from './sessions.js';
|
|
4
|
-
import {
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
|
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
|
-
|
|
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
|
};
|
package/dist/endpoints.d.ts
CHANGED
|
@@ -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.
|
|
@@ -91,7 +91,7 @@ const me = {
|
|
|
91
91
|
const mine = await membershipOf(req, String(full.id));
|
|
92
92
|
const from = { user: req.user, hat: worn?.id ?? null };
|
|
93
93
|
const setId = mine?.status === 'approved' ? idOf(mine.link) : null;
|
|
94
|
-
const asks = async (target, targetHats, h, sameAccount) => !(sameAccount && h.id === worn?.id) && (await needsStepUp(opts, { req, from, target, hats: targetHats, hat: h })) && !remembered(opts, s?.steppedUp, String(target.id), setId);
|
|
94
|
+
const asks = async (target, targetHats, h, sameAccount) => !(sameAccount && h.id === worn?.id) && (await needsStepUp(opts, { req, from, target, hats: targetHats, hat: h })) && !remembered(opts, s?.steppedUp, String(target.id), setId, h.id);
|
|
95
95
|
// The set as this account may see it: an account nobody has confirmed yet stays hidden, so a request never
|
|
96
96
|
// reveals whether an email has an account here.
|
|
97
97
|
const set = [];
|
|
@@ -238,7 +238,7 @@ async function switchCore(req, body) {
|
|
|
238
238
|
let gaveCode = false;
|
|
239
239
|
const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
|
|
240
240
|
const from = { user: req.user, hat: fromHat };
|
|
241
|
-
if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
|
|
241
|
+
if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId, hat.id)) {
|
|
242
242
|
if (!opts.stepUp)
|
|
243
243
|
refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
|
|
244
244
|
// Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
|
|
@@ -251,7 +251,9 @@ async function switchCore(req, body) {
|
|
|
251
251
|
return { ok: false, status: 401, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' };
|
|
252
252
|
if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
|
|
253
253
|
refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
|
|
254
|
-
|
|
254
|
+
const key = memoryKey(opts, to, setId, hat.id);
|
|
255
|
+
if (key !== null)
|
|
256
|
+
steppedUp[key] = new Date().toISOString();
|
|
255
257
|
gaveCode = true;
|
|
256
258
|
}
|
|
257
259
|
const users = req.payload.collections[opts.users].config;
|
|
@@ -373,9 +375,6 @@ const requestLink = {
|
|
|
373
375
|
refuse('Too many link requests. Try again later.', 429, 'tooMany');
|
|
374
376
|
}
|
|
375
377
|
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
378
|
// One record for every request, with the same fields. Only a real invitation's token can ever be used.
|
|
380
379
|
const token = newToken();
|
|
381
380
|
const hours = opts.confirmHours;
|
|
@@ -386,15 +385,9 @@ const requestLink = {
|
|
|
386
385
|
overrideAccess: true,
|
|
387
386
|
req,
|
|
388
387
|
})));
|
|
389
|
-
//
|
|
390
|
-
//
|
|
391
|
-
//
|
|
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.
|
|
388
|
+
// The asker's own note is the same every time and leaves the address out, so it can't tell them anything. It
|
|
389
|
+
// goes before anything that depends on the address (looking it up, checking its set, claiming it), so the
|
|
390
|
+
// work done before it, and when it arrives, is the same for a real address and a made-up one.
|
|
398
391
|
try {
|
|
399
392
|
await opts.sendEmail({
|
|
400
393
|
payload: req.payload,
|
|
@@ -406,6 +399,17 @@ const requestLink = {
|
|
|
406
399
|
catch (err) {
|
|
407
400
|
req.payload.logger.warn({ err }, 'Hats: link request note not sent');
|
|
408
401
|
}
|
|
402
|
+
const { docs } = await req.payload.find({ collection: opts.users, where: { email: { equals: email } }, limit: 1, depth: 0, overrideAccess: true, pagination: false, req });
|
|
403
|
+
const found = docs[0];
|
|
404
|
+
let target = found && String(found.id) !== me && !(await membershipOf(req, String(found.id))) ? found : null;
|
|
405
|
+
// One open invitation per account, from anyone, so nobody can fill an inbox with them. The database holds the
|
|
406
|
+
// rule: `holds` is unique, so of requests arriving together only one can claim the account. Every request makes
|
|
407
|
+
// the same two writes (a request with no account to claim rewrites its own hold), and any failure to claim
|
|
408
|
+
// means no invitation, so the asker sees the same thing either way.
|
|
409
|
+
const claim = target ? { account: relId(req.payload, opts.users, target.id), holds: holdFor(target) } : { holds: hold };
|
|
410
|
+
const claimed = await asPlugin(req, () => req.payload.update({ collection: REQUESTS, id: request.id, data: claim, overrideAccess: true, req })).then(() => true, () => false);
|
|
411
|
+
if (!claimed)
|
|
412
|
+
target = null;
|
|
409
413
|
if (!target)
|
|
410
414
|
return;
|
|
411
415
|
try {
|
|
@@ -574,7 +578,7 @@ const confirm = {
|
|
|
574
578
|
},
|
|
575
579
|
};
|
|
576
580
|
/** Whether `v` is an account id written the one way the users collection writes its ids. */
|
|
577
|
-
function exactId(req, opts, v) {
|
|
581
|
+
export function exactId(req, opts, v) {
|
|
578
582
|
if (typeof v !== 'string' && typeof v !== 'number')
|
|
579
583
|
return false;
|
|
580
584
|
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,13 @@
|
|
|
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 {
|
|
4
|
+
import { REMEMBER_PER } from './stepup.js';
|
|
5
|
+
import { asPlugin, changeWhere, holdEvents, newToken, ownHook, relId, removeWhere, serial, unmarkForeignHooks, watchTransactions } from './state.js';
|
|
5
6
|
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
6
7
|
export { hatsStateOf } from './state.js';
|
|
7
8
|
export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
|
|
8
9
|
export { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
10
|
+
export { approveLink, checkLinks, linkAccounts } from './link.js';
|
|
9
11
|
/**
|
|
10
12
|
* 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
13
|
* `POST /api/hats/switch`, in the same order (blocked, notLinked, showSwitch, the step-up checks, the session record,
|
|
@@ -22,6 +24,8 @@ export const switchSession = (req, input) => runSwitch(req, input);
|
|
|
22
24
|
* factor. Every switched session is checked against its linked set on every request, and ends the moment the set,
|
|
23
25
|
* the membership or the account's roles change.
|
|
24
26
|
*/
|
|
27
|
+
/** A set's label once the account that started it is deleted (its old label names that account). */
|
|
28
|
+
const DELETED_STARTER = 'Started by a deleted account';
|
|
25
29
|
export const hats = (options) => (config) => {
|
|
26
30
|
const opts = {
|
|
27
31
|
users: 'users',
|
|
@@ -37,6 +41,8 @@ export const hats = (options) => (config) => {
|
|
|
37
41
|
throw new Error('hats: maxLinked must be at least 2.');
|
|
38
42
|
if (typeof opts.linkAnswerMs !== 'number' || !Number.isFinite(opts.linkAnswerMs) || opts.linkAnswerMs < 0 || opts.linkAnswerMs > 2_147_483_647)
|
|
39
43
|
throw new Error('hats: linkAnswerMs must be a number of milliseconds, from 0 to 2147483647.');
|
|
44
|
+
if (opts.stepUp && opts.stepUp.rememberPer !== undefined && !REMEMBER_PER.includes(opts.stepUp.rememberPer))
|
|
45
|
+
throw new Error("hats: stepUp.rememberPer must be 'account', 'set' or 'hat'.");
|
|
40
46
|
const users = (config.collections ?? []).find((c) => c.slug === opts.users);
|
|
41
47
|
if (!users?.auth)
|
|
42
48
|
throw new Error(`hats: no auth collection "${opts.users}".`);
|
|
@@ -63,9 +69,14 @@ export const hats = (options) => (config) => {
|
|
|
63
69
|
// nothing here. It runs before the site's own afterDelete hooks, inside the delete's transaction where there is
|
|
64
70
|
// one. On SQL databases the foreign keys have already set these columns to null, so null rows go too. Payload runs
|
|
65
71
|
// 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
|
|
72
|
+
// throws, so the delete fails with it: with a transaction that Payload then ends, the whole delete is undone (a
|
|
73
|
+
// plain error in one document of a default bulk delete doesn't end it, see the README), and without one the caller
|
|
67
74
|
// still gets the error (a switched session through the deleted account is refused anyway, see `applyHat`).
|
|
68
|
-
|
|
75
|
+
// Its events (a leaving, revoked sessions) wait for the delete's transaction to commit, or for this to finish
|
|
76
|
+
// without one (see `holdEvents`). Once that transaction has ended under it, every database call made from here
|
|
77
|
+
// is refused at the moment the adapter looks up its transaction, one already under way included (see
|
|
78
|
+
// `watchTransactions`), so nothing of it is written outside the transaction.
|
|
79
|
+
const afterDelete = ownHook(async ({ id, req }) => holdEvents(req, async () => {
|
|
69
80
|
const p = req.payload;
|
|
70
81
|
const me = relId(p, opts.users, id);
|
|
71
82
|
const mineOrGone = (field) => ({ or: [{ [field]: { equals: me } }, { [field]: { exists: false } }] });
|
|
@@ -79,12 +90,15 @@ export const hats = (options) => (config) => {
|
|
|
79
90
|
// deleting an account frees nothing the asker could notice. At most one request holds the account.
|
|
80
91
|
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
92
|
// Who started a set, added or approved an account: cleared, along with the set's label, which names them.
|
|
82
|
-
|
|
93
|
+
// Only sets this account started: on SQL its foreign key has already cleared `requestedBy`, so a cleared one
|
|
94
|
+
// still carrying a starter's name counts too. Sets cleared before keep their label and aren't written again.
|
|
95
|
+
const startedBy = { or: [{ requestedBy: { equals: me } }, { and: [{ requestedBy: { exists: false } }, { label: { not_equals: DELETED_STARTER } }] }] };
|
|
96
|
+
await changeWhere(p, { collection: LINKS, where: startedBy, data: { requestedBy: null, label: DELETED_STARTER }, overrideAccess: true, req });
|
|
83
97
|
for (const field of ['addedBy', 'approvedBy'])
|
|
84
98
|
await changeWhere(p, { collection: MEMBERS, where: { and: [{ [field]: { equals: me } }, { user: { exists: true } }] }, data: { [field]: null }, overrideAccess: true, req });
|
|
85
99
|
}));
|
|
86
100
|
await revokeSessions(p, { or: [{ user: { equals: String(id) } }, { via: { equals: String(id) } }] }, 'account deleted', req);
|
|
87
|
-
});
|
|
101
|
+
}));
|
|
88
102
|
const afterLogout = ownHook(async ({ req }) => {
|
|
89
103
|
const sid = req.user?._sid;
|
|
90
104
|
if (sid)
|
|
@@ -114,6 +128,7 @@ export const hats = (options) => (config) => {
|
|
|
114
128
|
custom: { ...config.custom, hats: opts },
|
|
115
129
|
onInit: async (payload) => {
|
|
116
130
|
unmarkForeignHooks(payload);
|
|
131
|
+
watchTransactions(payload);
|
|
117
132
|
await onInit?.(payload);
|
|
118
133
|
wrapStrategies(payload, opts);
|
|
119
134
|
},
|
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[]>;
|