@extantape/payload-plugin-hats 0.6.1 → 0.7.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. 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 356 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
 
@@ -14,6 +14,7 @@ Linked accounts and role hats for Payload. One person links their accounts and s
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
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
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
+ - **Linking from server code.** `linkAccounts` and `approveLink` link and approve from your own code, with no emails and the same approval rule as the admin form. `checkLinks` lists sets written by hand that break the rules. See **Linking from your own server code** below.
17
18
  - **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.
18
19
 
19
20
  Needs Payload sessions (`auth.useSessions`, on by default).
@@ -72,7 +73,7 @@ The switch goes in the admin header (turn it off with `adminSwitch: false`). The
72
73
 
73
74
  **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
75
 
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.
76
+ 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
77
 
77
78
  Site options on `HatSwitcher`, all optional:
78
79
 
@@ -126,6 +127,50 @@ export async function POST(request: Request) {
126
127
  - 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.
127
128
  - 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.
128
129
 
130
+ ## Linking from your own server code
131
+
132
+ `linkAccounts(req, { account, with, approve? })` puts two accounts in one linked set from your own code, for example after your site has checked who the person is in its own way. `approveLink(req, { account })` approves a confirmed account. Both skip the emails: your site has already done the checking, and it tells the people involved itself. The plugin sends no email and runs no age check here. Your site decides who may be linked.
133
+
134
+ ```ts
135
+ import { approveLink, linkAccounts } from '@extantape/payload-plugin-hats'
136
+
137
+ // Inside your own route or hook, with the request Payload gave you (its transaction is joined).
138
+ const result = await linkAccounts(req, { account: childId, with: parentId })
139
+ if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status })
140
+ // Later, an approver who isn't in the set, signed in on `req`:
141
+ const approved = await approveLink(req, { account: childId })
142
+ ```
143
+
144
+ - `account` joins the set `with` is in, or the two start a new set. Both rows come out confirmed, with no token, `addedBy` set to the signed-in account (or empty when nobody is signed in) and `confirmedAt` set. Pass `approve: true` to approve them in the same call. That needs `req.user` to be an approver outside the set, as below, and the approver check then comes first, before anything about the accounts.
145
+ - `approveLink` acts for `req.user`, the approver signed in on the request, and takes no approver id. It runs the same rule as the admin form: `canApproveLinks` must answer exactly `true`, and an approver who is in the set, joining it, or signed in through an account in it is refused. That check comes before anything about the row, so someone who can't approve learns nothing about it.
146
+ - Both return `{ ok: true, link, rows, already }` or `{ ok: false, status, reason, message }`, and don't throw for a refusal. `rows` lists the named accounts' rows as `{ account, status }` after the call. A repeat of a call that already happened answers `already: true` and writes nothing. Asking `linkAccounts` to approve a confirmed pair approves it.
147
+ - Ids must be written exactly as your users collection writes them. Any other key in the input is ignored.
148
+ - They join `req`'s transaction, so an error in your code after the call rolls the rows back with everything else. Without a transaction, the rows are written in order and removed again if a later write fails, as the email confirmation does. Invitations still open for either account are released, and that undo puts them back as they were. The undo removes the call's rows first and puts invitations back after, so a `failed` answer never leaves a link standing. If an invitation can't be put back, the answer is `failed` with a message saying nothing is linked but an open invitation to one of the accounts was canceled. That invitation stays canceled, and the person who sent it has to send it again; the warning in the log gives only how many. If removing the call's own rows fails too, the message says the accounts may still be linked: look at their member rows before trying again, because a retry would then answer that they're linked already.
149
+ - **A database error inside your transaction ends it.** Payload aborts the whole transaction on such an error and clears `req.transactionID`, so your own earlier writes in it are rolled back too. The answer is then `failed`, with a message saying the transaction ended. Treat the transaction as gone and start again.
150
+ - If `req.transactionID` names a transaction that has already ended, nothing is written and the answer is `failed`. A promise there (Payload puts one while it starts a transaction) is waited for and replaced by the id it gives, as Payload does itself. One that rejected never started a transaction, so it gets the same ended-transaction answer, with nothing written. The plugin checks this in the adapter's list of open transactions (`payload.db.sessions`), before writing and again after. Payload's MongoDB adapter keeps that list, and this is tested there. Its SQL adapters keep a list under the same name, which isn't tested here, and an adapter without one isn't checked.
151
+ - If the set dissolves while an account joins it (another member left a set of two), nobody is left alone in a set that isn't there. Joining writes the set's own record, and dissolving deletes it. With transactions, MongoDB refuses whichever of the two writes it second: either the join answers `failed` and its row is undone, or the unlink, row delete or account deletion that would have dissolved the set fails with the error `Hats: a linked set was being changed at the same moment, so this couldn't finish. Try again.`, changes nothing and sends no events, and the join stands. Trying the unlink or deletion again works. Two calls joining the same set at the same moment can also collide this way, and one answers `failed`; try it again. Inside your own transaction the join holds the set's record until you commit, so an unlink from that set fails meanwhile. Without transactions, a dissolve also removes any row written for the set after it read it, so a join that answers `ok` at that moment may be gone a moment later, along with the rest of the set, and the events for it have already fired. This is tested on MongoDB with and without transactions, with the dissolve held at three points while the join runs, and with a row delete and an account deletion losing to a join; SQL isn't tested.
152
+ - **When the `unlinked` and `sessions-revoked` events from a leaving or an account deletion go out.** With a transaction, they wait until it commits, and they're dropped when it's rolled back or its commit fails. That covers a bulk delete too: when one of its documents loses to a join, the whole delete is undone and none of them reports anything. It covers a site's own afterDelete hook that throws after the plugin's, which undoes the delete and sends nothing. Without a transaction, they go out when the plugin's clean-up ends, and also when it fails part way, because what it changed by then stays changed. A site hook that throws after the plugin's can't undo that clean-up either, so its events stand. A plain database error in one account's clean-up during a bulk delete is different: Payload doesn't end the shared transaction for it, and commits the other accounts along with what that account's clean-up changed before the error. The delete answers with an error, and the events for everything that was committed go out, that account's included. Tested on MongoDB with and without transactions (bulk deletes of member rows and of accounts with one losing to a join, a bulk account delete with one clean-up failing at the database, a throwing site hook, a dissolve that fails); SQL isn't tested. A host transaction that's never committed or rolled back keeps its waiting events in memory. When a commit has events waiting, it sends them before it returns, one after another, waiting up to 2 seconds for each handler, so a hanging handler delays the delete's answer by up to 2 seconds per event.
153
+ - **After a transaction ends under the plugin's clean-up.** In a bulk delete Payload runs the documents side by side in one transaction. The transaction ends for all of them when one document loses to a join (MongoDB aborts it), and with `bulkOperationsSingleTransaction: true` on the adapter, when any document fails. From then on every call the clean-up of any other document makes through the adapter's `count`, `create`, `deleteMany`, `deleteOne`, `find`, `findOne`, `updateMany`, `updateOne` and `upsert`, reads included, is refused with `Hats: the transaction this change ran in ended (another change in it failed), so the plugin's clean-up stopped there. Try again.` The check runs when the adapter looks up the call's transaction, so a call already under way when the transaction ends is refused too, and none of the plugin's own clean-up is written outside the transaction. Other adapter methods aren't tied to the transaction this way: a hook of yours that runs inside the clean-up and calls `createVersion`, `updateGlobal` or another version, global or job method isn't refused. This needs the adapter's list of open transactions (`payload.db.sessions`), as above. In the default mode a plain database error in one document doesn't end the transaction: Payload commits the others, and the failed document's clean-up is left half done (a set can be left with one member, for example). Look at that account's set after such an error, or turn on `bulkOperationsSingleTransaction` so the whole delete is undone instead. Tested on MongoDB with transactions: the join case, the plain error case in the default mode, and a transaction rolled back just before the clean-up's own delete of a member row, with `req.transactionID` still set and cleared. Single-transaction mode itself isn't in this repo's tests; the security review's probe of it (a site hook refusing one account of a bulk delete) left every row in place in six of six runs.
154
+ - The events are `link-requested` (for a new set), `link-confirmed` for each account that joined, and `link-approved` for each approval, with ids only and `source: 'server'`. They go through the same bounded path as the others: a handler that throws or hangs can't fail the call. A call's events are sent side by side, the handler called once per event in that order, so a handler that hangs holds the call for 2 seconds at most in all.
155
+ - To move an account to another set, unlink it, then link it, in one transaction. There is no move function.
156
+
157
+ | Reason | Status | When |
158
+ | --- | --- | --- |
159
+ | `linkingOff` | 409 | `canApproveLinks` isn't set, so linking is off. |
160
+ | `blocked` | 409 | `blocked(req)` refuses, or throws. A check that throws or gives an answer that isn't a reason says linking isn't available right now. |
161
+ | `notAccount` | 404 | An id isn't exact, or there's no such account. |
162
+ | `sameAccount` | 400 | `account` and `with` are the same. |
163
+ | `otherSet` | 409 | `account` is already in a different set. |
164
+ | `setFull` | 409 | The set would pass `maxLinked`, or its approved accounts would. |
165
+ | `notApprover` | 403 | Approving, and `req.user` isn't an approver. |
166
+ | `ownSet` | 403 | Approving a set the approver is in, is joining, or signed in through. |
167
+ | `notConfirmed` | 409 | The account's row is still waiting for its email, or, for `approveLink`, it's in no set. |
168
+ | `failed` | 500 | Anything else went wrong, the set dissolved during the call, or the request's transaction has ended. The call's writes are undone, as above; the message says when an invitation stayed canceled or the undo didn't finish. |
169
+
170
+ Show people one plain message for every refusal, such as "Those accounts couldn't be linked. Ask an administrator." The reasons are for your logs and your own code.
171
+
172
+ `checkLinks(payload)` reads every set and returns only the ones that break the plugin's rules, as `{ link, problems, rows }` with ids only: `overFull` (more than `maxLinked` rows), `alone` (one account), `noApprover` (approved with no approver), `selfApproved` (approved by an account in the set), `liveToken` (a confirmed or approved row that still has a token), `missingAccount` and `missingSet`. It changes nothing. Run it once after writing link rows by hand, or after an import.
173
+
129
174
  ## Upgrading from 0.4.0
130
175
 
131
176
  Sets already approved keep working, and requests still pending from 0.4.0 complete through their old links with the same confirmations and approval.
@@ -149,7 +194,7 @@ Everything else that changes for a host, in full:
149
194
  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
195
  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
196
 
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.
197
+ 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, an account losing to a join (or any failure, with `bulkOperationsSingleTransaction`) ends Payload's shared transaction for every account in the call. The plugin's clean-up stops there (see above), but Payload itself can still delete an account it hadn't reached yet, outside any transaction (this case isn't tested), so that account can be deleted with their member rows, sets, requests and session records left behind (sessions through it stay refused). Delete linked accounts one at a time. Deleting an account clears the starter only on sets that account started. The plugin wraps the database adapter's `commitTransaction` and `rollbackTransaction`, and its `count`, `create`, `deleteMany`, `deleteOne`, `find`, `findOne`, `updateMany`, `updateOne` and `upsert`, once at start-up, for the whole process, and never puts them back. The nine data methods only change a call made inside the plugin's clean-up; any other call passes straight through. Events held for a transaction go out when `commitTransaction` is called for it, so a host that aborts a MongoDB session directly (not through `rollbackTransaction`) and then calls `commitTransaction` with that id gets events for a delete that was rolled back. End your transactions through the adapter's two methods. With `bulkOperationsSingleTransaction`, a document's own database error can read as `another change in it failed`, and the try-again collision message can appear on a rollback that had no real collision; nothing is written either way.
153
198
 
