@extantape/payload-plugin-hats 0.5.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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Linked accounts and role hats for Payload. One person links their accounts and switches between them, and an account with several roles acts in one at a time. Switching up into a sensitive role asks for a second factor.
4
4
 
5
- **Status:** early, 0.x. The server side passes 30 tests against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The redesigned switch (unreleased) has unit tests for its order, gating, button markup, code screen and focus targets, and was run in a browser at 390 and 1280 px wide on a local copy of a site with made-up accounts: keyboard open, Escape, the focus trap, Cancel back to the hat, a one-tap switch and the note after it (that browser run was before the button and note changes below, and wasn't repeated). A real authenticator code wasn't tried with the new switch; the server refused the made-up code, as it should. It isn't in use on any site yet.
5
+ **Status:** early, 0.x. All 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
 
@@ -12,6 +12,7 @@ Linked accounts and role hats for Payload. One person links their accounts and s
12
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).
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
+ - **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.
15
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).
16
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.
17
18
 
@@ -21,6 +22,8 @@ Needs Payload sessions (`auth.useSessions`, on by default).
21
22
 
22
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`.
23
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
+
24
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`.
25
28
 
26
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.
@@ -33,6 +36,8 @@ Needs Payload sessions (`auth.useSessions`, on by default).
33
36
 
34
37
  None of these are imported. The site connects them in its own config.
35
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
+
36
41
  **Family:** It's part of the **Identity** family (a working draft): plugins designed to sit together for accounts and access.
37
42
 
38
43
  ## Use
@@ -55,7 +60,7 @@ hats({
55
60
 
56
61
  Endpoints, under the API route:
57
62
 
58
- - `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.
59
64
  - `POST /hats/switch { account?, hat, code? }` switches hat or account.
60
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.
61
66
  - `GET` and `POST /hats/confirm` handle the email confirmation.
@@ -81,6 +86,17 @@ Colors and sizes come from `--hats-ink`, `--hats-paper`, `--hats-line`, `--hats-
81
86
 
82
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.
83
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
+
84
100
  ## Switching from your own route
85
101
 
86
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.
@@ -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
- const currentRadio = current ? radioId(base, undefined, current.id) : '';
71
- const firstGroup = groups[0];
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);
@@ -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;
@@ -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
- /** The hat worn now: the menu's hat, or the account's full set (the last hat) for a plain sign-in. */
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 already
57
- * there or when the narrowest would itself ask for a code.
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. */
@@ -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
- /** The hat worn now: the menu's hat, or the account's full set (the last hat) for a plain sign-in. */
13
- export const currentHatOf = (menu) => menu.hats.find((h) => h.id === menu.hat) ?? menu.hats.at(-1);
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 already
37
- * there or when the narrowest would itself ask for a code.
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
  }
@@ -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;
package/dist/endpoints.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'payload';
2
2
  import { addSessionToUser, generateCookie } from 'payload/shared';
3
3
  import { blockedBy, exactlyTrue } from './access.js';
4
- import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
4
+ import { cleanupSessions, isOffered, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
5
5
  import { memoryKey, needsStepUp, remembered } from './stepup.js';
6
6
  import { asPlugin, DISSOLVING, hashToken, hatsOptions, hatsStateOf, idOf, newToken, relId, removeWhere, tell, trackWork, unmarked, withMark } from './state.js';
7
7
  import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
@@ -57,7 +57,18 @@ async function linkedAccounts(req, userId) {
57
57
  }
58
58
  return { link, linked };
59
59
  }
