ExtantApe

payload plugin hats

by ExtantApe
Roles & permissions
v3
^3.80.0
MIT

Overview

Summary generated from the README

Lets one person link up to four approved accounts and act in one role (hat) at a time. Hats narrow the user before req.user exists, so admin, REST, GraphQL and Local API access rules follow the active role. Switching into a sensitive hat asks for a second factor. Requires Payload 3.80 or newer with sessions enabled, plus your own hatsOf and wear functions.

Features

  • Linked accounts with email confirmation and an approver outside the linked set
  • Role hats that narrow the user for admin, REST, GraphQL and Local API
  • Step-up second factor with remember per account, linked set or hat
  • Admin header switcher with a code screen, switched-to note and translatable text
  • Hidden hats, session revocation on unlink or role loss, and a server-side switchSession helper
  • Server functions to link and approve accounts from your own code

Use cases

  • Let staff act as a plain member by default and elevate to admin only after entering a code
  • Allow a guardian to switch into linked family accounts with an approval step
  • Enforce least-privilege by limiting a multi-role account to one role per session

From the author

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.

Installation

npm i @extantape/payload-plugin-hats

0

Stars

0

Forks

2

Open Issues

Yesterday

Last Updated

1.4k

Weekly Downloads

v0.8.1

npm Version

251.4 KB

Unpacked Size

0

Dependencies

GitHub stars

00 since Nov 8

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20260
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
Nov 21, 20260
Nov 20, 20260
Nov 19, 20260
Nov 18, 20260
Nov 17, 20260
Nov 16, 20260
Nov 15, 20260
Nov 14, 20260
Nov 13, 20260
Nov 12, 20260
Nov 11, 20260
Nov 10, 20260
Nov 9, 20260
Nov 8, 20260
npm weekly downloads

1.1K+1.1K since Nov 11

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 20261,101
Dec 5, 2026959
Dec 4, 2026946
Dec 3, 2026973
Dec 2, 2026969
Dec 1, 2026798
Nov 30, 2026762
Nov 29, 2026692
Nov 28, 2026683
Nov 27, 2026529
Nov 26, 2026677
Nov 25, 2026646
Nov 24, 2026637
Nov 23, 2026463
Nov 22, 2026532
Nov 21, 2026493
Nov 20, 2026469
Nov 19, 2026251
Nov 18, 2026230
Nov 17, 2026203
Nov 16, 2026189
Nov 15, 20260
Nov 14, 2026642
Nov 13, 2026562
Nov 12, 20260
Nov 11, 20260

Each point is npm's rolling 7-day download count.

Health Score

67/100Good

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1452242019-root.svg)](https://payloaddirectory.dev/plugins/1452242019-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1452242019-root"><img src="https://payloaddirectory.dev/badge/1452242019-root.svg" alt="Payload Directory"></a>
Updated Dec 4, 2026Created Nov 10, 2026Published Dec 4, 2026

README

payload-plugin-hats

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.

Status: early, 0.x. All 366 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.

What it does

  • 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.
  • A link request answers the same way whatever the address. The asker gets the same answer, the same note by email, the same records to read and the same wait (linkAnswerMs, default 2000 ms) whether or not the address has an account, whatever state it is in. Only an account that can be linked is invited, one open invitation per account from everyone (a unique key in the database holds this, even for requests that arrive together), and nothing joins a set until it confirms. Then the asker confirms from their own email. Open requests live in a hat-requests collection that no user can read and only the plugin can write, at most maxLinked × 2 per account.
  • 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.
  • Step-up. Switching into a sensitive hat asks for that account's second factor, remembered for 180 minutes (stepUp.rememberMinutes) per account, per linked set or per hat (see below).
  • 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.
  • 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.
  • One code per hat. stepUp.rememberPer: 'hat' remembers a good code for that account and that hat only. Another hat on the same account asks again, and so does the same hat on a linked account. Pick it when a site's hats differ a lot in what they can do, for example a moderator hat and an owner hat on one account, and a code given for the smaller one shouldn't open the bigger one. It asks more often, so 'account' suits a site whose sensitive hats are close to each other.
  • 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.
  • 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).
  • 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.
  • 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.

Needs Payload sessions (auth.useSessions, on by default).

On its own, and with others

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.

Needs: Payload ^3.80.0 as a peer dependency, with React ^19.0.0 optional. No other EXTANT APE plugin is required.

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.

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.

Works with:

  • MFA: MFA's isOnFor and verify make the stepUp. MFA's README has the two lines.
  • Masq: your blocked(req) can refuse switching while masquerading, using Masq's masqStateOf. Masq's canMasquerade should refuse a switched session, using hatsStateOf(user).via.
  • Guardians: Hats can be the switcher behind Guardians' required actingFor, so a guardian who switched into a kid's account is still seen as the guardian.
  • Audit Trail: pass onEvent through Audit Trail's fromPluginEvent, and use hatsStateOf(req) in its via, so an entry says which account signed in and which hat was worn.

None of these are imported. The site connects them in its own config.

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.