154
199
  The changelog lists every change.
155
200
 
@@ -0,0 +1,26 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import { type ResolvedHatsOptions } from './types.js';
3
+ /** Why an approval is refused. The admin form and `approveLink` share these, so the two can't drift. */
4
+ export type ApprovalRefusal = {
5
+ reason: 'notApprover' | 'ownSet' | 'setFull';
6
+ message: string;
7
+ };
8
+ /**
9
+ * Whether the request's user may approve links: signed in to the site's users collection, linking on, and
10
+ * `canApproveLinks` answering exactly `true`. A truthy value or a thrown error is a no.
11
+ */
12
+ export declare function isApprover(opts: ResolvedHatsOptions, req: PayloadRequest): Promise<boolean>;
13
+ /**
14
+ * The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
15
+ * - `req.user` isn't an approver (`notApprover`);
16
+ * - the approver, or the account they signed in with (`via`), is in the set or is one of the accounts joining it
17
+ * (`ownSet`), so nobody approves their own link;
18
+ * - the set's approved rows, leaving out `except`, plus `approving` would pass `maxLinked` (`setFull`).
19
+ * `link` is null for a set that doesn't exist yet. Returns null when the approval may go ahead.
20
+ */
21
+ export declare function approvalRefusal(req: PayloadRequest, opts: ResolvedHatsOptions, args: {
22
+ link: string | null;
23
+ joining?: string[];
24
+ approving: number;
25
+ except?: string;
26
+ }): Promise<ApprovalRefusal | null>;
@@ -0,0 +1,48 @@
1
+ import { exactlyTrue } from './access.js';
2
+ import { hatsStateOf } from './state.js';
3
+ import { MEMBERS } from './types.js';
4
+ /**
5
+ * Whether the request's user may approve links: signed in to the site's users collection, linking on, and
6
+ * `canApproveLinks` answering exactly `true`. A truthy value or a thrown error is a no.
7
+ */
8
+ export async function isApprover(opts, req) {
9
+ const user = req.user;
10
+ if (!user || user.collection !== opts.users || !opts.canApproveLinks)
11
+ return false;
12
+ const ask = opts.canApproveLinks;
13
+ return exactlyTrue(() => ask({ req, user }));
14
+ }
15
+ /**
16
+ * The one approval rule. The approver is `req.user`, never an id passed in. It's refused when:
17
+ * - `req.user` isn't an approver (`notApprover`);
18
+ * - the approver, or the account they signed in with (`via`), is in the set or is one of the accounts joining it
19
+ * (`ownSet`), so nobody approves their own link;
20
+ * - the set's approved rows, leaving out `except`, plus `approving` would pass `maxLinked` (`setFull`).
21
+ * `link` is null for a set that doesn't exist yet. Returns null when the approval may go ahead.
22
+ */
23
+ export async function approvalRefusal(req, opts, args) {
24
+ if (!(await isApprover(opts, req)))
25
+ return { reason: 'notApprover', message: 'You can’t approve links.' };
26
+ const me = req.user;
27
+ const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
28
+ const ownSet = { reason: 'ownSet', message: 'You can’t approve a set you belong to. Ask another administrator.' };
29
+ if ((args.joining ?? []).some((j) => people.includes(j)))
30
+ return ownSet;
31
+ if (args.link != null) {
32
+ const mine = await req.payload.count({ collection: MEMBERS, where: { and: [{ link: { equals: args.link } }, { user: { in: people } }] }, overrideAccess: true, req });
33
+ if (mine.totalDocs > 0)
34
+ return ownSet;
35
+ }
36
+ // The size limit holds at approval too, whatever happened before: a set never has more approved accounts than maxLinked.
37
+ const approved = args.link == null
38
+ ? 0
39
+ : (await req.payload.count({
40
+ collection: MEMBERS,
41
+ where: { and: [{ link: { equals: args.link } }, { status: { equals: 'approved' } }, ...(args.except != null ? [{ id: { not_equals: args.except } }] : [])] },
42
+ overrideAccess: true,
43
+ req,
44
+ })).totalDocs;
45
+ if (approved + args.approving > opts.maxLinked)
46
+ return { reason: 'setFull', message: `A set can hold at most ${opts.maxLinked} accounts.` };
47
+ return null;
48
+ }
@@ -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). */
@@ -1,7 +1,7 @@
1
1
  import { APIError, validations } from 'payload';