60
- const defaultShow = ({ hats, linked }) => hats.length > 1 || linked.some((l) => l.hats.length > 1);
60
+ /**
61
+ * Whether the switch is shown (and so allowed). The site's `showSwitch` gets every hat, hidden ones included, with
62
+ * their flags. The default counts only hats that are offered: more than one on this account, or on a linked account.
63
+ * 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
64
+ * switch away. Without `hidden` anywhere this is the earlier rule exactly.
65
+ */
66
+ export function showsSwitch(opts, args, worn) {
67
+ if (opts.showSwitch)
68
+ return opts.showSwitch(args);
69
+ const own = args.hats.filter(isOffered).length + (args.hats.some((h) => h.id === worn && !isOffered(h)) ? 1 : 0);
70
+ return own > 1 || args.linked.some((l) => l.hats.filter(isOffered).length > 1);
71
+ }
61
72
  async function blockedReason(req, opts) {
62
73
  if (!opts.blocked)
63
74
  return;
@@ -98,16 +109,21 @@ const me = {
98
109
  account: { id: full.id, label: labelOf(full) },
99
110
  signedInAs: person,
100
111
  hat: worn?.id ?? null,
101
- hats: await Promise.all(hats.map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
102
- linked: await Promise.all(linked.map(async (l) => ({
112
+ // Only offered hats are sent. A hidden hat worn now is named in `wearing`, so the switch can say what's worn,
113
+ // and is never a row. A linked account whose hats are all hidden isn't listed.
114
+ ...(worn && !isOffered(worn) ? { wearing: { id: worn.id, label: worn.label } } : {}),
115
+ hats: await Promise.all(hats.filter(isOffered).map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
116
+ linked: await Promise.all(linked
117
+ .filter((l) => !l.hats.length || l.hats.some(isOffered))
118
+ .map(async (l) => ({
103
119
  id: l.user.id,
104
120
  label: labelOf(l.user),
105
- hats: await Promise.all(l.hats.map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
121
+ hats: await Promise.all(l.hats.filter(isOffered).map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
106
122
  }))),
107
123
  link,
108
124
  set,
109
125
  canLink: Boolean(opts.canApproveLinks),
110
- showSwitch: (opts.showSwitch ?? defaultShow)({ user: full, hats, linked }),
126
+ showSwitch: showsSwitch(opts, { user: full, hats, linked }, worn?.id ?? null),
111
127
  maxLinked: opts.maxLinked,
112
128
  });
113
129
  },
@@ -204,18 +220,24 @@ async function switchCore(req, body) {
204
220
  if (to !== current && usersAuth.verify && target._verified === false)
205
221
  refuse('That account’s email isn’t confirmed yet.', 403, 'unverified');
206
222
  const { linked } = await linkedAccounts(req, current);
207
- if (!(opts.showSwitch ?? defaultShow)({ user: full, hats: opts.hatsOf(full), linked }))
223
+ const s = await sessionBySid(req.payload, state.sid, req);
224
+ const ownHats = opts.hatsOf(full);
225
+ const fromHat = wornHat(ownHats, s)?.id ?? ownHats.at(-1)?.id ?? null;
226
+ if (!showsSwitch(opts, { user: full, hats: ownHats, linked }, fromHat))
208
227
  refuse('Switching isn’t available for this account.', 403, 'notAvailable');
209
228
  const hats = opts.hatsOf(target);
210
- const hat = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
229
+ const picked = typeof body.hat === 'string' ? hats.find((h) => h.id === body.hat) : to === current ? undefined : hats[0];
230
+ // A hidden hat is refused the same way as one the account doesn't hold, whether it was named or would be the
231
+ // default. With no hat named, a linked switch goes to the account's narrowest hat only when that hat is offered: it
232
+ // never moves up to a wider one, so the caller names a hat instead.
233
+ const hat = picked && isOffered(picked) ? picked : undefined;
211
234
  if (!hat)
212
235
  refuse('Choose one of that account’s hats.', 400, 'chooseHat');
213
- const s = await sessionBySid(req.payload, state.sid, req);
214
236
  const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
215
237
  const steppedUp = { ...(s?.steppedUp ?? {}) };
216
238
  let gaveCode = false;
217
239
  const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
218
- const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
240
+ const from = { user: req.user, hat: fromHat };
219
241
  if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
220
242
  if (!opts.stepUp)
221
243
  refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
@@ -26,7 +26,17 @@ export declare function revokeSessions(payload: Payload, where: Where, reason: s
26
26
  export declare function dissolveIfAlone(payload: Payload, link: string, req: PayloadRequest): Promise<void>;
27
27
  /** The approved set two accounts are both in, or null. Read fresh every time. */
28
28
  export declare function sharedLink(payload: Payload, a: string, b: string, req?: PayloadRequest): Promise<string | null>;
29
- /** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
29
+ /**
30
+ * Whether a hat is offered to switch into. Only a missing `hidden` (undefined) or exactly `false` offers it: `true`,
31
+ * `null`, `'false'`, `1` or anything else hides it. Hiding only ever refuses switches and shows less, so an unclear
32
+ * value is read the narrow way.
33
+ */
34
+ export declare const isOffered: (h: Hat) => boolean;
35
+ /**
36
+ * The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest.
37
+ * `hidden` plays no part here: a session keeps a hidden hat it wears, and the fallback is the narrowest hat even when
38
+ * that one is hidden, because a wider fallback would give the session roles it didn't have.
39
+ */
30
40
  export declare function wornHat(hats: Hat[], s: Pick<SessionDoc, 'hat' | 'via'> | null): Hat | null;
31
41
  /**
32
42
  * The user as the rest of the site sees them: narrowed to the hat this session wears. A switched session whose set
package/dist/sessions.js CHANGED
@@ -68,7 +68,17 @@ export async function sharedLink(payload, a, b, req) {
68
68
  return x ? idOf(x.link) : null;
69
69
  return x && y && idOf(x.user) !== idOf(y.user) && idOf(x.link) === idOf(y.link) ? idOf(x.link) : null;
70
70
  }
71
- /** The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest. */
71
+ /**
72
+ * Whether a hat is offered to switch into. Only a missing `hidden` (undefined) or exactly `false` offers it: `true`,
73
+ * `null`, `'false'`, `1` or anything else hides it. Hiding only ever refuses switches and shows less, so an unclear
74
+ * value is read the narrow way.
75
+ */
76
+ export const isOffered = (h) => h.hidden === undefined || h.hidden === false;
77
+ /**
78
+ * The hat a session wears, from the account's current hats. A worn hat the account no longer has falls to the narrowest.
79
+ * `hidden` plays no part here: a session keeps a hidden hat it wears, and the fallback is the narrowest hat even when
80
+ * that one is hidden, because a wider fallback would give the session roles it didn't have.
81
+ */
72
82
  export function wornHat(hats, s) {
73
83
  if (!hats.length)
74
84
  return null;
package/dist/types.d.ts CHANGED
@@ -1,9 +1,17 @@
1
1
  import type { Payload, PayloadRequest, TypedUser } from 'payload';
2
- /** One role an account can act in. `sensitive` hats need the second factor before switching into them. */
2
+ /**
3
+ * One role an account can act in. `sensitive` hats need the second factor before switching into them.
4
+ *
5
+ * `hidden` hats aren't offered: they're left out of the switch and its Back to button, aren't picked for a switch that
6
+ * names no hat, and a switch into one is refused like a hat the account doesn't hold. A session already wearing one
7
+ * keeps it, and a plain sign-in still wears every role. Only a missing `hidden` or exactly `false` offers the hat; any
8
+ * other value hides it.
9
+ */
3
10
  export type Hat = {
4
11
  id: string;
5
12
  label: string;
6
13
  sensitive?: boolean;
14
+ hidden?: boolean;
7
15
  };
8
16
  /** Who is asking, passed to the site's two-step checks along with the target account. */
9
17
  export type StepUpContext = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Linked accounts and role hats for Payload: one person switches between their approved accounts, and acts in one role at a time, with a second factor before switching up.",
5
5
  "keywords": [
6
6
  "payload",