Family: It's part of the Identity family (a working draft): plugins designed to sit together for accounts and access.

Use

import { hats } from '@extantape/payload-plugin-hats'

hats({
  hatsOf: (user) => [{ id: 'member', label: 'Member' }, { id: 'admin', label: 'Administrator', sensitive: true }],
  wear: (user, hat) => ({ ...user, roles: hat === 'admin' ? user.roles : ['member'] }),
  canApproveLinks: ({ user }) => user.roles.includes('admin'),
  stepUp: { available: (user) => hasAuthenticator(user), verify: ({ user, code }) => checkCode(user, code), rememberPer: 'set' }, // rememberPer is optional
  // optional: ask only when the new hat holds something the current one doesn't
  stepUpWhen: ({ from, to }) => holdsMoreThan(to.user, from.user),
  limit: ({ user, email }) => allowAttempt('hatsLink', `${user.id}:${email}`), // optional
})

stepUp.rememberPer takes one of three values. Any other value stops startup.

ValueA good code coversAsks again for
'account' (default)every hat on the account it was given foranother account
'set'every hat on every account in the same linked set (an account in no set: that account)an account outside the set
'hat'the one hat on the one account it was given forany other hat, and the same hat on another account

The three are alternatives and don't combine: there is no per-set-and-hat value. A hat belongs to one account's hatsOf, and the same hat id on a linked account can stand for different roles, so 'hat' always counts the account too and never widens to the set. Every value expires after rememberMinutes, and only asks when sensitive or stepUpWhen says the switch needs a code. The memory is kept per session under the value in use, so after changing rememberPer on a running site, codes remembered under the old value stop counting and people are asked once more.

wear must return a narrowed copy of the user, never the user itself: Hats refuses the request if it gets the same object back, if a hat adds one the account doesn't hold, or if an ordinary hat keeps a sensitive one.

Endpoints, under the API route:

  • 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.
  • POST /hats/switch { account?, hat, code? } switches hat or account.
  • 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.
  • GET and POST /hats/confirm handle the email confirmation.
  • POST /hats/unlink { account? } takes an account out of the set.

Approvers approve in the admin, under Accounts → Linked accounts.

The switch goes in the admin header (turn it off with adminSwitch: false). The plugin doesn't pass options such as accountTitle or hatHelp to the header switch, so a site that needs them sets adminSwitch: false and registers its own wrapper around HatSwitcher. For a site's own pages, @extantape/payload-plugin-hats/client has HatSwitcher for the header, HatsSwitchedNote for pages without a switch (mount it once in your layout, as import { HatsSwitchedNote } from '@extantape/payload-plugin-hats/client', so a switch that lands on one of your own pages still shows its note), and LinkedAccounts for the account page. They need no Payload UI package.

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.

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.

Site options on HatSwitcher, all optional:

  • accountTitle(account): each group's heading, for example its job ("Maintainer account"). Default: This account, Linked account. The email sits under it, small.
  • hatHelp: a helper line under each hat, as { [hatId]: line } or (hat, account) => line.
  • orderHats(hats): the order inside a group. Default: as hatsOf gives them, with hats that ask for a code last.
  • anotherWay: text shown under Use another way on the code screen (recovery codes, say). Left out, the link isn't shown.
  • noteMs: how long the note stays. Default 5000.

Colors and sizes come from --hats-ink, --hats-paper, --hats-line, --hats-muted, --hats-hover, --hats-selected, --hats-error, --hats-focus (an outline value), --hats-row and the rest in src/client/styles.ts. Unset, they follow the Payload admin's theme variables, so the switch matches the admin in light and dark, and then the surrounding text. There are no fixed colors.

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.

What hidden doesn't do

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:

  • 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.
  • 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.
  • 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.
  • 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.

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.

Switching from your own route

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.

// app/api/enter-admin/route.ts (Next.js). Your own POST route, not the picker.
import { getPayload, type PayloadRequest } from 'payload'
import config from '@payload-config'
import { switchSession } from '@extantape/payload-plugin-hats'

