@extantape/payload-plugin-hats 0.1.5 → 0.2.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,13 +2,15 @@
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 22 tests against a real Payload 3.92 and MongoDB, with made-up roles and a fake second factor. The two React components were tried in a browser on a local copy of a real site (2026-11-09) with made-up accounts: keyboard, a real authenticator code, the approval form, and axe with 0 findings on the switch, the code prompt and the linking section in light and dark. It isn't in use on any site yet.
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 two React components were tried in a browser on a local copy of a real site (2026-11-09) with made-up accounts: keyboard, a real authenticator code, the approval form, and axe with 0 findings on the switch, the code prompt and the linking section in light and dark. It isn't in use on any site yet.
6
6
 
7
7
  ## What it does
8
8
 
9
9
  - **Linked accounts.** Up to 4 accounts per person. Linking needs both emails confirmed and an approver who isn't in the set. Unlinking is self-serve and immediate.
10
10
  - **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
- - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 3 hours per account.
11
+ - **Step-up.** Switching into a sensitive hat asks for that account's second factor, remembered for 3 hours per account (or per linked set, see below).
12
+ - **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
+ - **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.
12
14
  - **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.
13
15
  - **Link limits.** Pass `limit` to rate-limit link requests, per person and per email 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.
14
16
 
@@ -41,7 +43,9 @@ hats({
41
43
  hatsOf: (user) => [{ id: 'member', label: 'Member' }, { id: 'admin', label: 'Administrator', sensitive: true }],
42
44
  wear: (user, hat) => ({ ...user, roles: hat === 'admin' ? user.roles : ['member'] }),
43
45
  canApproveLinks: ({ user }) => user.roles.includes('admin'),
44
- stepUp: { available: (user) => hasAuthenticator(user), verify: ({ user, code }) => checkCode(user, code) },
46
+ stepUp: { available: (user) => hasAuthenticator(user), verify: ({ user, code }) => checkCode(user, code), rememberPer: 'set' }, // rememberPer is optional
47
+ // optional: ask only when the new hat holds something the current one doesn't
48
+ stepUpWhen: ({ from, to }) => holdsMoreThan(to.user, from.user),
45
49
  limit: ({ user, email }) => allowAttempt('hatsLink', `${user.id}:${email}`), // optional
46
50
  })
