@extantape/payload-plugin-hats 0.8.1 → 0.9.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 +151 -4
- package/dist/accounts.d.ts +63 -0
- package/dist/accounts.js +403 -0
- package/dist/approval.d.ts +6 -0
- package/dist/approval.js +16 -0
- package/dist/collections.js +13 -2
- package/dist/endpoints.d.ts +34 -1
- package/dist/endpoints.js +263 -146
- package/dist/index.d.ts +49 -3
- package/dist/index.js +50 -1
- package/dist/link.d.ts +1 -1
- package/dist/link.js +19 -2
- package/dist/linking.d.ts +119 -0
- package/dist/linking.js +270 -0
- package/dist/sessions.js +8 -0
- package/dist/signin.d.ts +62 -0
- package/dist/signin.js +109 -0
- package/dist/state.d.ts +11 -1
- package/dist/state.js +26 -0
- package/dist/types.d.ts +126 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
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 630 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
|
-
- **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set.
|
|
9
|
+
- **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Leaving a set is self-serve and immediate. Taking another account out needs an approved account in the set.
|
|
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
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).
|
|
@@ -15,7 +15,10 @@ Linked accounts and role hats for Payload. One person links their accounts and s
|
|
|
15
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.
|
|
16
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.
|
|
17
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
|
+
- **Who may be linked.** Pass `canBeLinked` to say which accounts may be in a set at all, for example to keep young people's accounts out. It is asked for both accounts when a link is requested, again at each confirmation and at approval, by `linkTrusted`, and before a switch into another account. Leaving a set is never asked. With `disable.isDisabled`, an account your site has disabled can't be linked either. See **Linking from server code**.
|
|
18
19
|
- **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.
|
|
20
|
+
- **Account controls.** `listLinkedAccounts`, `unlinkAccount`, `decouple`, `disableAccount` and `disableAll` let a site list a person's linked accounts, take one out, dissolve a set and disable accounts from its own server code, with the plugin's checks. `canControlAccounts` says who may do that to other people's accounts, and `disable` says what disabled means on your site. An optional `audit` hook runs before a change is committed, so a change that can't be recorded isn't made. See **Listing, unlinking, decoupling and disabling**.
|
|
21
|
+
- **Which account to sign in with.** `accountToSignIn` tells server code whether the person may sign in with a linked account, and which hat it would start in. It makes no session. See **Which account a person may sign in with**.
|
|
19
22
|
- **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.
|
|
20
23
|
|
|
21
24
|
Needs Payload sessions (`auth.useSessions`, on by default).
|
|
@@ -26,9 +29,9 @@ Needs Payload sessions (`auth.useSessions`, on by default).
|
|
|
26
29
|
|
|
27
30
|
**Needs:** Payload `^3.80.0` as a peer dependency, with React `^19.0.0` optional. No other EXTANT APE plugin is required.
|
|
28
31
|
|
|
29
|
-
**Only `true` counts.** `canApproveLinks`, `stepUp.available`, `stepUp.verify` and `limit` must answer exactly `true` (or a promise of it). Anything else is a no: `false`, `1`, `'yes'`, an object such as `{ valid: false }`, or an error thrown or rejected. A refused step-up answers 403 (`setUpTwoStep` or `wrongCode`), a refused approval 403 and a refused link request 429 (`tooMany`), never a 500. If your verifier returns a result object, pass its flag: `verify: async (a) => (await check(a)).valid === true`.
|
|
32
|
+
**Only `true` counts.** `canApproveLinks`, `canControlAccounts`, `canBeLinked`, `stepUp.available`, `stepUp.verify` and `limit` must answer exactly `true` (or a promise of it). `disable.isDisabled` is read the other way round: only an exact `false` means the account is in use, and `true`, any other answer or a throw counts as disabled. Anything else is a no: `false`, `1`, `'yes'`, an object such as `{ valid: false }`, or an error thrown or rejected. A refused step-up answers 403 (`setUpTwoStep` or `wrongCode`), a refused approval 403 and a refused link request 429 (`tooMany`), never a 500. If your verifier returns a result object, pass its flag: `verify: async (a) => (await check(a)).valid === true`.
|
|
30
33
|
|
|
31
|
-
**Only `null` goes ahead.** `blocked(req)` answers a reason or `null`. A non-empty string refuses switching, linking and
|
|
34
|
+
**Only `null` goes ahead.** `blocked(req, { action })` answers a reason or `null`. `action` says what is being asked for (`list`, `link`, `confirm`, `unlink`, `decouple`, `disable`, `switch` or `signIn`), so a hook can allow some and refuse others without reading the request's address. A hook that takes only `req` works as before. A non-empty string refuses switching, linking, unlinking, decoupling and disabling with 409 (`blocked`) and your reason. `null` or `undefined` goes ahead. Anything else, such as `''`, `false` or an object, and an error thrown or rejected, also refuses with 409 `blocked` and a general reason, never a 500.
|
|
32
35
|
|
|
33
36
|
**Works with:**
|
|
34
37
|
- **MFA:** MFA's `isOnFor` and `verify` make the `stepUp`. MFA's README has the two lines.
|
|
@@ -55,6 +58,9 @@ hats({
|
|
|
55
58
|
// optional: ask only when the new hat holds something the current one doesn't
|
|
56
59
|
stepUpWhen: ({ from, to }) => holdsMoreThan(to.user, from.user),
|
|
57
60
|
limit: ({ user, email }) => allowAttempt('hatsLink', `${user.id}:${email}`), // optional
|
|
61
|
+
canBeLinked: ({ user }) => isAdult(user), // optional: who may be in a set at all
|
|
62
|
+
disable: { isDisabled: (user) => user.status === 'disabled' }, // optional: your own status field
|
|
63
|
+
blocked: (req, { action }) => (isViewingAsSomeoneElse(req) ? 'Stop viewing as someone else first.' : null), // optional
|
|
58
64
|
})
|
|
59
65
|
```
|
|
60
66
|
|
|
@@ -77,6 +83,8 @@ Endpoints, under the API route:
|
|
|
77
83
|
- `POST /hats/link { email }` asks to link another account. It answers 202 after `linkAnswerMs` whatever the address. Set `linkAnswerMs` above your slowest email send: work still running when it's up carries on after the answer, which a host that stops work after a response would cut short.
|
|
78
84
|
- `GET` and `POST /hats/confirm` handle the email confirmation.
|
|
79
85
|
- `POST /hats/unlink { account? }` takes an account out of the set.
|
|
86
|
+
- `GET /hats/accounts` lists the acting account's linked accounts, as `listLinkedAccounts` does. A controller adds `?of=<account id>`.
|
|
87
|
+
- `POST /hats/decouple { account? }` dissolves the whole set.
|
|
80
88
|
|
|
81
89
|
Approvers approve in the admin, under Accounts → Linked accounts.
|
|
82
90
|
|
|
@@ -138,6 +146,145 @@ export async function POST(request: Request) {
|
|
|
138
146
|
- 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.
|
|
139
147
|
- 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.
|
|
140
148
|
|
|
149
|
+
## Linking from server code
|
|
150
|
+
|
|
151
|
+
Three functions for a site's own server code, beside the endpoints. `requestLink` acts only for `req.user`. None has an option that skips a check.
|
|
152
|
+
|
|
153
|
+
- `requestLink(req, { email })` is `POST /hats/link` as a function, for a site's own route. It returns `{ ok: true, reason: 'linkSent', message }` or `{ ok: false, status, reason, message }`, and doesn't throw for a refusal. `ok: true` means the request was taken, whatever the address, so a route should answer 202 with the same words every time.
|
|
154
|
+
- `linkTrusted(payload, { accounts, by, req? })` links accounts your site has already vetted, such as an account it made for someone or an invitation it sent and saw accepted. The accounts are approved at once. It skips the confirmation emails and the approver on purpose, and it skips nothing else: it runs the same check as a link request, a confirmation and an approval. `accounts` is two or more exact account ids. `by` is the account that vetted them, or `null` when the site itself did; it is recorded on the rows and in the `linked-trusted` event. Accounts already together in a set keep that set and the others join it, and rows still waiting there become approved. It returns `{ ok: true, set, accounts }`. A refusal is thrown as a `HatsRefusal`, an `Error` with a stable `reason` and a `status`; its message is written for logs. With a transaction (pass your `req` to join yours) a refused or failed call is rolled back. Without one, the rows the call made are taken back.
|
|
155
|
+
- `getLinkedSet(payload, accountId, { req? })` is a read-only look at an account's set: `{ link, rows: [{ account, status }], members, approved }`, all empty for an account in no set or an id that isn't exact. It checks nobody's access.
|
|
156
|
+
|
|
157
|
+
**`linkTrusted` and `getLinkedSet` are for server code only.** The plugin adds no endpoint for either, and Payload serves only collections and registered endpoints over REST and GraphQL, so nothing outside your server can call them. If you wrap one in a route of your own, that route's access is yours to get right. The collections stay closed as before: `hat-links` refuses create, update and delete from any user, and `hat-members` refuses a create from anything but the plugin, server code with `overrideAccess` included.
|
|
158
|
+
|
|
159
|
+
**One check for every way of linking.** A link request, the invited account's confirmation, the asker's own confirmation, an approval (the admin form, `approveLink` and a repeat `linkAccounts`), `linkAccounts` and `linkTrusted` all call one function, so they can't drift apart. In order it refuses: the same account twice (`sameAccount`), an account that is already in another set or would be in two (`alreadyLinked`), an account `disable.isDisabled` doesn't call in use (`disabled`), an account `canBeLinked` doesn't allow (`notLinkable`), and a set that would pass `maxLinked` (`setFull`). After a write that adds rows, the set is read again, and a call that finds it over `maxLinked` takes its own rows back. Two links that both pass the check a moment apart can therefore both be refused, and the set never ends up over the limit.
|
|
160
|
+
|
|
161
|
+
## Listing, unlinking, decoupling and disabling
|
|
162
|
+
|
|
163
|
+
Five more functions for a site's own server code. Each acts only for `req.user`, asks `blocked` first, has no option that skips a check, and returns `{ ok: true, ... }` or `{ ok: false, status, reason, message }`. None throws for a refusal, and an error from one of your hooks is a refusal too. Account ids must be written exactly as your users collection writes them.
|
|
164
|
+
|
|
165
|
+
- `listLinkedAccounts(req, { of? })` returns `{ ok, set, accounts: [{ id, label, you, status? }], maxLinked }`. A person sees themselves and the approved accounts. An account still waiting stays hidden, so a link request never shows whether an address has an account. With `of`, a controller reads another account's set: every row with its `status`, and an email in `label` only for approved accounts (the id otherwise). `GET /hats/accounts` is the same call, with `?of=` for a controller.
|
|
166
|
+
- `unlinkAccount(req, { account? })` takes one account out and returns `{ ok, account, signedOut }`. `POST /hats/unlink` is the same call.
|
|
167
|
+
- `decouple(req, { account? })` dissolves the whole set the account is in (yours by default) and returns `{ ok, unlinked, signedOut }`. Every account stays whole, and every session switched through the set ends. `POST /hats/decouple` is the same call. A person gets back the accounts they could see; a controller gets every account.
|
|
168
|
+
- `disableAccount(req, { account, decouple?, reason?, dryRun? })` disables one account through your `disable.apply`.
|
|
169
|
+
- `disableAll(req, { account, decouple?, reason?, dryRun? })` disables every approved account in that account's set. Both return `{ ok, disabled, skipped, unlinked }`, where `skipped` holds the accounts that were disabled already. With `decouple: true`, `disableAccount` also takes that account out of its set and `disableAll` dissolves the set. `dryRun: true` runs every refusal and writes nothing, so it works as a preview.
|
|
170
|
+
|
|
171
|
+
**Disable has no endpoint.** Call `disableAccount` and `disableAll` from your own admin route, behind your own screens and confirmation.
|
|
172
|
+
|
|
173
|
+
**Two options turn this on.** `canControlAccounts({ req, user })` says who may list another account's set, take an account out of any set, dissolve a set and disable accounts. It is separate from `canApproveLinks`, and nobody is a controller until you set it. `disable` says what disabled means on your site, because the plugin keeps no status of its own:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
hats({
|
|
177
|
+
canControlAccounts: ({ user }) => user.roles.includes('owner'),
|
|
178
|
+
disable: {
|
|
179
|
+
apply: ({ req, account, reason }) => req.payload.update({ collection: 'users', id: account.id, data: { status: 'disabled' }, req }),
|
|
180
|
+
isDisabled: (user) => user.status === 'disabled',
|
|
181
|
+
protect: ({ account }) => account.roles.includes('owner'), // optional
|
|
182
|
+
},
|
|
183
|
+
audit: ({ req, ...entry }) => req.payload.create({ collection: 'audit-log', data: entry, req }), // optional
|
|
184
|
+
})
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Write with the `req` you are given in `apply` and `audit`, so your writes join the plugin's transaction.
|
|
188
|
+
|
|
189
|
+
**What a disable does, in order.** Every check runs before anything is written. Then `apply` is called once for each account that isn't disabled yet. Then every session the plugin keeps a record for on those accounts ends: the ones switched into them, switched through them, or wearing a hat. Then, with `decouple`, the rows go. Then `audit` gets its entries, and only then is the change committed. A plain sign-in that never switched has no record with the plugin, so ending it is your `apply`'s job. An account approved into the set while a `disableAll` runs is disabled in the same call; if it can't be (a protected one, say) the call answers with that refusal.
|
|
190
|
+
|
|
191
|
+
**Audit.** `audit({ action, actor, account, via, hat, reason, req })` is called once for each account a trusted link, an unlink, a decouple or a disable touches. `action` is `linked-trusted`, `unlinked`, `decoupled` or `disabled`; an account that is both disabled and taken out gets one entry for each. It is awaited before the change is committed. If it throws, the call is refused with `auditFailed` (500). With transactions the change is undone. `linkTrusted` takes its rows back in either case. On a database without transactions an unlink, a decouple or a disable that was already written stays, and its entry is missing: running the call again finishes the job, but an account that is by then unlinked or disabled is skipped and gets no entry, so log the `auditFailed` answer yourself there. `onEvent` is separate and unchanged: best effort, after the change.
|
|
192
|
+
|
|
193
|
+
**A repeat finishes the job.** An account that is already disabled is skipped, and an account already out answers `notInSet`. So a run that stopped halfway, because `apply` failed on the second account for example, can be run again.
|
|
194
|
+
|
|
195
|
+
**The step-up challenge.** `stepUp.available` and `stepUp.verify` also get `hat`, the hat being switched into. `stepUp.challenge({ req, user, hat, signedIn, set })` is optional: the plugin calls it at the one moment a switch is about to answer `needsCode` and no code came with the request, so a site that sends its code by email sends it exactly then. It isn't called when the hat is already worn, when a code is remembered, or when a code was given. If it throws, the switch is refused (`failed`, 500).
|
|
196
|
+
|
|
197
|
+
## Which account a person may sign in with
|
|
198
|
+
|
|
199
|
+
`accountToSignIn(payload, accountId, { req, defaultHat? })` answers one question for server code: may the person behind `req` sign in with this linked account, and which hat would it start in. It is a read. It writes nothing and makes no session, cookie or token, on a yes or on a no.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
const result = await accountToSignIn(payload, accountId, { req, defaultHat: storedDefaultFor(accountId) })
|
|
203
|
+
// { ok: true, account, hat, via, needsStepUp } or { ok: false, reason }
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
- **Who is asking.** The caller is `req.user`, so pass the person's own signed-in request. Without it the answer is `signIn`. `via` is the account they signed in with, which differs from the account they are acting as after a switch.
|
|
207
|
+
- **Which accounts.** Only an account with an approved row in the same set as the account the caller is acting as. Both rows are read from the database on every call, so an answer never outlives an unlink. The caller's own account is refused (`sameAccount`). An account in another set, one still waiting, one that doesn't exist and an id that isn't exact all answer `notLinked`.
|
|
208
|
+
- **Masquerading.** `blocked` is asked first, with the action `signIn`. A hook that refuses while someone is viewing as another person refuses this too (`blocked`).
|
|
209
|
+
- **The same checks as linking and login.** The shared link check runs on the caller and the target, so a disabled account (`disabled`), one `canBeLinked` rules out (`notLinkable`) and a set over `maxLinked` (`setFull`) are refused. An account Payload's own login would turn away is refused too (`locked`, `unverified`), by the same code the switch uses.
|
|
210
|
+
- **The hat is the target account's own.** The plugin stores no default hat, so pass yours as `defaultHat`. It is used when the account holds it and it is offered. A default the account no longer holds, one it never held and a hidden one all fall to the account's narrowest hat, as does no default at all. The hat worn on the caller's account plays no part, so nothing is gained by asking from a wider hat. An account with no hats answers `hat: null`. An account whose narrowest hat is hidden is refused (`chooseHat`), as a switch that names no hat is.
|
|
211
|
+
- **A sensitive hat still needs its code.** When the hat would ask for a code in a switch, the answer is `ok: true` with `needsStepUp: true`. It uses the switch's own rule, `stepUpWhen` and a remembered code included, so the two agree. The helper sends no code and calls no `stepUp` hook. The only way to a session is `switchSession` or `POST /hats/switch`, which run every check again and ask for the code, so the step can't be skipped.
|
|
212
|
+
- **It doesn't throw for a refusal.** An error from one of your hooks is a refusal too (`failed`).
|
|
213
|
+
- **`onEvent`** gets `{ type: 'sign-in-account', req, from, account, hat, via, needsStepUp }` for each yes. Best effort, like the other events.
|
|
214
|
+
|
|
215
|
+
**The reason is for server code only.** The plugin adds no endpoint for this. If you put a route on top, send `signInAnswer(result)` and nothing else: it gives every refusal the same status and body (403, `notAvailable`), whatever the reason, and leaves `via` out of a yes. A route that passed the reason on would tell a caller who is linked to whom.
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
const { status, body } = signInAnswer(await accountToSignIn(payload, accountId, { req }))
|
|
219
|
+
return Response.json(body, { status })
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## What is refused
|
|
223
|
+
|
|
224
|
+
Every row fails closed. A hook that throws, or answers anything but the exact value, counts as a no.
|
|
225
|
+
|
|
226
|
+
| Action | Allowed | Refused with |
|
|
227
|
+
| --- | --- | --- |
|
|
228
|
+
| Any call | A signed-in account of the users collection, in a Hats session | `signIn` 401 |
|
|
229
|
+
| Any write | Only when `blocked` answers null | `blocked` 409 (covers masquerade and read-only sessions) |
|
|
230
|
+
| `listLinkedAccounts` for yourself | Always, including read-only sessions | none |
|
|
231
|
+
| `listLinkedAccounts` for `of` | Controller only | `notAllowed` 403 |
|
|
232
|
+
| `requestLink` | Both accounts pass `canBeLinked`, `canApproveLinks` is set, `limit` allows | `linkingOff` 403, `tooMany` 429, `setFull` 400. A non-linkable invitee answers 202 like any unknown address, so nothing leaks. |
|
|
233
|
+
| `linkAccounts`, `approveLink` | Server code. The same check as a person's request, so a minor's or disabled account is refused here too | `disabled`, `notLinkable`, `alreadyLinked` (as `otherSet`), `setFull`, returned as a result |
|
|
234
|
+
| `linkTrusted` | Server code. Plugin still enforces: different accounts, neither in another set, size limit, `canBeLinked` on both, no disabled account | `setFull`, `alreadyLinked`, `notLinkable`, `disabled` (thrown to server code, not shown to people) |
|
|
235
|
+
| `unlinkAccount` yourself | Always, even for a minor or a disabled account | `notInSet` 404 if not in a set |
|
|
236
|
+
| `unlinkAccount` another | An approved member of the same set, or any member while nobody in the set is approved yet, or a controller | `notAllowed` 403. An unconfirmed account answers `notInSet`, as today. |
|
|
237
|
+
| `decouple` | An approved member of that set, or a controller | `notAllowed` 403, `notInSet` 404 |
|
|
238
|
+
| `disableAccount`, `disableAll` | `canControlAccounts` answers exactly true | `notAllowed` 403 |
|
|
239
|
+
| Disable the acting account, or the account the session signed in with | Never | `cannotDisableSelf` 403 |
|
|
240
|
+
| Disable a protected account | Never through this API | `protectedAccount` 403 |
|
|
241
|
+
| Disable, set includes an unapproved invitee | Invitee is never touched | (skipped, not an error) |
|
|
242
|
+
| Any switch into a disabled account | Never | `disabled` 403 (new, from `isDisabled`) |
|
|
243
|
+
| Switch into an account `canBeLinked` refuses | Never | `notAvailable` 403 |
|
|
244
|
+
| `accountToSignIn` without the caller's own signed-in request | Never | `signIn` |
|
|
245
|
+
| `accountToSignIn` for an account that isn't approved in the caller's set | Never. An account in another set, one still waiting and no account answer the same | `notLinked` |
|
|
246
|
+
| `accountToSignIn` for the caller's own account | Never | `sameAccount` |
|
|
247
|
+
| `accountToSignIn` while `blocked` says no, as while masquerading | Never | `blocked` |
|
|
248
|
+
| `accountToSignIn` after an unlink | Never: the link is read on every call | `notLinked` |
|
|
249
|
+
| `accountToSignIn`, the hat | The target account's own default. One it no longer holds falls to its narrowest hat | `chooseHat` when that hat is hidden |
|
|
250
|
+
| `accountToSignIn`, a sensitive hat | Answered `needsStepUp: true`, with no session | (the switch asks for the code: `needsCode` 401) |
|
|
251
|
+
| `accountToSignIn` for a disabled, ruled-out or locked account | Never | `disabled`, `notLinkable`, `locked`, `unverified`, `setFull` |
|
|
252
|
+
| `accountToSignIn`, a host hook throws | Never goes ahead | `notLinkable`, `blocked`, `failed` |
|
|
253
|
+
| A route's answer for `accountToSignIn` | `signInAnswer` gives every refusal the same answer | `notAvailable` 403 |
|
|
254
|
+
| Switch when either the signed-in account or the target is refused by `canBeLinked` or disabled by `isDisabled` | Never | `notAvailable` 403 |
|
|
255
|
+
| Host hook (`audit`, `apply`, `blocked`, `canBeLinked`, `isDisabled`) throws | Never goes ahead | `auditFailed` 500, `failed` 500, `blocked` 409, `notLinkable` 403, `disabled` 403 |
|
|
256
|
+
|
|
257
|
+
What the table leaves to the rows around it:
|
|
258
|
+
|
|
259
|
+
- **Any call** covers every function above and `requestLink`. A switch from a sign-in with no session record (an API key, say) still answers `signIn` with 400, as it did.
|
|
260
|
+
- **Any write** covers a link request, a confirmation, an unlink, a decouple, a disable (a dry run included) and a switch. `blocked(req, { action })` is told which: `link`, `confirm`, `unlink`, `decouple`, `disable` or `switch`. A controller's listing of another account's set asks it too, with `list`, so a session you block can't read other people's sets. Listing your own set never asks. A blocked confirmation shows a page with your reason and status 409, and leaves the link unused, so it works once you allow it.
|
|
261
|
+
- **`listLinkedAccounts` for `of`** answers `notFound` (404) to a controller for an id that is no account.
|
|
262
|
+
- **`requestLink`** also refuses an asker `canBeLinked` doesn't allow (`notLinkable`, 403) and a disabled asker (`disabled`, 403). Both depend only on the asker, so they say nothing about the address.
|
|
263
|
+
- **`linkTrusted`** also throws `sameAccount` (400), `tooFew` for fewer than two accounts (400), `unknownAccount` for an id that isn't exact or isn't an account, `by` included (404), `auditFailed` (500), and `failed` (500) when a write didn't go through after three tries. `setFull` is 400, `alreadyLinked` 409, `notLinkable` and `disabled` 403.
|
|
264
|
+
- **`unlinkAccount` another** and **`decouple`**: an account outside your set, one still waiting to confirm, and an id that isn't exact all answer `notInSet`, the same as an account that doesn't exist. A controller can take out a waiting account, and gets `notInSet` only when the account is in no set.
|
|
265
|
+
- **`disableAccount`, `disableAll`** answer `disableOff` (403) to a controller when `disable.apply` isn't set, and `notFound` (404) for an id that is no account. `disableAll` on an account that isn't approved in a set disables that one account, since a link nobody approved isn't a link yet.
|
|
266
|
+
- **Protected accounts.** `disable.protect` is read the careful way round: only an exact `false` leaves an account open to a disable. `true`, any other answer and a throw protect it, and one protected account among several refuses the whole call. Without `protect` no account is protected.
|
|
267
|
+
- **Any switch into a disabled account** covers a hat change on a disabled account as well. The account is read again after the new session is made, so a switch and a disable at the same moment leave no session behind.
|
|
268
|
+
- **`accountToSignIn`** refusals carry a reason and nothing else: no status and no message, since they aren't for a browser. `signInAnswer` is what a route sends.
|
|
269
|
+
- **Host hooks.** A throw from `canBeLinked` is `notLinkable`, from `isDisabled` is `disabled`, from `canControlAccounts` is `notAllowed`, from `protect` is `protectedAccount`, and from `stepUp.challenge` is `failed`.
|
|
270
|
+
|
|
271
|
+
## Upgrading from 0.6.1 (unreleased)
|
|
272
|
+
|
|
273
|
+
No new collections or fields, so there is no migration and no types to regenerate. What a host can notice:
|
|
274
|
+
|
|
275
|
+
1. `blocked` gets a second argument, `{ action }`. A hook that takes only `req` is unaffected.
|
|
276
|
+
2. `blocked` is now asked before a confirmation too, with `action: 'confirm'`. The confirming request often has nobody signed in, so a hook that reads `req.user` must cope with that. A hook that throws there refuses the confirmation.
|
|
277
|
+
3. `POST /hats/link` and `POST /hats/unlink` answer `signIn` with 401 for a sign-in that has no session record. It was 400.
|
|
278
|
+
4. A confirmation into a set that filled up at the same moment is refused and its rows are taken back. Two confirmations that race for one seat can both be refused; asking again works.
|
|
279
|
+
5. With `canBeLinked` or `disable.isDisabled` set, link requests, confirmations, approvals and switches are refused for the accounts they rule out. Without them nothing changes.
|
|
280
|
+
6. New `onEvent` types `linked-trusted`, `decoupled` and `accounts-disabled`. A handler that ignores unknown types keeps working.
|
|
281
|
+
7. **Unlinking another account is tighter.** It needs an approved account in the same set, or any account in the set while nobody in it is approved yet, or a controller. Before, any account in a set could take another out, so an account still waiting could remove an approved one. Such a call now answers `notAllowed` (403). Leaving a set yourself is unchanged.
|
|
282
|
+
8. A switch into an account `disable.isDisabled` calls disabled is refused (`disabled`, 403). Only if `disable.isDisabled` is set.
|
|
283
|
+
9. `POST /hats/unlink` answers `{ ok, account, signedOut }`; `account` is new. It runs in a transaction where the database has them, and with transactions two unlinks of one account at the same moment give one `notInSet`.
|
|
284
|
+
10. `stepUp.available` and `stepUp.verify` get `hat` as well. Nothing to change in a hook that ignores it.
|
|
285
|
+
11. Two new endpoints, `GET /hats/accounts` and `POST /hats/decouple`. Both act only for the signed-in account and ask `blocked` as described above.
|
|
286
|
+
12. `blocked` can be asked with a new action, `signIn`, and `onEvent` has a new type, `sign-in-account`. Both happen only when your own code calls `accountToSignIn`.
|
|
287
|
+
|
|
141
288
|
## Linking from your own server code
|
|
142
289
|
|
|
143
290
|
`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.
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { type PayloadRequest } from 'payload';
|
|
2
|
+
import { type Refusal, type ResolvedHatsOptions } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Whether the acting account may control other people's accounts: list their sets, take accounts out, dissolve a set,
|
|
5
|
+
* disable. Only an exact `true` from `canControlAccounts` counts. Without the option nobody may.
|
|
6
|
+
*/
|
|
7
|
+
export declare function mayControl(opts: ResolvedHatsOptions, req: PayloadRequest): Promise<boolean>;
|
|
8
|
+
export type LinkedAccount = {
|
|
9
|
+
id: string | number;
|
|
10
|
+
label: string;
|
|
11
|
+
you: boolean; /** The account's row in the set, when it has one: `requested`, `confirmed` or `approved`. */
|
|
12
|
+
status?: string;
|
|
13
|
+
};
|
|
14
|
+
export type LinkedAccountsResult = {
|
|
15
|
+
ok: true;
|
|
16
|
+
set: string | null;
|
|
17
|
+
accounts: LinkedAccount[];
|
|
18
|
+
maxLinked: number;
|
|
19
|
+
} | Refusal;
|
|
20
|
+
/**
|
|
21
|
+
* The one listing, shared by GET /api/hats/accounts and `listLinkedAccounts`. Your own set is a read that is always
|
|
22
|
+
* open, so `blocked` isn't asked. Another account's set (`of`) is for a controller only, and `blocked` is asked with
|
|
23
|
+
* `list` first.
|
|
24
|
+
*/
|
|
25
|
+
export declare const runList: (req: PayloadRequest, input: {
|
|
26
|
+
of?: unknown;
|
|
27
|
+
} | null | undefined) => Promise<LinkedAccountsResult>;
|
|
28
|
+
export type UnlinkResult = {
|
|
29
|
+
ok: true;
|
|
30
|
+
account: string; /** Whether the acting session ended with the unlink. */
|
|
31
|
+
signedOut: boolean;
|
|
32
|
+
} | Refusal;
|
|
33
|
+
/** The one unlink, shared by POST /api/hats/unlink and `unlinkAccount`. */
|
|
34
|
+
export declare const runUnlink: (req: PayloadRequest, input: {
|
|
35
|
+
account?: unknown;
|
|
36
|
+
} | null | undefined) => Promise<UnlinkResult>;
|
|
37
|
+
export type DecoupleResult = {
|
|
38
|
+
ok: true; /** The accounts taken out, as the caller may see them. */
|
|
39
|
+
unlinked: string[]; /** Whether the acting session ended with the set. */
|
|
40
|
+
signedOut: boolean;
|
|
41
|
+
} | Refusal;
|
|
42
|
+
/** The one decouple, shared by POST /api/hats/decouple and `decouple`. */
|
|
43
|
+
export declare const runDecouple: (req: PayloadRequest, input: {
|
|
44
|
+
account?: unknown;
|
|
45
|
+
} | null | undefined) => Promise<DecoupleResult>;
|
|
46
|
+
export type DisableInput = {
|
|
47
|
+
/** The account to disable, exactly as the users collection writes its id. */
|
|
48
|
+
account: string | number;
|
|
49
|
+
/** Exactly `true` also unlinks: the one account for `disableAccount`, the whole set for `disableAll`. */
|
|
50
|
+
decouple?: boolean;
|
|
51
|
+
/** Why, in the host's own words. Passed to `disable.apply` and to `audit`. */
|
|
52
|
+
reason?: string;
|
|
53
|
+
/** Run every check and answer what would happen, without writing anything or calling `apply` or `audit`. */
|
|
54
|
+
dryRun?: boolean;
|
|
55
|
+
};
|
|
56
|
+
export type DisableResult = {
|
|
57
|
+
ok: true; /** Accounts this call disabled (or would, on a dry run). */
|
|
58
|
+
disabled: string[]; /** Accounts that were disabled already. */
|
|
59
|
+
skipped: string[]; /** Accounts taken out of their set. */
|
|
60
|
+
unlinked: string[];
|
|
61
|
+
} | Refusal;
|
|
62
|
+
/** The one disable, shared by `disableAccount` and `disableAll`. No endpoint reaches it: the host calls it from its own route. */
|
|
63
|
+
export declare const runDisable: (req: PayloadRequest, input: DisableInput | null | undefined, all: boolean) => Promise<DisableResult>;
|