export async function POST(request: Request) {
  const payload = await getPayload({ config })
  const { user } = await payload.auth({ headers: request.headers }) // the person's own sign-in cookie
  if (!user) return Response.json({ reason: 'signIn' }, { status: 401 })
  const { account, hat, code } = await request.json() // ids from your own screen; code only when it asked for one
  // The plugin reads method, Origin and Sec-Fetch-Site from this request and refuses a cross-site call.
  const req = { payload, user, headers: request.headers, method: request.method, url: request.url } as unknown as PayloadRequest
  const result = await switchSession(req, { account, hat, code })
  if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status }) // needsCode, wrongCode, blocked, notLinked, locked ...
  return new Response(null, { status: 204, headers: result.cookie ? { 'Set-Cookie': result.cookie } : {} })
}
  • It acts only for req.user. With nobody signed in it is refused (signIn, 401), and so is a switch into an account that is locked (locked, 403) or isn't email-verified when auth.verify is on (unverified, 403), as direct sign-in is. It has no option that skips a check: blocked, notLinked, showSwitch (notAvailable), the step-up checks, the session record and the old session's revoke all run, in the endpoint's order.
  • It returns { ok: true, account, hat, cookie } or { ok: false, status, reason, message }. cookie is the Set-Cookie value for the new session, or null when the hat changed on the same account. The reasons are the endpoint's, needsCode included. It doesn't throw for a refusal, and an error from one of your hooks, or any other error inside the switch, is a refusal (failed, 500). A switch is never let through by a failing check.
  • Call it only from a same-origin POST, never from a GET. A link on another site can send someone to a GET, and SameSite=Lax sends the sign-in cookie on that top-level request, so a GET that switches would move them into a stronger account whenever a code is still remembered. Opening /admin may show an Enter admin screen with a button, and the code field when one is needed. The button posts. Nothing switches on the page load. switchSession checks this itself, and fails closed: it refuses (notPost, 405) unless req.method is POST, and refuses (crossSite, 403) when an Origin header is present and isn't this site's own origin (the request's URL or Payload's serverURL), or when Sec-Fetch-Site is present and isn't same-origin. The request you pass must carry the method, headers and URL, as in the sample. Also set csrf in your Payload config to your site's origins, so Payload's own cookie sign-in checks the same list.
  • 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.
  • 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.

Linking from your own server code

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.

import { approveLink, linkAccounts } from '@extantape/payload-plugin-hats'

// Inside your own route or hook, with the request Payload gave you (its transaction is joined).
const result = await linkAccounts(req, { account: childId, with: parentId })
if (!result.ok) return Response.json({ reason: result.reason }, { status: result.status })
// Later, an approver who isn't in the set, signed in on `req`:
const approved = await approveLink(req, { account: childId })
  • 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.
  • 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.
  • 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.
  • Ids must be written exactly as your users collection writes them. Any other key in the input is ignored.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • To move an account to another set, unlink it, then link it, in one transaction. There is no move function.
ReasonStatusWhen
linkingOff409canApproveLinks isn't set, so linking is off.
blocked409blocked(req) refuses, or throws. A check that throws or gives an answer that isn't a reason says linking isn't available right now.
notAccount404An id isn't exact, or there's no such account.
sameAccount400account and with are the same.
otherSet409account is already in a different set.
setFull409The set would pass maxLinked, or its approved accounts would.
notApprover403Approving, and req.user isn't an approver.
ownSet403Approving a set the approver is in, is joining, or signed in through.
notConfirmed409The account's row is still waiting for its email, or, for approveLink, it's in no set.
failed500Anything 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.

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.

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.

Upgrading from 0.4.0

Sets already approved keep working, and requests still pending from 0.4.0 complete through their old links with the same confirmations and approval.

On MongoDB there is no database step. The plugin's 0.4.0 collections keep exactly the indexes 0.4.0 built, so a site with ensureIndexes: true starts on a 0.4.0 database as it is. Payload builds the new hat-requests collection's indexes when it starts. If you've turned Mongoose's autoIndex off, build those yourself before link requests are made, including the unique one on holds.

On Postgres or SQLite, run payload migrate:create, then payload migrate. The migration adds the hat_requests table, with its unique holds column, and makes hat_link_members.user_id and hat_requests.requested_by_id nullable so the database's foreign key can clear them while an account is deleted (the plugin removes those rows straight after and still requires both on every write). Schema push mode (push: true, the development default) can't move a 0.4.0 SQLite schema: it stops on the existing hat_members_link_idx index, so use a migration there too. In 0.4.0 on SQL databases linking didn't work (ids were written as strings) and deleting a linked account failed; both work now.

Everything else that changes for a host, in full:

  1. Regenerate types with payload generate:types (new hat-requests collection, new export REQUESTS).
  2. Review a custom reasons.linkSent text: it shouldn't name the address.
  3. Link requests answer 202 after linkAnswerMs (new option, 2000 ms by default). A value outside 0 to 2147483647, or one that isn't a number, stops startup.
  4. In an onEvent handler, use by for the asker on link-requested. It fires at ask time only when the asker is already in a set. Otherwise it fires as the other account confirms, just before link-confirmed, on that request: req.user there may be nobody, or the invited person, who may be a child.
  5. A handler that throws on link-requested, link-confirmed, unlinked or sessions-revoked is logged by a short error name and skipped, and what it reported still happened. The plugin waits at most 2 seconds for each of those handlers.
  6. Key limit by address as well as person.
  7. Startup refuses a config that already has a hat-requests collection.
  8. A hatsInternal or hatsDissolving key in context means nothing.
  9. confirmURL, sendEmail and onEvent run without the plugin's mark, and so do your own hooks and other plugins' hooks, on any collection and field. Their writes are checked like any other server write, so they can't write hat-requests.
  10. If your users collection has afterDelete hooks, the plugin's now runs first, and only for a delete that happened.
  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.
  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.

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.

The changelog lists every change.

Commands

npm test          # Vitest, in-memory MongoDB
npm run typecheck
npm run build

License

MIT. See LICENSE.

Similar plugins