2
- import { exactlyTrue } from './access.js';
2
+ import { approvalRefusal, isApprover } from './approval.js';
3
3
  import { dissolveIfAlone, revokeSessions } from './sessions.js';
4
- import { hatsStateOf, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
4
+ import { holdEvents, idOf, isDissolving, isInternal, ownHook, tell } from './state.js';
5
5
  import { LINKS, MEMBERS, REQUESTS, SESSIONS } from './types.js';
6
6
  const internal = isInternal;
7
7
  /**
@@ -17,18 +17,10 @@ const requiredOnWrite = (value, options) => validations.relationship(value, { ..
17
17
  * there needs the column to take null. On SQL databases the column is nullable and the rule moves to validation.
18
18
  */
19
19
  const requiredAccount = (sql) => (sql ? { validate: requiredOnWrite } : { required: true });
20
- /**
21
- * Whether the request's user may approve links. A person never approves their own link: an approver who is (or
22
- * who signed in as) a member of the set is refused, so the owner's own links need another approver. Only an exact
23
- * `true` from `canApproveLinks` counts: a truthy value or a thrown error is a no.
24
- */
25
- async function approver(opts, req) {
26
- const user = req.user;
27
- if (!user || user.collection !== opts.users || !opts.canApproveLinks)
28
- return false;
29
- const ask = opts.canApproveLinks;
30
- return exactlyTrue(() => ask({ req, user }));
31
- }
20
+ /** Whether the request's user may approve links (see `isApprover`). Who may approve a given set is `approvalRefusal`. */
21
+ const approver = isApprover;
22
+ /** The admin form's statuses for each refusal, as before `approveLink` shared the rule. */
23
+ const HOOK_STATUS = { notApprover: 403, ownSet: 403, setFull: 400 };
32
24
  export function hatCollections(opts, sql) {
33
25
  const canApprove = ({ req }) => approver(opts, req);
34
26
  const never = () => false;
@@ -91,36 +83,24 @@ export function hatCollections(opts, sql) {
91
83
  return data;
92
84
  if (originalDoc.status !== 'confirmed' || data.status !== 'approved')
93
85
  throw new APIError('Only a confirmed account can be approved, and an approval can’t be undone here: delete the row to unlink.', 400, undefined, true);
94
- const me = req.user;
95
- const people = [String(me.id), hatsStateOf(me)?.via].filter(Boolean);
96
- const mine = await req.payload.count({
97
- collection: MEMBERS,
98
- where: { and: [{ link: { equals: idOf(originalDoc.link) } }, { user: { in: people } }] },
99
- overrideAccess: true,
100
- req,
101
- });
102
- if (mine.totalDocs > 0)
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);
113
- return { ...data, approvedBy: me.id, approvedAt: new Date().toISOString() };
86
+ // The same rule `approveLink` runs: an approver outside the set, with room for one more approved account.
87
+ const refused = await approvalRefusal(req, opts, { link: idOf(originalDoc.link), approving: 1, except: String(originalDoc.id) });
88
+ if (refused)
89
+ throw new APIError(refused.message, HOOK_STATUS[refused.reason], undefined, true);
90
+ return { ...data, approvedBy: req.user.id, approvedAt: new Date().toISOString() };
114
91
  }),