47
51
  ```
package/dist/endpoints.js CHANGED
@@ -2,6 +2,7 @@ import { addDataAndFileToRequest, APIError, getFieldsToSign, jwtSign } from 'pay
2
2
  import { addSessionToUser, generateCookie } from 'payload/shared';
3
3
  import { blockedBy, exactlyTrue } from './access.js';
4
4
  import { cleanupSessions, revokeSessions, revokeSid, sessionBySid, sharedLink, tombstone, wornHat } from './sessions.js';
5
+ import { memoryKey, needsStepUp, remembered } from './stepup.js';
5
6
  import { asPlugin, hashToken, hatsOptions, hatsStateOf, idOf, newToken } from './state.js';
6
7
  import { LINKS, MEMBERS, SESSIONS } from './types.js';
7
8
  const json = (body, status = 200, cookies = []) => {
@@ -55,10 +56,6 @@ async function linkedAccounts(req, userId) {
55
56
  return { link, linked };
56
57
  }
57
58
  const defaultShow = ({ hats, linked }) => hats.length > 1 || linked.some((l) => l.hats.length > 1);
58
- const remembered = (opts, steppedUp, account) => {
59
- const at = steppedUp?.[account];
60
- return Boolean(at && Date.now() - new Date(at).getTime() < (opts.stepUp?.rememberMinutes ?? 180) * 60_000);
61
- };
62
59
  async function blockedReason(req, opts) {
63
60
  if (!opts.blocked)
64
61
  return;
@@ -79,6 +76,9 @@ const me = {
79
76
  const worn = wornHat(hats, state.hat ? { hat: state.hat, via: state.via } : null) ?? hats.at(-1) ?? null;
80
77
  const s = await sessionBySid(req.payload, state.sid, req);
81
78
  const mine = await membershipOf(req, String(full.id));
79
+ const from = { user: req.user, hat: worn?.id ?? null };
80
+ const setId = mine?.status === 'approved' ? idOf(mine.link) : null;
81
+ const asks = async (target, targetHats, h, sameAccount) => !(sameAccount && h.id === worn?.id) && (await needsStepUp(opts, { req, from, target, hats: targetHats, hat: h })) && !remembered(opts, s?.steppedUp, String(target.id), setId);
82
82
  // The set as this account may see it: an account nobody has confirmed yet stays hidden, so a request never
83
83
  // reveals whether an email has an account here.
84
84
  const set = [];
@@ -96,12 +96,12 @@ const me = {
96
96
  account: { id: full.id, label: labelOf(full) },
97
97
  signedInAs: person,
98
98
  hat: worn?.id ?? null,
99
- hats: hats.map((h) => ({ ...h, needsCode: Boolean(h.sensitive && h.id !== worn?.id && !remembered(opts, s?.steppedUp, String(full.id))) })),
100
- linked: linked.map((l) => ({
99
+ hats: await Promise.all(hats.map(async (h) => ({ ...h, needsCode: await asks(full, hats, h, true) }))),
100
+ linked: await Promise.all(linked.map(async (l) => ({
101
101
  id: l.user.id,
102
102
  label: labelOf(l.user),
103
- hats: l.hats.map((h) => ({ ...h, needsCode: Boolean(h.sensitive && !remembered(opts, s?.steppedUp, String(l.user.id))) })),
104
- })),
103
+ hats: await Promise.all(l.hats.map(async (h) => ({ ...h, needsCode: await asks(l.user, l.hats, h, false) }))),
104
+ }))),
105
105
  link,
106
106
  set,
107
107
  canLink: Boolean(opts.canApproveLinks),
@@ -144,19 +144,22 @@ const switchHat = {
144
144
  const nowWearing = to === current ? (wornHat(hats, s) ?? hats.at(-1)).id : null;
145
145
  const steppedUp = { ...(s?.steppedUp ?? {}) };
146
146
  let gaveCode = false;
147
- if (hat.sensitive && hat.id !== nowWearing && !remembered(opts, steppedUp, to)) {
147
+ const setId = (await membershipOf(req, to).then((m) => (m?.status === 'approved' ? idOf(m.link) : null))) ?? null;
148
+ const from = { user: req.user, hat: wornHat(opts.hatsOf(full), s)?.id ?? opts.hatsOf(full).at(-1)?.id ?? null };
149
+ if (hat.id !== nowWearing && (await needsStepUp(opts, { req, from, target: target, hats, hat: hat })) && !remembered(opts, steppedUp, to, setId)) {
148
150
  if (!opts.stepUp)
149
151
  refuse('This site has no second factor for switching up.', 403, 'noSecondFactor');
150
152
  // Only an exact `true` passes either check; a truthy answer such as `{ valid: false }`, or a thrown error, is a no.
151
153
  const stepUp = opts.stepUp;
152
- if (!(await exactlyTrue(() => stepUp.available(target))))
154
+ const ctx = { signedIn: (person === current ? full : await loadUser(req, person)) ?? full, set: setId };
155
+ if (!(await exactlyTrue(() => stepUp.available(target, ctx))))
153
156
  refuse('Set up two-step sign-in on that account first.', 403, 'setUpTwoStep');
154
157
  const code = typeof body.code === 'string' ? body.code.trim() : '';
155
158
  if (!code)
156
159
  return json({ ok: false, needsCode: true, reason: 'needsCode', message: 'Enter a code from that account’s authenticator app.' }, 401);
157
- if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code }))))
160
+ if (!(await exactlyTrue(() => stepUp.verify({ req, user: target, code, ...ctx }))))
158
161
  refuse('That code didn’t work. Try a new one.', 403, 'wrongCode');
159
- steppedUp[to] = new Date().toISOString();
162
+ steppedUp[memoryKey(opts, to, setId)] = new Date().toISOString();
160
163
  gaveCode = true;
161
164
  }
162
165
  const users = req.payload.collections[opts.users].config;
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { type HatsOptions } from './types.js';
3
3
  export { hatsStateOf } from './state.js';
4
4
  export { applyHat, cleanupSessions, revokeSessions } from './sessions.js';
5
5
  export { LINKS, MEMBERS, SESSIONS } from './types.js';
6
- export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser } from './types.js';
6
+ export type { Hat, HatsEvent, HatsOptions, HatsState, HatsUser, StepUpContext } from './types.js';
7
7
  /**
8
8
  * Hats for Payload. One person can link up to `maxLinked` accounts and switch between them, and an account that
9
9
  * holds several roles acts in one at a time (a "hat"). Switching into a sensitive hat asks for the site's second
@@ -0,0 +1,21 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { Hat, HatsUser, ResolvedHatsOptions } from './types.js';
3
+ /** The key a good code is remembered under: the linked set with `rememberPer: 'set'` (when the account is in one), else the account. */
4
+ export declare const memoryKey: (opts: ResolvedHatsOptions, account: string, set: string | null) => string;
5
+ /** Whether a good code was given recently enough to count. */
6
+ export declare const remembered: (opts: ResolvedHatsOptions, steppedUp: Record<string, string> | null | undefined, account: string, set: string | null) => boolean;
7
+ /**
8
+ * Does moving to `hat` on `target` need a code (before any memory is taken into account)? Without `stepUpWhen` that is
9
+ * the hat's `sensitive` flag. With it, the site's answer decides, and only an exact `false` skips the code: `true`, a
10
+ * throw, a rejection or any other answer (`'no'`, `0`, `undefined`) asks.
11
+ */
12
+ export declare function needsStepUp(opts: ResolvedHatsOptions, args: {
13
+ req: PayloadRequest;
14
+ from: {
15
+ user: HatsUser;
16
+ hat: string | null;
17
+ };
18
+ target: HatsUser;
19
+ hats: Hat[];
20
+ hat: Hat;
21
+ }): Promise<boolean>;
package/dist/stepup.js ADDED
@@ -0,0 +1,26 @@
1
+ /** The key a good code is remembered under: the linked set with `rememberPer: 'set'` (when the account is in one), else the account. */
2
+ export const memoryKey = (opts, account, set) => (opts.stepUp?.rememberPer === 'set' && set ? `set:${set}` : account);
3
+ /** Whether a good code was given recently enough to count. */
4
+ export const remembered = (opts, steppedUp, account, set) => {
5
+ const at = steppedUp?.[memoryKey(opts, account, set)];
6
+ return Boolean(at && Date.now() - new Date(at).getTime() < (opts.stepUp?.rememberMinutes ?? 180) * 60_000);
7
+ };
8
+ /**
9
+ * Does moving to `hat` on `target` need a code (before any memory is taken into account)? Without `stepUpWhen` that is
10
+ * the hat's `sensitive` flag. With it, the site's answer decides, and only an exact `false` skips the code: `true`, a
11
+ * throw, a rejection or any other answer (`'no'`, `0`, `undefined`) asks.
12
+ */
13
+ export async function needsStepUp(opts, args) {
14
+ const when = opts.stepUpWhen;
15
+ if (!when)
16
+ return Boolean(args.hat.sensitive);
17
+ try {
18
+ // The target as it would be worn: the account's last hat is all of its roles, so nothing is narrowed.
19
+ const user = args.hat.id === args.hats.at(-1)?.id ? args.target : opts.wear(args.target, args.hat.id);
20
+ const answer = await when({ req: args.req, from: args.from, to: { user, hat: args.hat.id } });
21
+ return answer !== false;
22
+ }
23
+ catch {
24
+ return true;
25
+ }
26
+ }
package/dist/types.d.ts CHANGED
@@ -5,6 +5,13 @@ export type Hat = {
5
5
  label: string;
6
6
  sensitive?: boolean;
7
7
  };
8
+ /** Who is asking, passed to the site's two-step checks along with the target account. */
9
+ export type StepUpContext = {
10
+ /** The account that actually signed in: the person (`via` when this session was switched in, else the account). */
11
+ signedIn: HatsUser;
12
+ /** The linked set's id, or null when the target account is in none. */
13
+ set: string | null;
14
+ };
8
15
  /** A user record as the plugin sees it. */
9
16
  export type HatsUser = TypedUser & {
10
17
  id: string | number;
@@ -44,16 +51,38 @@ export type HatsOptions = {
44
51
  /** The site's second factor, asked before switching into a sensitive hat. */
45
52
  stepUp?: {
46
53
  /** Whether the account has a second factor set up at all. May look it up (async), since it's often a hidden field. */
47
- available: (user: HatsUser) => boolean | Promise<boolean>;
54
+ available: (user: HatsUser, ctx: StepUpContext) => boolean | Promise<boolean>;
48
55
  /** Check a code for `user`. Resolve true only for a good code. */
49
56
  verify: (args: {
50
57
  req: PayloadRequest;
51
58
  user: HatsUser;
52
59
  code: string;
53
- }) => boolean | Promise<boolean>;
54
- /** How long a good code is remembered, per account, in minutes. Default 180 (three hours). */
60
+ } & StepUpContext) => boolean | Promise<boolean>;
61
+ /** How long a good code is remembered, in minutes. Default 180 (three hours). */
55
62
  rememberMinutes?: number;
63
+ /**
64
+ * What a good code is remembered for. `'account'` (default): the account it was given for. `'set'`: every account
65
+ * in the same linked set, so one two-step per person; an account in no set is still remembered on its own.
66
+ */
67
+ rememberPer?: 'account' | 'set';
56
68
  };
69
+ /**
70
+ * Decides whether a switch needs a code, in place of the hat's `sensitive` flag. Called with the account and hat
71
+ * worn now (`from`, as narrowed) and the account and hat it would become (`to`, as it would be worn). Answer `true`
72
+ * to ask for a code (unless one is remembered). Only an exact `false` skips the code: a throw or any other answer
73
+ * asks. Default: the target hat's `sensitive` flag.
74
+ */
75
+ stepUpWhen?: (args: {
76
+ req: PayloadRequest;
77
+ from: {
78
+ user: HatsUser;
79
+ hat: string | null;
80
+ };
81
+ to: {
82
+ user: HatsUser;
83
+ hat: string;
84
+ };
85
+ }) => boolean | Promise<boolean>;
57
86
  /**
58
87
  * Who sees the switch. Default: anyone whose own account, or another account in their linked set, has more than
59
88
  * one hat. Switching is refused where the switch isn't shown.
@@ -140,7 +169,7 @@ export type HatsEvent = {
140
169
  sessions: number;
141
170
  reason: string;
142
171
  };
143
- export type ResolvedHatsOptions = Required<Omit<HatsOptions, 'stepUp' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>> & Pick<HatsOptions, 'stepUp' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>;
172
+ export type ResolvedHatsOptions = Required<Omit<HatsOptions, 'stepUp' | 'stepUpWhen' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>> & Pick<HatsOptions, 'stepUp' | 'stepUpWhen' | 'canApproveLinks' | 'blocked' | 'limit' | 'onEvent' | 'confirmURL'>;
144
173
  export declare const LINKS = "hat-links";
145
174
  export declare const MEMBERS = "hat-members";
146
175
  export declare const SESSIONS = "hat-sessions";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.1.5",
3
+ "version": "0.2.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",