@extantape/payload-plugin-hats 0.4.0 → 0.6.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 +49 -5
- package/dist/client/HatSwitcher.js +5 -4
- package/dist/client/api.d.ts +8 -0
- package/dist/client/model.d.ts +14 -3
- package/dist/client/model.js +16 -5
- package/dist/collections.d.ts +1 -1
- package/dist/collections.js +67 -15
- package/dist/endpoints.d.ts +15 -0
- package/dist/endpoints.js +254 -65
- package/dist/index.d.ts +1 -1
- package/dist/index.js +45 -15
- package/dist/sessions.d.ts +11 -1
- package/dist/sessions.js +34 -17
- package/dist/state.d.ts +68 -4
- package/dist/state.js +165 -6
- package/dist/types.d.ts +18 -2
- package/dist/types.js +1 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -2,17 +2,19 @@
|
|
|
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. The server
|
|
5
|
+
**Status:** early, 0.x. All 222 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
|
+
- **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.
|
|
10
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.
|
|
11
12
|
- **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 180 minutes (`stepUp.rememberMinutes`) per account, or per linked set (see below).
|
|
12
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.
|
|
13
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.
|
|
14
|
-
- **
|
|
15
|
-
- **
|
|
15
|
+
- **Hidden hats.** Set `hidden: true` on a hat in `hatsOf` and it isn't offered: it's left out of the switch, out of its Back to row, and out of `GET /hats`. A linked switch that names no hat goes to the account's narrowest hat only when that hat is offered, and is refused otherwise (`chooseHat`); it never moves up to a wider one. A switch into a hidden hat is refused through `POST /hats/switch` and `switchSession` alike, with the same `chooseHat` answer an unknown hat gets, before any code is asked for. Only a missing `hidden` or exactly `false` offers a hat: any other value, `'false'` or `null` included, hides it. See **What hidden doesn't do** below.
|
|
16
|
+
- **Revocation.** Unlinking, deleting a row, losing a role or deleting an account ends every session switched into or through it. Switched sessions also re-check their set on every request. An ended session's record is kept, marked revoked, so a session that Payload writes back by accident (two writes to an account's sessions at once) stays signed out. Old records are deleted once their Payload session is gone, at most 50 per switch. A switched session whose signed-in account no longer exists is refused and ended, even if the clean-up after that account's delete didn't finish. If the database fails during that clean-up, or while an unlink dissolves a set, the call answers with an error. A single delete or unlink with a transaction is then undone; in other cases the account can be deleted with some of its link rows left (see the limits under Upgrading).
|
|
17
|
+
- **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.
|
|
16
18
|
|
|
17
19
|
Needs Payload sessions (`auth.useSessions`, on by default).
|
|
18
20
|
|
|
@@ -20,6 +22,8 @@ Needs Payload sessions (`auth.useSessions`, on by default).
|
|
|
20
22
|
|
|
21
23
|
**On its own:** it needs a users auth collection with Payload sessions, plus your `hatsOf` and `wear`, built from the roles you already have. Linking stays off until you set `canApproveLinks`, and switching into a sensitive hat is refused until you give it a `stepUp`.
|
|
22
24
|
|
|
25
|
+
**Needs:** Payload `^3.80.0` as a peer dependency, with React `^19.0.0` optional. No other EXTANT APE plugin is required.
|
|
26
|
+
|
|
23
27
|
**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`.
|
|
24
28
|
|
|
25
29
|
**Only `null` goes ahead.** `blocked(req)` answers a reason or `null`. A non-empty string refuses switching, linking and unlinking 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,6 +36,8 @@ Needs Payload sessions (`auth.useSessions`, on by default).
|
|
|
32
36
|
|
|
33
37
|
None of these are imported. The site connects them in its own config.
|
|
34
38
|
|
|
39
|
+
**Color Theory:** no direct link. The switcher uses its own `--hats-*` variables, which fall back to Payload's `--theme-*` colors, so it follows Color Theory's admin colors when its `applyToAdmin` option is on. The plain page it serves when your site has none of its own uses fixed colors and has no hook yet.
|
|
40
|
+
|
|
35
41
|
**Family:** It's part of the **Identity** family (a working draft): plugins designed to sit together for accounts and access.
|
|
36
42
|
|
|
37
43
|
## Use
|
|
@@ -54,9 +60,9 @@ hats({
|
|
|
54
60
|
|
|
55
61
|
Endpoints, under the API route:
|
|
56
62
|
|
|
57
|
-
- `GET /hats` lists the acting account, its hats and its linked accounts.
|
|
63
|
+
- `GET /hats` lists the acting account, its offered hats and its linked accounts. When the hat worn now is hidden, it also has `wearing: { id, label }`, so the switch can still say what the person is acting as.
|
|
58
64
|
- `POST /hats/switch { account?, hat, code? }` switches hat or account.
|
|
59
|
-
- `POST /hats/link { email }` asks to link another account.
|
|
65
|
+
- `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.
|
|
60
66
|
- `GET` and `POST /hats/confirm` handle the email confirmation.
|
|
61
67
|
- `POST /hats/unlink { account? }` takes an account out of the set.
|
|
62
68
|
|
|
@@ -80,6 +86,17 @@ Colors and sizes come from `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-
|
|
|
80
86
|
|
|
81
87
|
Every word is replaceable for translation: pass `text` (see `defaultText`) to `HatSwitcher`, `HatsSwitchedNote` and `LinkedAccounts`. Each visible or spoken string has a key with an English default: the switch (`title`, `close`, `trigger`, `switchHint`, `actingNow`, `current`, `needsCode`, `switching`, `backTo`, `accountThis`, `accountLinked`), the code screen (`confirmTitle`, `confirmBody`, `codeField`, `confirmButton`, `cancel`, `anotherWay`, `enterCode`), the note (`nowActing`, `switchBack`, `dismiss`) and the account page (`linkedHeading`, `linkedIntro`, `thisAccount`, `status`, `unlinkAsk`, `unlink`, `unlinkNamed`, `keep`, `setFull`, `emailLabel`, `send`, `youUnlinked`, `unlinked`). Keys that are functions take the hat, account or number they speak about. `accountThis` and `accountLinked` are the default group headings; `accountTitle` still overrides them. Server answers carry a stable `reason` (for example `wrongCode`), and `text.reasons` gives your words for each; anything you leave out shows the English.
|
|
82
88
|
|
|
89
|
+
### What hidden doesn't do
|
|
90
|
+
|
|
91
|
+
`hidden` only takes a hat out of the switch and refuses switches into it. It isn't a permission boundary, and it doesn't take any role away:
|
|
92
|
+
|
|
93
|
+
- A plain sign-in still wears the account's full set of roles, the last hat, even when that hat is hidden. The person can switch down from it, but can't switch back up until they sign in again.
|
|
94
|
+
- A session already wearing a hat keeps it when the site hides that hat later, with the same roles. The switch names it as the hat acting now, gives it no row and no Back to, and lets the person switch away. They can't switch back to it.
|
|
95
|
+
- A session whose worn hat is gone falls to the narrowest hat, as before, even when that one is hidden, because a wider fallback would add roles.
|
|
96
|
+
- The default `showSwitch` counts only offered hats, plus a hidden hat worn now. A site's own `showSwitch` gets every hat, with its `hidden` flag.
|
|
97
|
+
|
|
98
|
+
To keep someone out of a role, take it out of `hatsOf` or out of their roles. Without `hidden` set anywhere, the plugin behaves exactly as before.
|
|
99
|
+
|
|
83
100
|
## Switching from your own route
|
|
84
101
|
|
|
85
102
|
`switchSession(req, { account, hat, code })` does what `POST /api/hats/switch` does, so a site can switch someone from its own route or screen without the picker. Both call the same function, so they answer the same and set the same cookie.
|
|
@@ -109,6 +126,33 @@ export async function POST(request: Request) {
|
|
|
109
126
|
- 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.
|
|
110
127
|
- 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.
|
|
111
128
|
|
|
129
|
+
## Upgrading from 0.4.0
|
|
130
|
+
|
|
131
|
+
Sets already approved keep working, and requests still pending from 0.4.0 complete through their old links with the same confirmations and approval.
|
|
132
|
+
|
|
133
|
+
**On MongoDB there is no database step.** The plugin's 0.4.0 collections keep exactly the indexes 0.4.0 built, so a site with `ensureIndexes: true` starts on a 0.4.0 database as it is. Payload builds the new `hat-requests` collection's indexes when it starts. If you've turned Mongoose's `autoIndex` off, build those yourself before link requests are made, including the unique one on `holds`.
|
|
134
|
+
|
|
135
|
+
**On Postgres or SQLite**, run `payload migrate:create`, then `payload migrate`. The migration adds the `hat_requests` table, with its unique `holds` column, and makes `hat_link_members.user_id` and `hat_requests.requested_by_id` nullable so the database's foreign key can clear them while an account is deleted (the plugin removes those rows straight after and still requires both on every write). Schema push mode (`push: true`, the development default) can't move a 0.4.0 SQLite schema: it stops on the existing `hat_members_link_idx` index, so use a migration there too. In 0.4.0 on SQL databases linking didn't work (ids were written as strings) and deleting a linked account failed; both work now.
|
|
136
|
+
|
|
137
|
+
Everything else that changes for a host, in full:
|
|
138
|
+
|
|
139
|
+
1. Regenerate types with `payload generate:types` (new `hat-requests` collection, new export `REQUESTS`).
|
|
140
|
+
2. Review a custom `reasons.linkSent` text: it shouldn't name the address.
|
|
141
|
+
3. Link requests answer 202 after `linkAnswerMs` (new option, 2000 ms by default). A value outside 0 to 2147483647, or one that isn't a number, stops startup.
|
|
142
|
+
4. In an `onEvent` handler, use `by` for the asker on `link-requested`. It fires at ask time only when the asker is already in a set. Otherwise it fires as the other account confirms, just before `link-confirmed`, on that request: `req.user` there may be nobody, or the invited person, who may be a child.
|
|
143
|
+
5. A handler that throws on `link-requested`, `link-confirmed`, `unlinked` or `sessions-revoked` is logged by a short error name and skipped, and what it reported still happened. The plugin waits at most 2 seconds for each of those handlers.
|
|
144
|
+
6. Key `limit` by address as well as person.
|
|
145
|
+
7. Startup refuses a config that already has a `hat-requests` collection.
|
|
146
|
+
8. A `hatsInternal` or `hatsDissolving` key in `context` means nothing.
|
|
147
|
+
9. `confirmURL`, `sendEmail` and `onEvent` run without the plugin's mark, and so do your own hooks and other plugins' hooks, on any collection and field. Their writes are checked like any other server write, so they can't write `hat-requests`.
|
|
148
|
+
10. If your users collection has afterDelete hooks, the plugin's now runs first, and only for a delete that happened.
|
|
149
|
+
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
|
+
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
|
+
|
|
152
|
+
Limits to know about: with `autoIndex` off and no `holds` index, requests arriving together can each send an invitation. Don't call the link endpoint's handler inside a transaction your own code opened: a refused claim ends it. Anyone signed in can hold an account's one open invitation until it expires (`confirmHours`), which delays other invitations to that account. Without transactions, a database failure part way through an account's clean-up leaves the account deleted and some of its rows behind; sessions through it are still refused. In a bulk delete on MongoDB with transactions, one account's failed clean-up ends Payload's shared transaction: the error is reported, but that account itself is still deleted, with its member row, set, requests and session record left behind (sessions through it stay refused), and the other accounts in the call can be deleted too. Delete linked accounts one at a time.
|
|
153
|
+
|
|
154
|
+
The changelog lists every change.
|
|
155
|
+
|
|
112
156
|
## Commands
|
|
113
157
|
|
|
114
158
|
```bash
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
3
|
import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
|
|
4
4
|
import { defaultText, hatsApi } from './api.js';
|
|
5
|
-
import { actionFor, backHat, cleanCode, clip, currentHatOf, focusAfter, groupsOf, helpLine, radioId, saveNote, session } from './model.js';
|
|
5
|
+
import { actionFor, backHat, cleanCode, clip, currentHatOf, focusAfter, groupsOf, helpLine, radioId, saveNote, session, shownGroups } from './model.js';
|
|
6
6
|
import { css } from './styles.js';
|
|
7
7
|
import { HatsSwitchedNote } from './SwitchedNote.js';
|
|
8
8
|
const PHONE = '(max-width: 639.98px)';
|
|
@@ -21,7 +21,7 @@ export function SwitcherView(p) {
|
|
|
21
21
|
p.onSubmitCode?.();
|
|
22
22
|
}, children: [_jsx("p", { id: ids.codeHelp, children: t.confirmBody(hat.label, group.title) }), _jsx("label", { htmlFor: ids.code, children: t.codeField }), _jsx("input", { id: ids.code, className: "hats-sw-input", value: p.code, onChange: (e) => p.onCode?.(e.target.value), autoComplete: "one-time-code", inputMode: p.otherWay ? 'text' : 'numeric', autoCapitalize: "characters", spellCheck: false, "aria-invalid": p.codeError ? true : undefined, "aria-describedby": [ids.codeHelp, p.codeError ? ids.codeErr : null, p.otherWay && p.anotherWay ? ids.other : null].filter(Boolean).join(' ') }), _jsx("p", { id: ids.codeErr, className: "hats-sw-error", role: "alert", children: p.codeError }), p.anotherWay ? (p.otherWay ? (_jsx("p", { id: ids.other, className: "hats-sw-help hats-sw-more", children: p.anotherWay })) : (_jsx("p", { className: "hats-sw-more", children: _jsx("button", { type: "button", className: "hats-sw-link", onClick: p.onOtherWay, children: t.anotherWay }) }))) : null, _jsxs("div", { className: "hats-sw-actions", children: [_jsx("button", { type: "submit", className: "hats-sw-btn", "data-primary": "true", "aria-disabled": working || undefined, children: working ? t.switching : t.confirmButton(hat.label) }), _jsx("button", { type: "button", className: "hats-sw-btn", onClick: p.onCancelCode, children: t.cancel })] })] })] }));
|
|
23
23
|
}
|
|
24
|
-
return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "hats-sw-head", children: [_jsx("h2", { className: "hats-sw-title", id: ids.title, children: t.title }), _jsx("button", { type: "button", id: ids.close, className: "hats-sw-close", "aria-label": t.close, onClick: p.onClose, children: _jsx("span", { "aria-hidden": "true", children: "\u00D7" }) })] }), _jsxs("div", { className: "hats-sw-body", children: [current ? (_jsxs("div", { className: "hats-sw-now", children: [_jsx("p", { className: "hats-sw-now-label", children: t.actingNow }), _jsxs("p", { className: "hats-sw-now-hat", children: [_jsx("span", { children: current.label }), _jsx("span", { className: "hats-sw-tag", children: t.current })] }), _jsx("p", { className: "hats-sw-help", children: currentGroup.title }), help(current) ? _jsx("p", { className: "hats-sw-help", children: help(current) }) : null] })) : null, groups.map((g) => (_jsxs("fieldset", { className: "hats-sw-group", children: [_jsxs("legend", { children: [_jsx("span", { className: "hats-sw-acct", children: g.title }), _jsx("span", { className: "hats-sw-email", children: g.email })] }), _jsx("div", { className: "hats-sw-rows", "aria-busy": busy ? true : undefined, children: g.hats.map((h) => {
|
|
24
|
+
return (_jsxs(_Fragment, { children: [_jsxs("div", { className: "hats-sw-head", children: [_jsx("h2", { className: "hats-sw-title", id: ids.title, children: t.title }), _jsx("button", { type: "button", id: ids.close, className: "hats-sw-close", "aria-label": t.close, onClick: p.onClose, children: _jsx("span", { "aria-hidden": "true", children: "\u00D7" }) })] }), _jsxs("div", { className: "hats-sw-body", children: [current ? (_jsxs("div", { className: "hats-sw-now", children: [_jsx("p", { className: "hats-sw-now-label", children: t.actingNow }), _jsxs("p", { className: "hats-sw-now-hat", children: [_jsx("span", { children: current.label }), _jsx("span", { className: "hats-sw-tag", children: t.current })] }), _jsx("p", { className: "hats-sw-help", children: currentGroup.title }), help(current) ? _jsx("p", { className: "hats-sw-help", children: help(current) }) : null] })) : null, shownGroups(p.menu, groups).map((g) => (_jsxs("fieldset", { className: "hats-sw-group", children: [_jsxs("legend", { children: [_jsx("span", { className: "hats-sw-acct", children: g.title }), _jsx("span", { className: "hats-sw-email", children: g.email })] }), _jsx("div", { className: "hats-sw-rows", "aria-busy": busy ? true : undefined, children: g.hats.map((h) => {
|
|
25
25
|
const rid = radioId(base, g.account, h.id);
|
|
26
26
|
const isCurrent = actionFor(g, h, current) === 'none';
|
|
27
27
|
const line = help(h, g);
|
|
@@ -67,8 +67,9 @@ export function HatSwitcher({ apiRoute = '/api', onSwitched, text, anotherWay, n
|
|
|
67
67
|
const groups = signedIn ? groupsOf(signedIn, opts, t) : [];
|
|
68
68
|
const current = signedIn ? currentHatOf(signedIn) : undefined;
|
|
69
69
|
const back = signedIn ? backHat(signedIn) : null;
|
|
70
|
-
|
|
71
|
-
const
|
|
70
|
+
// The worn hat's row, when it has one (a hidden hat worn now has none), else the first row drawn.
|
|
71
|
+
const currentRadio = current && groups[0]?.hats.some((h) => h.id === current.id) ? radioId(base, undefined, current.id) : '';
|
|
72
|
+
const firstGroup = signedIn ? shownGroups(signedIn, groups)[0] : undefined;
|
|
72
73
|
const firstRow = firstGroup?.hats[0] ? radioId(base, firstGroup.account, firstGroup.hats[0].id) : '';
|
|
73
74
|
const close = useCallback((returnFocus = true) => {
|
|
74
75
|
setOpen(false);
|
package/dist/client/api.d.ts
CHANGED
|
@@ -15,6 +15,14 @@ export type HatsMenu = {
|
|
|
15
15
|
};
|
|
16
16
|
signedInAs: string;
|
|
17
17
|
hat: string | null;
|
|
18
|
+
/**
|
|
19
|
+
* The hat worn now when the site hides it, so the switch can still say what's worn. Absent otherwise. `hats`
|
|
20
|
+
* and `linked` list only hats that are offered.
|
|
21
|
+
*/
|
|
22
|
+
wearing?: {
|
|
23
|
+
id: string;
|
|
24
|
+
label: string;
|
|
25
|
+
};
|
|
18
26
|
hats: MenuHat[];
|
|
19
27
|
linked: {
|
|
20
28
|
id: string | number;
|
package/dist/client/model.d.ts
CHANGED
|
@@ -43,8 +43,18 @@ export type Group = {
|
|
|
43
43
|
export declare const isSensitive: (h: MenuHat) => boolean;
|
|
44
44
|
/** Default order: as given, with sensitive hats after the others. Stable, so the site's own order holds inside each part. */
|
|
45
45
|
export declare const defaultOrder: (hats: MenuHat[]) => MenuHat[];
|
|
46
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The hat worn now: the menu's hat, else the hidden hat the server named in `wearing`, else the account's full set
|
|
48
|
+
* (the last hat) for a plain sign-in. A hidden hat worn now is never one of the rows.
|
|
49
|
+
*/
|
|
47
50
|
export declare const currentHatOf: (menu: SignedInMenu) => MenuHat | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* The groups the panel draws: all of them, except the current account's when it has no rows because the hat worn
|
|
53
|
+
* there is hidden and nothing else on it is offered. An empty group would be a labeled group with nothing to choose.
|
|
54
|
+
*/
|
|
55
|
+
export declare const shownGroups: (menu: SignedInMenu, groups: Group[]) => Group[];
|
|
56
|
+
/** Whether the hat worn now is one of the current account's rows (it isn't when the site hides it). */
|
|
57
|
+
export declare const wornIsRow: (menu: SignedInMenu, current: MenuHat | undefined) => boolean;
|
|
48
58
|
/** The groups, current account first, then linked accounts in the order the server gives. */
|
|
49
59
|
export declare function groupsOf(menu: SignedInMenu, opts?: SwitcherOptions, words?: {
|
|
50
60
|
accountThis: string;
|
|
@@ -53,8 +63,9 @@ export declare function groupsOf(menu: SignedInMenu, opts?: SwitcherOptions, wor
|
|
|
53
63
|
/** What tapping a row does: nothing for the hat worn now, the code screen for one that asks, else switch at once. */
|
|
54
64
|
export declare function actionFor(group: Group, hat: MenuHat, current: MenuHat | undefined): 'none' | 'code' | 'switch';
|
|
55
65
|
/**
|
|
56
|
-
* The narrowest hat on the current account, offered as "Back to …" when the hat worn is above it. Null when
|
|
57
|
-
* there
|
|
66
|
+
* The narrowest offered hat on the current account, offered as "Back to …" when the hat worn is above it. Null when
|
|
67
|
+
* already there, when the narrowest would itself ask for a code, or when the hat worn is hidden: the menu doesn't say
|
|
68
|
+
* where a hidden hat sits, so "back" could be a step up, and the rows are there to switch away.
|
|
58
69
|
*/
|
|
59
70
|
export declare function backHat(menu: SignedInMenu): MenuHat | null;
|
|
60
71
|
/** Trigger words, at most `max` characters, cut with an ellipsis. */
|
package/dist/client/model.js
CHANGED
|
@@ -9,8 +9,18 @@ export function helpLine(help, hat, group) {
|
|
|
9
9
|
export const isSensitive = (h) => h.needsCode || h.sensitive === true;
|
|
10
10
|
/** Default order: as given, with sensitive hats after the others. Stable, so the site's own order holds inside each part. */
|
|
11
11
|
export const defaultOrder = (hats) => [...hats.filter((h) => !isSensitive(h)), ...hats.filter(isSensitive)];
|
|
12
|
-
/**
|
|
13
|
-
|
|
12
|
+
/**
|
|
13
|
+
* The hat worn now: the menu's hat, else the hidden hat the server named in `wearing`, else the account's full set
|
|
14
|
+
* (the last hat) for a plain sign-in. A hidden hat worn now is never one of the rows.
|
|
15
|
+
*/
|
|
16
|
+
export const currentHatOf = (menu) => menu.hats.find((h) => h.id === menu.hat) ?? (menu.wearing && menu.wearing.id === menu.hat ? { id: menu.wearing.id, label: menu.wearing.label, needsCode: false } : undefined) ?? menu.hats.at(-1);
|
|
17
|
+
/**
|
|
18
|
+
* The groups the panel draws: all of them, except the current account's when it has no rows because the hat worn
|
|
19
|
+
* there is hidden and nothing else on it is offered. An empty group would be a labeled group with nothing to choose.
|
|
20
|
+
*/
|
|
21
|
+
export const shownGroups = (menu, groups) => groups.filter((g) => g.hats.length > 0 || !(g.current && menu.wearing));
|
|
22
|
+
/** Whether the hat worn now is one of the current account's rows (it isn't when the site hides it). */
|
|
23
|
+
export const wornIsRow = (menu, current) => Boolean(current && menu.hats.some((h) => h.id === current.id));
|
|
14
24
|
/** The groups, current account first, then linked accounts in the order the server gives. */
|
|
15
25
|
export function groupsOf(menu, opts = {}, words = { accountThis: 'This account', accountLinked: 'Linked account' }) {
|
|
16
26
|
const order = opts.orderHats ?? defaultOrder;
|
|
@@ -33,13 +43,14 @@ export function actionFor(group, hat, current) {
|
|
|
33
43
|
return hat.needsCode ? 'code' : 'switch';
|
|
34
44
|
}
|
|
35
45
|
/**
|
|
36
|
-
* The narrowest hat on the current account, offered as "Back to …" when the hat worn is above it. Null when
|
|
37
|
-
* there
|
|
46
|
+
* The narrowest offered hat on the current account, offered as "Back to …" when the hat worn is above it. Null when
|
|
47
|
+
* already there, when the narrowest would itself ask for a code, or when the hat worn is hidden: the menu doesn't say
|
|
48
|
+
* where a hidden hat sits, so "back" could be a step up, and the rows are there to switch away.
|
|
38
49
|
*/
|
|
39
50
|
export function backHat(menu) {
|
|
40
51
|
const first = menu.hats[0];
|
|
41
52
|
const current = currentHatOf(menu);
|
|
42
|
-
if (!first || !current || first.id === current.id || first.needsCode)
|
|
53
|
+
if (!first || !current || first.id === current.id || first.needsCode || !wornIsRow(menu, current))
|
|
43
54
|
return null;
|
|
44
55
|
return first;
|
|
45
56
|
}
|
package/dist/collections.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { type CollectionConfig } from 'payload';
|
|
2
2
|
import { type ResolvedHatsOptions } from './types.js';
|
|
3
|
-
export declare function hatCollections(opts: ResolvedHatsOptions): CollectionConfig[];
|
|
3
|
+
export declare function hatCollections(opts: ResolvedHatsOptions, sql: boolean): CollectionConfig[];
|
package/dist/collections.js
CHANGED
|
@@ -1,9 +1,22 @@
|
|
|
1
|
-
import { APIError } from 'payload';
|
|
1
|
+
import { APIError, validations } from 'payload';
|
|
2
2
|
import { exactlyTrue } from './access.js';
|
|
3
3
|
import { dissolveIfAlone, revokeSessions } from './sessions.js';
|
|
4
|
-
import { hatsStateOf, idOf } from './state.js';
|
|
5
|
-
import { LINKS, MEMBERS, SESSIONS } from './types.js';
|
|
6
|
-
const internal =
|
|
4
|
+
import { hatsStateOf, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
|
|
5
|
+
import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
|
|
6
|
+
const internal = isInternal;
|
|
7
|
+
/**
|
|
8
|
+
* Required on every write, but nullable in the database. On SQL databases the account's foreign key sets these to
|
|
9
|
+
* null as the account is deleted; a NOT NULL column would refuse that, so the delete failed. The plugin removes those
|
|
10
|
+
* rows straight after, in the account's afterDelete.
|
|
11
|
+
*/
|
|
12
|
+
const requiredOnWrite = (value, options) => validations.relationship(value, { ...options, required: true });
|
|
13
|
+
/**
|
|
14
|
+
* An account relationship every row must have. On MongoDB it stays `required`, as in 0.4.0, so its indexes come out
|
|
15
|
+
* exactly as 0.4.0 built them (Payload makes a unique index sparse when the field isn't required, and a database that
|
|
16
|
+
* already has the 0.4.0 index then refuses to start with `ensureIndexes`). MongoDB has no foreign keys, so nothing
|
|
17
|
+
* there needs the column to take null. On SQL databases the column is nullable and the rule moves to validation.
|
|
18
|
+
*/
|
|
19
|
+
const requiredAccount = (sql) => (sql ? { validate: requiredOnWrite } : { required: true });
|
|
7
20
|
/**
|
|
8
21
|
* Whether the request's user may approve links. A person never approves their own link: an approver who is (or
|
|
9
22
|
* who signed in as) a member of the set is refused, so the owner's own links need another approver. Only an exact
|
|
@@ -16,7 +29,7 @@ async function approver(opts, req) {
|
|
|
16
29
|
const ask = opts.canApproveLinks;
|
|
17
30
|
return exactlyTrue(() => ask({ req, user }));
|
|
18
31
|
}
|
|
19
|
-
export function hatCollections(opts) {
|
|
32
|
+
export function hatCollections(opts, sql) {
|
|
20
33
|
const canApprove = ({ req }) => approver(opts, req);
|
|
21
34
|
const never = () => false;
|
|
22
35
|
const links = {
|
|
@@ -41,7 +54,7 @@ export function hatCollections(opts) {
|
|
|
41
54
|
access: { read: canApprove, create: never, update: canApprove, delete: canApprove },
|
|
42
55
|
fields: [
|
|
43
56
|
{ name: 'link', type: 'relationship', relationTo: LINKS, required: true, index: true, label: 'Linked set', admin: { readOnly: true, description: 'Filter the list by this set to see every account in it.' } },
|
|
44
|
-
{ name: 'user', type: 'relationship', relationTo: opts.users,
|
|
57
|
+
{ name: 'user', type: 'relationship', relationTo: opts.users, ...requiredAccount(sql), unique: true, admin: { readOnly: true } },
|
|
45
58
|
{
|
|
46
59
|
name: 'status',
|
|
47
60
|
type: 'select',
|
|
@@ -62,7 +75,7 @@ export function hatCollections(opts) {
|
|
|
62
75
|
],
|
|
63
76
|
hooks: {
|
|
64
77
|
beforeChange: [
|
|
65
|
-
async ({ data, originalDoc, operation, req }) => {
|
|
78
|
+
ownHook(async ({ data, originalDoc, operation, req }) => {
|
|
66
79
|
if (internal(req))
|
|
67
80
|
return data;
|
|
68
81
|
// Outside the plugin's own endpoints, the only change allowed is an approver approving a confirmed account.
|
|
@@ -88,25 +101,34 @@ export function hatCollections(opts) {
|
|
|
88
101
|
});
|
|
89
102
|
if (mine.totalDocs > 0)
|
|
90
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);
|
|
91
113
|
return { ...data, approvedBy: me.id, approvedAt: new Date().toISOString() };
|
|
92
|
-
},
|
|
114
|
+
}),
|
|
93
115
|
],
|
|
94
116
|
afterChange: [
|
|
95
|
-
async ({ doc, previousDoc, operation, req }) => {
|
|
117
|
+
ownHook(async ({ doc, previousDoc, operation, req }) => {
|
|
96
118
|
if (operation === 'update' && previousDoc?.status !== 'approved' && doc.status === 'approved' && !internal(req))
|
|
97
119
|
await opts.onEvent?.({ type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
|
|
98
|
-
},
|
|
120
|
+
}),
|
|
99
121
|
],
|
|
100
122
|
afterDelete: [
|
|
101
|
-
async ({ doc, req }) => {
|
|
123
|
+
ownHook(async ({ doc, req }) => {
|
|
102
124
|
const link = idOf(doc.link);
|
|
103
125
|
const account = idOf(doc.user);
|
|
104
126
|
await revokeSessions(req.payload, { and: [{ link: { equals: link } }, { or: [{ user: { equals: account } }, { via: { equals: account } }] }] }, 'unlinked', req);
|
|
105
127
|
if (!internal(req))
|
|
106
|
-
await
|
|
107
|
-
if (!req
|
|
128
|
+
await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: req.user ? String(req.user.id) : null });
|
|
129
|
+
if (!isDissolving(req))
|
|
108
130
|
await dissolveIfAlone(req.payload, link, req);
|
|
109
|
-
},
|
|
131
|
+
}),
|
|
110
132
|
],
|
|
111
133
|
},
|
|
112
134
|
};
|
|
@@ -127,5 +149,35 @@ export function hatCollections(opts) {
|
|
|
127
149
|
{ name: 'revokedAt', type: 'date', index: true },
|
|
128
150
|
],
|
|
129
151
|
};
|
|
130
|
-
|
|
152
|
+
// A link request waiting for the other account to confirm. Nobody reads or writes these but the plugin, so the
|
|
153
|
+
// person asking can't tell from them whether the address they gave has an account. One is written for every
|
|
154
|
+
// request, whatever the address; `account` is set only when an invitation was sent, and only one invitation to an
|
|
155
|
+
// account is open at a time, which the unique `holds` field enforces.
|
|
156
|
+
const requests = {
|
|
157
|
+
slug: REQUESTS,
|
|
158
|
+
admin: { hidden: true },
|
|
159
|
+
access: { read: never, create: never, update: never, delete: never },
|
|
160
|
+
fields: [
|
|
161
|
+
{ name: 'requestedBy', type: 'relationship', relationTo: opts.users, ...requiredAccount(sql), index: true },
|
|
162
|
+
{ name: 'account', type: 'relationship', relationTo: opts.users, index: true },
|
|
163
|
+
// Unique, so the database keeps it to one open invitation per account even when requests arrive together:
|
|
164
|
+
// `account:<id>` while an invitation is open, otherwise a random `none:` value that holds nothing.
|
|
165
|
+
{ name: 'holds', type: 'text', required: true, unique: true, index: true },
|
|
166
|
+
{ name: 'tokenHash', type: 'text', index: true },
|
|
167
|
+
{ name: 'expiresAt', type: 'date', required: true, index: true },
|
|
168
|
+
// The asker's set when they asked, so a confirmation can't put the account into a set the invitation came before.
|
|
169
|
+
{ name: 'link', type: 'text' },
|
|
170
|
+
],
|
|
171
|
+
hooks: {
|
|
172
|
+
beforeChange: [
|
|
173
|
+
ownHook(({ data, req }) => {
|
|
174
|
+
// Server code with overrideAccess included: a request written outside the plugin could be confirmed.
|
|
175
|
+
if (!internal(req))
|
|
176
|
+
throw new APIError('Only the hats plugin writes link requests.', 403, undefined, true);
|
|
177
|
+
return data;
|
|
178
|
+
}),
|
|
179
|
+
],
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
return [links, members, sessions, requests];
|
|
131
183
|
}
|
package/dist/endpoints.d.ts
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import { type Endpoint, type PayloadRequest } from 'payload';
|
|
2
2
|
import { revokeSessions } from './sessions.js';
|
|
3
|
+
import { type Hat, type HatsUser, type ResolvedHatsOptions } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Whether the switch is shown (and so allowed). The site's `showSwitch` gets every hat, hidden ones included, with
|
|
6
|
+
* their flags. The default counts only hats that are offered: more than one on this account, or on a linked account.
|
|
7
|
+
* The hat worn now counts too when it's hidden, so a session on a hidden hat with one offered hat to go to can still
|
|
8
|
+
* switch away. Without `hidden` anywhere this is the earlier rule exactly.
|
|
9
|
+
*/
|
|
10
|
+
export declare function showsSwitch(opts: ResolvedHatsOptions, args: {
|
|
11
|
+
user: HatsUser;
|
|
12
|
+
hats: Hat[];
|
|
13
|
+
linked: {
|
|
14
|
+
user: HatsUser;
|
|
15
|
+
hats: Hat[];
|
|
16
|
+
}[];
|
|
17
|
+
}, worn: string | null): boolean;
|
|
3
18
|
/** What a switch came to. A refusal carries the endpoint's `reason` (`needsCode` included) and its English message. */
|
|
4
19
|
export type SwitchResult = {
|
|
5
20
|
ok: true;
|