115
92
  ],
116
93
  afterChange: [
117
94
  ownHook(async ({ doc, previousDoc, operation, req }) => {
95
+ // Through the bounded path like every other link event, so a slow or failing handler can't fail an approval.
118
96
  if (operation === 'update' && previousDoc?.status !== 'approved' && doc.status === 'approved' && !internal(req))
119
- await opts.onEvent?.({ type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
97
+ await tell(req.payload, req, { type: 'link-approved', req, link: idOf(doc.link), account: idOf(doc.user), by: String(req.user.id) });
120
98
  }),
121
99
  ],
122
100
  afterDelete: [
123
- ownHook(async ({ doc, req }) => {
101
+ // Events wait for the delete's transaction to commit, the dissolve included, so a delete that's undone
102
+ // reports nothing (see `holdEvents`).
103
+ ownHook(async ({ doc, req }) => holdEvents(req, async () => {
124
104
  const link = idOf(doc.link);
125
105
  const account = idOf(doc.user);
126
106
  await revokeSessions(req.payload, { and: [{ link: { equals: link } }, { or: [{ user: { equals: account } }, { via: { equals: account } }] }] }, 'unlinked', req);
@@ -128,7 +108,7 @@ export function hatCollections(opts, sql) {
128
108
  await tell(req.payload, req, { type: 'unlinked', payload: req.payload, link, account, by: req.user ? String(req.user.id) : null });
129
109
  if (!isDissolving(req))
130
110
  await dissolveIfAlone(req.payload, link, req);
131
- }),
111
+ })),
132
112
  ],
133
113
  },
134
114
  };
@@ -1,6 +1,19 @@
1
1
  import { type Endpoint, type PayloadRequest } from 'payload';
2
2
  import { revokeSessions } from './sessions.js';
3
3
  import { type Hat, type HatsUser, type ResolvedHatsOptions } from './types.js';
4
+ export declare const loadUser: (req: PayloadRequest, id: string) => Promise<HatsUser | null>;
5
+ export declare const labelOf: (u: HatsUser) => string;
6
+ export declare function members(req: PayloadRequest, link: string): Promise<{
7
+ id: string;
8
+ user: unknown;
9
+ status: string;
10
+ }[]>;
11
+ export declare function membershipOf(req: PayloadRequest, userId: string): Promise<{
12
+ id: string;
13
+ link: unknown;
14
+ user: unknown;
15
+ status: string;
16
+ } | null>;
4
17
  /**
5
18
  * Whether the switch is shown (and so allowed). The site's `showSwitch` gets every hat, hidden ones included, with
6
19
  * their flags. The default counts only hats that are offered: more than one on this account, or on a linked account.
@@ -38,5 +51,7 @@ export type SwitchInput = {
38
51
  * `req.user` and has no option that skips a check. Any failure, an error from a host hook included, is a refusal.
39
52
  */
40
53
  export declare function runSwitch(req: PayloadRequest, input: SwitchInput | null | undefined): Promise<SwitchResult>;
54
+ /** Whether `v` is an account id written the one way the users collection writes its ids. */
55
+ export declare function exactId(req: PayloadRequest, opts: ResolvedHatsOptions, v: unknown): boolean;
41
56
  export declare const hatEndpoints: Endpoint[];
42
57
  export { revokeSessions };