@extantape/payload-plugin-hats 0.6.1 → 0.6.2

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. All 836 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.
5
+ **Status:** early, 0.x. All 238 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
 
@@ -72,7 +72,7 @@ The switch goes in the admin header (turn it off with `adminSwitch: false`). The
72
72
 
73
73
  **The switch.** A pill, "Acting as Author" (24 characters at most, never the email), opens a panel titled Switch role: a popover 360 px wide under the trigger, or a bottom sheet below 640 px (85% of the screen at most, scrolling inside, with a scrim and room for the phone's safe area). It shows the hat worn now, then one group per account, the current account first. Each group is a fieldset with a button per hat: safe hats first, then hats that ask for a code, tagged with a lock and Needs a code. The hat worn now is marked Current and does nothing. A safe hat switches in one tap (the hat worn is marked with `aria-current`, so a screen reader says which one it is). A hat that asks for a code opens a code screen, Confirm it's you, with Switch and Cancel; Cancel puts focus back on that hat. Escape on the code screen goes back to the list too, and keeps what was typed. Spaces and dashes in a pasted code are dropped. When the hat worn is above the narrowest one, a Back to Member row stays at the bottom. Escape, the close button and the scrim close it and return focus to the trigger; focus stays inside while it's open.
74
74
 
75
- After a switch the page reloads (or your `onSwitched` runs) and a note says "Now acting as Curator. Switch back to Member." in a status region with a dismiss button. A note with a Switch back link stays until it's dismissed, and focus stays where it was. A note without one goes after 5 seconds (longer while hovered or focused), and focus moves to the new page's heading. It's kept in sessionStorage across the reload.
75
+ After a switch the page reloads (or your `onSwitched` runs) and a note says "Now acting as Curator. Switch back to Member." in a status region with a dismiss button. A note with a Switch back link stays until it's dismissed, and focus stays where it was. A note without one goes after 5 seconds (longer while hovered or focused), and focus moves to the new page's heading. It's kept in sessionStorage across the reload, for at most 60 seconds, with the id of the account that switched and of the hat it put on. The next page asks `GET /hats` who is signed in, only when a note is waiting, and shows the note only to that account wearing that hat. For anyone else, signed out, or when the site can't be reached, the note is removed unshown.
76
76
 
77
77
  Site options on `HatSwitcher`, all optional:
78
78
 
@@ -125,7 +125,7 @@ export function HatSwitcher({ apiRoute = '/api', onSwitched, text, anotherWay, n
125
125
  const res = await api.switchTo({ account: group.account, hat: hat.id, code: withCode });
126
126
  if (res.ok) {
127
127
  const first = group.first;
128
- finish({ hat: hat.label, back: first && first.id !== hat.id && !first.needsCode ? { id: first.id, label: first.label } : null });
128
+ finish({ user: group.id, hatId: hat.id, hat: hat.label, back: first && first.id !== hat.id && !first.needsCode ? { id: first.id, label: first.label } : null });
129
129
  return;
130
130
  }
131
131
  setBusy(null);
@@ -2,7 +2,7 @@
2
2
  import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
4
4
  import { defaultText, hatsApi } from './api.js';
5
- import { dropNote, saveNote, session, takeNote } from './model.js';
5
+ import { dropNote, noteWaiting, saveNote, session, takeNote } from './model.js';
6
6
  import { css } from './styles.js';
7
7
  /** The page heading; on a page without an h1, the main region or the first content heading (Payload's dashboard). */
8
8
  function findHeading() {
@@ -35,34 +35,49 @@ export function HatsSwitchedNote({ apiRoute = '/api', text, onSwitched, noteMs =
35
35
  const [held, setHeld] = useState(false);
36
36
  const banner = useRef(null);
37
37
  useEffect(() => {
38
- // Read without removing: it's removed only once shown, so a page that mounts twice (Strict Mode) or is replaced
39
- // before the note appears still shows it.
40
- const found = takeNote(session(), Date.now(), true);
41
- if (!found)
38
+ // Nothing stored, or a note already shown: no need to ask who is signed in.
39
+ if (!noteWaiting(session()))
42
40
  return;
43
- // Shown a moment after the empty status region exists, so screen readers announce it.
44
- const shown = setTimeout(() => {
45
- dropNote(session());
46
- setNote(found);
47
- }, 150);
48
- // The page heading; on a page without an h1, the main region or the first content heading (Payload's dashboard).
49
- // Tried a few times, since the admin draws its heading after hydrating.
41
+ let gone = false;
42
+ let shown;
50
43
  let tries = 0;
51
44
  let heading;
52
- const toHeading = () => {
53
- const h = findHeading();
54
- if (!h) {
55
- if (++tries < 6)
56
- heading = setTimeout(toHeading, 300);
45
+ // The note belongs to one account wearing one hat. The site says who is signed in now; a note for anyone else,
46
+ // or read while signed out or while the site can't be reached, is removed and never shown.
47
+ void hatsApi(apiRoute)
48
+ .menu()
49
+ .then((menu) => {
50
+ if (gone)
57
51
  return;
58
- }
59
- focusQuietly(h);
60
- };
61
- // A note with a way back keeps focus where it is: it stays until dismissed, and moving focus would cut off
62
- // the announcement and take a keyboard user away from the quickest undo.
63
- if (!found.back)
64
- heading = setTimeout(toHeading, 300);
65
- return () => (clearTimeout(shown), clearTimeout(heading));
52
+ const reader = menu && menu.signedIn === true ? { user: menu.account.id, hat: menu.hat } : null;
53
+ // Read without removing: it's removed only once shown, so a page that mounts twice (Strict Mode) or is replaced
54
+ // before the note appears still shows it.
55
+ const found = takeNote(session(), reader, Date.now(), true);
56
+ if (!found)
57
+ return;
58
+ // Shown a moment after the empty status region exists, so screen readers announce it.
59
+ shown = setTimeout(() => {
60
+ dropNote(session());
61
+ setNote(found);
62
+ }, 150);
63
+ // The page heading; on a page without an h1, the main region or the first content heading (Payload's dashboard).
64
+ // Tried a few times, since the admin draws its heading after hydrating.
65
+ const toHeading = () => {
66
+ const h = findHeading();
67
+ if (!h) {
68
+ if (++tries < 6)
69
+ heading = setTimeout(toHeading, 300);
70
+ return;
71
+ }
72
+ focusQuietly(h);
73
+ };
74
+ // A note with a way back keeps focus where it is: it stays until dismissed, and moving focus would cut off
75
+ // the announcement and take a keyboard user away from the quickest undo.
76
+ if (!found.back)
77
+ heading = setTimeout(toHeading, 300);
78
+ });
79
+ return () => ((gone = true), clearTimeout(shown), clearTimeout(heading));
80
+ // eslint-disable-next-line react-hooks/exhaustive-deps
66
81
  }, []);
67
82
  useEffect(() => {
68
83
  // A note with a way back stays until it's dismissed (WCAG 2.2.1). One without goes after `noteMs`.
@@ -103,7 +118,7 @@ export function HatsSwitchedNote({ apiRoute = '/api', text, onSwitched, noteMs =
103
118
  const res = await hatsApi(apiRoute, t).switchTo({ hat: note.back.id });
104
119
  if (!res.ok)
105
120
  return setNoteError(res.message || t.failed);
106
- saveNote(session(), { hat: note.back.label, back: null });
121
+ saveNote(session(), { user: note.user, hatId: note.back.id, hat: note.back.label, back: null });
107
122
  if (onSwitched)
108
123
  onSwitched();
109
124
  else
@@ -86,7 +86,10 @@ export declare function focusAfter(action: 'cancel-code' | 'close' | 'open-code'
86
86
  * "123-456" both become "123456"). Recovery codes (`otherWay`) keep their dashes. Not capped; the server decides.
87
87
  */
88
88
  export declare const cleanCode: (raw: string, otherWay?: boolean) => string;
89
- /** The note kept across the reload after a switch, read once by the next page. */
89
+ /**
90
+ * The note kept across the reload after a switch, read once by the next page. `user` is the account acted as after
91
+ * the switch and `hatId` the hat put on, so the next page shows the note only to that account wearing that hat.
92
+ */
90
93
  export type SwitchedNote = {
91
94
  hat: string;
92
95
  back: {
@@ -94,19 +97,38 @@ export type SwitchedNote = {
94
97
  label: string;
95
98
  } | null;
96
99
  at: number;
100
+ user: string;
101
+ hatId: string;
102
+ };
103
+ /** Who the page is signed in as when it reads the note: the account's id and the id of the hat worn. */
104
+ export type NoteReader = {
105
+ user: string | number;
106
+ hat: string | null;
97
107
  };
98
108
  export declare const NOTE_KEY = "hats:switched";
99
109
  /** A note older than this is stale (a switch that never reloaded, or a tab left for later) and is dropped. */
100
110
  export declare const NOTE_MAX_AGE_MS = 60000;
111
+ /** Written over a shown note that storage refuses to remove, so later pages know it was shown. */
112
+ export declare const NOTE_SHOWN = "shown";
101
113
  type Store = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
102
- export declare function saveNote(store: Store | undefined, note: Omit<SwitchedNote, 'at'>, now?: number): void;
114
+ export declare function saveNote(store: Store | undefined, note: Omit<SwitchedNote, 'at' | 'user'> & {
115
+ user: string | number;
116
+ }, now?: number): void;
117
+ /** Whether something that could be a note is stored and hasn't been shown. Lets a page ask who is signed in only when there is a note to show. */
118
+ export declare function noteWaiting(store: Store | undefined): boolean;
119
+ /**
120
+ * Reads the note for `reader`, the account signed in now and the hat it wears. By default it's removed, so it shows
121
+ * once; `keep` leaves it for whoever shows it to remove (a page that mounts twice, or is replaced before the note
122
+ * appears, must not lose it). A note is dropped when it is malformed or stale, when it was already shown, when it
123
+ * names no account or hat, when it belongs to another account or another hat, or when the reader isn't known.
124
+ */
125
+ export declare function takeNote(store: Store | undefined, reader: NoteReader | null | undefined, now?: number, keep?: boolean): SwitchedNote | null;
103
126
  /**
104
- * Reads the note. By default it's removed, so it shows once; `keep` leaves it for whoever shows it to remove
105
- * (a page that mounts twice, or is replaced before the note appears, must not lose it). Anything malformed or stale
106
- * is dropped.
127
+ * Removes the note once it has been shown, or because it is bad. When storage refuses (removal throws, or the note
128
+ * is still there after), the note is remembered for this page and the shown marker is written over it, so it doesn't
129
+ * show again. If that write is refused too, only this page remembers: a later page load inside the note's 60 seconds
130
+ * shows it again.
107
131
  */
108
- export declare function takeNote(store: Store | undefined, now?: number, keep?: boolean): SwitchedNote | null;
109
- /** Removes the note once it has been shown. */
110
132
  export declare function dropNote(store: Store | undefined): void;
111
133
  /** This tab's sessionStorage, or nothing where there is none (server render, storage blocked). */
112
134
  export declare const session: () => Store | undefined;
@@ -77,52 +77,87 @@ export const cleanCode = (raw, otherWay = false) => raw.replace(otherWay ? /\s+/
77
77
  export const NOTE_KEY = 'hats:switched';
78
78
  /** A note older than this is stale (a switch that never reloaded, or a tab left for later) and is dropped. */
79
79
  export const NOTE_MAX_AGE_MS = 60_000;
80
+ /** Written over a shown note that storage refuses to remove, so later pages know it was shown. */
81
+ export const NOTE_SHOWN = 'shown';
82
+ /** The shown note each storage refused to remove, for this page's lifetime. It holds when the marker can't be written either. */
83
+ const shownHere = new WeakMap();
84
+ const read = (store) => {
85
+ try {
86
+ return store?.getItem(NOTE_KEY) ?? null;
87
+ }
88
+ catch {
89
+ // Storage blocked: there is no note to read.
90
+ return null;
91
+ }
92
+ };
80
93
  export function saveNote(store, note, now = Date.now()) {
81
94
  try {
82
- store?.setItem(NOTE_KEY, JSON.stringify({ ...note, at: now }));
95
+ store?.setItem(NOTE_KEY, JSON.stringify({ ...note, user: String(note.user), at: now }));
83
96
  }
84
97
  catch {
85
98
  // Storage full or blocked: the switch still happened, there's just no note.
86
99
  }
87
100
  }
101
+ /** Whether something that could be a note is stored and hasn't been shown. Lets a page ask who is signed in only when there is a note to show. */
102
+ export function noteWaiting(store) {
103
+ const raw = read(store);
104
+ return Boolean(raw) && raw !== NOTE_SHOWN && !(store && shownHere.get(store) === raw);
105
+ }
88
106
  /**
89
- * Reads the note. By default it's removed, so it shows once; `keep` leaves it for whoever shows it to remove
90
- * (a page that mounts twice, or is replaced before the note appears, must not lose it). Anything malformed or stale
91
- * is dropped.
107
+ * Reads the note for `reader`, the account signed in now and the hat it wears. By default it's removed, so it shows
108
+ * once; `keep` leaves it for whoever shows it to remove (a page that mounts twice, or is replaced before the note
109
+ * appears, must not lose it). A note is dropped when it is malformed or stale, when it was already shown, when it
110
+ * names no account or hat, when it belongs to another account or another hat, or when the reader isn't known.
92
111
  */
93
- export function takeNote(store, now = Date.now(), keep = false) {
112
+ export function takeNote(store, reader, now = Date.now(), keep = false) {
113
+ const raw = read(store);
114
+ if (!raw)
115
+ return null;
116
+ let n = null;
94
117
  try {
95
- const raw = store?.getItem(NOTE_KEY);
96
- if (!raw)
97
- return null;
98
- const n = JSON.parse(raw);
99
- const bad = typeof n.hat !== 'string' || typeof n.at !== 'number' || now - n.at > NOTE_MAX_AGE_MS || n.at > now + 5_000;
100
- if (!keep || bad)
101
- store?.removeItem(NOTE_KEY);
102
- if (bad)
103
- return null;
104
- if (typeof n.hat !== 'string' || typeof n.at !== 'number')
105
- return null;
106
- const back = n.back && typeof n.back.id === 'string' && typeof n.back.label === 'string' ? { id: n.back.id, label: n.back.label } : null;
107
- return { hat: n.hat, back, at: n.at };
118
+ const parsed = JSON.parse(raw);
119
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
120
+ n = parsed;
108
121
  }
109
122
  catch {
110
- try {
111
- store?.removeItem(NOTE_KEY);
112
- }
113
- catch {
114
- // Nothing more to do.
115
- }
116
- return null;
123
+ // Not JSON (the shown marker included): dropped below.
117
124
  }
125
+ const fresh = n !== null && typeof n.hat === 'string' && typeof n.at === 'number' && Number.isFinite(n.at) && now - n.at <= NOTE_MAX_AGE_MS && n.at <= now + 5_000;
126
+ const theirs = n !== null && Boolean(reader) && typeof n.user === 'string' && n.user !== '' && n.user === String(reader.user) && typeof n.hatId === 'string' && n.hatId === reader.hat;
127
+ const ok = fresh && theirs && !(store && shownHere.get(store) === raw);
128
+ // A bad note is always removed. A good one is removed unless `keep`; if removing fails it is still returned, once.
129
+ if (!ok || !keep)
130
+ dropNote(store);
131
+ if (!ok || n === null)
132
+ return null;
133
+ const back = n.back && typeof n.back === 'object' && typeof n.back.id === 'string' && typeof n.back.label === 'string' ? { id: n.back.id, label: n.back.label } : null;
134
+ return { hat: n.hat, back, at: n.at, user: n.user, hatId: n.hatId };
118
135
  }
119
- /** Removes the note once it has been shown. */
136
+ /**
137
+ * Removes the note once it has been shown, or because it is bad. When storage refuses (removal throws, or the note
138
+ * is still there after), the note is remembered for this page and the shown marker is written over it, so it doesn't
139
+ * show again. If that write is refused too, only this page remembers: a later page load inside the note's 60 seconds
140
+ * shows it again.
141
+ */
120
142
  export function dropNote(store) {
143
+ if (!store)
144
+ return;
145
+ const raw = read(store);
146
+ try {
147
+ store.removeItem(NOTE_KEY);
148
+ if (read(store) === null)
149
+ return;
150
+ }
151
+ catch {
152
+ // Storage blocked: handled below.
153
+ }
154
+ if (raw && raw !== NOTE_SHOWN)
155
+ shownHere.set(store, raw);
121
156
  try {
122
- store?.removeItem(NOTE_KEY);
157
+ store.setItem(NOTE_KEY, NOTE_SHOWN);
123
158
  }
124
159
  catch {
125
- // Storage blocked: nothing was kept anyway.
160
+ // Storage refuses writes too: the page's own record is all there is.
126
161
  }
127
162
  }
128
163
  /** This tab's sessionStorage, or nothing where there is none (server render, storage blocked). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@extantape/payload-plugin-hats",
3
- "version": "0.6.1",
3
+ "version": "0.6.2",
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",